diff --git a/.github/workflows/bazel-npm.yml b/.github/workflows/bazel-npm.yml index 699a19c2d..0b625b1ac 100644 --- a/.github/workflows/bazel-npm.yml +++ b/.github/workflows/bazel-npm.yml @@ -2,9 +2,10 @@ name: Bazel patch compatibility (npm) # The npm flows of the real-Bazel tests (`npm::` in `e2e_bazel_build`): # hosted and vendored mode for a package that aspect_rules_js links from a -# pnpm lock, on each Bazel release below. bazel-compatibility.yml holds the -# legs and what every ecosystem shares; this file says when the npm legs run -# and on which releases. +# pnpm lock, and agent mode for the copy of it in `node_modules`, on each +# Bazel release below. bazel-compatibility.yml holds the legs and what +# every ecosystem shares; this file says when the npm legs run and on which +# releases. # # Beyond what every leg needs, an npm leg downloads Node from nodejs.org and # ruleset archives from codeload.github.com; its repository cache holds them @@ -38,9 +39,11 @@ on: # file also holds the Composer, Cargo and Go parts of the gate, so a # 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 + # the core, the files of the `vex` command, and `bazel/` of the core, + # which reads the workspace files and decides whether Bazel builds what + # was patched. Every flow holds the exact document socket-patch writes + # about its build, patched or not, 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. # @@ -69,6 +72,7 @@ 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/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' push: @@ -97,6 +101,7 @@ 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/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' diff --git a/.github/workflows/bazel-pypi.yml b/.github/workflows/bazel-pypi.yml index 6299fc1c3..cd5198576 100644 --- a/.github/workflows/bazel-pypi.yml +++ b/.github/workflows/bazel-pypi.yml @@ -1,8 +1,8 @@ name: Bazel patch compatibility (PyPI) -# The PyPI flow of the real-Bazel tests (`pypi::` in `e2e_bazel_build`): -# hosted mode for a package that rules_python's `pip.parse` resolves from a -# hashed `requirements.txt`, on each Bazel release below. +# The PyPI flows of the real-Bazel tests (`pypi::` in `e2e_bazel_build`): +# hosted and vendored mode for a package that rules_python's `pip.parse` +# resolves from a hashed `requirements.txt`, on each Bazel release below. # bazel-compatibility.yml holds the legs and what every ecosystem shares; # this file says when the PyPI legs run and on which releases. # @@ -36,10 +36,12 @@ on: # 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 + # installed wheel. Last, the VEX code: `vex/` of the core, the files of + # the `vex` command, and `bazel/` of the core, which reads the workspace + # files and decides whether Bazel builds what was patched. Every flow + # holds the exact document socket-patch writes about its build, patched + # or not, 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. # @@ -73,6 +75,7 @@ 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/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' push: @@ -106,6 +109,7 @@ 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/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' diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index 07183b368..1615b3a12 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -30,10 +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. - # 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 + # Last, the VEX code: `vex/` of the core, the files of the `vex` + # command, and `bazel/` of the core, which reads the workspace files and + # decides whether Bazel builds what was patched. 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. # @@ -64,6 +66,7 @@ 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/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' push: @@ -88,6 +91,7 @@ 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/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' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 829f9efa4..489be8ef2 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -291,7 +291,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | `show` | `--stat` | — | The summary and the list of changed files, without the diffs | | `show` | `--no-pager` | — | Print everything at once instead of opening the patch full-screen (what a pipe gets) | | `apply`, `scan`, `vendor` | `--vex` | `SOCKET_VEX` | Generate an OpenVEX 0.2.0 document at this path on a successful run; see "embedded VEX" below | -| `apply`, `scan`, `vendor` | `--vex-product`, `--vex-no-verify`, `--vex-doc-id`, `--vex-compact` | `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | Passthrough to the embedded VEX builder; mirror the standalone `vex` knobs. Inert unless `--vex` is set | +| `apply`, `scan`, `vendor` | `--vex-product`, `--vex-no-verify`, `--vex-no-bazel`, `--vex-doc-id`, `--vex-compact` | `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | Passthrough to the embedded VEX builder; mirror the standalone `vex` knobs. Inert unless `--vex` is set | | `scan` | positional `[PATHS]...` | — | (v5.0) Meaning depends on the mode. **Hosted / vendored** (bare `scan` included): each PATH, or directory glob (`apps/*`), is a project directory scanned on its own as if it were `--cwd`. **Agent** (and a mode-less `--prune`/`--global` report): path globs scoping DISCOVERY to packages installed under matching paths (`packages/foo`, `apps/**`). See "Path-scoped scans" below | | `scan` | `--mode ` | — | The documented selector for the three patch-application modes (v5.0 default: `hosted`, except that a `--prune` or `--global`/`--global-prefix` scan with no mode is report-only). v5.0 removes the hidden value aliases `host`/`redirect`/`vendor` (now an invalid-value usage error), and the hidden boolean spellings `--redirect`, `--vendor` and `--apply` (now unknown-argument usage errors). `--sync` selects agent mode, so `--sync` with any other `--mode` is a usage error (exit 2, enforced in `resolve_mode_flags` — clap's `conflicts_with` is value-independent); `--mode agent --sync` is accepted. `--prune` is an orthogonal GC knob and never conflicts — but hosted mode runs no GC, so `--mode hosted --prune` emits an explicit `redirect_prune_ignored` warning (JSON `warnings[]` + stderr) instead of silently dropping the flag | | `scan` | `--prune` / `--sync` | — | `--prune` = GC after the scan (ignored with a `redirect_prune_ignored` warning in hosted mode); `--sync` = `--mode agent --prune` | @@ -305,7 +305,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | `get` | positional `identifier`; `--id` / `--cve` / `--ghsa` / `--package` (`-p`); `--save-only`; `--mode ` | `SOCKET_SAVE_ONLY` | Patch lookup + consumption mode (v3.6). `--mode` reuses scan's value enum (same hidden value aliases `host`/`redirect`/`vendor`; deliberately no env binding, matching scan). Default (v5.0): the mode the project's patch state records, like scan (see **Mode resolution**), so `hosted` for a project with no state; `agent` (save + apply in place) when `--save-only` or `--global`/`--global-prefix` is given. An explicit `--mode hosted\|vendored` with `--global`/`--global-prefix` is a usage error (exit 2, scan's wording: global installs have no project lockfile). An explicit `--save-only` conflicts with `--mode hosted\|vendored` — rejected with **exit 1** via get's established self-enforced-conflict style (unlike scan's exit-2 mode conflicts; see the exit-code table) | | `remove` | positional `identifier` (target grammar: UUID, PURL with or without version, or exact package name); `--skip-rollback`; `--preserve-state` (v5.0) | `SOCKET_SKIP_ROLLBACK`, `SOCKET_PRESERVE_STATE` | Manifest entry removal. The identifier matches like a `rollback` target (a PyPI name compares by its PEP 503 canonical form). `--preserve-state` is the single-patch twin of `rollback --preserve-state`: restore the tree and unwind the identifier's vendored/hosted wiring, but keep the manifest entry, the vendored artifact + ledger entry, and skip all GC. Combining it with `--skip-rollback` is a self-enforced usage error (exit 2): one flag keeps the tree and drops the state, the other restores the tree and keeps the state — together they select the do-nothing quadrant ("the combination would be a no-op: nothing would change"). The conflict fires whether either flag is spelled on the command line or sourced from its env var | | `rollback` | optional variadic positional `targets` (PURL \| UUID \| package name \| path glob); `--preserve-state` (v5.0) | `SOCKET_PRESERVE_STATE` | Rollback scope. Multiple targets union. A token becomes a path glob ONLY when it is path-SHAPED — contains a separator (`/` or `\`) or a glob metacharacter (`*?[`), or starts with `./`, or is absolute (an npm `@scope/name` is a name, not a path; a relative slash name without glob metacharacters or `.`/`..` segments — composer `vendor/pkg`, a go module path — is a name when it selects a recorded or hosted patch); a `pkg:` prefix is a PURL and every other token keeps the target grammar (UUID, PURL or exact package name), so a mistyped identifier or truncated UUID stays a safe exit-1 "No patch found matching identifier: X" (with a hint suggesting `./X` or `X/**` for directory targeting) instead of silently becoming a path scope. An unparseable glob is a usage error (exit 2) | -| `vex` | `--output` / `-O`, `--product`, `--no-verify`, `--doc-id`, `--compact` | `SOCKET_VEX_OUTPUT`, `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | OpenVEX 0.2.0 document generation; see "vex output channels" below | +| `vex` | `--output` / `-O`, `--product`, `--no-verify`, `--no-bazel`, `--doc-id`, `--compact` | `SOCKET_VEX_OUTPUT`, `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | OpenVEX 0.2.0 document generation; see "vex output channels" below | | `repair` | `--download-only` | `SOCKET_DOWNLOAD_ONLY` | Repair-specific cleanup mode (mutually exclusive with `--offline`; combining them is a usage error, exit 2) | **pnpm hosted-mode contract**: `scan --mode hosted` handles block and flow resolutions in legacy `shrinkwrap.yaml` and lockfileVersion 5.x, 6.0, and 9.0. The [pinned compatibility matrix](../../docs/testing/pnpm-compatibility.md) samples pnpm majors 1–12. Early shrinkwrapVersion 3 without a positive minor version is refused with `redirect_pnpm_legacy_lockfile_unsupported`: pnpm 1.0.0 discards hosted URLs even on frozen installs. Upgrade to a tested release (1.43.1 or newer) and regenerate the lock, or use agent mode. @@ -657,14 +657,14 @@ CI recipe: `socket-patch scan --json --max-new-patches 5 | jq '.rollout.counts.d ### Embedded VEX (`apply --vex` / `scan --vex` / `vendor --vex`) -`--vex ` folds OpenVEX 0.2.0 generation into `apply`, `scan`, and `vendor`: on a successful run the command writes the document to `` using the same engine as the standalone `vex` command. The `--vex-*` flags mirror `vex`'s `--product` / `--no-verify` / `--doc-id` / `--compact` knobs (namespaced to avoid colliding with the host command), and reuse the standalone env vars (`SOCKET_VEX_PRODUCT`, etc.). They are inert unless `--vex` is set. +`--vex ` folds OpenVEX 0.2.0 generation into `apply`, `scan`, and `vendor`: on a successful run the command writes the document to `` using the same engine as the standalone `vex` command. The `--vex-*` flags mirror `vex`'s `--product` / `--no-verify` / `--no-bazel` / `--doc-id` / `--compact` knobs (namespaced to avoid colliding with the host command), and reuse the standalone env vars (`SOCKET_VEX_PRODUCT`, etc.). They are inert unless `--vex` is set. Contract details: * **Always written to the file** — never stdout — so the document never races the command's own `--json` output. * **Fail-the-command**: if `--vex` was requested but generation fails (product PURL undetectable, nothing to attest in the manifest / vendor ledger / lockfiles, all patches omitted, a corrupt vendor ledger, unwritable path), the command exits non-zero **even when the apply/scan itself succeeded**. In `--json` mode the failure surfaces in the envelope's `error` (`apply`) / top-level `error` (`scan`), with a stable code (`product_undetected`, `no_applicable_patches`, `write_failed`, …). * **Built from the post-run state** — the manifest, the `.socket/vendor/state.json` ledger and the project's lockfile references, with hosted records fetched from the API (see "Manifest-less VEX" below) — and verified against on-disk state (unless `--vex-no-verify`; the wiring gates apply either way). Generated for real applies and read-only `scan` alike; `--dry-run` skips generation on every host command (nothing was changed, and a preview must not write an attestation — `scan --json` marks it `vex: {skipped: true, reason: "dry_run"}`). -* **JSON success surface**: `apply` adds a top-level `vex` object to its envelope; `scan` adds a top-level `vex` key to its result. Both carry `{ path, statements, format: "openvex-0.2.0" }`. +* **JSON success surface**: `apply` adds a top-level `vex` object to its envelope; `scan` adds a top-level `vex` key to its result. Both carry `{ path, statements, format: "openvex-0.2.0" }`, and `affected`, how many of the statements say `affected`, when any does (see `vex_bazel_not_in_build`). * `apply`'s no-manifest early exit (the `noManifest` success no-op; v5.0: its human line is `No patch manifest found; nothing to apply.` — it names the missing `.socket/manifest.json`, not the folder, since `.socket/` may legitimately hold vendored state) and `vendor`'s (`No manifest found, nothing to vendor.` — a project with hosted pins ejects instead, v5.0) still generate the document from the lockfiles and the vendor ledger (manifest-less VEX: hosted / vendored checkouts carry no manifest). Nothing referenced anywhere keeps the calm exit 0 (a stale document at the path is removed; `--json` carries any discovery diagnostics in `warnings[]`); any other VEX failure fails the command with exit 1 — including a run whose only candidates are omitted `record_unavailable` (an `--offline` run over a lockfile-wired checkout with no local records), so an ambient `SOCKET_VEX` there fails the install. `--dry-run` skips generation on both, and so does `apply --check` — it stays read-only and offline-safe, leaving the output path untouched. `scan` has no such early exit: with no manifest and nothing wired anywhere its `--vex` fails with `manifest_not_found`. * **Stale-doc removal (v3.5)**: a run that ends in a VEX error removes a recognizably-OpenVEX file (JSON whose `@context` names openvex.dev) already sitting at the output path — a pipeline reusing one path can never ship yesterday's attestation for a now-unpatched tree. Unrelated files at the path are never touched; a mid-write partial that no longer parses as JSON is left for downstream parsers to reject loudly. * **Additive warnings (v3.5)**: `product_not_iri` (the `--product`/`--vex-product` override is neither a `pkg:` purl nor an absolute IRI; honored verbatim, warned), its document-id twin `doc_id_not_iri` (the `--doc-id`/`--vex-doc-id` override has no IRI scheme; honored, warned), `vex_not_verified` (the run used `--no-verify` / `--vex-no-verify` / `SOCKET_VEX_NO_VERIFY`: the detail starts ` of VEX statements were emitted without on-disk verification`, see the provenance markers below) and `vendored_tree_out_of_sync` (a healthy vendored attestation stands on the committed artifact + lock wiring while the PRESENT installed tree hash-mismatches the patched bytes — run the package manager's install (for a project with Hatch environments the detail also names `hatch env remove `, since Hatch keeps an installed release; for a pypi package of a project whose governing pdm.lock was written by PDM < 2.11 it names `pdm sync --reinstall`, or removing the installed copy first on PDM 1.x; for a gem the detail instead names each gem-home copy and says that a Bundler run of the lock loads the vendored path, that no `bundle install` replaces or removes what an earlier install left there, and that only a load outside that Bundler setup still runs it; the remedy is `bundle clean` for the project's own bundle path, or `gem uninstall` in any other gem home no other project uses); the attestation itself is unchanged). Both ride stderr in human mode and `warnings[]` in the standalone `vex --json` envelope. Same channel for `product_multiple_manifests` (auto-detect found several project manifests and names the one it used), `vex_stale_doc_removed` (the stale-doc removal above happened), the manifest-less plan's advisories — `vex_wiring_conflict` (the lockfiles wire a package to different patches: which files, which uuids, how to fix it), `vex_record_superseded` (a recorded patch replaced by the lockfile-wired one), `vex_claim_unwired` (a ledger claim whose patch the lockfiles still mention, but not as wiring), `vex_record_offline` / `vex_record_not_found` / `vex_record_fetch_failed` (why a lockfile-wired patch has no record — the detail behind a `record_unavailable` skip) and `api_auth_fallback` (the public proxy served free patches only: the authenticated API refused the credentials, `get` / `scan`'s warning text; or, v5.0, a token was set with no `--org` / `SOCKET_ORG_SLUG` / socket-cli `defaultOrg` and the org could not be resolved, so the whole run used the proxy — standalone `vex --json` carries it when it fetched records, and `scan --json` / `get --json` report this case in their top-level `warnings[]`) — and, standalone only, `org_looks_like_path` (`-o`/`--org` given a file-shaped value — `-O` is `--output`). The standalone error envelope carries `warnings[]` too. An embedded `--vex` that fails also folds each omitted patch into the host command's `warnings[]` as `vex_omitted` (`: ()` — standalone `vex` lists them as `skipped` events), and `--silent` lists them as `omitted: ()` lines under the error. A corrupt `.socket/vendor/state.json` is no longer degraded with a warning: every form of vex fails with `vendor_ledger_corrupt` (see the error-code table). A malformed pre-v5 `redirect-state.json` is, as of v5.0, only the `redirect_ledger_corrupt` warning (hosted mode keeps no ledger; the file is an optional migration record source). @@ -685,6 +685,8 @@ Every VEX statement's impact string records which patch-application mode persist **Unverified statements (`--no-verify`).** `--no-verify` / `--vex-no-verify` (and an ambient `SOCKET_VEX_NO_VERIFY`) skip every on-disk hash check, so a statement emitted under it rests on the patch records and the wiring gates alone — for an agent-mode patch on nothing but the manifest, even when the installed files are unpatched or absent. Such a run is never silent. Each purl it attests ends its impact-statement part with `; not verified on disk`, appended AFTER the marker, so the three marker strings above stay intact as prefixes (`Patched via Socket patch (vendored); not verified on disk`), and the run raises the `vex_not_verified` warning (stderr in human mode, `warnings[]` / `vex.warnings` under `--json`) naming how many statements carry the suffix. The purls an in-run `scan --mode hosted --vex` confirmed are attested from that run's own evidence in either mode and never carry it. A default (verifying) run's document is unchanged: it never contains the suffix. +**The installed tree (`--no-bazel`).** `--no-bazel` / `--vex-no-bazel` (and an ambient `SOCKET_VEX_NO_BAZEL`, read like `SOCKET_VEX_NO_VERIFY`: `1` or `true` sets it, an empty value does not) say that the document describes what the package manager installed, for a repository that ships that tree while a Bazel hub reads the same lock for something else, such as its tests. The Bazel workspace is then not read: no package is attested as `affected` for `vex_bazel_not_in_build`, and the document, the events, the warnings, the exit code and every printed line are those of the same checkout without its Bazel files. Without the option nothing changes, and outside a Bazel workspace the option changes nothing and is accepted silently. `--vex-no-bazel` is inert unless `--vex` is set. + **Identifier overrides.** `--product` / `--vex-product` and `--doc-id` / `--vex-doc-id` are emitted with surrounding whitespace trimmed (a blank value means unset). **No product to detect.** The product is read from the git `origin` remote, then from the name and version in `package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `composer.json`, `pom.xml`, the root's single `.csproj` or its single `.gemspec`. An application with none of these (a Bundler or pip project in a directory that has no git remote) has no product, and the run stops with `product_undetected` (`vex`: exit 2; embedded `--vex`: the host command's exit 1). No product is assumed: a directory name is not an identity (one checkout is `app` in a container and `workspace` in CI, and unrelated projects share those names), so a document issued under it could be read as a statement about another project. The message says what detection read, names any of those files that exists without a usable name and version, and ends with the run's own flag and a value built from the directory name, ready to paste: `… Pass a name that identifies this project, for example: --product pkg:generic/my-app` (`--vex-product …` on an embedded run). A run started in the project directory says `the current directory` instead of `.`. @@ -2106,7 +2108,7 @@ Empty string means unset at every layer: exported-but-empty flag-bound vars are | `SOCKET_PRESERVE_STATE` | `rollback --preserve-state` / `remove --preserve-state` | `false` | (v5.0) Shared by `rollback`/`remove` (boolish, empty-tolerant parse like the other bool flags): restore the system but keep the local patch state — manifest entries, vendored artifacts + ledger entries — and skip all GC. On `remove`, combining it with `--skip-rollback` is a usage error (exit 2) **whether either side is flag- or env-sourced** (`SOCKET_PRESERVE_STATE=true remove --skip-rollback` exits 2 too). | | `SOCKET_DOWNLOAD_ONLY` | `repair --download-only` | `false` | Local to `repair`. | | `SOCKET_VENDOR_REVERT` | `vendor --revert` | `false` | Local to `vendor`. | -| `SOCKET_VEX` | `apply --vex` / `scan --vex` / `vendor --vex` | (none) | Embedded OpenVEX output path. The `SOCKET_VEX_*` knobs (`_PRODUCT`, `_NO_VERIFY`, `_DOC_ID`, `_COMPACT`) are shared with the standalone `vex` command; on the host commands they bind to `--vex-product` etc. | +| `SOCKET_VEX` | `apply --vex` / `scan --vex` / `vendor --vex` | (none) | Embedded OpenVEX output path. The `SOCKET_VEX_*` knobs (`_PRODUCT`, `_NO_VERIFY`, `_NO_BAZEL`, `_DOC_ID`, `_COMPACT`) are shared with the standalone `vex` command; on the host commands they bind to `--vex-product` etc. | | `SOCKET_VEX_OUTPUT` | `vex --output` / `-O` | (none) | Local to the standalone `vex`: document output path (required with `--json`). | ### Config-layer toggles (env-only) @@ -2944,7 +2946,7 @@ A `list` or bare `rollback` that covers patched project directories below `--cwd | Code | Meaning | |---|---| -| `0` | A non-empty OpenVEX document was produced | +| `0` | A non-empty OpenVEX document was produced (a statement may say `affected`: see `vex_bazel_not_in_build`) | | `1` | Nothing attested: `no_applicable_patches` (every candidate was omitted — by verification, a wiring gate, or a missing record; the omissions ride `skipped` events) or `no_patches` (an empty manifest file and nothing wired anywhere) | | `2` | Hard error: `manifest_not_found` (no manifest AND no vendor-ledger record / lockfile reference anywhere), `manifest_invalid` / `manifest_unreadable`, `vendor_ledger_corrupt` (v5.0: `redirect_ledger_corrupt` is a warning), `json_requires_output`, `product_undetected`, `serialize_failed`, `write_failed` | @@ -2958,12 +2960,12 @@ The VEX document is JSON-LD, which collides with the standard `--json` envelope |---|---|---|---| | unset | unset | stdout | stderr (one-line summary) | | set to `` | unset | `` | stdout (one-line summary) | -| set to `` | set | `` | stdout (full envelope, with one `verified` event per emitted subcomponent) | +| set to `` | set | `` | stdout (full envelope, with one `verified` event per subcomponent of a `not_affected` statement and one `skipped` event, `errorCode: vex_bazel_not_in_build`, per subcomponent of an `affected` one; `details.status` is the `status` of the statement) | | unset | set | (error: `json_requires_output`, exit `2`) | stdout (envelope-only) | -`--output -` means stdout (the first row). With `--dry-run`, a document bound for `--output` is built and verified but not written, a previous document at that path is left alone, the one-line summary reads `[dry-run] Would write OpenVEX document with N statements to `, and the envelope's `dryRun` is `true`. A written file ends with a newline, like the stdout form. +`--output -` means stdout (the first row). With `--dry-run`, a document bound for `--output` is built and verified but not written, a previous document at that path is left alone, the one-line summary reads `[dry-run] Would write OpenVEX document with N statements to `, and the envelope's `dryRun` is `true`. In every one-line summary the count reads `N statements (K affected)` when K of the statements say `affected`. A written file ends with a newline, like the stdout form. -When verification is enabled (the default) and a patch is omitted, the failed PURLs are surfaced on stderr in plain mode or as `skipped` events on the envelope in JSON mode (one per patch, sorted by PURL; `errorCode` is the tag). Plain mode prints one line per reason, largest first: `Warning: omitting 82 packages from VEX: the patched files still hold the original content (not_applied): @sigstore/core@1.1.0, @sigstore/core@2.0.0, @simple-git/argv-parser@1.1.1 and 79 more (--verbose lists them all)`; a reason with a single patch keeps the per-patch line `Warning: omitting from VEX: ()`, and `--verbose` prints that line for every patch. The run's advisories print before them, folded the same way: the first of each kind in full, then ` ... and 9 more like these: glob@10.4.5, glob@11.0.3, minimatch@3.1.2 and 6 more (--verbose lists them all)` (the packages are named where each advisory opens with one). When nothing could be attested, the `Error: No applied patches with vulnerability metadata to attest.` line is followed by the remedy for the patches that only need installing (`The patched packages are not installed yet: ... Reinstall from the lockfile (hosted or vendored patches) or run \`socket-patch apply\` (agent-mode patches), then run \`socket-patch vex\` again.`, or `N of the patched packages ...` when other reasons are among them). `--json` is unchanged: every advisory is its own `warnings[]` entry and every omission its own `skipped` event. Status becomes `partialFailure` when at least one patch was omitted but at least one was emitted. +When verification is enabled (the default) and a patch is omitted, the failed PURLs are surfaced on stderr in plain mode or as `skipped` events on the envelope in JSON mode (one per patch, sorted by PURL; `errorCode` is the tag). Plain mode prints one line per reason, largest first: `Warning: omitting 82 packages from VEX: the patched files still hold the original content (not_applied): @sigstore/core@1.1.0, @sigstore/core@2.0.0, @simple-git/argv-parser@1.1.1 and 79 more (--verbose lists them all)`; a reason with a single patch keeps the per-patch line `Warning: omitting from VEX: ()`, and `--verbose` prints that line for every patch. The run's advisories print before them, folded the same way: the first of each kind in full, then ` ... and 9 more like these: glob@10.4.5, glob@11.0.3, minimatch@3.1.2 and 6 more (--verbose lists them all)` (the packages are named where each advisory opens with one). When nothing could be attested, the `Error: No applied patches with vulnerability metadata to attest.` line is followed by the remedy for the patches that only need installing (`The patched packages are not installed yet: ... Reinstall from the lockfile (hosted or vendored patches) or run \`socket-patch apply\` (agent-mode patches), then run \`socket-patch vex\` again.`, or `N of the patched packages ...` when other reasons are among them). `--json` is unchanged: every advisory is its own `warnings[]` entry and every omission its own `skipped` event. Status becomes `partialFailure` when at least one patch was omitted but at least one was emitted. It is `partialFailure` too, with exit `0`, when a statement of the document says `affected`, also when every one does: `summary.verified` counts the packages attested as patched and no other. ## Semver policy @@ -3931,6 +3933,7 @@ match it, withholds the statement: | `gradle_unpatched_copy` | `failed[].reason` | The purl the warning above (or `vex_gradle_derived_cache_check_failed`) withheld. | | `vex_gradle_derived_cache_check_failed` | run warning | The derived-cache check of an attested Gradle copy did not finish (it crashed), so a copy derived from the unpatched jar cannot be ruled out; no statement for that purl. | | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | +| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (no build has shown what rules_ruby does with one), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 21f858e85..cdda3eb5a 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -766,6 +766,7 @@ pub const LOCAL_ARG_ENV_VARS: &[&str] = &[ "SOCKET_VEX_OUTPUT", "SOCKET_VEX_PRODUCT", "SOCKET_VEX_NO_VERIFY", + "SOCKET_VEX_NO_BAZEL", "SOCKET_VEX_DOC_ID", "SOCKET_VEX_COMPACT", ]; @@ -1569,10 +1570,12 @@ mod tests { ("SOCKET_DOWNLOAD_ONLY", &["socket-patch", "repair"]), ("SOCKET_VENDOR_REVERT", &["socket-patch", "vendor"]), ("SOCKET_VEX_NO_VERIFY", &["socket-patch", "vex"]), + ("SOCKET_VEX_NO_BAZEL", &["socket-patch", "vex"]), ("SOCKET_VEX_COMPACT", &["socket-patch", "vex"]), // The embedded `--vex-*` twins share the same env vars and must // not abort host commands (e.g. apply from a CI step). ("SOCKET_VEX_NO_VERIFY", &["socket-patch", "apply"]), + ("SOCKET_VEX_NO_BAZEL", &["socket-patch", "vendor"]), ("SOCKET_VEX_COMPACT", &["socket-patch", "scan"]), ]; diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 79afc8a2a..58498eaa2 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1329,6 +1329,7 @@ pub async fn run(args: ApplyArgs) -> i32 { env.vex = Some(VexSummary { path: vex_path().display().to_string(), statements: summary.statements, + affected: summary.affected, format: "openvex-0.2.0".to_string(), warnings: summary.warnings.clone(), }); @@ -1351,7 +1352,11 @@ pub async fn run(args: ApplyArgs) -> i32 { match &vex_result { Some(ManifestlessVex::Written(summary)) if !args.common.silent => println!( "{}", - crate::commands::vex::format_vex_written(summary.statements, vex_path()) + crate::commands::vex::format_vex_written( + summary.statements, + summary.affected, + vex_path(), + ) ), // Errors print even under --silent (same as the main path). Some(ManifestlessVex::Failed(e)) => e.print_embedded(&args.common), @@ -2081,6 +2086,7 @@ pub(crate) async fn run_locked( .display() .to_string(), statements: summary.statements, + affected: summary.affected, format: "openvex-0.2.0".to_string(), // note_warning suppressed these on stderr under // --json; the envelope copy is their only @@ -2107,6 +2113,7 @@ pub(crate) async fn run_locked( "{}", crate::commands::vex::format_vex_written( summary.statements, + summary.affected, args.vex .vex .as_ref() diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 422d0af6e..59b344e08 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2088,6 +2088,7 @@ async fn run_redirect_selected_untracked( // `commands::vex_sources`). Requested-but-failed VEX (including "nothing // to attest") flips the exit code. let mut vex_statements: Option = None; + let mut vex_affected = 0; // VEX run-level advisories: `note_warning` keeps them off stderr under // --json, so the envelope's `vex.warnings` is their only channel there. let mut vex_warnings: Vec = Vec::new(); @@ -2163,6 +2164,7 @@ async fn run_redirect_selected_untracked( match generate_vex_from_manifest_path(common, ¶ms, &manifest_path).await { Ok(summary) => { vex_statements = Some(summary.statements); + vex_affected = summary.affected; vex_warnings = summary.warnings; } Err(e) => { @@ -2285,6 +2287,7 @@ async fn run_redirect_selected_untracked( .display() .to_string(), statements, + affected: vex_affected, format: "openvex-0.2.0".to_string(), warnings, }); @@ -2431,11 +2434,12 @@ async fn run_redirect_selected_untracked( } if let Some(statements) = vex_statements { eprintln!( - "Wrote OpenVEX document with {} to {} (hosted patches are attested \ + "Wrote OpenVEX document with {}{} to {} (hosted patches are attested \ from their patch records, not hash-verified — their bytes are fetched at install \ time; run `socket-patch vex` after installing to verify against the \ installed tree).", crate::ui::plural(statements, "statement", "statements"), + crate::commands::vex::affected_note(vex_affected), vex.vex .as_ref() .expect("vex_statements is Some only when --vex was given") diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 746e3f31f..0fd37f39b 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -458,6 +458,7 @@ async fn embed_vex_into_json( .display() .to_string(), statements: summary.statements, + affected: summary.affected, format: "openvex-0.2.0".to_string(), warnings: summary.warnings, }); @@ -516,6 +517,7 @@ async fn embed_vex_human( "{}", crate::commands::vex::format_vex_written( summary.statements, + summary.affected, vex_args .vex .as_ref() diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index cb80e2857..72017356b 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1137,6 +1137,7 @@ pub async fn run(args: VendorArgs) -> i32 { .display() .to_string(), statements: summary.statements, + affected: summary.affected, format: "openvex-0.2.0".to_string(), warnings: summary.warnings.clone(), }); @@ -1157,6 +1158,7 @@ pub async fn run(args: VendorArgs) -> i32 { "{}", crate::commands::vex::format_vex_written( summary.statements, + summary.affected, args.vex .vex .as_ref() @@ -1274,6 +1276,7 @@ pub async fn run(args: VendorArgs) -> i32 { env.vex = Some(VexSummary { path: vex_path.display().to_string(), statements: summary.statements, + affected: summary.affected, format: "openvex-0.2.0".to_string(), // note_warning suppressed these on stderr under // --json; the envelope copy is their only @@ -2498,6 +2501,7 @@ async fn run_eject( env.vex = Some(VexSummary { path: vex_path.display().to_string(), statements: summary.statements, + affected: summary.affected, format: "openvex-0.2.0".to_string(), warnings: summary.warnings, }); diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 885ce0f7f..2505e0cfd 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -21,11 +21,12 @@ use std::path::{Path, PathBuf}; use clap::Args; use socket_patch_core::api::client::ApiClient; +use socket_patch_core::bazel::built::{unbuilt, Patched, Unbuilt}; use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::telemetry::{track_vex_failed, track_vex_generated, TelemetryAuth}; use socket_patch_core::vex::verify::{npm_manifest_after_hash, DEPENDENCY_NOT_INSTALLED}; use socket_patch_core::vex::{ - build_document_with, detect_product, Attested, BuildOptions, Document, FailedPatch, + build_document_with, detect_product, Attested, BuildOptions, Document, FailedPatch, Status, VendorContext, VerifyOutcome, NOT_VERIFIED_SUFFIX, }; @@ -90,6 +91,18 @@ pub struct VexArgs { )] pub no_verify: bool, + /// Describe what the package manager installed, and do not read a Bazel + /// workspace: no package is attested as affected because a Bazel hub + /// builds it from a lock without the patch. Use this when what you ship + /// is the installed tree, not what Bazel builds. + #[arg( + long = "no-bazel", + env = "SOCKET_VEX_NO_BAZEL", + default_value_t = false, + value_parser = parse_bool_flag, + )] + pub no_bazel: bool, + /// Override the document `@id`. Default is `urn:uuid:`, /// regenerated on every invocation. Pin this to get a reproducible /// doc identifier across runs. @@ -143,6 +156,18 @@ pub struct VexEmbedArgs { )] pub vex_no_verify: bool, + /// Have the VEX document describe what the package manager installed, + /// without reading a Bazel workspace: no package is attested as affected + /// because a Bazel hub builds it from a lock without the patch. See + /// `socket-patch vex --no-bazel`. + #[arg( + long = "vex-no-bazel", + env = "SOCKET_VEX_NO_BAZEL", + default_value_t = false, + value_parser = parse_bool_flag, + )] + pub vex_no_bazel: bool, + /// Pin the VEX document `@id`. See `socket-patch vex --doc-id`. #[arg(long = "vex-doc-id", env = "SOCKET_VEX_DOC_ID")] pub vex_doc_id: Option, @@ -171,6 +196,7 @@ impl VexEmbedArgs { output: self.vex.clone(), product: self.vex_product.clone(), no_verify: self.vex_no_verify, + no_bazel: self.vex_no_bazel, doc_id: self.vex_doc_id.clone(), compact: self.vex_compact, assume_applied: Vec::new(), @@ -196,6 +222,9 @@ pub(crate) struct VexBuildParams { pub output: Option, pub product: Option, pub no_verify: bool, + /// The document is about what the package manager installed: the Bazel + /// workspace of the project is not read ([`unbuilt_by_bazel`]). + pub no_bazel: bool, pub doc_id: Option, pub compact: bool, /// In-run `scan --mode hosted --vex` only: the PURLs whose lockfile rewrite @@ -281,6 +310,8 @@ impl VexBuildParams { /// Successful result of [`generate_vex`]. pub(crate) struct VexWriteSummary { pub statements: usize, + /// How many of them say `affected` ([`unbuilt_by_bazel`]). + pub affected: usize, pub failed: Vec, /// The built document — returned so the standalone `vex` command can /// emit its per-subcomponent envelope without rebuilding. @@ -387,6 +418,7 @@ pub async fn run(args: VexArgs) -> i32 { output: output.clone(), product: args.product.clone(), no_verify: args.no_verify, + no_bazel: args.no_bazel, doc_id: args.doc_id.clone(), compact: args.compact, assume_applied: Vec::new(), @@ -416,14 +448,15 @@ pub async fn run(args: VexArgs) -> i32 { if args.common.json { emit_envelope_success(&summary, params.dry_run); } else if !args.common.silent { + let count = summary.statements; match &output { Some(path) if summary.wrote_file => { - println!("{}", format_vex_written(summary.statements, path)); + println!("{}", format_vex_written(count, summary.affected, path)); } Some(path) => { - println!("{}", format_vex_dry_run(summary.statements, path)); + println!("{}", format_vex_dry_run(count, summary.affected, path)); } - None => eprintln!("{}", format_vex_emitted(summary.statements)), + None => eprintln!("{}", format_vex_emitted(count, summary.affected)), } } 0 @@ -505,12 +538,23 @@ fn format_manifest_not_found_hint(message: &str, manifest_path: &str) -> String } } +/// ` (1 affected)`, after the count of statements in each line below, for +/// a document in which that many of them say `affected`. Nothing for a +/// document of `not_affected` statements alone. +pub(crate) fn affected_note(affected: usize) -> String { + match affected { + 0 => String::new(), + affected => format!(" ({affected} affected)"), + } +} + /// `Wrote OpenVEX document with 1 statement to out.json` — the one-line /// summary after writing a document to a file. -pub(crate) fn format_vex_written(statements: usize, path: &Path) -> String { +pub(crate) fn format_vex_written(statements: usize, affected: usize, path: &Path) -> String { format!( - "Wrote OpenVEX document with {} to {}", + "Wrote OpenVEX document with {}{} to {}", plural(statements, "statement", "statements"), + affected_note(affected), path.display() ) } @@ -533,19 +577,21 @@ pub(crate) fn format_vex_nothing_to_attest() -> String { } /// The `--dry-run` twin of [`format_vex_written`]: nothing was written. -pub(crate) fn format_vex_dry_run(statements: usize, path: &Path) -> String { +pub(crate) fn format_vex_dry_run(statements: usize, affected: usize, path: &Path) -> String { format!( - "[dry-run] Would write OpenVEX document with {} to {}", + "[dry-run] Would write OpenVEX document with {}{} to {}", plural(statements, "statement", "statements"), + affected_note(affected), path.display() ) } /// The stderr summary after the document went to stdout. -pub(crate) fn format_vex_emitted(statements: usize) -> String { +pub(crate) fn format_vex_emitted(statements: usize, affected: usize) -> String { format!( - "Emitted {}", - plural(statements, "VEX statement", "VEX statements") + "Emitted {}{}", + plural(statements, "VEX statement", "VEX statements"), + affected_note(affected) ) } @@ -1293,6 +1339,13 @@ async fn generate_vex( outcome.applied = kept; } + // What the checks above verified is what the project's own package + // manager uses. Where a Bazel hub builds the package from a lock, that + // is another copy, and the last word: every form of the command comes + // through here, `--no-verify` and the in-run ones included. A run told + // that the installed tree is what ships (`--no-bazel`) skips the step. + let affected = unbuilt_by_bazel(&mut outcome, &plan, common, params, warnings).await; + // The plan's gate omissions (record_unavailable / record_mismatch / // vendor_unwired / redirect_unwired / wiring_conflict) join the omission // channel so they surface as per-purl `skipped` events like any @@ -1408,6 +1461,7 @@ async fn generate_vex( // A package no installed build of which holds any file of // its patch: not affected because the code is not there. code_not_present: &outcome.code_not_present, + affected: &affected, }, &opts, ) { @@ -1507,8 +1561,10 @@ async fn generate_vex( ) .await; + let says_affected = |st: &&socket_patch_core::vex::Statement| st.status == Status::Affected; Ok(VexWriteSummary { statements: doc.statements.len(), + affected: doc.statements.iter().filter(says_affected).count(), failed: outcome.failed, doc, warnings: Vec::new(), @@ -1836,6 +1892,124 @@ async fn withhold_stale_go_tools( })); } +/// Run warning: the files of the project's Bazel workspace show that Bazel +/// builds the package from a file that does not hold the patch, so the +/// document says `affected` of it. +const BAZEL_NOT_IN_BUILD: &str = "vex_bazel_not_in_build"; + +/// The `reason` of the `skipped` event `vex --json` reports for a package +/// of such a statement. +const AFFECTED_REASON: &str = "attested as affected, not as patched: Bazel does not build the \ + patched copy of this package; the run warning names what it builds from"; + +/// The closing sentence of the action statement, and so of the run warning, +/// of a package that is affected because its patch is in the installed copy +/// alone. +const INSTALLED_TREE_SHIPS: &str = "If what you ship is the installed tree and not what Bazel \ + builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor)."; + +/// In a Bazel workspace, a hub of aspect_rules_js, rules_python or +/// rules_ruby builds a package from the lock a workspace file names, never +/// from the copy a package manager installed, and rules_python builds +/// nothing from a line that points at a copy under `.socket/vendor` +/// ([`socket_patch_core::bazel::built`]). A patch that is only in such a +/// copy is in no build of Bazel's, so its package is not attested as +/// patched: it leaves `outcome.applied` and is returned with what to do +/// about it, for statements that say `affected` +/// ([`build_document_with_affected`]). A run warning tells a person the +/// same. Nothing is omitted for this, so a document is always written. +/// The package also leaves `outcome.vendored_out_of_sync`: that warning +/// says the attestation is based on the committed copy and to install +/// again, where the statement now says to revert the copy. +/// +/// A hosted pin is left alone, and so is everything outside a Bazel +/// workspace, in a `--global` run, or behind workspace files that cannot +/// be read with certainty: the statement stays the one of a project +/// without Bazel. So is a patch whose record names no advisory: no run +/// writes a statement for it, and it is left out for that reason alone. +/// +/// With `--no-bazel` / `--vex-no-bazel` (`params.no_bazel`) the user has +/// said that the document is about the installed tree, which is what the +/// repository ships, and not about what Bazel builds: the step returns +/// before it opens a file, and the run is the one of the same checkout +/// without its Bazel files. +/// +/// One project is asked about, `common.cwd`: it is where the installed +/// copies were looked for, and it is the manifest's project, whose files +/// the pins of a vendored copy are from. `vex` runs in that project, and +/// every host command refuses a `--manifest-path` in another one. +async fn unbuilt_by_bazel( + outcome: &mut VerifyOutcome, + plan: &Plan, + common: &GlobalArgs, + params: &VexBuildParams, + warnings: &mut Vec, +) -> Vec<(String, String)> { + if params.no_bazel || common.is_global() { + return Vec::new(); + } + let patched = |purl: &String| { + let record = plan.view.patches.get(purl)?; + let judged = !plan.hosted.contains_key(purl) && !record.vulnerabilities.is_empty(); + judged.then(|| Patched { + purl: purl.clone(), + uuid: record.uuid.clone(), + pins: plan.vendor_pins.get(purl).cloned(), + }) + }; + let mut packages: Vec = outcome.applied.iter().filter_map(patched).collect(); + // The applied set is in the order of a hash map: warn in one order. + packages.sort_by(|a, b| a.purl.cmp(&b.purl)); + let calls = unbuilt(&common.cwd, packages.clone()).await; + let mut affected = Vec::new(); + for (package, call) in packages.into_iter().zip(calls) { + let Some(call) = call else { continue }; + let action = bazel_build_action(&package, &call); + let detail = format!("{}: the VEX document says affected. {action}", package.purl); + note_warning(warnings, common, BAZEL_NOT_IN_BUILD, detail); + outcome.applied.retain(|purl| *purl != package.purl); + let drifted = &mut outcome.vendored_out_of_sync; + drifted.retain(|purl| *purl != package.purl); + affected.push((package.purl, action)); + } + affected +} + +/// The action statement for `package`, whose patch Bazel does not build: +/// what `call` builds the package from, and what to run so that the build +/// holds the patch. Hosted mode pins a patch in the lock of the project it +/// runs in, so the remedy names the directory of the lock. +/// +/// For an installed copy it ends with the way out of a repository that +/// ships the installed tree and keeps the hub for something else: the +/// option, in both spellings, since the statement is the same whichever +/// command wrote the document. Not for a committed PyPI copy: there the +/// build is broken or takes the registry's package, and the installed tree +/// is not the patched one either. +fn bazel_build_action(package: &Patched, call: &Unbuilt) -> String { + let Patched { uuid, pins, .. } = package; + let Unbuilt { + call: tag, + file, + line, + lock, + } = call; + match pins { + None => format!( + "Bazel builds this package from {lock} (`{tag}`, {file}:{line}), which does not \ + name Socket patch {uuid}: the patch is only in the installed copy. Run \ + `socket-patch scan --mode hosted` in the directory of that lock to pin the patch \ + there. {INSTALLED_TREE_SHIPS}" + ), + Some(_) => format!( + "Bazel builds no package from the line of {lock} that points at the copy of Socket \ + patch {uuid} under .socket/vendor (`{tag}`, {file}:{line}): the build fails, or \ + takes the registry's package. Run `socket-patch vendor --revert`, then \ + `socket-patch scan --mode hosted`." + ), + } +} + /// The `vendored_tree_out_of_sync` detail for `purl`. `copies` are the /// installed copies that drifted, `notes` the manager-specific remedies /// (Hatch, PDM) appended to the generic one. @@ -2685,15 +2859,19 @@ fn emit_envelope_success(summary: &VexWriteSummary, dry_run: bool) { for st in &summary.doc.statements { for prod in &st.products { for sub in &prod.subcomponents { - env.record( - PatchEvent::new(PatchAction::Verified, sub.id.clone()).with_details( - serde_json::json!({ - "vulnerability": st.vulnerability.name, - "aliases": st.vulnerability.aliases, - "status": "not_affected", - }), - ), - ); + // A package the document says is affected is not reported + // as verified, nor counted as such: it is skipped, like a + // patch the document leaves out, under its own code. + let event = match st.status { + Status::Affected => PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason(BAZEL_NOT_IN_BUILD, AFFECTED_REASON), + _ => PatchEvent::new(PatchAction::Verified, sub.id.clone()), + }; + env.record(event.with_details(serde_json::json!({ + "vulnerability": st.vulnerability.name, + "aliases": st.vulnerability.aliases, + "status": st.status, + }))); } } } @@ -2703,7 +2881,7 @@ fn emit_envelope_success(summary: &VexWriteSummary, dry_run: bool) { .with_reason(f.reason.clone(), omission_reason_message(&f.reason)), ); } - if !summary.failed.is_empty() { + if !summary.failed.is_empty() || summary.affected > 0 { env.mark_partial_failure(); } env.warnings = summary.warnings.clone(); @@ -2827,7 +3005,7 @@ mod tests { fn vex_summary_lines_pluralize() { let p = Path::new("out.json"); assert_eq!( - format_vex_written(1, p), + format_vex_written(1, 0, p), "Wrote OpenVEX document with 1 statement to out.json" ); assert_eq!( @@ -2835,23 +3013,46 @@ mod tests { "Skipping VEX generation (--dry-run: nothing was applied)." ); assert_eq!( - format_vex_written(0, p), + format_vex_written(0, 0, p), "Wrote OpenVEX document with 0 statements to out.json" ); assert_eq!( - format_vex_written(3, Path::new("dir/é.json")), + format_vex_written(3, 0, Path::new("dir/é.json")), "Wrote OpenVEX document with 3 statements to dir/é.json" ); assert_eq!( - format_vex_dry_run(1, p), + format_vex_dry_run(1, 0, p), "[dry-run] Would write OpenVEX document with 1 statement to out.json" ); assert_eq!( - format_vex_dry_run(2, p), + format_vex_dry_run(2, 0, p), "[dry-run] Would write OpenVEX document with 2 statements to out.json" ); - assert_eq!(format_vex_emitted(1), "Emitted 1 VEX statement"); - assert_eq!(format_vex_emitted(12), "Emitted 12 VEX statements"); + assert_eq!(format_vex_emitted(1, 0), "Emitted 1 VEX statement"); + assert_eq!(format_vex_emitted(12, 0), "Emitted 12 VEX statements"); + } + + /// Each line says how many of the statements say `affected`, when any + /// does. + #[test] + fn vex_summary_lines_count_the_affected_statements() { + let p = Path::new("out.json"); + assert_eq!( + format_vex_written(2, 1, p), + "Wrote OpenVEX document with 2 statements (1 affected) to out.json" + ); + assert_eq!( + format_vex_written(1, 1, p), + "Wrote OpenVEX document with 1 statement (1 affected) to out.json" + ); + assert_eq!( + format_vex_dry_run(3, 2, p), + "[dry-run] Would write OpenVEX document with 3 statements (2 affected) to out.json" + ); + assert_eq!( + format_vex_emitted(2, 2), + "Emitted 2 VEX statements (2 affected)" + ); } fn failed(purl: &str, reason: &str) -> FailedPatch { @@ -3144,7 +3345,10 @@ mod tests { Vex(VexArgs), } + // Serial, like every test that parses with the environment: the table + // of env-bound flags in `args` sets `SOCKET_VEX_*` for its own parses. #[test] + #[serial_test::serial] fn parses_with_defaults() { let w = Wrap::parse_from(["test", "vex"]); match w.cmd { @@ -3152,6 +3356,7 @@ mod tests { assert!(args.output.is_none()); assert!(args.product.is_none()); assert!(!args.no_verify); + assert!(!args.no_bazel); assert!(args.doc_id.is_none()); assert!(!args.compact); } @@ -3159,6 +3364,7 @@ mod tests { } #[test] + #[serial_test::serial] fn parses_all_flags() { let w = Wrap::parse_from([ "test", @@ -3168,6 +3374,7 @@ mod tests { "--product", "pkg:npm/app@1.0.0", "--no-verify", + "--no-bazel", "--doc-id", "urn:uuid:fixed", "--compact", @@ -3177,6 +3384,7 @@ mod tests { assert_eq!(args.output.unwrap().to_str(), Some("out.vex.json")); assert_eq!(args.product.as_deref(), Some("pkg:npm/app@1.0.0")); assert!(args.no_verify); + assert!(args.no_bazel); assert_eq!(args.doc_id.as_deref(), Some("urn:uuid:fixed")); assert!(args.compact); } @@ -3322,6 +3530,7 @@ mod npm_prior_tests { output: Some(out.to_path_buf()), product: Some("pkg:npm/app@1.0.0".into()), no_verify: false, + no_bazel: false, doc_id: Some("urn:uuid:00000000-0000-4000-8000-000000000000".into()), compact: false, assume_applied: Vec::new(), @@ -3458,6 +3667,7 @@ mod mirror_refusal_tests { let plan = Plan { view, vendor_entries: HashMap::from([(purls[3].to_string(), vendor_entry)]), + vendor_pins: HashMap::new(), redirected: vec![purls[0].to_string(), purls[2].to_string()], lockfile_basis: HashSet::from([purls[0].to_string(), purls[2].to_string()]), hosted, @@ -3579,6 +3789,7 @@ mod mirror_refusal_tests { let plan = Plan { view, vendor_entries: HashMap::new(), + vendor_pins: HashMap::new(), redirected: vec![gem.to_string(), npm.to_string()], lockfile_basis: HashSet::from([gem.to_string(), npm.to_string()]), hosted, @@ -3754,6 +3965,7 @@ mod unjudged_tests { let plan = Plan { view, vendor_entries: HashMap::new(), + vendor_pins: HashMap::new(), redirected: purls.map(str::to_string).to_vec(), lockfile_basis: purls .map(str::to_string) @@ -3797,3 +4009,150 @@ mod unjudged_tests { } } } + +#[cfg(test)] +mod bazel_tests { + use super::*; + use crate::commands::vex_sources::HostedWiring; + use socket_patch_core::manifest::schema::PatchRecord; + use std::collections::BTreeMap; + + /// The step that finds what Bazel does not build, on a workspace on + /// disk whose hubs read the project's pnpm lock and requirements file. + /// A project run takes the npm patch of the installed copy and the + /// PyPI patch of the committed copy out of the applied set and gives + /// each back with its action statement, which names the call and what + /// to run; a warning says the same after the package, in the order of + /// the packages whatever the order of the applied set. Nothing is + /// omitted. The PyPI package also leaves the list of those whose + /// installed tree differs from the committed copy, which the crate + /// stays on: that warning is about an attestation of the copy. The + /// step leaves the hosted pin and the crate alone, and so a + /// patch of the installed copy whose record names no advisory, which + /// no run attests. A `--global` run, whose packages are not the + /// project's, changes nothing. Nor does a run with `--vex-no-bazel`, + /// whose document is about the installed tree: the step returns before + /// it asks about a package, and every set it was given is as it was. + #[tokio::test] + async fn the_bazel_step_finds_what_no_hub_builds_in_a_project_run_only() { + let tmp = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + let module = "module(name = \"shop\")\n\ + bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + bazel_dep(name = \"rules_python\", version = \"2.5.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock(name = \"npm\", pnpm_lock = \"//:pnpm-lock.yaml\")\n\ + pip = use_extension(\"@rules_python//python/extensions:pip.bzl\", \"pip\")\n\ + pip.parse(hub_name = \"pip\", requirements_lock = \"//:requirements.txt\")\n"; + let lock = "lockfileVersion: '9.0'\n\npackages:\n\n is-odd@3.0.1:\n \ + resolution: {integrity: sha512-AAAA}\n\n left-pad@1.3.0:\n \ + resolution: {integrity: sha512-BBBB}\n\n is-even@1.0.0:\n \ + resolution: {integrity: sha512-CCCC}\n"; + let files = [ + (".git/HEAD", "ref: refs/heads/main\n"), + ("MODULE.bazel", module), + ("pnpm-lock.yaml", lock), + ( + "requirements.txt", + "./.socket/vendor/pypi/u/idna-3.6-py3-none-any.whl\n", + ), + ]; + for (path, text) in files { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + let purls = [ + "pkg:npm/left-pad@1.3.0", + "pkg:pypi/idna@3.6", + "pkg:npm/is-odd@3.0.1", + "pkg:cargo/serde@1.0.0", + "pkg:npm/is-even@1.0.0", + ]; + let advisory = serde_json::json!({ "GHSA-test-aaaa-bbbb": { + "cves": [], "summary": "s", "severity": "high", "description": "d", + }}); + let mut view = PatchManifest::new(); + for (index, purl) in purls.iter().enumerate() { + let record: PatchRecord = serde_json::from_value(serde_json::json!({ + "uuid": format!("00000000-0000-4000-8000-00000000000{index}"), + "exportedAt": "2026-01-01T00:00:00Z", + "files": {"index.js": {"beforeHash": "a".repeat(64), "afterHash": "b".repeat(64)}}, + "vulnerabilities": if index < 4 { advisory.clone() } else { serde_json::json!({}) }, + "description": "test", "license": "MIT", "tier": "free" + })) + .unwrap(); + view.patches.insert(purl.to_string(), record); + } + let wiring = HostedWiring { + uuid: view.patches[purls[2]].uuid.clone(), + refs: Vec::new(), + }; + let plan = Plan { + view, + vendor_entries: HashMap::new(), + vendor_pins: HashMap::from([(purls[1].to_string(), vec!["requirements.txt".into()])]), + redirected: vec![purls[2].to_string()], + lockfile_basis: HashSet::new(), + hosted: BTreeMap::from([(purls[2].to_string(), wiring)]), + gated: Vec::new(), + notes: Vec::new(), + }; + for (global, no_bazel) in [(false, false), (true, false), (false, true)] { + let common = GlobalArgs { + cwd: root.clone(), + json: true, + no_telemetry: true, + global, + ..Default::default() + }; + let embedded = VexEmbedArgs { + vex_no_bazel: no_bazel, + ..Default::default() + }; + let params = embedded.to_build_params(None); + let drifted = [purls[1], purls[3]].map(str::to_string); + let applied: Vec = purls.iter().rev().map(|purl| purl.to_string()).collect(); + let mut outcome = VerifyOutcome { + applied: applied.clone(), + vendored_out_of_sync: drifted.to_vec(), + ..Default::default() + }; + let mut warnings = Vec::new(); + let affected = + unbuilt_by_bazel(&mut outcome, &plan, &common, ¶ms, &mut warnings).await; + assert!(outcome.failed.is_empty(), "{:?}", outcome.failed); + let details: Vec<&str> = warnings.iter().map(|w| w.detail.as_str()).collect(); + if global || no_bazel { + let run = format!("--global: {global}, --vex-no-bazel: {no_bazel}"); + assert_eq!(outcome.applied, applied, "{run}"); + assert_eq!(outcome.vendored_out_of_sync, drifted, "{run}"); + assert_eq!((affected, details), (vec![], vec![]), "{run}"); + continue; + } + assert_eq!(outcome.applied, applied[..3]); + assert_eq!(outcome.vendored_out_of_sync, drifted[1..]); + let codes: Vec<&str> = warnings.iter().map(|w| w.code.as_str()).collect(); + assert_eq!(codes, [BAZEL_NOT_IN_BUILD; 2]); + let installed = "Bazel builds this package from pnpm-lock.yaml \ + (`npm.npm_translate_lock`, MODULE.bazel:5), which does not name Socket patch \ + 00000000-0000-4000-8000-000000000000: the patch is only in the installed copy. \ + Run `socket-patch scan --mode hosted` in the directory of that lock to pin the \ + patch there. If what you ship is the installed tree and not what Bazel builds, \ + pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor)."; + let committed = "Bazel builds no package from the line of requirements.txt that \ + points at the copy of Socket patch 00000000-0000-4000-8000-000000000001 under \ + .socket/vendor (`pip.parse`, MODULE.bazel:7): the build fails, or takes the \ + registry's package. Run `socket-patch vendor --revert`, then `socket-patch scan \ + --mode hosted`."; + let expected = [(purls[0], installed), (purls[1], committed)]; + let said: Vec<(&str, &str)> = (affected.iter()) + .map(|(purl, action)| (purl.as_str(), action.as_str())) + .collect(); + assert_eq!(said, expected); + let warned = expected + .map(|(purl, action)| format!("{purl}: the VEX document says affected. {action}")); + assert_eq!(details, warned); + } + } +} diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 2cdf01a1f..50f56bab3 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -166,6 +166,11 @@ pub(crate) struct Plan { /// Vendored-basis entries, keyed by view purl — the verification /// routing for `applied_patches_with_vendor`. pub vendor_entries: HashMap, + /// For each key of `vendor_entries`, the project files that point at + /// its committed copy: those lockfile discovery found the vendored + /// reference in, each from the project with `/` between its parts. + /// Empty for an entry that is live without such a reference. + pub vendor_pins: HashMap>, /// Live hosted-basis view purls (the `(redirected)` marker and the /// property-7 bypass). pub redirected: Vec, @@ -865,6 +870,7 @@ pub(crate) async fn plan( setup: manifest.setup.clone(), }, vendor_entries: HashMap::new(), + vendor_pins: HashMap::new(), redirected: Vec::new(), lockfile_basis: HashSet::new(), hosted: BTreeMap::new(), @@ -892,6 +898,7 @@ pub(crate) async fn plan( // statement and a skip at once. if plan.view.patches.remove(&cand.key).is_some() { plan.vendor_entries.remove(&cand.key); + plan.vendor_pins.remove(&cand.key); plan.redirected.retain(|k| *k != cand.key); plan.lockfile_basis.remove(&cand.key); plan.hosted.remove(&cand.key); @@ -903,6 +910,10 @@ pub(crate) async fn plan( match basis { Basis::Installed => {} Basis::Vendored(entry) => { + let found = cand.discovered.iter(); + let found = found.filter(|r| r.mode == WiringMode::Vendored); + let pins = found.map(|r| r.source_file.to_string_lossy().replace('\\', "/")); + plan.vendor_pins.insert(cand.key.clone(), pins.collect()); plan.vendor_entries.insert(cand.key.clone(), *entry); } Basis::Hosted { lockfile_basis } => { @@ -2407,6 +2418,47 @@ mod tests { ); } + /// The pin files of a vendored package are the files its vendored + /// reference was found in. A second file that pins the same patch on + /// the patch host points at no committed copy, and is none. + #[tokio::test] + async fn the_pins_of_a_vendored_package_are_the_files_that_point_at_its_copy() { + const PURL: &str = "pkg:pypi/idna@3.6"; + let tmp = tempfile::tempdir().unwrap(); + let mut manifest = PatchManifest::new(); + manifest.patches.insert(PURL.into(), record(U1)); + let copy = format!(".socket/vendor/pypi/{U1}/idna-3.6-py3-none-any.whl"); + let vref = vendor_ref(©).unwrap(); + let hosted = PatchedRef::hosted( + PURL.to_string(), + U1.to_string(), + "requirements-dev.txt", + None, + None, + true, + ); + let found = discovery(vec![ + hosted, + PatchedRef::vendored(PURL.into(), &vref, "requirements.txt", None), + ]); + let plan = plan( + &common(tmp.path()), + Sources { + manifest, + vendor: VendorState::new(), + redirect: None, + discovery: found, + hosted_uuids: Vec::new(), + }, + &[], + &RunApiClient::new(), + ) + .await; + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + assert_eq!(plan.vendor_entries[PURL].artifact.path, copy); + assert_eq!(plan.vendor_pins[PURL], ["requirements.txt"]); + } + /// Ledger-only records with no wiring anywhere are gated, except the /// manifest-owned one, which falls back to agent-mode verification; an /// in-run confirmed purl is live by construction. diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index 874a90fea..d8d88b7a7 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -158,6 +158,10 @@ pub struct VexSummary { pub path: String, /// Number of OpenVEX statements in the document. pub statements: usize, + /// How many of them say `affected` (see `vex_bazel_not_in_build`), not + /// `not_affected`. Omitted from JSON when none does. + #[serde(skip_serializing_if = "is_zero")] + pub affected: usize, /// Document format tag, e.g. `"openvex-0.2.0"`. pub format: String, /// Run-level advisories raised during VEX generation (e.g. @@ -170,6 +174,10 @@ pub struct VexSummary { pub warnings: Vec, } +fn is_zero(count: &usize) -> bool { + *count == 0 +} + impl Envelope { /// Build a fresh envelope. `summary` starts at zero — callers are /// expected to push events with `Envelope::record` (or update fields @@ -1095,12 +1103,16 @@ mod tests { env.vex = Some(VexSummary { path: "/tmp/openvex.json".into(), statements: 3, + affected: 0, format: "openvex-0.2.0".into(), warnings: Vec::new(), }); let v = env.to_value(); assert_eq!(v["vex"]["path"], "/tmp/openvex.json"); assert_eq!(v["vex"]["statements"], 3); + assert!(!v["vex"].as_object().unwrap().contains_key("affected")); + env.vex.as_mut().unwrap().affected = 2; + assert_eq!(env.to_value()["vex"]["affected"], 2); assert_eq!(v["vex"]["format"], "openvex-0.2.0"); assert!( !v["vex"].as_object().unwrap().contains_key("warnings"), diff --git a/crates/socket-patch-cli/src/lib.rs b/crates/socket-patch-cli/src/lib.rs index 7466821ad..b31b58d68 100644 --- a/crates/socket-patch-cli/src/lib.rs +++ b/crates/socket-patch-cli/src/lib.rs @@ -313,6 +313,7 @@ fn short_help_hidden_own(sub: &str) -> &'static [&'static str] { "all_releases", "vex_product", "vex_no_verify", + "vex_no_bazel", "vex_doc_id", "vex_compact", "no_socket_yml", @@ -320,9 +321,21 @@ fn short_help_hidden_own(sub: &str) -> &'static [&'static str] { "max_new_patches", ], "get" => &["id", "cve", "ghsa", "package", "save_only", "all_releases"], - "vex" => &["doc_id", "compact"], - "apply" => &["vex_product", "vex_no_verify", "vex_doc_id", "vex_compact"], - "vendor" => &["vex_product", "vex_no_verify", "vex_doc_id", "vex_compact"], + "vex" => &["no_bazel", "doc_id", "compact"], + "apply" => &[ + "vex_product", + "vex_no_verify", + "vex_no_bazel", + "vex_doc_id", + "vex_compact", + ], + "vendor" => &[ + "vex_product", + "vex_no_verify", + "vex_no_bazel", + "vex_doc_id", + "vex_compact", + ], _ => &[], } } diff --git a/crates/socket-patch-cli/tests/cli_parse_apply.rs b/crates/socket-patch-cli/tests/cli_parse_apply.rs index 9cfafbff2..a876a1fb4 100644 --- a/crates/socket-patch-cli/tests/cli_parse_apply.rs +++ b/crates/socket-patch-cli/tests/cli_parse_apply.rs @@ -49,6 +49,7 @@ fn bool_flags(a: &ApplyArgs) -> Vec<(&'static str, bool)> { ("force", a.force), ("check", a.check), ("vex_no_verify", a.vex.vex_no_verify), + ("vex_no_bazel", a.vex.vex_no_bazel), ("vex_compact", a.vex.vex_compact), ] } @@ -112,6 +113,7 @@ fn defaults_match_contract() { assert_eq!(a.vex.vex, None); assert_eq!(a.vex.vex_product, None); assert!(!a.vex.vex_no_verify); + assert!(!a.vex.vex_no_bazel); assert_eq!(a.vex.vex_doc_id, None); assert!(!a.vex.vex_compact); @@ -152,6 +154,7 @@ fn vex_passthrough_flags() { "--vex-product", "pkg:npm/app@1.0.0", "--vex-no-verify", + "--vex-no-bazel", "--vex-doc-id", "urn:uuid:fixed", "--vex-compact", @@ -159,11 +162,12 @@ fn vex_passthrough_flags() { assert_eq!(a.vex.vex, Some(PathBuf::from("out.vex.json"))); assert_eq!(a.vex.vex_product.as_deref(), Some("pkg:npm/app@1.0.0")); assert!(a.vex.vex_no_verify); + assert!(a.vex.vex_no_bazel); assert_eq!(a.vex.vex_doc_id.as_deref(), Some("urn:uuid:fixed")); assert!(a.vex.vex_compact); - // Only the two vex booleans should be set; nothing else (e.g. --force) may - // ride along on the vex passthrough. - assert_only_true(&a, &["vex_no_verify", "vex_compact"]); + // Only the three vex booleans should be set; nothing else (e.g. --force) + // may ride along on the vex passthrough. + assert_only_true(&a, &["vex_no_verify", "vex_no_bazel", "vex_compact"]); } /// The `manifest_path` default is contract — many scripts hard-code diff --git a/crates/socket-patch-cli/tests/cli_parse_scan.rs b/crates/socket-patch-cli/tests/cli_parse_scan.rs index 71ba340b4..44fc4c82f 100644 --- a/crates/socket-patch-cli/tests/cli_parse_scan.rs +++ b/crates/socket-patch-cli/tests/cli_parse_scan.rs @@ -71,6 +71,7 @@ fn defaults_match_contract() { assert_eq!(args.vex.vex, None); assert_eq!(args.vex.vex_product, None); assert!(!args.vex.vex_no_verify); + assert!(!args.vex.vex_no_bazel); assert_eq!(args.vex.vex_doc_id, None); assert!(!args.vex.vex_compact); } @@ -93,6 +94,7 @@ fn vex_passthrough_flags() { "--vex-product", "pkg:npm/app@1.0.0", "--vex-no-verify", + "--vex-no-bazel", "--vex-doc-id", "urn:uuid:fixed", "--vex-compact", @@ -100,6 +102,7 @@ fn vex_passthrough_flags() { assert_eq!(args.vex.vex, Some(std::path::PathBuf::from("out.vex.json"))); assert_eq!(args.vex.vex_product.as_deref(), Some("pkg:npm/app@1.0.0")); assert!(args.vex.vex_no_verify); + assert!(args.vex.vex_no_bazel); assert_eq!(args.vex.vex_doc_id.as_deref(), Some("urn:uuid:fixed")); assert!(args.vex.vex_compact); } diff --git a/crates/socket-patch-cli/tests/cli_parse_vendor.rs b/crates/socket-patch-cli/tests/cli_parse_vendor.rs index 35da21ce3..a8282a907 100644 --- a/crates/socket-patch-cli/tests/cli_parse_vendor.rs +++ b/crates/socket-patch-cli/tests/cli_parse_vendor.rs @@ -54,6 +54,7 @@ struct Snap { vex: Option, vex_product: Option, vex_no_verify: bool, + vex_no_bazel: bool, vex_doc_id: Option, vex_compact: bool, } @@ -66,6 +67,7 @@ fn snapshot(a: &VendorArgs) -> Snap { vex: a.vex.vex.clone(), vex_product: a.vex.vex_product.clone(), vex_no_verify: a.vex.vex_no_verify, + vex_no_bazel: a.vex.vex_no_bazel, vex_doc_id: a.vex.vex_doc_id.clone(), vex_compact: a.vex.vex_compact, } @@ -80,6 +82,7 @@ fn expected_defaults() -> Snap { vex: None, vex_product: None, vex_no_verify: false, + vex_no_bazel: false, vex_doc_id: None, vex_compact: false, } @@ -165,6 +168,7 @@ fn vex_passthrough_knobs_each_set_their_field() { "--vex-product", "pkg:npm/app@1.0.0", "--vex-no-verify", + "--vex-no-bazel", "--vex-doc-id", "urn:uuid:fixed", "--vex-compact", @@ -173,6 +177,7 @@ fn vex_passthrough_knobs_each_set_their_field() { want.vex = Some(PathBuf::from("out.vex.json")); want.vex_product = Some("pkg:npm/app@1.0.0".to_string()); want.vex_no_verify = true; + want.vex_no_bazel = true; want.vex_doc_id = Some("urn:uuid:fixed".to_string()); want.vex_compact = true; // Only the vex fields move; nothing (e.g. --force) rides along on the diff --git a/crates/socket-patch-cli/tests/cli_parse_vex.rs b/crates/socket-patch-cli/tests/cli_parse_vex.rs index 4340b6876..4012fb9c3 100644 --- a/crates/socket-patch-cli/tests/cli_parse_vex.rs +++ b/crates/socket-patch-cli/tests/cli_parse_vex.rs @@ -47,6 +47,7 @@ struct Snap { output: Option, product: Option, no_verify: bool, + no_bazel: bool, doc_id: Option, compact: bool, } @@ -57,6 +58,7 @@ fn snapshot(a: &VexArgs) -> Snap { output: a.output.clone(), product: a.product.clone(), no_verify: a.no_verify, + no_bazel: a.no_bazel, doc_id: a.doc_id.clone(), compact: a.compact, } @@ -69,6 +71,7 @@ fn expected_defaults() -> Snap { output: None, product: None, no_verify: false, + no_bazel: false, doc_id: None, compact: false, } @@ -145,6 +148,58 @@ fn empty_vex_compact_env_parses_as_false_on_scan() { } } +/// `vex --no-bazel` is the flag or `SOCKET_VEX_NO_BAZEL`, read as +/// `SOCKET_VEX_NO_VERIFY` is: `1` and `true` set it, an exported-but-empty +/// value and no value leave it off, and it moves no other field. +#[test] +#[serial_test::serial] +fn no_bazel_is_the_flag_or_a_truthy_variable_on_vex() { + let unset = parse_vex(try_parse(&["socket-patch", "vex"])); + assert_eq!(snapshot(&unset), expected_defaults()); + let mut set = expected_defaults(); + set.no_bazel = true; + let flag = parse_vex(try_parse(&["socket-patch", "vex", "--no-bazel"])); + assert_eq!(snapshot(&flag), set); + for (value, want) in [("1", &set), ("true", &set), ("", &expected_defaults())] { + let a = parse_vex(try_parse_with_env( + &[("SOCKET_VEX_NO_BAZEL", value)], + &["socket-patch", "vex"], + )); + assert_eq!(snapshot(&a), *want, "SOCKET_VEX_NO_BAZEL={value:?}"); + } +} + +/// The same option on each command that takes `--vex`, as `--vex-no-bazel`: +/// the flag, and the one variable, which must not abort the parse of a +/// host command. Each field of the embedded options is compared, so a value +/// that lands in a second one fails too. +#[test] +#[serial_test::serial] +fn no_bazel_is_the_flag_or_a_truthy_variable_on_each_host() { + let embedded = |cli: Result, run: &str| { + let vex = match cli.unwrap_or_else(|e| panic!("{run}: {e}")).command { + Commands::Apply(a) => a.vex, + Commands::Scan(a) => a.vex, + Commands::Vendor(a) => a.vex, + _ => panic!("{run}: not a host of --vex"), + }; + let other = (vex.vex, vex.vex_product, vex.vex_doc_id); + assert_eq!(other, (None, None, None), "{run}"); + [vex.vex_no_bazel, vex.vex_no_verify, vex.vex_compact] + }; + for host in ["apply", "scan", "vendor"] { + let bare = ["socket-patch", host]; + assert_eq!(embedded(try_parse(&bare), host), [false; 3]); + let flag = ["socket-patch", host, "--vex-no-bazel"]; + assert_eq!(embedded(try_parse(&flag), host), [true, false, false]); + for (value, set) in [("1", true), ("true", true), ("", false)] { + let run = format!("SOCKET_VEX_NO_BAZEL={value:?} {host}"); + let cli = try_parse_with_env(&[("SOCKET_VEX_NO_BAZEL", value)], &bare); + assert_eq!(embedded(cli, &run), [set, false, false], "{run}"); + } + } +} + /// The explicit CLI flags keep working through the env fix (the custom /// value parser must not change flag-only usage). #[test] 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 201b666a1..d0fdc9917 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -153,13 +153,20 @@ const PRODUCT: &str = "pkg:generic/socket-fixture@0.0.0"; /// shared API stand-in, and of the records a flow writes itself. const ADVISORY: &str = "GHSA-test-aaaa-bbbb"; +/// The code of the warning with which `socket-patch` says that Bazel does +/// not build the patched copy of a package, so that its document says the +/// package is affected. +pub const NOT_IN_BUILD: &str = "vex_bazel_not_in_build"; + /// The mode a flow patched its package in, which a document says after the -/// patch id. +/// patch id. Or [`How::Unbuilt`]: the patch is in a copy that Bazel does +/// not build, and a document says the package is affected. #[derive(Clone, Copy)] pub enum How { Hosted, Vendored, Agent, + Unbuilt, } impl How { @@ -167,23 +174,47 @@ impl How { match self { How::Hosted => " (redirected)", How::Vendored => " (vendored)", - How::Agent => "", + How::Agent | How::Unbuilt => "", } } } /// 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. +/// document of an earlier run says it. Or, for [`Claim::unbuilt`], that the +/// package is affected, and what to do about it. pub struct Claim<'a> { pub purl: &'a str, pub uuid: &'a str, pub how: How, + /// What the action statement of an affected package names, and the + /// warning of its run: the call's file and line, the file Bazel builds + /// the package from, what to run. + names: &'a [String], } impl<'a> Claim<'a> { pub fn new(purl: &'a str, uuid: &'a str, how: How) -> Claim<'a> { - Claim { purl, uuid, how } + let names = &[]; + Claim { + purl, + uuid, + how, + names, + } + } + + /// The package is affected: its patch `uuid` is in a copy that Bazel + /// does not build, and `names` is what the document has to name. + pub fn unbuilt(purl: &'a str, uuid: &'a str, names: &'a [String]) -> Claim<'a> { + Claim { + names, + ..Claim::new(purl, uuid, How::Unbuilt) + } + } + + fn affected(&self) -> bool { + matches!(self.how, How::Unbuilt) } } @@ -211,7 +242,7 @@ fn document_at(test: &str, path: &Path) -> (String, Value) { /// 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. +/// and the patch, or for an affected package what to do. fn wording(mut document: Value) -> Value { fn without(of: &mut Value, fields: &[&str]) { let Some(object) = of.as_object_mut() else { @@ -772,8 +803,9 @@ pub struct Cell { /// 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, + /// this checkout, which every later one is held to: of the first that + /// says not affected, and of the first that says affected. + wording: [OnceLock; 2], // Dropped after `Cell::drop` has stopped the server. scratch: Scratch, } @@ -830,7 +862,7 @@ impl Cell { numbers, socket_bin, downloads: None, - wording: OnceLock::new(), + wording: Default::default(), scratch, }) } @@ -872,7 +904,7 @@ impl Cell { numbers: self.numbers, socket_bin: self.socket_bin.clone(), downloads: None, - wording: OnceLock::new(), + wording: Default::default(), scratch: Scratch::new(Some(self.scratch.repository_cache.clone())), }; for (rel, bytes) in files { @@ -1112,6 +1144,70 @@ impl Cell { [out.stdout, out.stderr].map(|stream| String::from_utf8_lossy(&stream).into_owned()) } + /// [`Cell::socket_patch_person`] for a command that is given + /// [`with_vex`] for `path` among `args`, in a checkout where Bazel does + /// not build the patched copy of the one package the run attests. The + /// command passes and writes the document, which says `claim`: the + /// package is affected. It prints the line `warned` on stderr and no + /// error, and says that it wrote a document with one statement, which + /// says affected (a hosted scan on stderr, with a note after it). With + /// `--silent` among `args` it prints nothing at all. + pub fn tells_a_person( + &self, + api: &str, + args: &[&str], + env: &[(&str, &str)], + path: &Path, + claim: &Claim, + warned: &str, + ) { + let _ = std::fs::remove_file(path); + let mut cmd = self.socket_patch_command(api, args, env); + let out = cmd.output().expect("spawn socket-patch"); + let code = out.status.code(); + let [stdout, stderr] = + [out.stdout, out.stderr].map(|stream| String::from_utf8_lossy(&stream).into_owned()); + let test = &self.test; + let said = + format!("{test}: {args:?}\nexit {code:?}\n--- stdout\n{stdout}\n--- stderr\n{stderr}"); + assert_eq!(code, Some(0), "{said}"); + self.attests(path, claim, true); + if args.contains(&"--silent") { + assert_eq!([stdout.as_str(), stderr.as_str()], ["", ""], "{said}"); + return; + } + let wrote = format!( + "Wrote OpenVEX document with 1 statement (1 affected) to {}", + path.display() + ); + let mut lines = stdout.lines().chain(stderr.lines()); + assert!(lines.any(|line| line.starts_with(&wrote)), "{said}"); + let printed = stderr.lines().any(|line| line == warned); + assert!(printed, "no {warned:?}:\n{said}"); + assert!(!stderr.contains("Error"), "{said}"); + } + + /// What `socket-patch `, a command that is to write its document + /// to `path`, gives a script and a person: of a run with `--json` and + /// of one without, the exit code, all it printed on stdout and on + /// stderr, and what the document it wrote says ([`wording`]: all but + /// its id and its times), null when it left none. Two commands that + /// give the same differ in nothing a script or a person sees. + pub fn gives(&self, api: &str, args: &[&str], env: &[(&str, &str)], path: &Path) -> Value { + let run = |form: &[&str]| { + let _ = std::fs::remove_file(path); + let mut cmd = self.socket_patch_command(api, &[args, form].concat(), env); + let out = cmd.output().expect("spawn socket-patch"); + let [stdout, stderr] = [out.stdout, out.stderr] + .map(|stream| String::from_utf8_lossy(&stream).into_owned()); + let written = path + .exists() + .then(|| wording(document_at(&self.test, path).1)); + json!({ "code": out.status.code(), "stdout": stdout, "stderr": stderr, "document": written }) + }; + json!([run(&["--json"]), run(&[])]) + } + /// 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. @@ -1123,10 +1219,14 @@ impl Cell { /// `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. + /// when the run did not check the files (`verified` is false). For + /// [`Claim::unbuilt`] the one statement is `affected` for that + /// advisory, product and package, with no justification and no impact + /// statement, and an action statement that holds the patch and each + /// name of the claim. And it says so in the words of every other + /// document of that status 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); @@ -1136,9 +1236,6 @@ impl Cell { 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 @@ -1150,13 +1247,27 @@ impl Cell { 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; + if claim.affected() { + assert_eq!(statement["status"], "affected", "{test}: {text}"); + let reserved = ["justification", "impact_statement"]; + let reserved = reserved.map(|key| statement.get(key).is_some()); + assert_eq!(reserved, [false, false], "{test}: {text}"); + let action = statement["action_statement"].as_str().unwrap_or_default(); + for name in claim.names.iter().map(String::as_str).chain([uuid]) { + assert!(action.contains(name), "{test}: no {name:?} in {action:?}"); + } + } else { + assert_eq!(statement["status"], "not_affected", "{test}: {text}"); + let justification = "inline_mitigations_already_exist"; + assert_eq!(statement["justification"], justification, "{test}: {text}"); + let mut impact = format!("Patched via Socket patch {uuid}{how}"); + if !verified { + impact += NOT_VERIFIED_SUFFIX; + } + assert_eq!(statement["impact_statement"], impact, "{test}: {text}"); } - assert_eq!(statement["impact_statement"], impact, "{test}: {text}"); let said = wording(document); - let first = self.wording.get_or_init(|| said.clone()); + let first = self.wording[usize::from(claim.affected())].get_or_init(|| said.clone()); assert_eq!( said, *first, "{test}: not the words of the first document of this checkout:\n{text}" @@ -1168,7 +1279,11 @@ impl Cell { /// 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. + /// that it checked no file. Of an affected package it says the same + /// with and without that option, and does not report it as verified: + /// its one event is `skipped` with the code [`NOT_IN_BUILD`] and the + /// status `affected`, the run is a partial failure that exits 0, and + /// its one warning names what the claim names. 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); @@ -1176,19 +1291,35 @@ impl Cell { 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 affected = usize::from(claim.affected()); + let [status, action, state] = [ + ["success", "verified", "not_affected"], + ["partialFailure", "skipped", "affected"], + ][affected]; + assert_eq!(ran.envelope["status"], status, "{test}: {said}"); + assert_eq!(event["action"], action, "{test}: {said}"); + let code = [Value::Null, json!(NOT_IN_BUILD)][affected].clone(); + assert_eq!(event["errorCode"], code, "{test}: {said}"); + let summary = &ran.envelope["summary"]; + let counted = [&summary["verified"], &summary["skipped"]].map(Value::as_u64); + let expected = [[Some(1), Some(0)], [Some(0), Some(1)]][affected]; + assert_eq!(counted, expected, "{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["status"], state, "{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}"); + let warned: &[&str] = match (claim.affected(), verified) { + (true, _) => &[NOT_IN_BUILD], + (false, true) => &[], + (false, false) => &["vex_not_verified"], + }; + let warnings = &ran.envelope["warnings"]; + assert_eq!(codes_in(warnings), warned, "{test}: {said}"); + self.names_the_build(warnings, claim, said); self.attests(&path, claim, verified); } @@ -1218,7 +1349,7 @@ impl Cell { "{test}: {said}" ); let (text, document) = document_at(test, &path); - let mut named = self.wording.get().cloned().expect("a document here"); + let mut named = self.wording[0].get().cloned().expect("a document here"); named["statements"][0]["products"][0]["@id"] = product.into(); assert_eq!(wording(document), named, "{test}: {said}\n{text}"); } @@ -1227,19 +1358,25 @@ impl Cell { /// 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. + /// come with the next build. A run whose document says the package is + /// affected counts that statement as such, warns of it once, and names + /// what the claim names. 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}"); + let affected = [Value::Null, json!(1)][usize::from(claim.affected())].clone(); + assert_eq!(vex["affected"], affected, "{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 => &[], + How::Unbuilt => &[NOT_IN_BUILD], }; assert_eq!(codes_in(&vex["warnings"]), warned, "{test}: {said}"); + self.names_the_build(&vex["warnings"], claim, said); self.attests(path, claim, true); } @@ -1268,7 +1405,7 @@ impl Cell { 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()); + let (here, there) = (self.wording[0].get(), fresh.wording[0].get()); assert_eq!(there, here, "{test}: the two checkouts word it apart"); } @@ -1288,6 +1425,43 @@ impl Cell { assert!(removed, "{test}: {said}"); } + /// For [`Claim::unbuilt`], the one [`NOT_IN_BUILD`] warning of + /// `warnings` is about the package of `claim`, says that the document + /// says affected, and holds each name of the claim. For every other + /// claim there is no such warning. + fn names_the_build(&self, warnings: &Value, claim: &Claim, said: &str) { + let test = &self.test; + let ours = |warning: &&Value| warning["code"] == NOT_IN_BUILD; + let ours: Vec<&Value> = warnings + .as_array() + .into_iter() + .flatten() + .filter(ours) + .collect(); + if !claim.affected() { + assert!(ours.is_empty(), "{test}: {said}"); + return; + } + let [warning] = ours[..] else { + panic!("{test}: not one {NOT_IN_BUILD} warning: {said}"); + }; + let detail = warning["detail"].as_str().unwrap_or_default(); + let (about, rest) = detail.split_once(": ").unwrap_or_default(); + assert_eq!( + normalize_purl(about), + normalize_purl(claim.purl), + "{test}: {said}" + ); + let affected = "the VEX document says affected. "; + assert!(rest.starts_with(affected), "{test}: {detail:?}"); + for name in claim.names { + assert!( + rest.contains(name.as_str()), + "{test}: no {name:?} in {detail:?}" + ); + } + } + /// `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> { @@ -1364,7 +1538,7 @@ pub fn cell_without_bazel(release: &str) -> Cell { numbers: numbers(release).expect("a release"), socket_bin: None, downloads: None, - wording: OnceLock::new(), + wording: Default::default(), scratch: Scratch::new(None), } } 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 06acc4969..0a504ed13 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs @@ -44,9 +44,19 @@ //! 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. +//! where the fixture has no such file. +//! +//! `socket-patch` reads `MODULE.bazel` for the calls that hand a lock to a +//! ruleset, and says of a package whose patch such a ruleset does not +//! build that it is affected: a patch in the copy a package manager +//! installed, or a PyPI one in a copy committed under `.socket/vendor`. +//! Two flows hold it to that +//! (`npm::agent_npm_translate_lock`, `pypi::vendored_pip_parse`): the +//! build is not the patched one, every form of `vex` writes a document +//! that says affected and names the call and the file Bazel builds from, +//! and after what the document says to do the build is patched and the +//! document says not affected. 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 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 c590d55ca..b8f6646b4 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -1,6 +1,7 @@ -//! Hosted and vendored mode for an npm package that aspect_rules_js links -//! from a pnpm lock: `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` -//! under Bzlmod, with a lock of `lockfileVersion: '9.0'`. +//! Hosted, vendored and agent mode for an npm package that aspect_rules_js +//! links from a pnpm lock: +//! `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` under Bzlmod, +//! with a lock of `lockfileVersion: '9.0'`. //! //! rules_js reads the lock itself. Every entry of `packages:` becomes one //! repository, which Bazel's downloader fetches from the entry's `tarball` @@ -9,8 +10,9 @@ //! pnpm runs, no `node_modules` of the checkout is read, and the machine //! needs no Node: the ruleset downloads the one that runs the consumer. //! -//! Two flows, one test each, on the Bazel the run is given ([`FIXTURE`] -//! says which ruleset goes with its release), each in a fresh output base: +//! The hosted and the vendored flow, one test each, on the Bazel the run is +//! given ([`FIXTURE`] says which ruleset goes with its release), each in a +//! fresh output base: //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker, and Bazel fetched the upstream tarball from the stand-in @@ -53,6 +55,19 @@ //! //! Both flows assert the VEX document of their patch as `main.rs` says. //! +//! A third flow is agent mode ([`agent_npm_translate_lock`]), which patches +//! the copy of the package that the user's `pnpm install` left in +//! `node_modules`. rules_js does not read that directory, so the build is +//! the unpatched one before the command and after it. The flow asserts +//! that; that every form of `vex` writes a document that says the package +//! is affected, and names the call of `MODULE.bazel` that builds it from +//! the lock; that `vex --no-bazel`, for a repository that ships the +//! installed tree, says not affected of that tree while the build is still +//! the unpatched one; and that hosted mode, which the document names, then +//! ends in the patched build and in a document that says not affected. +//! Tests that need no Bazel run the same steps in a copy of the fixture, +//! and in workspaces where the statement must stay as it is without Bazel. +//! //! 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 @@ -84,12 +99,12 @@ 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::envelope::{codes_in, event_triples}; use crate::harness::{ - changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, Run, StandIn, Tree, - CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, + Run, StandIn, Tree, CONSUMER, NOTHING, NOT_IN_BUILD, }; -use crate::hosted_memory_common::{Patch, ORG}; +use crate::hosted_memory_common::{read_tree, Patch, ORG}; /// The workspace the tests build, and the ruleset each Bazel release builds /// it with. @@ -294,6 +309,11 @@ fn registry(upstream: &Package) -> StandIn { /// for its tarball. The API names the sha512 of the patch's own tarball, /// whatever is served. fn grant(standin: &StandIn, upstream: &Package, patch: &Patched, served: &[u8]) { + grant_recorded(standin, patch, served, &record(upstream, patch)); +} + +/// [`grant`] with `record` as the record of the patch. +fn grant_recorded(standin: &StandIn, patch: &Patched, served: &[u8], record: &Value) { let url = format!("{}{}", standin.origin(), patch.route); let reference = json!({ "status": "granted", @@ -314,7 +334,16 @@ fn grant(standin: &StandIn, upstream: &Package, patch: &Patched, served: &[u8]) standin.api(&[granted]); // Priority 1: ahead of the shared API mock's patch record, whose hashes // are fixed, because vendored mode holds the downloaded file to `afterHash`. - let record = json!({ + let record = serde_json::to_vec(record).expect("a JSON document"); + let record_route = format!("/v0/orgs/{ORG}/patches/view/{}", patch.uuid); + standin.serve(1, &record_route, &record); + standin.serve(5, &patch.route, served); +} + +/// The record of `patch`: the entry file of `upstream` becomes the one of +/// the patch. +fn record(upstream: &Package, patch: &Patched) -> Value { + json!({ "uuid": patch.uuid, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", @@ -328,11 +357,55 @@ fn grant(standin: &StandIn, upstream: &Package, patch: &Patched, served: &[u8]) "description": "fixture", "license": "MIT", "tier": "free", - }); - let record = serde_json::to_vec(&record).expect("a JSON document"); - let record_route = format!("/v0/orgs/{ORG}/patches/view/{}", patch.uuid); - standin.serve(1, &record_route, &record); - standin.serve(5, &patch.route, served); + }) +} + +/// [`grant`] of the patch's own tarball, with a `record` that carries both +/// entry files: agent mode patches the installed copy from the record and +/// asks for no tarball, and hosted mode pins the tarball as in the hosted +/// flow. +fn grant_installed(standin: &StandIn, upstream: &Package, patch: &Patched) { + let b64 = |text: &str| base64::engine::general_purpose::STANDARD.encode(text); + let mut record = record(upstream, patch); + let file = &mut record["files"]["package/index.js"]; + file["blobContent"] = b64(&patch.package.index_js).into(); + file["beforeBlobContent"] = b64(&upstream.index_js).into(); + grant_recorded(standin, patch, &patch.package.tarball, &record); +} + +/// The directory of the package in pnpm's virtual store, from the checkout. +fn store() -> String { + let entry = format!("{}@{VERSION}", NAME.replace('/', "+")); + format!("node_modules/.pnpm/{entry}/node_modules/{NAME}") +} + +/// What the user's `pnpm install` leaves for the package in the project +/// of `cell` (in its directory `project`: `""` for the checkout itself, +/// else with a `/` at its end): the two files of `upstream`'s tarball in +/// pnpm's virtual store, and the link to that directory which a `require` +/// of the project resolves. The store is the project's own, or with +/// `shared` the one at the root of the checkout, where pnpm keeps it for +/// the members of a workspace. No pnpm runs here, so the files pnpm keeps +/// for itself (`.modules.yaml`, the store's `lock.yaml`) are not there. +/// Gives the entry file, from the checkout. +fn install(cell: &Cell, project: &str, shared: bool, upstream: &Package) -> String { + let store = match shared { + true => store(), + false => format!("{project}{}", store()), + }; + cell.write(&format!("{store}/package.json"), MANIFEST); + let entry = format!("{store}/index.js"); + cell.write(&entry, &upstream.index_js); + let link = cell.path(&format!("{project}node_modules/{NAME}")); + std::fs::create_dir_all(link.parent().expect("the scope")).expect("create the scope"); + // From the scope's directory in `node_modules`: to the store beside + // it, or up to the root of the checkout and down into the store there. + let target = match shared { + true => "../".repeat(project.matches('/').count() + 2) + &store, + false => self::store().replacen("node_modules/", "../", 1), + }; + std::os::unix::fs::symlink(target, &link).expect("link the package"); + entry } /// Send Bazel's downloader to `standin` for the registry's files of the @@ -700,6 +773,923 @@ fn vendored_npm_translate_lock() { ); } +/// The file that hands the lock to rules_js, and the call that does. +const MODULE: &str = "MODULE.bazel"; +const HUB: &str = "npm.npm_translate_lock"; + +/// What `socket-patch` has to name when it says that the package is +/// affected: the lock `lock` that Bazel builds the package from, with the +/// hub's call and its line in the workspace file `file` of `cell`, and the +/// mode that patches that lock. +fn names(cell: &Cell, file: &str, lock: &str) -> Vec { + let workspace_file = text(&cell.tree(), file); + let call = format!("{HUB}("); + let above = workspace_file.lines().take_while(|line| *line != call); + vec![ + format!("from {lock} (`{HUB}`, {file}:{})", above.count() + 1), + "`socket-patch scan --mode hosted`".to_string(), + ] +} + +/// Agent mode in the project of `cell` (in its directory `project`, as +/// [`install`] takes it), where [`install`] left the package with the entry +/// file `entry`: `scan --mode agent --yes` patches the installed copy, from +/// the record of `patch`, and changes no other file of the project, and the +/// `apply` of a later install finds it patched. Then what the two say with +/// `--vex`, and what `vex` and +/// `vex --no-verify` say: all four pass and write one document. With +/// `unbuilt`, the [`names`] of the call that builds the package from the +/// lock, it says that the package is affected, and names them. Without, no +/// workspace file hands a lock of the project to Bazel, and it attests the +/// package through the patch, as in a checkout without Bazel. Gives the +/// files of the checkout. +fn patches_the_installed_copy( + cell: &Cell, + standin: &StandIn, + project: &str, + patch: &Patched, + entry: &str, + unbuilt: Option<&[String]>, +) -> Tree { + let test = &cell.test; + let before = cell.tree(); + let claim = match unbuilt { + Some(names) => Claim::unbuilt(PURL, &patch.uuid, names), + None => Claim::new(PURL, &patch.uuid, How::Agent), + }; + let directory = ["--cwd", project.trim_end_matches('/')]; + let run = |cell: &Cell, args: &[&str]| { + let at: &[&str] = if project.is_empty() { &[] } else { &directory }; + socket_patch(cell, standin, &[args, at].concat()) + }; + + let in_run = cell.document("in-run"); + let agent = ["scan", "--mode", "agent", "--yes"]; + let scan = run(cell, &[&agent[..], &with_vex(&in_run)].concat()); + let said = &scan.dump; + assert_eq!(scan.code, 0, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); + let patched = cell.tree(); + let wrote = changed(&before, &patched); + let outside: Vec<&String> = wrote + .iter() + .filter(|file| !file.starts_with(&format!("{project}.socket/"))) + .collect(); + assert_eq!(outside, [entry], "{test}: {said}"); + let installed = patched[entry] == patch.package.index_js.as_bytes(); + assert!(installed, "{test}: {entry} is not the patched file"); + + let again = cell.document("apply"); + let apply = run(cell, &[&["apply"][..], &with_vex(&again)].concat()); + assert_eq!( + apply.envelope["status"], "success", + "{test}: {}", + apply.dump + ); + cell.wrote_in_run(&scan, &in_run, &claim); + cell.wrote_in_run(&apply, &again, &claim); + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); + assert_eq!(changed(&patched, &cell.tree()), NOTHING, "{test}"); + patched +} + +/// What the document of an affected package tells the user to do, in the +/// checkout of `cell` that agent mode patched: `scan --mode hosted --yes` +/// pins `patch` in the lock, which rules_js builds the package from. Its +/// document and the one of `vex` now attest the package, through the pin. +/// Gives the files of the checkout. +fn pins_the_lock(cell: &Cell, standin: &StandIn, patch: &Patched) -> Tree { + let test = &cell.test; + let claim = Claim::new(PURL, &patch.uuid, How::Hosted); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, args); + let document = cell.document("hosted"); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let scan = run(cell, &[&hosted[..], &with_vex(&document)].concat()); + let applied = &scan.envelope["summary"]["applied"]; + assert_eq!(*applied, 1, "{test}: {}", scan.dump); + cell.wrote_in_run(&scan, &document, &claim); + cell.stands_alone(run, &claim, true); + cell.tree() +} + +/// Agent mode beside a hub that builds the package from the lock. +/// +/// - (a) After the user's `pnpm install` ([`install`]), `bazel build` and +/// `bazel run //:consumer` print the unpatched marker: rules_js builds +/// the package from the tarball the lock names, and reads no +/// `node_modules` of the checkout, which `.bazelignore` names. +/// - (b) `scan --mode agent --yes` patches the copy in `node_modules`, and +/// `apply` finds it patched ([`patches_the_installed_copy`]). Both pass, +/// and they and `vex` write a document that says the package is +/// affected: it names `pnpm-lock.yaml`, which Bazel builds the package +/// from, the call of `MODULE.bazel` that reads it, and hosted mode, +/// which patches that lock. +/// - (c) The same two Bazel commands print the unpatched marker again, as +/// the document said, and `vex` says affected again. `vex --no-bazel` +/// says not affected ([`speaks_of_the_installed_tree`]): its document +/// then speaks of `node_modules`, which holds the patch, and not of the +/// Bazel build, which is still the unpatched one. It is for a repository +/// that ships what its package manager installed. +/// - (d) What the document says to do: `scan --mode hosted --yes` pins the +/// patch in the lock ([`pins_the_lock`]), the same two Bazel commands +/// print the patched marker, with the tarball from the stand-in patch +/// host, and `vex` attests the package as not affected. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn agent_npm_translate_lock() { + let test = "npm::agent_npm_translate_lock"; + let started = Instant::now(); + let Some((cell, standin, upstream)) = open(test) else { + return; + }; + let release = cell.release().to_string(); + let patch = Patched::new(); + grant_installed(&standin, &upstream, &patch); + + // (a) The unpatched build, with the installed tree beside it. + let entry = install(&cell, "", false, &upstream); + builds_upstream(&cell, &standin, &upstream); + + // (b) Agent mode patches the installed copy, and says it is affected. + let names = names(&cell, MODULE, LOCK); + let patched = patches_the_installed_copy(&cell, &standin, "", &patch, &entry, Some(&names)); + + // (c) The build is the one of (a): Bazel never reads the patched copy. + cell.builds(&upstream.marker); + assert_eq!(changed(&patched, &cell.tree()), NOTHING, "{test}"); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + cell.stands_alone(run, &Claim::unbuilt(PURL, &patch.uuid, &names), true); + // Told that the installed tree is what ships, `vex` attests that tree. + speaks_of_the_installed_tree(&cell, &standin, &patch); + assert_eq!(changed(&patched, &cell.tree()), NOTHING, "{test}"); + + // (d) Hosted mode patches what Bazel builds, and `vex` says so. + let pinned = pins_the_lock(&cell, &standin, &patch); + cell.builds_patched(&pinned, &patch.package.marker); + assert!( + standin.asked(&patch.route) > 0, + "{test}: the patched build did not fetch the tarball from the stand-in patch host" + ); + let claim = Claim::new(PURL, &patch.uuid, How::Hosted); + cell.stands_alone(run, &claim, true); + + println!( + "{test}: Bazel {release} built {:?} before and after `scan --mode agent` patched {}; \ + every form of `vex` said the package is affected, and named {names:?}, and \ + `vex --no-bazel` said it is not affected in the installed tree; after \ + `scan --mode hosted` it built {:?}, and `vex` said it is not affected; {:?}", + upstream.marker, + store(), + patch.package.marker, + started.elapsed() + ); +} + +/// Without a Bazel: a checkout with the fixture's `MODULE.bazel` at its +/// root and the fixture's project in the directory `project` of it (as +/// [`install`] takes it), with the lock that pins the upstream package of +/// this run and the stand-in that holds it, as [`open`] makes them, the +/// package installed in the project, and a patch of the package granted to +/// agent mode. Gives the entry file of the installed copy last. +/// +/// With `member`, the project is a member of a pnpm workspace at the root +/// of the checkout, laid out as `pnpm install` leaves one: the lock is the +/// workspace's, at the root, and names the project among its importers, +/// the project has no lock of its own, and the store is the root's. +fn checkout_of(project: &str, member: bool) -> (Cell, StandIn, Patched, String) { + let cell = cell_without_bazel("9.3.2"); + for part in ["common", "e9"] { + for (rel, bytes) in read_tree(&fixture_path(FIXTURE.dir).join(part)) { + let at = if rel == MODULE { "" } else { project }; + cell.write(&format!("{at}{rel}"), bytes); + } + } + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + let upstream = Package::upstream(); + let lock = lock_pinning(&upstream); + if member { + let (own, named) = ("\n .:\n", project.trim_end_matches('/')); + assert_eq!(lock.matches(own).count(), 1, "{lock}"); + let shared = lock.replace(own, &format!("\n .: {{}}\n\n {named}:\n")); + std::fs::remove_file(cell.path(&format!("{project}{LOCK}"))).expect("the member's lock"); + cell.write(LOCK, shared); + cell.write("pnpm-workspace.yaml", format!("packages:\n - {named}\n")); + cell.write( + "package.json", + "{\"name\": \"workspace\", \"private\": true}\n", + ); + } else { + cell.write(&format!("{project}{LOCK}"), lock); + } + let standin = registry(&upstream); + let patch = Patched::new(); + grant_installed(&standin, &upstream, &patch); + let entry = install(&cell, project, member, &upstream); + (cell, standin, patch, entry) +} + +/// [`checkout_of`] a project with a lock and a store of its own. +fn checkout(project: &str) -> (Cell, StandIn, Patched, String) { + checkout_of(project, false) +} + +/// The action statement of a package of the fixture's checkout that is +/// affected because `patch` is in its installed copy alone: it names the +/// lock and its `call` as [`names`] gives them first, and ends with the +/// option for a repository that ships the installed tree. +fn action(patch: &Patched, call: &str) -> String { + format!( + "Bazel builds this package {call}, which does not name Socket patch {}: the patch is \ + only in the installed copy. Run `socket-patch scan --mode hosted` in the directory of \ + that lock to pin the patch there. If what you ship is the installed tree and not what \ + Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).", + patch.uuid + ) +} + +/// The line a person reads on stderr when the document says that the +/// fixture's package is affected: the run warning, which says so and then +/// what the [`action`] statement says. +fn warns(patch: &Patched, call: &str) -> String { + let action = action(patch, call); + format!("Warning: {PURL}: the VEX document says affected. {action}") +} + +/// Without a Bazel: step (b) of [`agent_npm_translate_lock`] in the +/// fixture's checkout, where `MODULE.bazel` hands the lock to rules_js. +/// Then `apply --vex` and `scan --mode agent --vex` as a person runs them: +/// each passes and writes the document, with the warning on stderr, the +/// line that it wrote a document on stdout, and no error; with `--silent` +/// each passes, writes the document and prints nothing. +#[test] +fn an_installed_patch_is_affected_beside_a_hub_that_reads_the_lock() { + let (cell, standin, patch, entry) = checkout(""); + let names = names(&cell, MODULE, LOCK); + let call = "from pnpm-lock.yaml (`npm.npm_translate_lock`, MODULE.bazel:7)"; + assert_eq!(names[0], call); + patches_the_installed_copy(&cell, &standin, "", &patch, &entry, Some(&names)); + + let origin = standin.origin(); + let registry = format!("{origin}/{REGISTRY}"); + let env = [ + ("SOCKET_PATCH_SERVER_URL", origin.as_str()), + ("SOCKET_NPM_REGISTRY", registry.as_str()), + ]; + let document = cell.document("person"); + let claim = Claim::unbuilt(PURL, &patch.uuid, &names); + let warned = warns(&patch, &names[0]); + let scan = ["scan", "--mode", "agent", "--yes"]; + for command in [&["apply"][..], &scan[..]] { + let loud = [command, &with_vex(&document)].concat(); + cell.tells_a_person(&origin, &loud, &env, &document, &claim, &warned); + let silent = [&loud[..], &["--silent"]].concat(); + cell.tells_a_person(&origin, &silent, &env, &document, &claim, &warned); + } + + // What the document says to do ends in one that says not affected. + pins_the_lock(&cell, &standin, &patch); +} + +/// `vex --no-bazel` in the checkout of `cell`, where `patch` is in the +/// installed copy alone and a hub builds the package from the lock, so +/// that `vex` says affected: it exits 0, reports the package as verified +/// and warns of nothing, and its one statement says not affected, through +/// the patch. The document then speaks of `node_modules`, which a +/// repository that ships its installed tree puts in what it ships, and not +/// of what Bazel builds. +fn speaks_of_the_installed_tree(cell: &Cell, standin: &StandIn, patch: &Patched) { + let path = cell.document("installed"); + let args = ["vex", "--no-bazel", "--output"]; + let vex = socket_patch( + cell, + standin, + &[&args[..], &[path.to_str().expect("a path")]].concat(), + ); + let (test, said) = (&cell.test, &vex.dump); + assert_eq!(vex.code, 0, "{test}: {said}"); + assert_eq!(vex.envelope["status"], "success", "{test}: {said}"); + let verified = [(canonical_purl(PURL), "verified".into(), String::new())]; + assert_eq!(reported(&vex.envelope), verified, "{test}: {said}"); + let warned = codes_in(&vex.envelope["warnings"]); + assert_eq!(warned, NOTHING, "{test}: {said}"); + let written = std::fs::read_to_string(&path).expect("a document"); + let document: Value = serde_json::from_str(&written).expect("a JSON document"); + let statements = document["statements"].as_array().map(Vec::as_slice); + let Some([statement]) = statements else { + panic!("{test}: not one statement:\n{written}"); + }; + let says = ["status", "impact_statement", "action_statement"].map(|key| &statement[key]); + let impact = json!(format!("Patched via Socket patch {}", patch.uuid)); + let expected = [&json!("not_affected"), &impact, &Value::Null]; + assert_eq!(says, expected, "{test}: {written}"); +} + +/// Without a Bazel: a repository that ships what its package manager +/// installed, beside a hub that reads the same lock. Every form says +/// affected, as [`an_installed_patch_is_affected_beside_a_hub_that_reads_the_lock`] +/// holds. With `--no-bazel` on `vex`, `--vex-no-bazel` on `apply` and on +/// `scan --mode agent`, or `SOCKET_VEX_NO_BAZEL=1` on any of them, the +/// document attests the package through the patch, and the run is the one +/// of the same checkout without its `MODULE.bazel`, to a script and to a +/// person: the exit code, both streams byte for byte, and what the document +/// says. In that checkout, which is no Bazel workspace, the option changes +/// nothing and no run remarks on it. +#[test] +fn the_option_makes_the_run_the_one_of_a_checkout_without_bazel() { + let (cell, standin, patch, entry) = checkout(""); + let names = names(&cell, MODULE, LOCK); + patches_the_installed_copy(&cell, &standin, "", &patch, &entry, Some(&names)); + speaks_of_the_installed_tree(&cell, &standin, &patch); + + let origin = standin.origin(); + let registry = format!("{origin}/{REGISTRY}"); + let env = [ + ("SOCKET_PATCH_SERVER_URL", origin.as_str()), + ("SOCKET_NPM_REGISTRY", registry.as_str()), + ("SOCKET_VEX_NO_BAZEL", "1"), + ]; + let document = cell.document("shipped"); + let scan = ["scan", "--mode", "agent", "--yes"]; + let forms = [ + ( + vec!["vex", "--output", document.to_str().expect("a path")], + "--no-bazel", + ), + ( + [&["apply"][..], &with_vex(&document)].concat(), + "--vex-no-bazel", + ), + ([&scan[..], &with_vex(&document)].concat(), "--vex-no-bazel"), + ]; + let gives = |args: &[&str], env: &[(&str, &str)]| cell.gives(&origin, args, env, &document); + let claim = Claim::new(PURL, &patch.uuid, How::Agent); + let mut beside_the_hub = Vec::new(); + for (args, option) in &forms { + let with_option = [&args[..], &[*option]].concat(); + if args[0] != "vex" { + let ran = socket_patch(&cell, &standin, &with_option); + cell.wrote_in_run(&ran, &document, &claim); + } + beside_the_hub.push([gives(&with_option, &env[..2]), gives(args, &env)]); + } + + let patched = cell.tree(); + std::fs::remove_file(cell.path(MODULE)).expect(MODULE); + for ((args, option), [by_option, by_variable]) in forms.iter().zip(&beside_the_hub) { + let without_bazel = gives(args, &env[..2]); + assert_eq!(*by_option, without_bazel, "{args:?} {option}"); + assert_eq!( + *by_variable, without_bazel, + "{args:?}, SOCKET_VEX_NO_BAZEL=1" + ); + let outside = gives(&[&args[..], &[*option]].concat(), &env[..2]); + assert_eq!(outside, without_bazel, "{args:?} {option}, no {MODULE}"); + for run in without_bazel.as_array().into_iter().flatten() { + let says = [&run["code"], &run["document"]["statements"][0]["status"]]; + assert_eq!( + says, + [&json!(0), &json!("not_affected")], + "{args:?}: {run:#}" + ); + } + println!("{args:?} with {option}, and without {MODULE}:\n{without_bazel:#}"); + } + assert_eq!(changed(&patched, &cell.tree()), [MODULE], "{}", cell.test); +} + +/// Without a Bazel: the installed patch is affected beside a second patch +/// of the manifest whose package this checkout does not have, as a +/// manifest shared by several projects holds one. Every form omits that +/// one with or without Bazel. `apply --vex` passes and writes the document +/// of the first, as it did when it attested it as patched. So does `vex`, +/// which reports both as skipped, each with its own code. +#[test] +fn an_installed_patch_is_affected_beside_a_patch_that_is_omitted_for_another_reason() { + let (cell, standin, patch, entry) = checkout(""); + let names = names(&cell, MODULE, LOCK); + patches_the_installed_copy(&cell, &standin, "", &patch, &entry, Some(&names)); + + let manifest = ".socket/manifest.json"; + let mut recorded: Value = serde_json::from_str(&text(&cell.tree(), manifest)).expect(manifest); + let patches = recorded["patches"].as_object_mut().expect("the patches"); + let [(_, record)] = &patches.iter().collect::>()[..] else { + panic!("not one patch: {patches:?}"); + }; + let mut absent = (*record).clone(); + absent["uuid"] = uuid::Uuid::new_v4().to_string().into(); + let other = "pkg:npm/%40socketsecurity/bazel-fixture-absent@1.0.0"; + patches.insert(other.to_string(), absent); + cell.write( + manifest, + serde_json::to_vec_pretty(&recorded).expect(manifest), + ); + + let document = cell.document("beside"); + let apply = [&["apply"][..], &with_vex(&document)].concat(); + let apply = socket_patch(&cell, &standin, &apply); + assert_eq!(apply.envelope["status"], "success", "{}", apply.dump); + cell.wrote_in_run( + &apply, + &document, + &Claim::unbuilt(PURL, &patch.uuid, &names), + ); + + let alone = cell.document("alone"); + let vex = ["vex", "--output", alone.to_str().expect("a path")]; + let vex = socket_patch(&cell, &standin, &vex); + let (test, said) = (&cell.test, &vex.dump); + assert_eq!(vex.code, 0, "{test}: {said}"); + assert_eq!(vex.envelope["status"], "partialFailure", "{test}: {said}"); + let ours = (canonical_purl(PURL), "skipped".into(), NOT_IN_BUILD.into()); + let absent = ( + canonical_purl(other), + "skipped".into(), + "package_not_found".into(), + ); + assert_eq!(reported(&vex.envelope), [ours, absent], "{test}: {said}"); + let written: Value = + serde_json::from_str(&std::fs::read_to_string(&alone).expect("a document")) + .expect("a JSON document"); + let statuses: Vec<&Value> = (written["statements"].as_array().into_iter().flatten()) + .map(|statement| &statement["status"]) + .collect(); + assert_eq!(statuses, ["affected"], "{test}: {written:#}"); +} + +/// A second package in the checkout of `cell`, patched in its installed +/// copy alone, as agent mode leaves one: an entry of the lock as pnpm +/// writes one for a registry package, the patched files where +/// `pnpm install` puts them, and the patched file among the blobs. Gives +/// its patch, its purl and the record agent mode keeps in the manifest, +/// which names the advisory of the fixture's own patch. +fn second_installed_patch(cell: &Cell) -> (Patched, String, Value) { + let second = Patched::new(); + let renamed = |text: &str| text.replace("upstream", "second"); + let (name, purl) = (renamed(NAME), renamed(PURL)); + let lock = text(&cell.tree(), LOCK); + let snapshots = "\nsnapshots:\n"; + assert_eq!(lock.matches(snapshots).count(), 1, "{lock}"); + let entry = renamed(&lock_entry(&placeholder())); + cell.write( + LOCK, + lock.replace(snapshots, &format!("\n{entry}{snapshots}")), + ); + let store = renamed(&store()); + cell.write(&format!("{store}/package.json"), renamed(MANIFEST)); + cell.write(&format!("{store}/index.js"), &second.package.index_js); + let link = cell.path(&format!("node_modules/{name}")); + std::fs::create_dir_all(link.parent().expect("the scope")).expect("create the scope"); + std::os::unix::fs::symlink(store.replacen("node_modules/", "../", 1), &link) + .expect("link the package"); + let mut record = record(&Package::upstream(), &second); + record["purl"] = purl.as_str().into(); + record["exportedAt"] = record["publishedAt"].take(); + let patched = record["files"]["package/index.js"]["afterHash"].as_str(); + let blob = format!(".socket/blobs/{}", patched.expect("a hash")); + cell.write(&blob, &second.package.index_js); + (second, purl, record) +} + +/// What `vex --output ` of `cell` says to a script and to a person, +/// in a checkout where it writes a document: it exits 0 both times. Gives +/// the envelope's status, its events (each as its purl, its action, its +/// code and the status of its details, in the order of the purls), the +/// verified and skipped counts of its summary, the codes of its warnings, +/// the statements of the document without their times, and the lines with +/// which it tells a person what it wrote: to the file, to the file had it +/// not been a dry run, and to stdout. +fn vex_says(cell: &Cell, standin: &StandIn, name: &str) -> (Value, Vec, [String; 3]) { + let path = cell.document(name); + let args = ["vex", "--output", path.to_str().expect("a path")]; + let vex = socket_patch(cell, standin, &args); + let (test, said) = (&cell.test, &vex.dump); + assert_eq!(vex.code, 0, "{test}: {said}"); + let events = vex.envelope["events"].as_array().into_iter().flatten(); + let mut events: Vec = events + .map(|event| { + let purl = canonical_purl(event["purl"].as_str().unwrap_or_default()); + let (code, status) = (&event["errorCode"], &event["details"]["status"]); + json!([purl, event["action"], code, status]) + }) + .collect(); + events.sort_by_key(|event| event[0].as_str().map(str::to_string)); + let summary = &vex.envelope["summary"]; + let machine = json!({ + "status": vex.envelope["status"], + "events": events, + "verified": summary["verified"], + "skipped": summary["skipped"], + "warnings": codes_in(&vex.envelope["warnings"]), + }); + let written = std::fs::read_to_string(&path).expect("a document"); + let mut document: Value = serde_json::from_str(&written).expect("a JSON document"); + let statements = document["statements"].as_array_mut().expect("statements"); + for statement in statements.iter_mut() { + let object = statement.as_object_mut().expect("a statement"); + assert!(object.remove("timestamp").is_some(), "{written}"); + } + let origin = standin.origin(); + let env = [("SOCKET_PATCH_SERVER_URL", origin.as_str())]; + let told = |args: &[&str], starts: &str| { + let streams = cell.socket_patch_person(&origin, args, &env); + assert!(!streams[1].contains("Error"), "{test}: {streams:?}"); + let mut lines = streams.iter().flat_map(|stream| stream.lines()); + let line = lines.find(|line| line.starts_with(starts)); + let line = line.unwrap_or_else(|| panic!("{test}: no {starts:?} line: {streams:?}")); + line.replace(path.to_str().expect("a path"), "") + }; + let dry = [&args[..], &["--dry-run"]].concat(); + let wrote = [ + told(&args, "Wrote "), + told(&dry, "[dry-run] "), + told(&args[..1], "Emitted "), + ]; + println!("{test}: the document of `vex`:\n{written}"); + (machine, std::mem::take(statements), wrote) +} + +/// The statement of a document of the fixture's product about the package +/// `id` and the advisory of the fixture's patches, without its status. +fn about(id: &Value) -> Value { + json!({ + "vulnerability": { "name": "GHSA-test-aaaa-bbbb", "aliases": ["CVE-2024-0001"] }, + "products": [{ "@id": PRODUCT, "subcomponents": [{ "@id": id }] }], + }) +} + +/// Without a Bazel: a document says of each package what Bazel builds of +/// it. Hosted mode pinned the fixture's package in the lock, which rules_js +/// builds it from. The lock lists a second package, which is patched in its +/// installed copy alone, as agent mode leaves one, and both patches are for +/// the same advisory. `vex` and `apply --vex` exit 0, and their document +/// holds two statements for that advisory: the first package is not +/// affected, through its pin, and the second is affected, with what to do +/// about it. `vex` reports the first as verified and the second as +/// skipped, so the run is a partial failure, and tells a person how many +/// of the statements say affected; `apply --vex` counts them in its +/// envelope. +#[test] +fn a_document_says_of_each_package_what_bazel_builds_of_it() { + let (cell, standin, patch, _) = checkout(""); + std::fs::remove_dir_all(cell.path("node_modules")).expect("remove the installed tree"); + pins_the_lock(&cell, &standin, &patch); + let (second, purl, record) = second_installed_patch(&cell); + let manifest = json!({ "patches": { purl.as_str(): record } }); + cell.write(".socket/manifest.json", manifest.to_string()); + + let names = names(&cell, MODULE, LOCK); + let (machine, statements, wrote) = vex_says(&cell, &standin, "each"); + let test = &cell.test; + let (first, other) = (canonical_purl(PURL), canonical_purl(&purl)); + let expected = json!({ + "status": "partialFailure", + "events": [ + [other, "skipped", NOT_IN_BUILD, "affected"], + [first, "verified", null, "not_affected"], + ], + "verified": 1, + "skipped": 1, + "warnings": [NOT_IN_BUILD], + }); + assert_eq!(machine, expected, "{test}"); + let told = [ + "Wrote OpenVEX document with 2 statements (1 affected) to ", + "[dry-run] Would write OpenVEX document with 2 statements (1 affected) to ", + "Emitted 2 VEX statements (1 affected)", + ]; + assert_eq!(wrote, told, "{test}"); + + let ids = statements + .iter() + .map(|statement| &statement["products"][0]["subcomponents"][0]["@id"]); + let ids: Vec<&Value> = ids.collect(); + let mut expected = [about(ids[0]), about(ids[1])]; + expected[0]["status"] = "not_affected".into(); + expected[0]["justification"] = "inline_mitigations_already_exist".into(); + let impact = format!("Patched via Socket patch {} (redirected)", patch.uuid); + expected[0]["impact_statement"] = impact.into(); + expected[1]["status"] = "affected".into(); + expected[1]["action_statement"] = action(&second, &names[0]).into(); + assert_eq!(statements, expected, "{test}"); + let named: Vec = ids + .iter() + .map(|id| canonical_purl(id.as_str().unwrap_or_default())) + .collect(); + assert_eq!(named, [first, other], "{test}"); + + let in_run = cell.document("each-apply"); + let apply = [&["apply"][..], &with_vex(&in_run)].concat(); + let apply = socket_patch(&cell, &standin, &apply); + let (summary, said) = (&apply.envelope["vex"], &apply.dump); + assert_eq!(apply.code, 0, "{test}: {said}"); + let counted = [&summary["statements"], &summary["affected"]]; + assert_eq!(counted, [&json!(2), &json!(1)], "{test}: {said}"); + assert_eq!( + codes_in(&summary["warnings"]), + [NOT_IN_BUILD], + "{test}: {said}" + ); +} + +/// Without a Bazel: two packages that are patched in their installed +/// copies alone, by two patches for one advisory, while the hub reads the +/// lock that lists both. `vex` exits 0 with a document of two statements +/// for that advisory, one per package: each names its package alone, and +/// its action statement names the patch of that package. It reports both +/// as skipped and none as verified, warns of each, and tells a person that +/// both statements say affected. +#[test] +fn each_affected_package_of_an_advisory_has_a_statement_of_its_own() { + let (cell, standin, patch, entry) = checkout(""); + let names = names(&cell, MODULE, LOCK); + patches_the_installed_copy(&cell, &standin, "", &patch, &entry, Some(&names)); + let (second, purl, record) = second_installed_patch(&cell); + let manifest = ".socket/manifest.json"; + let mut recorded: Value = serde_json::from_str(&text(&cell.tree(), manifest)).expect(manifest); + recorded["patches"][purl.as_str()] = record; + cell.write(manifest, recorded.to_string()); + + let (machine, statements, wrote) = vex_says(&cell, &standin, "both"); + let test = &cell.test; + let (first, other) = (canonical_purl(PURL), canonical_purl(&purl)); + let expected = json!({ + "status": "partialFailure", + "events": [ + [other, "skipped", NOT_IN_BUILD, "affected"], + [first, "skipped", NOT_IN_BUILD, "affected"], + ], + "verified": 0, + "skipped": 2, + "warnings": [NOT_IN_BUILD, NOT_IN_BUILD], + }); + assert_eq!(machine, expected, "{test}"); + let told = [ + "Wrote OpenVEX document with 2 statements (2 affected) to ", + "[dry-run] Would write OpenVEX document with 2 statements (2 affected) to ", + "Emitted 2 VEX statements (2 affected)", + ]; + assert_eq!(wrote, told, "{test}"); + + let said: Vec<(String, Value)> = statements + .iter() + .map(|statement| { + let id = &statement["products"][0]["subcomponents"][0]["@id"]; + let mut expected = about(id); + expected["status"] = "affected".into(); + expected["action_statement"] = statement["action_statement"].clone(); + assert_eq!(*statement, expected, "{test}"); + let action = statement["action_statement"].clone(); + (canonical_purl(id.as_str().unwrap_or_default()), action) + }) + .collect(); + let expected = [ + (other, json!(action(&second, &names[0]))), + (first, json!(action(&patch, &names[0]))), + ]; + assert_eq!(said, expected, "{test}"); +} + +/// Without a Bazel: a patch whose record names no advisory gets no +/// statement from any run, so the hub decides nothing for it. `apply --vex` +/// over that patch alone fails beside the hub as it fails in the same +/// checkout without a workspace file: the same exit code and envelope, +/// and the same lines for a person, none of them about Bazel. +#[test] +fn a_patch_without_an_advisory_fails_the_run_as_it_does_without_bazel() { + let (cell, standin, patch, entry) = checkout(""); + let names = names(&cell, MODULE, LOCK); + patches_the_installed_copy(&cell, &standin, "", &patch, &entry, Some(&names)); + + let manifest = ".socket/manifest.json"; + let mut recorded: Value = serde_json::from_str(&text(&cell.tree(), manifest)).expect(manifest); + let patches = recorded["patches"].as_object_mut().expect("the patches"); + for record in patches.values_mut() { + record["vulnerabilities"] = json!({}); + } + cell.write( + manifest, + serde_json::to_vec_pretty(&recorded).expect(manifest), + ); + + let document = cell.document("no-advisory"); + let apply = [&["apply"][..], &with_vex(&document)].concat(); + let origin = standin.origin(); + let env = [("SOCKET_PATCH_SERVER_URL", origin.as_str())]; + let run = || { + let ran = socket_patch(&cell, &standin, &apply); + let person = cell.socket_patch_person(&origin, &apply, &env); + (ran.code, ran.envelope, person) + }; + let beside = run(); + std::fs::remove_file(cell.path(MODULE)).expect(MODULE); + assert_eq!(beside, run()); + + let (code, envelope, [_, stderr]) = beside; + let said = format!("{envelope:#}\n{stderr}"); + assert_eq!(code, 1, "{said}"); + let error = json!({ + "code": "no_applicable_patches", + "message": "No applied patches with vulnerability metadata to attest.", + }); + assert_eq!(envelope["error"], error, "{said}"); + assert!(!said.contains("Bazel"), "{said}"); + assert!(!document.exists(), "{said}"); +} + +/// What a case of a test below does to its checkout before the commands +/// run. +type Arrange = fn(&Cell); + +/// The fixture's `MODULE.bazel` in `cell` with `label` as the lock its hub +/// reads. +fn reads(cell: &Cell, label: &str) { + let module = text(&cell.tree(), MODULE); + let own = format!("\"//:{LOCK}\""); + assert!(module.contains(&own), "{module}"); + cell.write(MODULE, module.replace(&own, &format!("\"{label}\""))); +} + +/// Without a Bazel: the package is affected wherever a workspace file +/// hands Bazel the lock of the project, which lists the package. +/// +/// - The hub is in a file that `MODULE.bazel` includes, as a workspace +/// keeps the hubs of one language apart: the document names the call +/// in that file. +/// - The project is a directory of the workspace, and the hub reads the +/// project's lock. +/// - The project is a member of a pnpm workspace at the root, and the hub +/// reads the workspace's lock there, which names the project among its +/// importers. The patched copy is in the store at the root. +#[test] +fn an_installed_patch_is_affected_wherever_a_hub_reads_the_lock_of_the_project() { + let included = "tools/npm.MODULE.bazel"; + let web = format!("web/{LOCK}"); + let cases: [(&str, bool, &str, &str, Arrange); 3] = [ + ("", false, included, LOCK, |cell| { + let module = text(&cell.tree(), MODULE); + let (head, hub) = module.split_once("npm = use_extension(").expect("the hub"); + let include = "include(\"//tools:npm.MODULE.bazel\")\n"; + cell.write(MODULE, format!("{head}{include}")); + cell.write( + "tools/npm.MODULE.bazel", + format!("npm = use_extension({hub}"), + ); + }), + ("web/", false, MODULE, &web, |cell| { + reads(cell, &format!("//web:{LOCK}")); + }), + ("web/", true, MODULE, LOCK, |_| ()), + ]; + for (project, member, file, lock, arrange) in cases { + let (mut cell, standin, patch, entry) = checkout_of(project, member); + cell.test = format!("{project:?}, {member}, {file}, {lock}"); + arrange(&cell); + let names = names(&cell, file, lock); + patches_the_installed_copy(&cell, &standin, project, &patch, &entry, Some(&names)); + } +} + +/// Without a Bazel: `scan --mode hosted --vex` over the patch that agent +/// mode left in the installed copy, at a patch service that has no hosted +/// artifact of it. The scan pins nothing, skips the package and passes, as +/// it does without `--vex`. Its document says the package is affected, +/// and names the call that builds it from the lock, in its envelope and as +/// a person runs it. +#[test] +fn an_installed_patch_is_affected_after_a_hosted_scan_that_pins_nothing() { + let (cell, standin, patch, entry) = checkout(""); + let names = names(&cell, MODULE, LOCK); + patches_the_installed_copy(&cell, &standin, "", &patch, &entry, Some(&names)); + let patched = cell.tree(); + drop(standin); + let other = StandIn::start(); + let granted = Patch { + purl: PURL.to_string(), + uuid: patch.uuid.clone(), + reference: json!({ "status": "granted", "purl": PURL }), + }; + other.api(&[granted]); + + let document = cell.document("hosted"); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let hosted = [&hosted[..], &with_vex(&document)].concat(); + let scan = socket_patch(&cell, &other, &hosted); + let (test, said) = (&cell.test, &scan.dump); + let skipped = [(canonical_purl(PURL), "skipped".into(), "no_url".into())]; + assert_eq!(reported(&scan.envelope), skipped, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + // A hosted scan says of every document it writes that it hashed no + // file for a hosted patch. + let summary = &scan.envelope["vex"]; + let counted = [&summary["statements"], &summary["affected"]]; + assert_eq!(counted, [&json!(1), &json!(1)], "{test}: {said}"); + let warned = ["vex_hosted_unverified", NOT_IN_BUILD]; + assert_eq!(codes_in(&summary["warnings"]), warned, "{test}: {said}"); + let claim = Claim::unbuilt(PURL, &patch.uuid, &names); + + let origin = other.origin(); + let env = [("SOCKET_PATCH_SERVER_URL", origin.as_str())]; + let warned = warns(&patch, &names[0]); + cell.tells_a_person(&origin, &hosted, &env, &document, &claim, &warned); + let silent = [&hosted[..], &["--silent"]].concat(); + cell.tells_a_person(&origin, &silent, &env, &document, &claim, &warned); + assert_eq!(changed(&patched, &cell.tree()), NOTHING, "{test}"); +} + +/// Without a Bazel: workspaces that give `socket-patch` no ground to say +/// that the package is affected, each made from the fixture's +/// `MODULE.bazel`. Every form says of the installed patch what it says in +/// a checkout without Bazel. +/// +/// - The project is a directory of the workspace, and the hub reads the +/// lock of another directory beside it, which lists the package too: +/// Bazel builds nothing of this project. +/// - The project is a directory of the workspace with a lock of its own, +/// which no hub reads. The hub reads a lock at the root, above the +/// project, that lists the package too and does not name the project +/// among its importers: the lock of another project. +/// - The hub reads a lock below the project that lists the package too: +/// again the lock of another project. +/// - The hub's lines are a comment. +/// - The workspace cannot be read with certainty: it includes a file that +/// is not there, so calls may be missing from what was read. +/// - A `WORKSPACE` file defines repositories of its own, which the module +/// files do not show; Bazel 7 reads it beside them. +#[test] +fn an_installed_patch_is_attested_where_no_hub_is_shown_to_build_it() { + let cases: [(&str, &str, Arrange); 6] = [ + ("the lock of another project", "web/", |cell| { + let lock = text(&cell.tree(), &format!("web/{LOCK}")); + cell.write(&format!("other/{LOCK}"), lock); + reads(cell, &format!("//other:{LOCK}")); + }), + ( + "a lock above that does not name the project", + "web/", + |cell| { + cell.write(LOCK, text(&cell.tree(), &format!("web/{LOCK}"))); + }, + ), + ("a lock below the project", "", |cell| { + cell.write(&format!("tools/{LOCK}"), text(&cell.tree(), LOCK)); + reads(cell, &format!("//tools:{LOCK}")); + }), + ("a hub in a comment", "", |cell| { + let module = text(&cell.tree(), MODULE); + let (head, hub) = module.split_once("npm = use_extension(").expect("the hub"); + let hub = format!("npm = use_extension({hub}"); + let comment: String = hub.lines().map(|line| format!("# {line}\n")).collect(); + cell.write(MODULE, format!("{head}{comment}")); + }), + ("an included file that is missing", "", |cell| { + let module = text(&cell.tree(), MODULE); + let include = "include(\"//tools:missing.MODULE.bazel\")\n"; + cell.write(MODULE, format!("{module}{include}")); + }), + ("a WORKSPACE file that defines repositories", "", |cell| { + let rule = "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n"; + cell.write("WORKSPACE", rule); + }), + ]; + for (case, project, arrange) in cases { + let (mut cell, standin, patch, entry) = checkout(project); + cell.test = case.to_string(); + arrange(&cell); + patches_the_installed_copy(&cell, &standin, project, &patch, &entry, None); + } +} + +/// Without a Bazel: what makes a package affected is a patch in a copy +/// Bazel does not build from, and a hosted pin is none. Here a second hub +/// reads a second lock in the project's directory, under a name of its +/// own, that lists the package without the patch, as the project's lock +/// did before hosted mode pinned it there. Hosted mode pins the project's +/// lock and no other, and its document and the one of `vex` attest the +/// package, as they do without the second hub. Whether Bazel links the +/// package from that other lock is not looked at yet. Nothing is installed +/// in this checkout: an installed copy without the patch leaves a hosted +/// pin out of the document with or without Bazel. +#[test] +fn a_hosted_pin_is_attested_beside_a_second_hub_that_lists_the_package() { + let (cell, standin, patch, _) = checkout(""); + std::fs::remove_dir_all(cell.path("node_modules")).expect("remove the installed tree"); + let beside = format!("tools.{LOCK}"); + cell.write(&beside, text(&cell.tree(), LOCK)); + let module = text(&cell.tree(), MODULE); + let second = format!( + "npm.npm_translate_lock(\n name = \"tools\",\n pnpm_lock = \"//:{beside}\",\n)\n" + ); + cell.write( + MODULE, + format!("{module}{second}use_repo(npm, \"tools\")\n"), + ); + let pinned = pins_the_lock(&cell, &standin, &patch); + assert!(text(&pinned, LOCK).contains(&patch.uuid), "{LOCK}"); + assert!(!text(&pinned, &beside).contains(&patch.uuid), "{beside}"); +} + /// Without a Bazel, what stays fixed now that no sum is committed: the /// 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 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 5d48ad304..336469dea 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -1,9 +1,9 @@ -//! Hosted mode for a PyPI package that comes through rules_python's -//! `pip.parse(requirements_lock = "//:requirements.txt")` under Bzlmod: a -//! root `requirements.txt` in pip's hash-checking mode. +//! Hosted and vendored mode for a PyPI package that comes through +//! rules_python's `pip.parse(requirements_lock = "//:requirements.txt")` +//! under Bzlmod: a root `requirements.txt` in pip's hash-checking mode. //! -//! One flow, on the Bazel the run is given ([`FIXTURE`] says which ruleset -//! goes with its release), in a fresh output base: +//! The hosted flow, on the Bazel the run is given ([`FIXTURE`] says which +//! ruleset goes with its release), in a fresh output base: //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker. The hub asked the index about the package, and Bazel fetched @@ -42,6 +42,15 @@ //! 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. //! +//! The vendored flow ([`vendored_pip_parse`]) commits the patched wheel and +//! points the package's line of `requirements.txt` at it. rules_python +//! builds no wheel from such a line: the build fails until +//! `vendor --revert` has put the pin back. The flow asserts that; that +//! every form of `vex` meanwhile writes a document that says the package +//! is affected, and names the call of `MODULE.bazel` that reads the file; +//! and that the revert and hosted mode, which the document names, end in +//! the patched build and in a document that says not affected. +//! //! 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 //! the index, and the JSON document `rollback` reads through @@ -80,12 +89,15 @@ 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 crate::harness::{ - changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, Tree, - CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, + StandIn, Tree, CONSUMER, NOTHING, }; -use crate::hosted_memory_common::Patch; +use crate::hosted_memory_common::{read_tree, Patch, ORG}; // The wheel builder of the in-process Python suites. Its other helpers // mount a grant on a server of those suites. @@ -191,8 +203,12 @@ impl Wheel { /// wheel has bytes, and a sha256, that no other run has: Bazel's repository /// cache, which keeps every download that has a checksum, cannot hold it. fn package(marker: &str, run: &str) -> Wheel { - let module = format!("# Built for run {run}.\ndef value():\n return \"{marker}\"\n"); - Wheel::new(NAME, VERSION, &["spdep"], &module) + Wheel::new(NAME, VERSION, &["spdep"], &module(marker, run)) +} + +/// The one module of [`package`]: `spvictim/__init__.py`. +fn module(marker: &str, run: &str) -> String { + format!("# Built for run {run}.\ndef value():\n return \"{marker}\"\n") } /// The upstream wheels of the run `run`, as the index serves them: the @@ -239,6 +255,11 @@ fn publish(standin: &StandIn, wheel: &Wheel) { /// is the one `patched_wheel::mount_grant` also writes, for a server of the /// in-process suites: a change to the shape of a grant is a change to both. fn grant(standin: &StandIn, uuid: &str, pinned: &Wheel) -> String { + grant_by(standin, uuid, pinned, json!({ "sha256": pinned.sha256 })) +} + +/// [`grant`] with `integrity` as the sums the grant names for the wheel. +fn grant_by(standin: &StandIn, uuid: &str, pinned: &Wheel, integrity: Value) -> String { let filename = pinned.filename(); let route = format!("/patch/pypi/{NAME}/{VERSION}/grant-token/{uuid}/{filename}"); let url = format!("{}{route}", standin.origin()); @@ -249,7 +270,7 @@ fn grant(standin: &StandIn, uuid: &str, pinned: &Wheel) -> String { "artifacts": [{ "kind": "tarball", "url": url, - "integrity": { "sha256": pinned.sha256 }, + "integrity": integrity, }], "registryOverride": null, }); @@ -539,6 +560,389 @@ fn hosted_pip_parse() { ); } +/// What the vendored flow patches with: the upstream wheels of a run on a +/// stand-in index, and one patch of the package, which the Socket API on +/// the stand-in grants as a wheel on its patch host and records with the +/// hashes of the module it changes. Vendored mode holds the wheel it +/// downloads to that record. +struct Vendoring { + standin: StandIn, + /// The id of the run and of its patch. + uuid: String, + wheels: [Wheel; 2], + patched: Wheel, + /// The record of the patch, as the API serves it. + record: Value, +} + +/// The line of `requirements.txt` that vendored mode puts in the place of +/// the package's pin: the path of the committed wheel `copy`, its sha256, +/// and the pin it stands for. +fn vendored_line(copy: &str, wheel: &Wheel) -> String { + let (sha256, name, version) = (&wheel.sha256, wheel.name, wheel.version); + format!("./{copy} --hash=sha256:{sha256} # socket-patch vendor: {name}=={version}\n") +} + +impl Vendoring { + fn new() -> Vendoring { + let uuid = uuid::Uuid::new_v4().to_string(); + let wheels = upstream(&uuid); + let marker = format!("PATCHED {uuid}"); + let patched = package(&marker, &uuid); + let standin = StandIn::start(); + wheels.iter().for_each(|wheel| publish(&standin, wheel)); + standin.serve(5, OTHER_PROJECTS, NO_FILES.as_bytes()); + // Vendored mode downloads the wheel itself, and takes it only by + // its sha512. + let sha512 = + base64::engine::general_purpose::STANDARD.encode(Sha512::digest(&patched.bytes)); + let sums = json!({ "sha256": patched.sha256, "sha512": format!("sha512-{sha512}") }); + let route = grant_by(&standin, &uuid, &patched, sums); + standin.serve(5, &route, &patched.bytes); + let hash = |marker: &str| compute_git_sha256_from_bytes(module(marker, &uuid).as_bytes()); + let record = json!({ + "uuid": uuid, + "purl": PURL, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { "spvictim/__init__.py": { + "beforeHash": hash("PRISTINE"), + "afterHash": hash(&marker), + }}, + "vulnerabilities": { "GHSA-test-aaaa-bbbb": { + "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "fixture", + "license": "MIT", + "tier": "free", + }); + let record_route = format!("/v0/orgs/{ORG}/patches/view/{uuid}"); + standin.serve(1, &record_route, record.to_string().as_bytes()); + Vendoring { + standin, + uuid, + wheels, + patched, + record, + } + } + + /// `socket-patch ` in `cell`, with the stand-in as the Socket + /// API, the patch server and the index's JSON API. + fn run(&self, cell: &Cell, args: &[&str]) -> Ran { + let origin = self.standin.origin(); + let json_api = format!("{origin}/{INDEX}/pypi"); + let env = [ + ("SOCKET_PATCH_SERVER_URL", origin.as_str()), + ("SOCKET_PYPI_JSON_API", json_api.as_str()), + ]; + cell.socket_patch(&origin, args, &env) + } +} + +/// What `socket-patch` has to name when it says that the package is +/// affected: the file that points at the committed wheel, the hub's call +/// with its line in the `MODULE.bazel` of `cell`, and the two commands +/// that patch what Bazel builds. +fn names(cell: &Cell) -> Vec { + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let above = module.lines().take_while(|line| *line != "pip.parse("); + vec![ + format!("the line of {REQUIREMENTS} that points at"), + format!("(`pip.parse`, MODULE.bazel:{})", above.count() + 1), + "`socket-patch vendor --revert`, then `socket-patch scan --mode hosted`".to_string(), + ] +} + +/// Vendored mode in the checkout of `cell`, whose `requirements.txt` pins +/// the wheels of `with`: `scan --mode vendored --yes` commits the patched +/// wheel under `.socket/vendor/pypi` and points the package's line of +/// `requirements.txt` at it. The command passes, and with `--vex` it +/// writes a document that says the package is affected; so do +/// `apply --vex` and `vendor --vex`, and `vex` and `vex --no-verify`. Each +/// names the call of `MODULE.bazel` that hands `requirements.txt` to +/// rules_python, and the way out. Gives the files of the checkout. +fn vendors_the_wheel(cell: &Cell, with: &Vendoring) -> Tree { + let test = &cell.test; + let before = cell.tree(); + let run = |cell: &Cell, args: &[&str]| with.run(cell, args); + + let in_run = cell.document("in-run"); + let vendoring = ["scan", "--mode", "vendored", "--yes"]; + 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}"); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); + // The wheel the patch host served, with its ledger under + // `.socket/vendor`, and the one file that names it. + let vendored = cell.tree(); + let dir = format!(".socket/vendor/pypi/{}", with.uuid); + let copy = format!("{dir}/{}", with.patched.filename()); + let written = [ + format!("{dir}/.gitattributes"), + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + copy.clone(), + ".socket/vendor/state.json".to_string(), + REQUIREMENTS.to_string(), + ]; + assert_eq!(changed(&before, &vendored), written, "{test}: {said}"); + assert!(vendored[©] == with.patched.bytes, "{test}: {copy}"); + let [dependency, _] = &with.wheels; + let rewritten = dependency.requirement() + &vendored_line(©, &with.patched); + let requirements = String::from_utf8_lossy(&vendored[REQUIREMENTS]); + assert_eq!(requirements, rewritten, "{test}: {said}"); + + let names = names(cell); + let claim = Claim::unbuilt(PURL, &with.uuid, &names); + cell.wrote_in_run(&scan, &in_run, &claim); + // A vendored checkout has no manifest: the two commands have nothing + // to do, and write the document the scan wrote. + for command in ["apply", "vendor"] { + let document = cell.document(command); + let ran = run(cell, &[&[command][..], &with_vex(&document)].concat()); + assert_eq!(ran.envelope["status"], "noManifest", "{test}: {}", ran.dump); + cell.wrote_in_run(&ran, &document, &claim); + } + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + vendored +} + +/// What the document of an affected package tells the user to do, in the +/// checkout of `cell` that vendored mode patched: `vendor --revert` puts +/// every file back as it was in `before`, and `scan --mode hosted --yes` +/// then pins the patch of `with` in `requirements.txt`. Its document and +/// the one of `vex` attest the package, through the pin. +fn reverts_and_pins(cell: &Cell, with: &Vendoring, before: &Tree) { + let test = &cell.test; + let run = |cell: &Cell, args: &[&str]| with.run(cell, args); + let undo = run(cell, &["vendor", "--revert", "--yes"]); + let said = &undo.dump; + assert_eq!(undo.code, 0, "{test}: {said}"); + assert_eq!(undo.envelope["summary"]["removed"], 1, "{test}: {said}"); + assert_eq!(changed(before, &cell.tree()), NOTHING, "{test}: {said}"); + + let claim = Claim::new(PURL, &with.uuid, How::Hosted); + let document = cell.document("hosted"); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let scan = run(cell, &[&hosted[..], &with_vex(&document)].concat()); + cell.pinned_by(&scan, PURL, &with.uuid, before, &[REQUIREMENTS]); + cell.wrote_in_run(&scan, &document, &claim); + cell.stands_alone(run, &claim, true); +} + +/// Vendored mode beside a hub that reads `requirements.txt`. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the unpatched +/// marker. +/// - (b) `scan --mode vendored --yes` commits the patched wheel and points +/// the package's line of `requirements.txt` at it +/// ([`vendors_the_wheel`]). The command passes, and it and every other +/// form of `vex` write a document that says the package is affected: +/// each names the call of `MODULE.bazel` that reads the file, and the +/// way out. +/// - (c) The same `bazel build` fails, as the document said it may: +/// rules_python takes the path of that line for the name of a project +/// and leaves the hub without a repository it can name. No build holds +/// the patched wheel, and `vex` says affected again. +/// - (d) What the document says to do ([`reverts_and_pins`]): +/// `vendor --revert` puts every file back, `scan --mode hosted --yes` +/// pins the patch in `requirements.txt`, the same two Bazel commands +/// print the patched marker, and `vex` attests the package as not +/// affected. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_pip_parse() { + let test = "pypi::vendored_pip_parse"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let with = Vendoring::new(); + cell.route_downloads(&downloads(&with.standin.origin(), &with.wheels)); + cell.write(REQUIREMENTS, requirements(&with.wheels)); + + // (a) The unpatched build. + let before = cell.builds_unpatched(UNPATCHED); + + // (b) Vendored mode commits the wheel, and says it is affected. + let vendored = vendors_the_wheel(&cell, &with); + + // (c) The build fails on the line that names the committed wheel, and + // changes no file of the checkout. + let build = cell.bazel("build", &[CONSUMER]); + let named = with.patched.filename().replace(['-', '.'], "_"); + assert!( + !build.ok() && build.stderr().contains(&named), + "{test}: the build did not fail on the vendored line ({named}):\n{}", + build.dump() + ); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + let run = |cell: &Cell, args: &[&str]| with.run(cell, args); + let names = names(&cell); + cell.stands_alone(run, &Claim::unbuilt(PURL, &with.uuid, &names), true); + + // (d) The way out: the undo, then hosted mode, whose pin Bazel builds. + reverts_and_pins(&cell, &with, &before); + let marker = format!("OUT: PATCHED {}", with.uuid); + cell.builds(&marker); + let claim = Claim::new(PURL, &with.uuid, How::Hosted); + cell.stands_alone(run, &claim, true); + + println!( + "{test}: Bazel {release} built {UNPATCHED:?}, and failed to build after `scan --mode \ + vendored`, while every form of `vex` said the package is affected; after `vendor \ + --revert` and `scan --mode hosted` it built {marker:?}, and `vex` said it is not \ + affected; {:?}", + started.elapsed() + ); +} + +/// Without a Bazel: the fixture in a checkout of its own, with the +/// `requirements.txt` that pins the wheels of `with`. +fn checkout(with: &Vendoring) -> Cell { + let cell = cell_without_bazel("9.3.2"); + for part in ["common", "e9"] { + for (rel, bytes) in read_tree(&fixture_path(FIXTURE.dir).join(part)) { + cell.write(&rel, bytes); + } + } + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + cell.write(REQUIREMENTS, requirements(&with.wheels)); + cell +} + +/// Without a Bazel: steps (b) and (d) of [`vendored_pip_parse`] in the +/// fixture's checkout, where `MODULE.bazel` hands `requirements.txt` to +/// rules_python. Between them, `scan --mode vendored --vex`, `vendor --vex` +/// and `apply --vex` as a person runs them: each passes and writes the +/// document, with the warning on stderr, the line that it wrote a document +/// on stdout, and no error; with `--silent` each passes, writes the +/// document and prints nothing. After them, `vendor --vex` moves the +/// hosted pin into a committed copy again, and says affected again. +#[test] +fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { + let with = Vendoring::new(); + let cell = checkout(&with); + let before = cell.tree(); + let names = names(&cell); + assert_eq!(names[1], "(`pip.parse`, MODULE.bazel:15)"); + let vendored = vendors_the_wheel(&cell, &with); + + let origin = with.standin.origin(); + let document = cell.document("person"); + let env = [("SOCKET_PATCH_SERVER_URL", origin.as_str())]; + let warned = format!( + "Warning: {PURL}: the VEX document says affected. Bazel builds no package from {} the \ + copy of Socket patch {} under .socket/vendor {}: the build fails, or takes the \ + registry's package. Run {}.", + names[0], with.uuid, names[1], names[2] + ); + let claim = Claim::unbuilt(PURL, &with.uuid, &names); + let scan = ["scan", "--mode", "vendored", "--yes"]; + for command in [&scan[..], &["vendor"], &["apply"]] { + let loud = [command, &with_vex(&document)].concat(); + cell.tells_a_person(&origin, &loud, &env, &document, &claim, &warned); + let silent = [&loud[..], &["--silent"]].concat(); + cell.tells_a_person(&origin, &silent, &env, &document, &claim, &warned); + } + assert_eq!(changed(&vendored, &cell.tree()), NOTHING); + + reverts_and_pins(&cell, &with, &before); + + // `vendor` in a checkout of hosted pins commits a copy of each: the + // line of `requirements.txt` points at the wheel again. + let ejected = cell.document("eject"); + let eject = [&["vendor", "--yes"][..], &with_vex(&ejected)].concat(); + let eject = with.run(&cell, &eject); + assert_eq!(eject.envelope["status"], "success", "{}", eject.dump); + cell.wrote_in_run(&eject, &ejected, &claim); + let line = String::from_utf8_lossy(&cell.tree()[REQUIREMENTS]).into_owned(); + assert!(line.contains(".socket/vendor/pypi/"), "{line}"); +} + +/// Without a Bazel: `vendor --vex` in a checkout whose manifest records +/// the patch, as agent mode leaves one. It commits the wheel, points +/// `requirements.txt` at it, and passes; its document says the package is +/// affected and names the call that reads the file, as the scan of +/// [`vendors_the_wheel`] does. +#[test] +fn a_wheel_vendored_from_a_manifest_is_affected_beside_the_hub() { + let with = Vendoring::new(); + let cell = checkout(&with); + let mut record = with.record.clone(); + record["exportedAt"] = record["publishedAt"].take(); + let manifest = json!({ "patches": { PURL: record } }); + cell.write(".socket/manifest.json", manifest.to_string()); + + let document = cell.document("vendor"); + let vendor = [&["vendor", "--yes"][..], &with_vex(&document)].concat(); + let vendor = with.run(&cell, &vendor); + let line = String::from_utf8_lossy(&cell.tree()[REQUIREMENTS]).into_owned(); + assert!( + line.contains(".socket/vendor/pypi/"), + "{line}\n{}", + vendor.dump + ); + assert_eq!(vendor.envelope["status"], "success", "{}", vendor.dump); + let names = names(&cell); + cell.wrote_in_run( + &vendor, + &document, + &Claim::unbuilt(PURL, &with.uuid, &names), + ); +} + +/// Without a Bazel: `vex` with a `--manifest-path` in another project +/// attests that project, and asks the workspace about the files of that +/// project. The checkout holds `svc`, where vendored mode pointed +/// `requirements.txt` at the wheel, and `app`, where the command is run. +/// While the hub reads the file of `svc`, the document says the package +/// is affected and names that file. While it reads the file of `app`, +/// which pins the same release, the wheel of `svc` is attested as +/// patched: no call hands Bazel the file that points at it. +#[test] +fn a_vendored_wheel_is_judged_by_the_files_of_the_manifest_s_project() { + let with = Vendoring::new(); + let cell = checkout(&with); + std::fs::remove_file(cell.path(REQUIREMENTS)).expect(REQUIREMENTS); + for project in ["svc", "app"] { + cell.write( + &format!("{project}/{REQUIREMENTS}"), + requirements(&with.wheels), + ); + } + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let own = format!("\"//:{REQUIREMENTS}\""); + assert!(module.contains(&own), "{module}"); + let reads = |project: &str| { + let label = format!("\"//{project}:{REQUIREMENTS}\""); + cell.write("MODULE.bazel", module.replace(&own, &label)); + }; + reads("svc"); + let vendoring = ["scan", "--mode", "vendored", "--yes", "--cwd", "svc"]; + let scan = with.run(&cell, &vendoring); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + + let foreign = [ + "--cwd", + "app", + "--manifest-path", + "../svc/.socket/manifest.json", + ]; + let run = |cell: &Cell, args: &[&str]| with.run(cell, &[args, &foreign].concat()); + let mut names = names(&cell); + names[0] = format!("the line of svc/{REQUIREMENTS} that points at"); + cell.stands_alone(run, &Claim::unbuilt(PURL, &with.uuid, &names), true); + + reads("app"); + let claim = Claim::new(PURL, &with.uuid, How::Vendored); + cell.stands_alone(run, &claim, true); +} + /// Without a Bazel: the fixture's directories are those of its table, and /// the workflow runs each release on its era. The fixture holds no /// `requirements.txt`: every era names the one the test writes, which pins diff --git a/crates/socket-patch-cli/tests/in_process_alternate_installers.rs b/crates/socket-patch-cli/tests/in_process_alternate_installers.rs index 0fbbab596..2d16db2ef 100644 --- a/crates/socket-patch-cli/tests/in_process_alternate_installers.rs +++ b/crates/socket-patch-cli/tests/in_process_alternate_installers.rs @@ -1250,6 +1250,7 @@ async fn apply_check_and_vex_see_unpatched_member_named_like_a_build_dir() { output: Some(vex_path.clone()), product: Some("pkg:npm/root@1.0.0".to_string()), no_verify: false, + no_bazel: false, doc_id: None, compact: false, }) @@ -1321,6 +1322,7 @@ async fn apply_check_and_vex_see_unpatched_member_in_a_hidden_dir() { output: Some(vex_path.clone()), product: Some("pkg:npm/root@1.0.0".to_string()), no_verify: false, + no_bazel: false, doc_id: None, compact: false, }) diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs new file mode 100644 index 000000000..6c86baad8 --- /dev/null +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -0,0 +1,1012 @@ +//! Whether the Bazel build of a workspace takes the copy of a package that +//! socket-patch patched. +//! +//! Three rulesets hand the packages of an ecosystem to Bazel through one +//! tag of a module extension, a hub: aspect_rules_js reads a pnpm lock +//! (`npm.npm_translate_lock`), rules_python reads requirements files +//! (`pip.parse`) and rules_ruby reads a Gemfile and its lock +//! (`ruby.bundle_fetch`). Each fetches what those files name into +//! repositories of Bazel's own and builds from there. None of them reads +//! what a package manager installed in the checkout (`node_modules`, a +//! virtualenv, a gem home), so a patch that is only in such a copy is not +//! in the build. And rules_python builds no package from a line that +//! points at a copy committed under `.socket/vendor`: 2.5.0-rc4 takes the +//! path for the name of a project and fails the build of everything the +//! hub serves (Bazel 9.3.2, 8.8.2 and 7.7.2). rules_js does build a +//! vendored tarball. What rules_ruby does with a vendored gem no build has +//! shown, so a vendored gem is not judged. +//! +//! [`unbuilt`] names, for a patched package, the call that builds it from a +//! file without its patch. It says so only when the files of the workspace +//! show it: the reader's answer is certain ([`Workspace::doubts`] and the +//! [`Tags::doubts`] of the hub are empty), no `WORKSPACE` file defines +//! anything beside the module files ([`Workspace::legacy`]), the call names +//! the file as a plain string, and the file can be read and says so +//! plainly. In every other case it says nothing, and what socket-patch +//! says of the package is what it says without Bazel. +//! +//! For an installed copy the file must be the project's own lock: the one +//! in the project's directory, or the lock of a pnpm workspace above it +//! that names that directory among its importers. A lock elsewhere that +//! lists the same package (in a directory beside the project, below it, or +//! above it without naming it) is the lock of another project, and says +//! nothing of this one: a project of the checkout that Bazel does not +//! build keeps what socket-patch says of it. +//! +//! Only a call that is a statement of its own counts ([`Call::whole`]): +//! it runs, once. One in a comprehension, behind an `and`, in a +//! conditional or in the arguments of another call may never run, and is +//! passed over. So is a call that passes `*` or `**`, whose arguments are +//! not all written out, and a `pip.parse` with `uv_lock`: rules_python +//! (2.2.0 and later) can take the packages of such a call from that file +//! alone, which is not read here. +//! +//! A lock is read like a file of the workspace ([`disk`]): never through a +//! link that leads out of the Bazel root, although Bazel follows such a +//! link. It is read only when it lies where the project's own lock can +//! lie, once however many calls name it, and up to 64 MiB; its text is +//! searched once for the patches of all the packages, and not kept. Of a +//! pnpm lock the project documents are read, for their keys alone: +//! rules_js links nothing of the document pnpm 11 keeps for its own +//! configuration. +//! +//! Not looked at: what a `--override_repository` or an rc file changes, +//! BUILD files, and hubs of other rulesets. +//! +//! [`Tags::doubts`]: super::workspace::Tags::doubts + +use std::collections::{HashMap, HashSet}; +use std::io::Read; +use std::path::{Component, Path}; + +use aho_corasick::AhoCorasick; + +use super::starlark::{Call, Value}; +use super::workspace::{disk, Extension, Repo, Workspace}; +use crate::formats::gem::locked_specs; +use crate::formats::pnpm::grammar::documents; +use crate::formats::pnpm::workspace::lock_text_member_importers; +use crate::formats::pnpm::{pnpm_registry_key, PnpmDocument, PnpmLock}; +use crate::utils::fs::{open_regular_file_sync, run_blocking}; +use crate::utils::group_commit; +use crate::utils::purl::purl_parts; +use crate::utils::purl_key::PurlKey; +use crate::utils::requirements::{exact_pin, logical_lines, strip_comment}; + +/// A package that socket-patch patched in a project, and where the patch +/// is. +#[derive(Debug, Clone)] +pub struct Patched { + /// `pkg:npm/left-pad@1.3.0`, in any spelling. + pub purl: String, + /// The id of the patch. + pub uuid: String, + /// `None`: the patch is in the copy a package manager installed. + /// `Some`: it is a copy committed under `.socket/vendor`, and these + /// files of the project point at it, each by its path from the project + /// with `/` between its parts. + pub pins: Option>, +} + +/// The call that builds a package from a file without its patch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Unbuilt { + /// The tag, as a workspace file writes it: `npm.npm_translate_lock`. + pub call: String, + /// The file the call is in, from the Bazel root, and its line. + pub file: String, + pub line: usize, + /// The file the call names for the package, from the Bazel root: for an + /// installed copy the lock that lists the package, for a committed copy + /// the file that points at it. + pub lock: String, +} + +/// The tag of a module extension that names the files a ruleset builds the +/// packages of an ecosystem from. +struct Hub { + /// The type of the ecosystem's purls. + ecosystem: &'static str, + extension: Extension<'static>, + tag: &'static str, + /// The attributes that name such a file: a label, or a dict with a + /// label as each key. + files: &'static [&'static str], + /// The packages a file lists plainly, each as its name and version. + lists: fn(&str) -> Vec<(String, String)>, + /// The directories below a file's own whose lock the file is as well, + /// each from that directory: the members of a pnpm workspace. + members: fn(&str) -> Vec, + /// Whether a call of the tag may build a package from a line that + /// points at a copy under `.socket/vendor`: rules_js does, and of + /// rules_ruby no build has shown that it does not. + builds_vendored: bool, +} + +const HUBS: [Hub; 3] = [ + Hub { + ecosystem: "npm", + extension: Extension { + module: "aspect_rules_js", + file: "//npm:extensions.bzl", + name: "npm", + }, + tag: "npm_translate_lock", + files: &["pnpm_lock"], + lists: |text| { + let project = documents(text).into_iter(); + let project = project.filter(|(_, kind)| *kind == PnpmDocument::Project); + let locks = project.map(|(span, _)| PnpmLock::parse_keys(&text[span])); + let locks: Vec<_> = locks.collect(); + let keys = locks.iter().flat_map(|lock| lock.packages()); + owned(keys.filter_map(|package| pnpm_registry_key(package.key))) + }, + members: lock_text_member_importers, + builds_vendored: true, + }, + Hub { + ecosystem: "pypi", + extension: Extension { + module: "rules_python", + file: "//python/extensions:pip.bzl", + name: "pip", + }, + tag: "parse", + files: &[ + "requirements_lock", + "requirements_by_platform", + "requirements_darwin", + "requirements_linux", + "requirements_windows", + ], + lists: |text| { + let lines = logical_lines(text); + owned( + lines + .iter() + .filter_map(|line| exact_pin(strip_comment(&line.text))), + ) + }, + members: |_| Vec::new(), + builds_vendored: false, + }, + Hub { + ecosystem: "gem", + extension: Extension { + module: "rules_ruby", + file: "//ruby:extensions.bzl", + name: "ruby", + }, + tag: "bundle_fetch", + files: &["gemfile_lock", "gemfile"], + lists: |text| owned(locked_specs(text).into_iter()), + members: |_| Vec::new(), + builds_vendored: true, + }, +]; + +fn owned<'a>(listed: impl Iterator) -> Vec<(String, String)> { + listed + .map(|(name, version)| (name.to_string(), version.to_string())) + .collect() +} + +/// The type of a purl, when it has a name and a version. +fn ecosystem(purl: &str) -> Option { + purl_parts(purl).map(|(ecosystem, _, _)| ecosystem) +} + +/// For each of `packages`, patched in the project at `project`: the call of +/// the project's Bazel workspace that builds the package from a file +/// without the patch, or `None` when the files of the workspace show no +/// such call (see the module docs for what that takes). +/// +/// Nothing is read for packages no hub is known for, nor outside a Bazel +/// workspace ([`super::bazel_root`], whose bounds these are). +pub async fn unbuilt(project: &Path, packages: Vec) -> Vec> { + let hub = |package: &Patched| { + let of = ecosystem(&package.purl); + HUBS.iter().any(|hub| of.as_deref() == Some(hub.ecosystem)) + }; + if !packages.iter().any(hub) { + return vec![None; packages.len()]; + } + let project = project.to_path_buf(); + run_blocking(move || { + let Some(root) = super::bazel_root(&project) else { + return vec![None; packages.len()]; + }; + let workspace = Workspace::read(&disk(&root.dir)); + let read = |file: &str| lock_text(&root.dir, file); + // Bazel has `/` between the parts of a path on every system. + let parts = root.project.components(); + let parts: Vec<_> = parts + .map(|part| part.as_os_str().to_string_lossy()) + .collect(); + judge(&workspace, &parts.join("/"), &read, &packages) + }) + .await +} + +/// The most of a lock that is read: the lock of a large pnpm workspace has +/// some tens of MiB. A larger file decides nothing. +const MAX_LOCK: u64 = 64 << 20; + +/// The text of the lock `file` of the workspace at `root`, a canonical +/// path, read as [`disk`] reads a file of the workspace: a file this run +/// wrote and has not committed yet as the run left it, when `file` names it +/// in plain parts, and nothing through a link that leads out of the +/// workspace. `None` for that, for what is no file (a directory, which +/// Windows does not even open, like any other) or not UTF-8, and for a +/// file over [`MAX_LOCK`]. +fn lock_text(root: &Path, file: &str) -> Option { + let path = root.join(file); + let mut bytes = Vec::new(); + let plain = |part| matches!(part, Component::Normal(_)); + let plain = Path::new(file).components().all(plain); + match plain.then(|| group_commit::read(&path)).flatten() { + Some(pending) => bytes = pending.ok()?, + None => { + let real = std::fs::canonicalize(&path).ok()?; + let inside = real.starts_with(root).then_some(real)?; + let (file, _) = open_regular_file_sync(&inside).ok()?; + file.take(MAX_LOCK + 1).read_to_end(&mut bytes).ok()?; + } + } + let whole = bytes.len() as u64 <= MAX_LOCK; + whole.then(|| String::from_utf8(bytes).ok())? +} + +/// [`unbuilt`] for the workspace `workspace` and the project in its +/// directory `project` (empty: the root itself), with `read` for the text +/// of a file of the workspace. +fn judge( + workspace: &Workspace, + project: &str, + read: &dyn Fn(&str) -> Option, + packages: &[Patched], +) -> Vec> { + let mut found = vec![None; packages.len()]; + if !workspace.doubts.is_empty() || workspace.legacy.is_some() { + return found; + } + for hub in &HUBS { + let ours = |at: &usize| ecosystem(&packages[*at].purl).as_deref() == Some(hub.ecosystem); + let ours: Vec = (0..packages.len()).filter(ours).collect(); + if ours.is_empty() { + continue; + } + let tags = workspace.tags(&hub.extension, hub.tag); + if !tags.doubts.is_empty() { + continue; + } + // What a file lists, and which patches of the packages its text + // names: read when a package first asks and once for all the calls + // that name it, and the text is not kept. `None` for a file that + // is not the project's lock or cannot be read. + let mut listed = HashMap::new(); + let elsewhere = |call: &Call| call.unpacks() || call.arg("uv_lock").is_some(); + for tag in (tags.calls.iter()).filter(|tag| tag.call.whole && !elsewhere(tag.call)) { + for lock in files(workspace, tag.call, hub.files) { + for &at in &ours { + let package = &packages[at]; + let unpatched = match &package.pins { + Some(pins) => { + !hub.builds_vendored + && pins.iter().any(|pin| below(project, pin) == lock) + } + None => { + let listed = listed.entry(lock.clone()).or_insert_with(|| { + let member = from_lock(project, &lock)?; + let text = read(&lock)?; + let named = || (hub.members)(&text).iter().any(|m| m == member); + if !(member.is_empty() || named()) { + return None; + } + let listed = (hub.lists)(&text).into_iter(); + let key = |(name, version)| { + PurlKey::new(&format!("pkg:{}/{name}@{version}", hub.ecosystem)) + }; + // One pass over the text for all the patches. + let uuid = |at: usize| packages[at].uuid.as_str(); + let ids = ours.iter().map(|at| uuid(*at)); + let named = AhoCorasick::new(ids).ok()?; + let named = named.find_overlapping_iter(&text); + let named = named.map(|id| uuid(ours[id.pattern()])); + Some((listed.map(key).collect(), named.collect())) + }); + // A file that names the patch may hold it. + let lists = |(listed, named): &(HashSet<_>, HashSet<_>)| { + listed.contains(&PurlKey::new(&package.purl)) + && !named.contains(package.uuid.as_str()) + }; + listed.as_ref().is_some_and(lists) + } + }; + if unpatched && found[at].is_none() { + found[at] = Some(Unbuilt { + call: format!("{}.{}", hub.extension.name, hub.tag), + file: tag.file.to_string(), + line: tag.call.line, + lock: lock.clone(), + }); + } + } + } + } + } + found +} + +/// The files of the main repository that `call` names under `attributes`, +/// each by its path from the Bazel root. An attribute that is not written +/// out as a string, or as a dict with strings as keys, names none. +fn files(workspace: &Workspace, call: &Call, attributes: &[&str]) -> Vec { + let mut labels: Vec<&str> = Vec::new(); + for attribute in attributes { + match call.arg(attribute) { + Some(Value::Str(label)) => labels.push(label), + Some(Value::Dict(entries)) => { + labels.extend(entries.iter().map(|(label, _)| label.as_str())) + } + _ => {} + } + } + let main = |label: &&str| { + let label = workspace + .label(label) + .filter(|label| label.repo == Repo::Main); + label.map(|label| label.path()) + }; + labels.iter().filter_map(main).collect() +} + +/// The path from the Bazel root of `file`, a path from the project in the +/// directory `project`. +fn below(project: &str, file: &str) -> String { + let file = file.trim_start_matches("./"); + match project { + "" => file.to_string(), + project => format!("{project}/{file}"), + } +} + +/// The directory `project` from the directory of the workspace's file +/// `lock`: empty for the project the file lies in, `apps/web` for one that +/// far below it. `None` for a project that is neither: no file beside the +/// project, or below it, is its lock. +fn from_lock<'a>(project: &'a str, lock: &str) -> Option<&'a str> { + let directory = lock.rsplit_once('/').map_or("", |(directory, _)| directory); + match project.strip_prefix(directory)? { + rest if directory.is_empty() || rest.is_empty() => Some(rest), + rest => rest.strip_prefix('/'), + } +} + +#[cfg(test)] +mod tests { + use super::super::workspace::Entry; + use super::*; + + const UUID: &str = "7a11e000-0000-4000-8000-0000000000b1"; + + /// A workspace with the three hubs: the npm one of `web`, two Python + /// ones (one with a file per platform) and the Ruby one in a file the + /// root includes. + const ROOT: &str = r#"module(name = "shop", version = "0.0.0") + +bazel_dep(name = "aspect_rules_js", version = "3.6.0") +bazel_dep(name = "rules_python", version = "2.5.0-rc4") +bazel_dep(name = "rules_ruby", version = "1.0.0-rc2") + +npm = use_extension("@aspect_rules_js//npm:extensions.bzl", "npm") +npm.npm_translate_lock( + name = "npm", + pnpm_lock = "//web:pnpm-lock.yaml", +) +use_repo(npm, "npm") + +pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") +pip.parse( + hub_name = "pypi", + python_version = "3.11", + requirements_lock = "//api:requirements.txt", +) +pip.parse( + hub_name = "tools", + python_version = "3.11", + requirements_by_platform = { + "//tools:requirements_linux.txt": "linux_*", + "//tools:requirements_darwin.txt": "osx_*", + }, +) +use_repo(pip, "pypi", "tools") + +include("//billing:ruby.MODULE.bazel") +"#; + + const RUBY: &str = r#"ruby = use_extension("@rules_ruby//ruby:extensions.bzl", "ruby") +ruby.bundle_fetch( + name = "bundle", + gemfile = "//billing:Gemfile", + gemfile_lock = "//billing:Gemfile.lock", +) +use_repo(ruby, "bundle") +"#; + + const PNPM_LOCK: &str = + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n \ + left-pad:\n specifier: 1.3.0\n version: 1.3.0\n\npackages:\n\n \ + '@shop/ui@2.0.0':\n resolution: {integrity: sha512-AAAA}\n\n \ + left-pad@1.3.0:\n resolution: {integrity: sha512-BBBB}\n\nsnapshots:\n\n \ + '@shop/ui@2.0.0': {}\n\n left-pad@1.3.0: {}\n"; + + const REQUIREMENTS: &str = "# pip-compile\nFlask_Cors==4.0.0 \\\n \ + --hash=sha256:aaaa\nrequests>=2.31.0\n# idna==3.6\n"; + + const GEMFILE_LOCK: &str = "GEM\n remote: https://rubygems.org/\n specs:\n \ + nokogiri (1.16.5-arm64-darwin)\n rack (2.2.8)\n\nPLATFORMS\n arm64-darwin\n\n\ + DEPENDENCIES\n nokogiri\n rack\n"; + + const SHOP: [(&str, &str); 8] = [ + ("MODULE.bazel", ROOT), + ("billing/ruby.MODULE.bazel", RUBY), + ("web/pnpm-lock.yaml", PNPM_LOCK), + ("api/requirements.txt", REQUIREMENTS), + ("tools/requirements_linux.txt", "idna==3.6\n"), + ("tools/requirements_darwin.txt", "idna==3.7\n"), + ( + "billing/Gemfile", + "source \"https://rubygems.org\"\ngem \"rack\"\n", + ), + ("billing/Gemfile.lock", GEMFILE_LOCK), + ]; + + /// What [`judge`] says of one package of the project in `project`, in + /// the workspace of `files`: `call file:line lock`. + fn said(files: &[(&str, &str)], project: &str, purl: &str, pins: Option<&[&str]>) -> String { + read_and_said(files, project, purl, pins).1 + } + + /// The locks [`judge`] read, in order, and what it [`said`]. + fn read_and_said( + files: &[(&str, &str)], + project: &str, + purl: &str, + pins: Option<&[&str]>, + ) -> (Vec, String) { + let text = |path: &str| { + files + .iter() + .find(|(name, _)| *name == path) + .map(|(_, text)| *text) + }; + let workspace = Workspace::read(&|path| match text(path) { + Some(text) => Entry::Text(text.to_string()), + None => Entry::Absent, + }); + let package = Patched { + purl: purl.to_string(), + uuid: UUID.to_string(), + pins: pins.map(|pins| pins.iter().map(|pin| pin.to_string()).collect()), + }; + let asked = std::cell::RefCell::new(Vec::new()); + let read = |path: &str| { + asked.borrow_mut().push(path.to_string()); + text(path).map(str::to_string) + }; + let found = judge(&workspace, project, &read, &[package]).remove(0); + let show = |found: Unbuilt| { + format!( + "{} {}:{} {}", + found.call, found.file, found.line, found.lock + ) + }; + (asked.into_inner(), found.map(show).unwrap_or_default()) + } + + /// The shop with `text` in the place of the file `path`, or as a new + /// file. + fn with(path: &'static str, text: &'static str) -> Vec<(&'static str, &'static str)> { + let mut files: Vec<_> = SHOP.into_iter().filter(|(name, _)| *name != path).collect(); + files.push((path, text)); + files + } + + const NPM: &str = "npm.npm_translate_lock MODULE.bazel:8 web/pnpm-lock.yaml"; + + #[test] + fn an_installed_copy_is_not_what_a_hub_builds() { + let installed = |project, purl| said(&SHOP, project, purl, None); + // The lock of the project, in every spelling of the package. + assert_eq!(installed("web", "pkg:npm/left-pad@1.3.0"), NPM); + assert_eq!(installed("web", "pkg:npm/%40shop/ui@2.0.0"), NPM); + assert_eq!(installed("web", "pkg:npm/@shop/ui@2.0.0?x=1"), NPM); + // A pin with hashes, a name pip folds. + let pypi = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!(installed("api", "pkg:pypi/flask-cors@4.0.0"), pypi); + assert_eq!(installed("api", "pkg:pypi/Flask_Cors@4.0.0"), pypi); + // A file per platform: each is one the hub builds from. + let linux = "pip.parse MODULE.bazel:20 tools/requirements_linux.txt"; + assert_eq!(installed("tools", "pkg:pypi/idna@3.6"), linux); + let darwin = "pip.parse MODULE.bazel:20 tools/requirements_darwin.txt"; + assert_eq!(installed("tools", "pkg:pypi/idna@3.7"), darwin); + // A hub in an included file, and a gem of one platform. + let gem = "ruby.bundle_fetch billing/ruby.MODULE.bazel:2 billing/Gemfile.lock"; + assert_eq!(installed("billing", "pkg:gem/rack@2.2.8"), gem); + let platform = "pkg:gem/nokogiri@1.16.5?platform=arm64-darwin"; + assert_eq!(installed("billing", platform), gem); + } + + /// The lock of a pnpm workspace is the lock of each member it names + /// among its importers, in either spelling of the key, and of no other + /// directory below it. + #[test] + fn the_lock_of_a_pnpm_workspace_is_the_lock_of_its_members() { + let shared = |importers: &str| { + let lock = PNPM_LOCK.replace("packages:\n", &format!("{importers}\npackages:\n")); + assert_ne!(lock, PNPM_LOCK); + let lock: &'static str = Box::leak(lock.into_boxed_str()); + with("web/pnpm-lock.yaml", lock) + }; + let member = + |files: &[(&str, &str)], project| said(files, project, "pkg:npm/left-pad@1.3.0", None); + for importers in [ + " apps/admin:\n dependencies: {}\n", + " 'apps/admin': {}\n", + ] { + let files = shared(importers); + assert_eq!(member(&files, "web/apps/admin"), NPM, "{importers}"); + assert_eq!(member(&files, "web"), NPM, "{importers}"); + for other in [ + "web/apps", + "web/apps/admin/src", + "web/admin", + "apps/admin", + "", + ] { + assert_eq!(member(&files, other), "", "{importers} {other}"); + } + } + // A lock that names no member is the lock of its directory alone. + assert_eq!(member(&SHOP, "web/apps/admin"), ""); + // Only a pnpm lock has members. + let nested = "pkg:pypi/flask-cors@4.0.0"; + assert_ne!(said(&SHOP, "api", nested, None), ""); + assert_eq!(said(&SHOP, "api/worker", nested, None), ""); + } + + /// A lock is read only where the project's own lock can lie, and once + /// however many calls name it. + #[test] + fn a_lock_is_read_once_and_only_where_the_project_s_lock_can_lie() { + let twice: &'static str = Box::leak( + format!( + "{ROOT}npm.npm_translate_lock(name = \"again\", pnpm_lock = \"//web:pnpm-lock.yaml\")\n\ + npm.npm_translate_lock(name = \"below\", pnpm_lock = \"//web/site:pnpm-lock.yaml\")\n" + ) + .into_boxed_str(), + ); + let mut files = with("MODULE.bazel", twice); + files.push(("web/site/pnpm-lock.yaml", PNPM_LOCK)); + let read = |project| read_and_said(&files, project, "pkg:npm/left-pad@1.3.0", None); + assert_eq!( + read("web"), + (vec!["web/pnpm-lock.yaml".to_string()], NPM.to_string()) + ); + // From a directory below it a lock is read for its importers. + let below = vec!["web/pnpm-lock.yaml", "web/site/pnpm-lock.yaml"]; + assert_eq!(read("web/site/app").0, below); + assert_eq!(read("mobile"), (vec![], String::new())); + assert_eq!(read(""), (vec![], String::new())); + } + + #[test] + fn a_package_no_hub_is_shown_to_build_is_left_alone() { + let installed = |project, purl| said(&SHOP, project, purl, None); + // The lock of another project, also one whose name starts alike. + assert_eq!(installed("mobile", "pkg:npm/left-pad@1.3.0"), ""); + assert_eq!(installed("webby", "pkg:npm/left-pad@1.3.0"), ""); + assert_eq!(installed("web", "pkg:gem/rack@2.2.8"), ""); + // A lock below the project, and one above it that does not name + // it: the project has a lock of its own, or none. + assert_eq!(installed("", "pkg:npm/left-pad@1.3.0"), ""); + assert_eq!(installed("web/admin", "pkg:npm/left-pad@1.3.0"), ""); + assert_eq!(installed("", "pkg:gem/rack@2.2.8"), ""); + assert_eq!(installed("billing/app", "pkg:gem/rack@2.2.8"), ""); + // Another version, another package, a range, a comment. + assert_eq!(installed("web", "pkg:npm/left-pad@1.2.0"), ""); + assert_eq!(installed("web", "pkg:npm/right-pad@1.3.0"), ""); + assert_eq!(installed("api", "pkg:pypi/requests@2.31.0"), ""); + assert_eq!(installed("api", "pkg:pypi/idna@3.6"), ""); + // An ecosystem without a hub here, and no purl at all. + assert_eq!(installed("web", "pkg:cargo/serde@1.0.0"), ""); + assert_eq!(installed("web", "pkg:golang/example.com/m@v1.0.0"), ""); + assert_eq!(installed("web", "left-pad"), ""); + } + + #[test] + fn a_committed_copy_is_not_built_from_a_line_that_points_at_it() { + let vendored = |project, purl, pins: &[&str]| said(&SHOP, project, purl, Some(pins)); + let pypi = "pip.parse MODULE.bazel:15 api/requirements.txt"; + let requests = "pkg:pypi/requests@2.31.0"; + assert_eq!(vendored("api", requests, &["requirements.txt"]), pypi); + assert_eq!(vendored("api", requests, &["./requirements.txt"]), pypi); + // rules_js builds a committed tarball. What rules_ruby does with a + // committed gem no build has shown: it is not judged, in the + // Gemfile or in its lock, while an installed one is. + let (npm, gem) = ("pkg:npm/left-pad@1.3.0", "pkg:gem/rack@2.2.8"); + assert_eq!(vendored("web", npm, &["pnpm-lock.yaml"]), ""); + assert_eq!(vendored("billing", gem, &["Gemfile", "Gemfile.lock"]), ""); + assert_eq!(vendored("billing", gem, &["Gemfile"]), ""); + assert_ne!(said(&SHOP, "billing", gem, None), ""); + // Not judged yet: a copy that files point at which no hub reads, + // while the lock the hub does read lists the registry's package. + let listed = "pkg:pypi/flask-cors@4.0.0"; + assert_ne!(said(&SHOP, "api", listed, None), ""); + assert_eq!(vendored("api", listed, &["pyproject.toml", "uv.lock"]), ""); + assert_eq!(vendored("web", npm, &["package-lock.json"]), ""); + // The same name in another project, and no file at all. + assert_eq!(vendored("mobile", requests, &["requirements.txt"]), ""); + assert_eq!(vendored("api", "pkg:pypi/flask-cors@4.0.0", &[]), ""); + } + + #[test] + fn a_lock_that_names_the_patch_is_left_alone() { + let hosted: &'static str = Box::leak( + PNPM_LOCK + .replace( + "sha512-BBBB", + &format!("sha512-CCCC, tarball: https://h/patch/{UUID}/a.tgz"), + ) + .into_boxed_str(), + ); + assert_ne!(hosted, PNPM_LOCK); + let files = with("web/pnpm-lock.yaml", hosted); + assert_eq!(said(&files, "web", "pkg:npm/left-pad@1.3.0", None), ""); + // The lock without it is judged as before. + assert_eq!(said(&SHOP, "web", "pkg:npm/left-pad@1.3.0", None), NPM); + + // Each package is judged by its own patch, also where two share + // one, and a package the lock does not list by none. + let other = "7a11e000-0000-4000-8000-0000000000b2"; + let patched = |files: &[(&'static str, &'static str)], uuids: [&str; 3]| { + let text = |path: &str| files.iter().find(|(name, _)| *name == path); + let workspace = Workspace::read(&|path| match text(path) { + Some((_, text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + }); + let purls = [ + "pkg:npm/left-pad@1.3.0", + "pkg:npm/@shop/ui@2.0.0", + "pkg:npm/is-odd@3.0.1", + ]; + let packages: Vec<_> = (purls.iter().zip(uuids)) + .map(|(purl, uuid)| Patched { + purl: purl.to_string(), + uuid: uuid.to_string(), + pins: None, + }) + .collect(); + let read = |path: &str| text(path).map(|(_, text)| text.to_string()); + let found = judge(&workspace, "web", &read, &packages); + found.iter().map(Option::is_some).collect::>() + }; + assert_eq!(patched(&files, [UUID, other, UUID]), [false, true, false]); + assert_eq!(patched(&files, [UUID, UUID, other]), [false, false, false]); + assert_eq!(patched(&files, [other, other, UUID]), [true, true, false]); + assert_eq!(patched(&SHOP, [UUID, UUID, UUID]), [true, true, false]); + } + + #[test] + fn nothing_is_said_of_a_workspace_that_is_not_read_with_certainty() { + let npm = |files: &[(&str, &str)]| said(files, "web", "pkg:npm/left-pad@1.3.0", None); + let gem = |files: &[(&str, &str)]| said(files, "billing", "pkg:gem/rack@2.2.8", None); + assert_eq!(npm(&SHOP), NPM); + // A file the root includes is missing: a doubt on every answer. + let missing: Vec<_> = SHOP + .into_iter() + .filter(|(name, _)| !name.ends_with("ruby.MODULE.bazel")) + .collect(); + assert_eq!( + (npm(&missing), gem(&missing)), + (String::new(), String::new()) + ); + // A `WORKSPACE` file that defines something, in each of its names; + // one that only names the workspace is none. + let rule = "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n"; + for name in ["WORKSPACE", "WORKSPACE.bazel", "WORKSPACE.bzlmod"] { + assert_eq!(npm(&with(name, rule)), "", "{name}"); + assert_eq!( + npm(&with(name, "workspace(name = \"shop\")\n")), + NPM, + "{name}" + ); + } + assert_eq!(npm(&with("WORKSPACE", "http_archive(\n")), ""); + // A proxy that is handed on: a doubt on that hub alone. + let handed: &'static str = Box::leak(format!("{ROOT}print(npm)\n").into_boxed_str()); + let files = with("MODULE.bazel", handed); + assert_eq!(npm(&files), ""); + assert_ne!(gem(&files), ""); + // No module file at all. + assert_eq!(npm(&SHOP[1..]), ""); + } + + /// Only a call that is a statement of its own is known to run. One in + /// a comprehension, behind an `and`, in a conditional or in the + /// arguments of another call may never run: it withholds nothing, for + /// an installed copy and for a committed one. + #[test] + fn a_call_that_may_not_run_withholds_nothing() { + let hub = "npm.npm_translate_lock(\n name = \"npm\",\n pnpm_lock = \"//web:pnpm-lock.yaml\",\n)\n"; + let npm = |call: &str| { + let root = ROOT.replace(hub, &format!("{call}\n")); + assert_ne!(root, ROOT, "{call}"); + let root: &'static str = Box::leak(root.into_boxed_str()); + let files = with("MODULE.bazel", root); + said(&files, "web", "pkg:npm/left-pad@1.3.0", None) + }; + let call = "npm.npm_translate_lock(pnpm_lock = \"//web:pnpm-lock.yaml\")"; + assert_eq!(npm(call), NPM); + assert_eq!(npm(&format!("hub = {call}")), NPM); + for may_not_run in [ + format!("[{call} for version in []]"), + format!("ENABLE and {call}"), + format!("{call} if ENABLE else None"), + format!("print({call})"), + ] { + assert_eq!(npm(&may_not_run), "", "{may_not_run}"); + } + let pip = "pip.parse(\n hub_name = \"pypi\",\n python_version = \"3.11\",\n requirements_lock = \"//api:requirements.txt\",\n)\n"; + let looped = + "[pip.parse(requirements_lock = \"//api:requirements.txt\") for version in []]\n"; + let root = ROOT.replace(pip, looped); + assert_ne!(root, ROOT); + let root: &'static str = Box::leak(root.into_boxed_str()); + let files = with("MODULE.bazel", root); + let requests = "pkg:pypi/requests@2.31.0"; + assert_eq!( + said(&files, "api", requests, Some(&["requirements.txt"])), + "" + ); + assert_eq!(said(&files, "api", "pkg:pypi/flask-cors@4.0.0", None), ""); + // A call of the same hub that does run is judged as before. + assert_ne!(said(&files, "tools", "pkg:pypi/idna@3.6", None), ""); + } + + /// A call whose arguments are not all written out is passed over, and + /// so is a `pip.parse` with `uv_lock`: rules_python can take the + /// packages of such a call from that file, whatever the requirements + /// file lists or points at. + #[test] + fn a_call_that_may_read_another_file_withholds_nothing() { + let lock = " requirements_lock = \"//api:requirements.txt\",\n"; + let pypi = |argument: &str| { + let root = ROOT.replace(lock, &format!("{lock} {argument},\n")); + assert_ne!(root, ROOT, "{argument}"); + let root: &'static str = Box::leak(root.into_boxed_str()); + let files = with("MODULE.bazel", root); + let pins = ["requirements.txt"]; + [ + said(&files, "api", "pkg:pypi/flask-cors@4.0.0", None), + said(&files, "api", "pkg:pypi/requests@2.31.0", Some(&pins)), + ] + }; + let judged = "pip.parse MODULE.bazel:15 api/requirements.txt".to_string(); + assert_eq!(pypi("quiet = False"), [judged.clone(), judged]); + for elsewhere in ["uv_lock = \"//api:uv.lock\"", "**COMMON", "*LOCKS"] { + assert_eq!( + pypi(elsewhere), + [String::new(), String::new()], + "{elsewhere}" + ); + } + } + + /// pnpm 11 keeps the packages of its own configuration in a first + /// document of the lock. rules_js links what the project documents + /// list: a package of that document alone is not one the hub builds. + #[test] + fn a_package_of_the_env_document_of_a_pnpm_lock_is_not_listed() { + let env = + "---\nlockfileVersion: '9.0'\n\nimporters:\n\n .:\n configDependencies:\n \ + is-odd:\n specifier: 3.0.1\n version: 3.0.1\n\npackages:\n\n \ + is-odd@3.0.1:\n resolution: {integrity: sha512-DDDD}\n\nsnapshots:\n\n \ + is-odd@3.0.1: {}\n\n---\n"; + let lock: &'static str = Box::leak(format!("{env}{PNPM_LOCK}").into_boxed_str()); + let files = with("web/pnpm-lock.yaml", lock); + assert_eq!(said(&files, "web", "pkg:npm/is-odd@3.0.1", None), ""); + assert_eq!(said(&files, "web", "pkg:npm/left-pad@1.3.0", None), NPM); + // The same entry in a lock of one document is a package of the + // project. + let one = lock + .replace("---\n", "") + .replace("configDependencies", "dependencies"); + let one: &'static str = Box::leak(one.into_boxed_str()); + let files = with("web/pnpm-lock.yaml", one); + assert_eq!(said(&files, "web", "pkg:npm/is-odd@3.0.1", None), NPM); + } + + #[test] + fn only_a_label_written_out_in_the_main_repository_names_a_file() { + let npm = |label: &str| { + let root = ROOT.replace("\"//web:pnpm-lock.yaml\"", label); + assert_ne!(root, ROOT, "{label}"); + let root: &'static str = Box::leak(root.into_boxed_str()); + said( + &with("MODULE.bazel", root), + "web", + "pkg:npm/left-pad@1.3.0", + None, + ) + }; + for main in [ + "\"@//web:pnpm-lock.yaml\"", + "\"@@//web:pnpm-lock.yaml\"", + "\"@shop//web:pnpm-lock.yaml\"", + ] { + assert_eq!(npm(main), NPM, "{main}"); + } + // A relative label is read from the root, where there is no lock. + for none in [ + "\"pnpm-lock.yaml\"", + "\":pnpm-lock.yaml\"", + "\"@other//web:pnpm-lock.yaml\"", + "\"//web:missing.yaml\"", + "LOCK", + "\"//web:\" + \"pnpm-lock.yaml\"", + "Label(\"//web:pnpm-lock.yaml\")", + ] { + assert_eq!(npm(none), "", "{none}"); + } + } + + #[test] + fn a_project_is_in_the_directory_of_a_lock_or_below_it_or_neither() { + for (project, lock, from) in [ + ("", "pnpm-lock.yaml", Some("")), + ("a/b", "pnpm-lock.yaml", Some("a/b")), + ("a/b", "a/pnpm-lock.yaml", Some("b")), + ("a/b", "a/b/pnpm-lock.yaml", Some("")), + ("", "a/b/pnpm-lock.yaml", None), + ("a/b", "a/b/c/pnpm-lock.yaml", None), + ("a/b", "a/c/pnpm-lock.yaml", None), + ("a/b", "a/bc/pnpm-lock.yaml", None), + ("a/bc", "a/b/pnpm-lock.yaml", None), + ("a", "b/pnpm-lock.yaml", None), + ] { + assert_eq!(from_lock(project, lock), from, "{project:?} {lock}"); + } + assert_eq!(below("", "./requirements.txt"), "requirements.txt"); + assert_eq!(below("a/b", "requirements.txt"), "a/b/requirements.txt"); + } + + /// On disk: the Bazel root is found from the project, the files are + /// read there, and nothing is looked for when no package has a hub or + /// no workspace is around the project. + #[tokio::test] + async fn the_workspace_of_a_project_on_disk_is_read() { + let tmp = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + let write = |path: &str, text: &str| { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + }; + write(".git/HEAD", "ref: refs/heads/main\n"); + for (path, text) in SHOP { + write(path, text); + } + let package = |purl: &str, pins: Option>| Patched { + purl: purl.to_string(), + uuid: UUID.to_string(), + pins, + }; + let packages = vec![ + package("pkg:cargo/serde@1.0.0", None), + package("pkg:npm/left-pad@1.3.0", None), + package("pkg:npm/left-pad@1.2.0", None), + ]; + let found = unbuilt(&root.join("web"), packages.clone()).await; + let locks: Vec<_> = found + .iter() + .map(|found| found.as_ref().map(|found| found.lock.as_str())) + .collect(); + assert_eq!(locks, [None, Some("web/pnpm-lock.yaml"), None]); + let pins = Some(vec!["requirements.txt".to_string()]); + let vendored = vec![package("pkg:pypi/requests@2.31.0", pins)]; + let found = unbuilt(&root.join("api"), vendored.clone()).await; + assert_eq!(found[0].as_ref().map(|found| found.line), Some(15)); + // A directory is no lock, on every system. + assert_eq!( + lock_text(&root, "web/pnpm-lock.yaml").as_deref(), + Some(PNPM_LOCK) + ); + assert_eq!(lock_text(&root, "web"), None); + + // No package of a hub: the project is not even looked for. + let found = unbuilt(&root.join("no/such/project"), packages[..1].to_vec()).await; + assert_eq!(found, [None]); + // No workspace file: every statement stays. + std::fs::remove_file(root.join("MODULE.bazel")).unwrap(); + assert_eq!( + unbuilt(&root.join("web"), packages).await, + [None, None, None] + ); + assert_eq!(unbuilt(&root.join("api"), vendored).await, [None]); + } + + /// On disk a lock is read as a file of the workspace is: through a + /// link that stays inside the Bazel root and not through one that + /// leads out of it, not past its bound, and as the run left a file it + /// has not committed yet. + #[cfg(unix)] + #[tokio::test] + async fn a_lock_is_read_inside_the_workspace_and_within_its_bound() { + use crate::utils::fs::atomic_write_bytes; + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let root = base.join("repo"); + let write = |path: &str, text: &str| { + let path = base.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + }; + write("repo/.git/HEAD", "ref: refs/heads/main\n"); + for (path, text) in SHOP { + write(&format!("repo/{path}"), text); + } + write("repo/locks/pnpm-lock.yaml", PNPM_LOCK); + write("outside/pnpm-lock.yaml", PNPM_LOCK); + let name = "web/pnpm-lock.yaml"; + let lock = root.join(name); + let package = vec![Patched { + purl: "pkg:npm/left-pad@1.3.0".to_string(), + uuid: UUID.to_string(), + pins: None, + }]; + // The project as a caller names it, which need not be its real + // path: the root that locks are held to is the real one. + let project = tmp.path().join("repo/web"); + let withheld = || async { unbuilt(&project, package.clone()).await[0].is_some() }; + assert!(withheld().await); + + std::fs::remove_file(&lock).unwrap(); + symlink("../locks/pnpm-lock.yaml", &lock).unwrap(); + assert!(withheld().await, "a link inside the root"); + std::fs::remove_file(&lock).unwrap(); + symlink(base.join("outside/pnpm-lock.yaml"), &lock).unwrap(); + assert!(!withheld().await, "a link that leads out of the root"); + assert_eq!(lock_text(&root, name), None); + std::fs::remove_file(&lock).unwrap(); + + // One byte past the bound, a directory, and bytes that are no text. + let large = std::fs::File::create(&lock).unwrap(); + large.set_len(MAX_LOCK + 1).unwrap(); + assert_eq!(lock_text(&root, name), None); + std::fs::remove_file(&lock).unwrap(); + std::fs::create_dir(&lock).unwrap(); + assert_eq!(lock_text(&root, name), None); + std::fs::remove_dir(&lock).unwrap(); + std::fs::write(&lock, b"caf\xe9").unwrap(); + assert_eq!(lock_text(&root, name), None); + std::fs::write(&lock, PNPM_LOCK).unwrap(); + assert_eq!(lock_text(&root, name).as_deref(), Some(PNPM_LOCK)); + + // A run that has pinned the patch in the lock, before its commit. + let run = crate::utils::group_commit::GroupCommit::begin(&root); + let pinned = PNPM_LOCK.replace("sha512-BBBB", &format!("sha512-CCCC, tarball: {UUID}")); + atomic_write_bytes(&lock, pinned.as_bytes()).await.unwrap(); + assert_eq!(std::fs::read_to_string(&lock).unwrap(), PNPM_LOCK); + assert!(!withheld().await, "the lock as the run left it"); + // Only a path of plain parts is asked of the run, as for every + // file of the workspace: another spelling reads the disk. + assert_eq!(lock_text(&root, name).as_deref(), Some(pinned.as_str())); + let dotted = "./web/pnpm-lock.yaml"; + assert_eq!(lock_text(&root, dotted).as_deref(), Some(PNPM_LOCK)); + drop(run); + assert!(withheld().await); + } +} diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index e6f8e1913..f2d19a28d 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -8,6 +8,7 @@ pub const WORKSPACE_FILES: [&str; 4] = ["MODULE.bazel", "REPO.bazel", "WORKSPACE", "WORKSPACE.bazel"]; +pub mod built; pub mod ignore; pub mod maven; pub mod rc; diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index a73175e7e..27bfb9403 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -430,7 +430,7 @@ impl<'t> PnpmLock<'t> { /// [`PnpmPackage::resolution`] is `None`) or document tags (every /// entry is [`PnpmDocument::Project`]), for a reader of keys and entry /// fields only: its document queries mean nothing. - fn parse_keys(text: &'t str) -> Self { + pub(crate) fn parse_keys(text: &'t str) -> Self { PnpmLock { text, packages: pnpm_packages(text, Resolve::No), diff --git a/crates/socket-patch-core/src/formats/pnpm/workspace.rs b/crates/socket-patch-core/src/formats/pnpm/workspace.rs index 69cbdb2d3..cfd43e448 100644 --- a/crates/socket-patch-core/src/formats/pnpm/workspace.rs +++ b/crates/socket-patch-core/src/formats/pnpm/workspace.rs @@ -215,6 +215,37 @@ pub(crate) fn lock_text_has_member_importers(text: &str) -> bool { }) } +/// The importers besides the root `.` that a whole `pnpm-lock.yaml` text +/// names: the directories of the workspace's members, each from the +/// directory of the lock. Read as [`lock_text_has_member_importers`] reads +/// them (the project documents alone, comment lines and CRLF as there), +/// to the end of the `importers` section of each: a lock has some +/// hundred lines of packages for each of them. +pub(crate) fn lock_text_member_importers(text: &str) -> Vec { + use super::grammar::{documents, PnpmDocument}; + let mut members = Vec::new(); + let project = |(_, kind): &(_, PnpmDocument)| *kind == PnpmDocument::Project; + for (span, _) in documents(text).into_iter().filter(project) { + let mut in_importers = false; + for line in strip_bom(&text[span]).split('\n') { + let line = line.strip_suffix('\r').unwrap_or(line); + if line.trim_start().starts_with('#') { + continue; + } + if !line.is_empty() && !line.starts_with([' ', '\t']) { + if in_importers { + break; + } + in_importers = line.trim_end() == "importers:"; + } else if in_importers { + let key = super::lines::parse_key_line(line, 2).map(|(key, _, _)| key); + members.extend(key.filter(|key| *key != ".").map(str::to_string)); + } + } + } + members +} + /// Insert `block` at line `at` of `lines` (a file split at `\n`), ending /// its lines as the file ends its own (`eol`, the file's /// [`terminator`](crate::utils::line_endings::terminator)): in a CRLF file @@ -676,6 +707,40 @@ mod tests { assert!(lock_has_member_importers(&crlf)); } + /// The members a lock names, in the key spelling of each lock + /// generation, and none from an env document. + #[test] + fn member_importers_are_named_as_the_lock_names_them() { + let v9 = "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies: {}\n\n \ + apps/web:\n dependencies:\n a:\n specifier: 1.0.0\n\n \ + packages/ui: {}\n\npackages:\n\n a@1.0.0:\n resolution: {}\n"; + assert_eq!(lock_text_member_importers(v9), ["apps/web", "packages/ui"]); + let v6 = "lockfileVersion: '6.0'\r\nimporters:\r\n '.': {}\r\n 'packages/a': {}\r\n"; + assert_eq!(lock_text_member_importers(v6), ["packages/a"]); + let env = "---\nlockfileVersion: '9.0'\n\nimporters:\n\n .: {}\n\n tooling:\n \ + configDependencies: {}\n\n"; + assert_eq!( + lock_text_member_importers(&format!("{env}---\n{v9}")), + ["apps/web", "packages/ui"] + ); + let none: [&str; 0] = []; + assert_eq!(lock_text_member_importers("lockfileVersion: '9.0'\n"), none); + // The reading ends with the section: what a later key holds, also + // under the same name, is not read. + let late = format!("{v9}\nimporters:\n\n late: {{}}\n"); + assert_eq!( + lock_text_member_importers(&late), + ["apps/web", "packages/ui"] + ); + // A commented-out importer is none, and a comment at column 0 + // does not end the section. + let commented = v9.replace(" packages/ui:", "# kept\n # apps/old: {}\n packages/ui:"); + assert_eq!( + lock_text_member_importers(&commented), + ["apps/web", "packages/ui"] + ); + } + /// #1952: a commented-out importer is not a member, a column-0 comment /// does not end `importers:`, and the env document's importers never /// count; the line and text forms agree. diff --git a/crates/socket-patch-core/src/utils/process.rs b/crates/socket-patch-core/src/utils/process.rs index 2c0deb069..036617486 100644 --- a/crates/socket-patch-core/src/utils/process.rs +++ b/crates/socket-patch-core/src/utils/process.rs @@ -113,6 +113,7 @@ pub const CHILD_ENV_SCRUB: &[&str] = &[ "SOCKET_VEX_OUTPUT", "SOCKET_VEX_PRODUCT", "SOCKET_VEX_NO_VERIFY", + "SOCKET_VEX_NO_BAZEL", "SOCKET_VEX_DOC_ID", "SOCKET_VEX_COMPACT", // Socket-specific service URLs read from the environment alone. diff --git a/crates/socket-patch-core/src/vex/build.rs b/crates/socket-patch-core/src/vex/build.rs index 885fd5122..5dac36818 100644 --- a/crates/socket-patch-core/src/vex/build.rs +++ b/crates/socket-patch-core/src/vex/build.rs @@ -10,6 +10,13 @@ //! single manifest entry has both — the manifest's key and `cves` — //! the latter become aliases. When two patches fix the same vuln ID //! they merge into one statement with both PURLs as subcomponents. +//! +//! A package the caller knows the build takes without its patch gets +//! `affected` statements ([`build_document_with`] with +//! [`Attested::affected`]): one per +//! vulnerability ID, of its own, after the `not_affected` one of the same +//! ID. Such statements are not merged, so that the action statement of +//! each is about one subcomponent. use std::collections::{BTreeMap, BTreeSet, HashSet}; @@ -41,7 +48,7 @@ pub struct BuildOptions { /// only declares them applied, as `--no-verify` does, says which with /// [`build_document_marking_unverified`]). Manifest entries not in /// `applied` are silently dropped — see the design note in -/// `vex::verify` for why we never emit `affected`. +/// `vex::verify` for why a check that fails never emits `affected`. /// /// PURLs in `vendored` (a subset of `applied`, from /// `VerifyOutcome::vendored`) carry the impact-statement phrasing @@ -94,7 +101,7 @@ pub fn build_document_marking_unverified( vendored, redirected, unverified, - code_not_present: &[], + ..Attested::default() }, opts, ) @@ -116,6 +123,9 @@ pub struct Attested<'a> { /// installed build of the package /// ([`VerifyOutcome::code_not_present`](crate::vex::verify::VerifyOutcome::code_not_present)). pub code_not_present: &'a [String], + /// PURLs whose patch the caller knows the build does not take, each + /// with what to do about it. See [`build_document_with`]. + pub affected: &'a [(String, String)], } /// What the impact statement says of a PURL in @@ -124,14 +134,31 @@ pub const CODE_NOT_PRESENT_PREFIX: &str = "The code this vulnerability is in is not in the installed build of the package: no file of \ Socket patch"; -/// [`build_document_marking_unverified`], where the PURLs in -/// `attested.code_not_present` are not affected because the code the patch -/// changes is not in any installed build of the package, with no patch -/// applied to them. Their impact-statement part says so and names the -/// patch whose files were looked for. A statement all of whose PURLs are -/// of that kind carries the justification `vulnerable_code_not_present`; -/// any other keeps `inline_mitigations_already_exist`, with one part per -/// PURL saying which is which. With no such PURL the document is +/// [`build_document_marking_unverified`], with two more kinds of PURL. +/// +/// The PURLs in `attested.code_not_present` are not affected because the +/// code the patch changes is not in any installed build of the package, +/// with no patch applied to them. Their impact-statement part says so and +/// names the patch whose files were looked for. A statement all of whose +/// PURLs are of that kind carries the justification +/// `vulnerable_code_not_present`; any other keeps +/// `inline_mitigations_already_exist`, with one part per PURL saying which +/// is which. +/// +/// `attested.affected` names the PURLs whose patch the caller knows the +/// build does not take, each with what to do about it. Every vulnerability +/// of such a PURL's record gets a statement of the PURL's own with the +/// status `affected`: the PURL is the one subcomponent of the product, and +/// the action statement is what the caller gave for it, so a reader knows +/// which package to act on. It has no justification and no impact +/// statement, which belong to `not_affected`. +/// +/// A PURL is in `applied` or in `affected`, and `affected` wins for one +/// in both. A vulnerability that PURLs of both kinds share has the +/// `not_affected` statement of the patched ones first, then one +/// `affected` statement per PURL: a reader that keeps the last statement +/// of a document about a product and a vulnerability keeps one that says +/// `affected`. With neither kind of PURL the document is /// [`build_document_marking_unverified`]'s, byte for byte. pub fn build_document_with( manifest: &PatchManifest, @@ -147,15 +174,23 @@ pub fn build_document_with( let redirected_set = set(attested.redirected); let unverified_set = set(attested.unverified); let code_not_present_set = set(attested.code_not_present); - - // vuln-id -> (aliases, impact-statement parts, subcomponent PURLs) + let actions: BTreeMap<&str, &str> = attested + .affected + .iter() + .map(|(purl, action)| (purl.as_str(), action.as_str())) + .collect(); + + // (vuln-id, affected PURL) -> (aliases, statement parts, subcomponent + // PURLs): the patched PURLs of an ID share a group, and each affected + // one has its own. // BTreeMap/BTreeSet keep every output field sorted, which keeps // statement order deterministic and helps reproducibility for // downstream diffs. - let mut grouped: BTreeMap = BTreeMap::new(); + let mut grouped: BTreeMap<(String, Option<&str>), VulnGroup> = BTreeMap::new(); for (purl, record) in &manifest.patches { - if !applied_set.contains(purl.as_str()) { + let action = actions.get(purl.as_str()); + if action.is_none() && !applied_set.contains(purl.as_str()) { continue; } // A basis that rests on the patch's own artifact (vendored, @@ -166,9 +201,14 @@ pub fn build_document_with( && !redirected_set.contains(purl.as_str()) && !unverified_set.contains(purl.as_str()); for (vuln_id, info) in &record.vulnerabilities { - let entry = grouped.entry(vuln_id.clone()).or_default(); + let alone = action.map(|_| purl.as_str()); + let entry = grouped.entry((vuln_id.clone(), alone)).or_default(); entry.aliases.extend(info.cves.iter().cloned()); entry.subcomponents.insert(purl.clone()); + if let Some(action) = action { + entry.parts.insert(action.to_string()); + continue; + } let mut part = if code_not_present { format!("{CODE_NOT_PRESENT_PREFIX} {} is part of it", record.uuid) } else if vendored_set.contains(purl.as_str()) { @@ -182,7 +222,7 @@ pub fn build_document_with( part.push_str(NOT_VERIFIED_SUFFIX); } entry.patched |= !code_not_present; - entry.impact_parts.insert(part); + entry.parts.insert(part); } } @@ -191,7 +231,7 @@ pub fn build_document_with( } let mut statements = Vec::with_capacity(grouped.len()); - for (vuln_id, group) in grouped { + for ((vuln_id, affected), group) in grouped { let subcomponents = group .subcomponents .into_iter() @@ -207,16 +247,22 @@ pub fn build_document_with( // (purl, vuln) pair, so every group present in `grouped` // has ≥1 entry. The defensive `None` arm stays in case a // future refactor decouples grouping from impact tracking. - let impact_statement = if group.impact_parts.is_empty() { + let words = if group.parts.is_empty() { None } else { - Some( - group - .impact_parts - .into_iter() - .collect::>() - .join("; "), - ) + Some(group.parts.into_iter().collect::>().join("; ")) + }; + let (status, justification, impact_statement, action_statement) = if affected.is_some() { + (Status::Affected, None, None, words) + } else { + // A patch in place for any subcomponent is a mitigation; with + // none, the statement rests on the code not being there. + let justification = if group.patched { + Justification::InlineMitigationsAlreadyExist + } else { + Justification::VulnerableCodeNotPresent + }; + (Status::NotAffected, Some(justification), words, None) }; statements.push(Statement { @@ -233,17 +279,11 @@ pub fn build_document_with( hashes: None, subcomponents, }], - status: Status::NotAffected, + status, supplier: None, - // A patch in place for any subcomponent is a mitigation; with - // none, the statement rests on the code not being there. - justification: Some(if group.patched { - Justification::InlineMitigationsAlreadyExist - } else { - Justification::VulnerableCodeNotPresent - }), + justification, impact_statement, - action_statement: None, + action_statement, }); } @@ -264,7 +304,9 @@ pub fn build_document_with( struct VulnGroup { aliases: BTreeSet, subcomponents: BTreeSet, - impact_parts: BTreeSet, + /// What each PURL adds to the impact statement of a `not_affected` + /// statement, or the action statement of an `affected` one. + parts: BTreeSet, /// Some subcomponent is attested because a patch is in place. patched: bool, } @@ -322,6 +364,23 @@ mod tests { build_document(manifest, applied, &[], &[], &opts()) } + /// [`build_document_with`] with `applied` and `affected` only. + fn build_affected( + manifest: &PatchManifest, + applied: &[String], + affected: &[(String, String)], + ) -> Option { + build_document_with( + manifest, + &Attested { + applied, + affected, + ..Attested::default() + }, + &opts(), + ) + } + #[test] fn empty_applied_returns_none() { let manifest = PatchManifest::new(); @@ -1159,6 +1218,7 @@ mod tests { redirected, unverified, code_not_present: ¬_present, + ..Attested::default() }, &opts(), ) @@ -1176,4 +1236,105 @@ mod tests { ); } } + + /// A PURL the build takes without its patch is attested as affected: + /// each vulnerability of its record gets a statement that names the + /// PURL under the product as a `not_affected` statement does, and + /// tells in its action statement what to do. It carries no + /// justification and no impact statement. A document of such + /// statements alone is a document. + #[test] + fn an_affected_purl_gets_an_affected_statement_per_vulnerability() { + let mut manifest = PatchManifest::new(); + manifest.patches.insert( + "pkg:npm/x@1.0.0".to_string(), + record( + "u1", + vec![("GHSA-aaaa", vec!["CVE-1"]), ("GHSA-bbbb", vec![])], + ), + ); + let affected = [("pkg:npm/x@1.0.0".to_string(), "Pin it.".to_string())]; + let doc = build_affected(&manifest, &[], &affected).unwrap(); + let said: Vec<_> = (doc.statements.iter()) + .map(|st| (st.vulnerability.name.as_str(), &st.vulnerability.aliases)) + .collect(); + let cve = vec!["CVE-1".to_string()]; + assert_eq!(said, [("GHSA-aaaa", &cve), ("GHSA-bbbb", &vec![])]); + let patched = build_plain(&manifest, &["pkg:npm/x@1.0.0".to_string()]).unwrap(); + for (st, not_affected) in doc.statements.iter().zip(&patched.statements) { + assert_eq!(st.status, Status::Affected); + assert_eq!(st.action_statement.as_deref(), Some("Pin it.")); + assert_eq!((st.justification, &st.impact_statement), (None, &None)); + assert_eq!(st.products, not_affected.products); + assert_eq!(st.timestamp.as_deref(), Some(doc.timestamp.as_str())); + } + } + + /// A vulnerability that a patched PURL and affected ones share has the + /// `not_affected` statement of the patched one first, then an + /// `affected` statement for each of the others, with that PURL alone + /// and its own action, also where two share a patch and so the words. + /// A PURL in both sets is affected, and one whose record names no + /// vulnerability gets no statement. + #[test] + fn each_affected_purl_of_a_vulnerability_has_a_statement_of_its_own() { + let mut manifest = PatchManifest::new(); + for (purl, uuid, vulns) in [ + ("pkg:npm/built@1.0.0", "u-built", vec!["GHSA-shared"]), + ("pkg:npm/lost@1.0.0", "u-lost", vec!["GHSA-shared"]), + ("pkg:npm/lost@2.0.0", "u-lost", vec!["GHSA-shared"]), + ( + "pkg:pypi/gone@3.0", + "u-gone", + vec!["GHSA-shared", "GHSA-own"], + ), + ("pkg:npm/silent@1.0.0", "u-silent", vec![]), + ] { + let vulns = vulns.into_iter().map(|id| (id, vec!["CVE-1"])).collect(); + manifest + .patches + .insert(purl.to_string(), record(uuid, vulns)); + } + let applied = [ + "pkg:npm/built@1.0.0".to_string(), + "pkg:npm/lost@1.0.0".to_string(), + ]; + let affected = [ + ("pkg:npm/lost@1.0.0", "Pin u-lost."), + ("pkg:npm/lost@2.0.0", "Pin u-lost."), + ("pkg:pypi/gone@3.0", "Revert u-gone."), + ("pkg:npm/silent@1.0.0", "Pin u-silent."), + ] + .map(|(purl, action)| (purl.to_string(), action.to_string())); + let doc = build_affected(&manifest, &applied, &affected).unwrap(); + let said: Vec<_> = (doc.statements.iter()) + .map(|st| { + let subs = &st.products[0].subcomponents; + let subs: Vec<&str> = subs.iter().map(|sub| sub.id.as_str()).collect(); + let words = st + .impact_statement + .as_deref() + .or(st.action_statement.as_deref()); + (st.vulnerability.name.as_str(), st.status, subs, words) + }) + .collect(); + let affected_by = |id, purl, action| (id, Status::Affected, vec![purl], Some(action)); + assert_eq!( + said, + [ + affected_by("GHSA-own", "pkg:pypi/gone@3.0", "Revert u-gone."), + ( + "GHSA-shared", + Status::NotAffected, + vec!["pkg:npm/built@1.0.0"], + Some("Patched via Socket patch u-built") + ), + affected_by("GHSA-shared", "pkg:npm/lost@1.0.0", "Pin u-lost."), + affected_by("GHSA-shared", "pkg:npm/lost@2.0.0", "Pin u-lost."), + affected_by("GHSA-shared", "pkg:pypi/gone@3.0", "Revert u-gone."), + ] + ); + let silent = [affected[3].clone()]; + assert!(build_affected(&manifest, &[], &silent).is_none()); + } } diff --git a/crates/socket-patch-core/src/vex/conformance_tests.rs b/crates/socket-patch-core/src/vex/conformance_tests.rs index 7e33eef33..9cbb9154f 100644 --- a/crates/socket-patch-core/src/vex/conformance_tests.rs +++ b/crates/socket-patch-core/src/vex/conformance_tests.rs @@ -234,10 +234,10 @@ fn builder_only_emits_not_affected_with_justification() { #[test] fn affected_statement_in_json_omits_justification() { - // We never construct affected statements via the builder, but - // we DO ship the type — pin the schema invariant that an - // affected statement with no justification serializes without - // emitting a `justification` key (per spec). + // Pin the schema invariant at the type: an affected statement + // with no justification serializes without emitting a + // `justification` key (per spec). Section 19 holds the builder's + // own affected statements to it. let s = Statement { id: None, vulnerability: Vulnerability { @@ -668,8 +668,9 @@ fn statement_level_id_renders_under_at_sign() { #[test] fn no_two_statements_share_a_vulnerability_name() { // The builder's transpose groups by vuln id, so a well-formed doc - // never emits two statements for the same vulnerability — merging - // collapses them into one (with all PURLs as subcomponents). Pin + // of patched packages never emits two statements for the same + // vulnerability — merging collapses them into one (with all PURLs as + // subcomponents; section 19 has the `affected` statement beside it). Pin // that at the document layer: `sample_doc` carries two *distinct* // vulns (GHSA-aaaa / GHSA-bbbb) and `merged_doc` collapses a shared // one (GHSA-shared) to a single statement. A grouping regression @@ -713,3 +714,116 @@ fn fixtures_carry_subcomponents_so_at_id_walks_have_teeth() { "merged_doc must produce a product with >=2 subcomponents" ); } + +// ── 19. `affected` statements ─────────────────────────────────── + +/// `sample_doc`'s manifest, with lodash as a package the build takes +/// without its patch. `patched` says whether minimist is attested as +/// patched beside it: without it the document holds `affected` +/// statements alone. +fn affected_doc(patched: bool) -> Document { + let mut manifest = PatchManifest::new(); + manifest.patches.insert( + "pkg:npm/lodash@4.17.20".to_string(), + record("uuid-1", &[("GHSA-aaaa", &["CVE-2024-1", "CVE-2024-2"])]), + ); + manifest.patches.insert( + "pkg:npm/minimist@1.2.0".to_string(), + record("uuid-2", &[("GHSA-aaaa", &["CVE-2024-1"])]), + ); + let applied: &[String] = if patched { + &["pkg:npm/minimist@1.2.0".to_string()] + } else { + &[] + }; + let action = "Run `socket-patch scan --mode hosted`.".to_string(); + let affected = [("pkg:npm/lodash@4.17.20".to_string(), action)]; + build_document_with( + &manifest, + &Attested { + applied, + affected: &affected, + ..Attested::default() + }, + &options(), + ) + .expect("build affected doc") +} + +#[test] +fn an_affected_statement_carries_an_action_statement_and_no_justification() { + // Spec: a statement with the status `affected` MUST carry an action + // statement; `justification` and `impact_statement` go with + // `not_affected`. A document of `affected` statements alone is a + // document: it has a statement, and every required field. + let alone = affected_doc(false); + assert_eq!(alone.statements.len(), 1); + let mixed = affected_doc(true); + // The patched package and the affected one each have a statement for + // the vulnerability they share. + let said: Vec<_> = (mixed.statements.iter()) + .map(|st| (st.vulnerability.name.as_str(), st.status)) + .collect(); + assert_eq!( + said, + [ + ("GHSA-aaaa", Status::NotAffected), + ("GHSA-aaaa", Status::Affected) + ] + ); + for doc in [alone, mixed] { + let v = serde_json::to_value(&doc).unwrap(); + for key in [ + "@context", + "@id", + "author", + "timestamp", + "version", + "statements", + ] { + assert!(v.get(key).is_some(), "required key {key:?} missing"); + } + for (st, json) in doc + .statements + .iter() + .zip(v["statements"].as_array().unwrap()) + { + let obj = json.as_object().unwrap(); + for key in ["vulnerability", "timestamp", "products", "status"] { + assert!(obj.contains_key(key), "required key {key:?} missing"); + } + assert_eq!(st.timestamp.as_deref(), Some(doc.timestamp.as_str())); + assert!(!st.vulnerability.name.is_empty()); + let [product] = &st.products[..] else { + panic!("not one product: {json}"); + }; + assert_eq!(product.id, "pkg:npm/test-app@1.0.0"); + assert!(!product.subcomponents.is_empty()); + assert!(product.subcomponents.iter().all(|sub| !sub.id.is_empty())); + let reserved = ["justification", "impact_statement"]; + match st.status { + Status::Affected => { + assert_eq!(json["status"], "affected"); + let action = st.action_statement.as_deref().unwrap_or_default(); + assert!(!action.is_empty(), "affected requires an action_statement"); + assert_eq!(json["action_statement"], action); + let about = product.subcomponents.len(); + assert_eq!(about, 1, "an action statement is about one package"); + for key in reserved { + assert!(!obj.contains_key(key), "{key} goes with not_affected"); + } + } + _ => { + assert_eq!(json["status"], "not_affected"); + assert!(st.justification.is_some() && st.impact_statement.is_some()); + assert!(!obj.contains_key("action_statement")); + } + } + } + // Nothing is `null`, and the text reads back as the document. + let text = serde_json::to_string_pretty(&doc).unwrap(); + assert!(!text.contains("null"), "{text}"); + let reparsed: Document = serde_json::from_str(&text).unwrap(); + assert_eq!(reparsed, doc); + } +} diff --git a/crates/socket-patch-core/src/vex/schema.rs b/crates/socket-patch-core/src/vex/schema.rs index 0a6c88182..e08ad3c68 100644 --- a/crates/socket-patch-core/src/vex/schema.rs +++ b/crates/socket-patch-core/src/vex/schema.rs @@ -92,9 +92,8 @@ pub struct Statement { /// Free-form explanation paired with `not_affected`. #[serde(skip_serializing_if = "Option::is_none", default)] pub impact_statement: Option, - /// Canonical companion to `status == affected` (per spec). - /// We never emit `affected` today, but the field exists so the type - /// round-trips a richer doc through our parser. + /// Canonical companion to `status == affected` (per spec): what to + /// do about it. Set by `vex::build::build_document_with`. #[serde(skip_serializing_if = "Option::is_none", default)] pub action_statement: Option, } diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index 8be01fe27..decda81f4 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -6,6 +6,9 @@ //! the patch from the VEX document. Callers feed the failures into a //! stderr warning + `--json` envelope warning list; the spec we agreed //! on is "never emit `affected` or `under_investigation` — just omit". +//! A failed check shows no more than that this copy is not the patched +//! one. `affected` is for a package the caller knows the build takes +//! unpatched (`vex::build::build_document_with`). //! //! The CLI is responsible for resolving PURL → on-disk package path //! (it already does this for `apply` / `scan` via the ecosystem diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 7c455c09b..bc0ec3d68 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2736,9 +2736,123 @@ 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 +installed. In a Bazel workspace (the Bazel root of the section on `.bazelignore` above) they +also read `MODULE.bazel` and the files it includes, for the calls of three rulesets that hand +a lock to Bazel: + +| Call | Files it names | +|---|---| +| aspect_rules_js `npm.npm_translate_lock` | `pnpm_lock` | +| rules_python `pip.parse` | `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` | +| rules_ruby `ruby.bundle_fetch` | `gemfile_lock`, `gemfile` | + +Each of them builds a package from what those files name, in a repository of Bazel's own, +and never from `node_modules`, a virtualenv or a gem home. So two kinds of patch are in no +build of Bazel's, and the document says of their package that it is `affected`, not that it +is patched: + +- **A patch in the installed copy** (agent mode) of an npm, PyPI or RubyGems package, when + such a call names the project's own lock and that lock lists the package at that version + without naming the patch. The project's own lock is the one in the project's directory, or + the lock of a pnpm workspace above it that names that directory among its `importers`. + Measured for rules_js 3.6.0 on Bazel 9.3.2, 8.8.2 and 7.7.2: the build prints the + unpatched package before `scan --mode agent` and after it. +- **A PyPI patch committed under `.socket/vendor`** (vendored mode), when such a call names + the file that points at the copy. rules_python 2.5.0-rc4 takes the path of the line for + the name of a project, and the build of everything the hub serves fails (same three + releases). A vendored npm tarball is built by rules_js and keeps its statement. So does a + vendored gem, for another reason: no build here has shown what rules_ruby does with one, + so nothing is said of it. + +Each advisory of such a patch gets a statement of the package's own with the status +`affected`. It names that package alone under the product, and its `action_statement` says +what Bazel builds the package from and what to run so that the build holds the patch. It +has no `justification` and no `impact_statement`. Packages that share an advisory are not +merged into one such statement, so each action statement is about one package; the +`not_affected` statement of the advisory, for the packages that are patched, comes first: + +```json +{ + "vulnerability": { "name": "GHSA-xxxx-xxxx-xxxx", "aliases": ["CVE-2024-0001"] }, + "timestamp": "2026-11-19T15:14:47Z", + "products": [ + { "@id": "pkg:npm/shop@1.0.0", "subcomponents": [{ "@id": "pkg:npm/left-pad@1.3.0" }] } + ], + "status": "affected", + "action_statement": "Bazel builds this package from pnpm-lock.yaml (`npm.npm_translate_lock`, MODULE.bazel:6), which does not name Socket patch 7a11e000-...: the patch is only in the installed copy. Run `socket-patch scan --mode hosted` in the directory of that lock to pin the patch there. If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor)." +} +``` + +The last sentence is for a repository that ships the installed tree (see `--no-bazel` below). +For a vendored PyPI package the action statement does not have it, since the installed tree is +not the patched one there either: + +``` +Bazel builds no package from the line of requirements.txt that points at the copy of Socket patch 7a11e000-... under .socket/vendor (`pip.parse`, MODULE.bazel:15): the build fails, or takes the registry's package. Run `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. +``` + +Both ways out are tested on real Bazel: after the hosted scan the build prints the patched +package and the document says `not_affected`. + +A run tells a person the same in a warning (`vex_bazel_not_in_build`, one per package): + +``` +Warning: pkg:npm/left-pad@1.3.0: the VEX document says affected. Bazel builds this package from pnpm-lock.yaml (`npm.npm_translate_lock`, MODULE.bazel:6), which does not name Socket patch 7a11e000-...: the patch is only in the installed copy. Run `socket-patch scan --mode hosted` in the directory of that lock to pin the patch there. If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor). +``` + +Nothing is left out of the document for this reason, so the document is always written: +`vex` exits 0 with it, also when every statement says `affected`, and `scan --vex`, +`apply --vex` and `vendor --vex` write it and keep their exit code. No run reports such a +package as patched. `vex --json` reports each `affected` statement as a `skipped` event with +`errorCode: "vex_bazel_not_in_build"` and `details.status: "affected"`, beside the +`verified` events of the `not_affected` ones. `summary.verified` counts only those, and the +envelope's `status` is `partialFailure`, as for every run that leaves a patch unattested. A +command run with `--vex` keeps its own status, and the `vex` object of its envelope says +how many statements were written (`statements`) and how many of them say `affected` +(`affected`, left out when none does), with the warning in `vex.warnings`. The line a +person reads counts them too: `Wrote OpenVEX document with 2 statements (1 affected) to +out.json`. `--no-verify` changes none of this. + +When a hub reads the project's own lock, the document describes what Bazel builds from that +lock. A repository that ships what its package manager installed (a container image built +with `pnpm install` and `socket-patch apply`, say) and keeps the hub for something else, such +as its tests, says so with `--no-bazel` on `vex`, with `--vex-no-bazel` on `scan`, `apply` and +`vendor`, or with `SOCKET_VEX_NO_BAZEL=1` in the environment. The Bazel workspace is then not +read: the document describes the installed tree, and it, the warnings, the exit code and +every line of the run are those of the same checkout without its Bazel files. The option +changes nothing outside a Bazel workspace. + +Nothing changes where the files do not show such a call: outside a Bazel workspace, in a +`--global` run, for a hosted pin, for a project whose own lock no call names, and wherever +the workspace is not read with certainty: the statement is then `not_affected`, as without +Bazel. A lock elsewhere that lists the same package is the +lock of another project and decides nothing for this one: in a directory beside the project, +below it, or above it without naming it among the importers of a pnpm workspace (a pnpm app +beside a Java build; a project with a lock of its own under a root whose lock a hub reads; a +Python or Ruby project below the directory of the file a hub reads). The workspace is not +read with certainty when a module file is missing, cannot be read or holds a statement the +reader does not follow (a `load`, an `if`, a hub proxy handed to anything but `use_repo` or +`inject_repo`); when the call gives its file as anything but a plain string label of the +main repository, passes `*` or `**`, or is a `pip.parse` with `uv_lock`, whose packages +rules_python 2.2.0 and later can take from that file; when the lock cannot be read, is +larger than 64 MiB, or is a link that leads out of the Bazel root (Bazel follows such a +link; socket-patch reads no file outside the root); and when a `WORKSPACE`, +`WORKSPACE.bazel` or `WORKSPACE.bzlmod` at the root holds more than a `workspace(...)` call. +Bazel 7 reads that file beside `MODULE.bazel`, and its calls are not read yet; Bazel 9 never +reads it, so a workspace on Bazel 9 that still has such a file keeps its `not_affected` +statements although nothing builds the patched copy. A workspace without a `MODULE.bazel` +is not read at all. In each of these the document is the one of a +project without Bazel. Flags outside the committed files (`--override_repository`, an rc +file) and BUILD files are not read either. + +Three more things change no statement. A call counts only when it is a statement of its own, +which Bazel runs once: one in a comprehension, behind an `and`, in a conditional or in the +arguments of another call may never run. Of a pnpm lock the project documents are read: a +package that only the document pnpm 11 keeps for its own configuration lists is not one +rules_js links. And a patch whose record names no advisory gets no statement from any run, +so it is not looked at here: a run over such a patch alone ends as it does without Bazel. + +The document and the build 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 @@ -2755,18 +2869,45 @@ after the undo `vex` writes no document. For PyPI on Bazel 8.5 and later a hoste `--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. +In every other Bazel shape nothing checks the document against the build, and in these the +document is still wrong (`not_affected` while Bazel builds the unpatched package, or while +the build is broken): + +- **Agent mode beside rules_js, rules_python or rules_ruby**, wherever the statement does + not say `affected` above. `npm_translate_lock` is given an `npm_package_lock` or a + `yarn_lock`, which are not read, or `pip.parse` a `uv_lock`. The hub reads a lock above + the project that does not name the project among its importers. The hub reads a lock + below the directory the command runs in: a run at the repository root while the hub reads + `web/pnpm-lock.yaml`. A Python or Ruby project lies below the directory of the file the + hub reads. The call is not a statement of its own, or passes `*` or `**`. A `WORKSPACE` + file at the root defines something, or the workspace has no `MODULE.bazel`. Measured for + rules_js, which builds from the lock and never reads the patched `node_modules`. +- **Vendored mode for PyPI**, where the workspace is not read with certainty: a + `WORKSPACE` file that defines something, no `MODULE.bazel`, a call that is not a statement + of its own, a file that is not given as a plain string label. And where the line that + points at the copy is in a requirements file that the file the call names brings in with + `-r`. Measured for PyPI, where the build fails. +- **Vendored mode for RubyGems** beside `ruby.bundle_fetch`. rules_ruby 1.0.0-rc2 runs + `bundle install` in a repository that holds the Gemfile, its lock and the files the call + lists as `srcs`, so the path of the copy may not exist there. Read from its source; no + build has been run, so the statement is left as it is. +- **A vendored package whose own files the hub does not read**, while the lock the hub does + read still lists the registry's package: a uv or Poetry project vendored through + `pyproject.toml` and its lock while `pip.parse` reads a requirements file exported before; + an npm package vendored through `package-lock.json` while `npm_translate_lock` reads a + `pnpm-lock.yaml`. Bazel builds the registry's package. The check of an installed copy is + not applied to them yet: rules_js can rewrite the pnpm lock from the other files under + `update_pnpm_lock`, `npm_package_lock` or `yarn_lock`, and rules_python can take the + packages from `uv_lock`, so the lock a call names does not always decide. +- **Hosted mode for PyPI**, when a `pip.parse` or `pip_parse` takes the requirements of the + build's platform from another file than the one socket-patch rewrote. +- **Go** under a `go_repository` rule of a `WORKSPACE`, in hosted and vendored mode; and + 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. + +Do not publish a document for an artifact that Bazel built outside the shapes listed above +as tested. 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 diff --git a/docs/usage.md b/docs/usage.md index 95cae7ff8..fd94cf856 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -278,6 +278,12 @@ any file, so it also attests an agent-mode patch whose files are unpatched or mi It never does so silently: the run warns how many statements it emitted that way, and each one ends its impact statement with `; not verified on disk`. +In a Bazel workspace the document describes what Bazel builds from the project's lock, and +says `affected` of a package whose patch is only in the installed copy (see +[Bazel workspaces: VEX](ecosystems.md#bazel-workspaces-vex)). `--no-bazel` (`--vex-no-bazel` +on `scan`, `apply` and `vendor`, or `SOCKET_VEX_NO_BAZEL` in the environment) makes it describe +what the package manager installed; use it when the installed tree is what you ship. + The product identifier is inferred from the Git origin or project metadata. Use `--product ` when inference is unavailable or unsuitable. A project with neither (an application with no Git remote and no named project file) must diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 183cb589a..4e6f49f99 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 1459 + "max": 1711 }, "lock-readers": { "paths": [