diff --git a/README.md b/README.md index 6b2073014..d2a39c4c1 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,8 @@ socket-patch scan --package lodash # limit selection to a package socket-patch scan --max-new-patches 5 # introduce at most five new patches socket-patch scan 'apps/*' # scan projects in a monorepo socket-patch get pkg:npm/lodash@4.17.20 # target one package version +socket-patch show pkg:npm/lodash@4.17.20 # look inside a patch: fixes, measurements, diff +socket-patch list # what is patched here; in a terminal, browse and open patches socket-patch vendor # eject an existing hosted patch set socket-patch repair # restore agent or vendored patch artifacts socket-patch rollback lodash # restore one package to upstream diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 522d792d9..c2cf6cc82 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -21,6 +21,7 @@ For task-oriented guidance, start with [usage](../../docs/usage.md), | `vendor` | — | Eject patched dependencies into committable `.socket/vendor/` and rewire lockfiles | | `list` | — | Print patches in the local manifest, plus the vendor ledger's records (v5.0) and the hosted pins the lockfiles wire (labeled; see the action matrix; an empty project exits 0) | | `get` | — | Fetch a selected patch in the project's current mode (hosted for a project with no patch state); `--mode agent` selects in-place application, also the default with `--save-only` or global targeting. Requires positional `identifier`. | +| `show` | — | (additive) Read-only: print what is inside one patch — the advisories it fixes, what Socket measured about it, the files it changes and the unified diff of each. Requires positional `identifier` (a patch UUID, or a PURL, package name, CVE or GHSA id; several matching patches open a menu on a terminal, and the best ranked is shown otherwise, with the others named on stderr). Changes nothing in the project and takes no lock. See [`show`](#show-inspect-a-patch). | | `apply` | — | Agent mode: apply patches from the local manifest | | `rollback` | — | **Full-state rollback (v5.0, MAJOR)**: restore original files AND unwind vendored lockfile wiring / restore hosted pins to their upstream registry entries, remove the rolled-back entries from the manifest, and GC their blobs/archives; takes optional variadic positional `targets` (PURL \| UUID \| package name \| path glob). See [Rollback command contract](#rollback-command-contract-v50) | | `remove` | — | Restore and remove one patch across hosted, vendored, and agent state; requires positional `identifier`. | @@ -239,7 +240,7 @@ it holds no patch. | Mechanism | Evidence | | --- | --- | -| pnpm | `pnpm.patchedDependencies` in `package.json`; `patchedDependencies` in `pnpm-workspace.yaml` and `pnpm-lock.yaml`; registry lock keys carrying `patch_hash` or `patched` markers, including legacy and multi-document locks | +| pnpm | `pnpm.patchedDependencies` in `package.json`; `patchedDependencies` in `pnpm-workspace.yaml` and `pnpm-lock.yaml`; registry lock keys carrying `patch_hash` or `patched` markers, including legacy and multi-document locks. A key carries the hash of the package it names as a group of its own (`a@1.0.0(patch_hash=…)`); a dependent's key that only repeats a patched peer's key inside its peer group (`b@2.0.0(a@1.0.0(patch_hash=…))`) is not evidence for `b`, which pnpm installs unpatched | | Yarn Berry | User `patch:` references in dependency/resolution fields or lock resolutions; builtin-only compatibility patches are exempt | | `patch-package` (npm / Yarn Classic / other npm layouts) | Default `patches/` filenames, including scoped (`@scope+name`, or a `@scope/` subdirectory: the directory is read recursively, as patch-package reads it), nested (`++`), sequenced and `.dev.patch` files; literal `--patch-dir` paths in package scripts. A patch protects every version of its package: patch-package applies it to whichever version is installed and only warns when the file name's version differs | | Native npm / Bun | Root `patchedDependencies`; npm lock `patched` records; Bun text-lock declarations (binary Bun installs also have the root declaration) | @@ -286,6 +287,9 @@ Beyond the globals above, each subcommand defines a small set of local arguments | `vendor` | `--revert` | `SOCKET_VENDOR_REVERT` | Undo vendoring: restore recorded original lockfile fragments + remove `.socket/vendor/` artifacts. Works without a manifest. A package vendored over a hosted pin returns to its upstream registry entry, never to hosted (see "Takeover reconciliation") | | `vendor` | `--check` | — | Offline, read-only artifact and wiring audit; exits 1 on drift. Conflicts with `--revert`. | | `vendor` | `--local-repo ` | — | With `--check`, also inspect suffixed Maven jar/POM copies in this cache for conflicts. | +| `show` | `--file ` (repeatable) | — | Print the diff of these files only: a path of the patch, or the end of one at a `/` (`a.js` selects `lib/a.js`). A path the patch does not change is an error (exit 1, `file_not_in_patch`) that lists the ones it does | +| `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 | | `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 | @@ -330,9 +334,19 @@ For a **9.0 root lock**, the CLI ensures `pnpm-workspace.yaml` carries `trustLoc **Withdrawn pins (`scan --mode hosted`, additive/MINOR)**: before the rewrite, a hosted scan checks every patch uuid the lockfiles pin, for a package this run covered, against the reference endpoint. A pin the server reports `withdrawn` (unpublished) or `not_found` (no such patch) no longer installs (the patch server answers 410), so it is restored to its default upstream registry entry: the same restore `rollback` runs (see "Hosted unwind coverage"), under the apply lock, `--dry-run` previewing it without writing. If the package has a replacement patch on offer, the rewrite that follows pins the replacement. Each restored pin is one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "patch_withdrawn"` and `details.mode: "hosted"`; the restore's advisories (`redirect_bun_reinstall_required`, `redirect_pypi_reinstall_required`, `redirect_vlt_reinstall_required`) join `warnings[]`. Only those two statuses unpin: a pin merely absent from the search results (a failed batch, the free-only proxy fallback, a lapsed paid entitlement), or one reported `forbidden`, `pending_build` or `build_failed`, is kept. If the reference lookup fails, every pin is kept with a `redirect_withdrawn_check_failed` warning; a pin the restore refuses, or whose restored files cannot be written (or the apply lock being held), is kept with a `redirect_withdrawn_restore_failed` warning naming the remedy, and is never reported as `rolledBack`: the write is all or nothing (see "Hosted unwind coverage"), so a failed one leaves every pin of that restore in place. Neither changes the status or the exit code. The one exception is a write that failed part-way and could not put a file back: the lockfiles are then neither pinned nor restored, so the run stops before the rewrite with the top-level error `lockfile_write_failed` (exit 1), whose message names each such file and the state it is left in. A run whose every search batch failed exits before the check. +### `show`: inspect a patch + +`socket-patch show ` reads one patch from the patch service and prints it. It never reads or writes the project's patch state, takes no lock, and needs network access (`--offline` is `offline_unsupported`, exit 1). A read the service refuses the run's token (401 / 403) is asked of the public service, which has the free patches; when that has no such patch either, the refusal is the error reported. The search for the patches an identifier names follows the same rule, and any other failure of it (the service down, throttled) is `patch_lookup_failed`: the public service is not asked, so its "nothing for this package" never stands in for an outage. The rows and the pages of `list` on a terminal are read the same way. What the service says about a patch (its description, license, advisory summaries, file paths) is shown as text: control characters in it are left out, and a diff line spells them in caret notation, so nothing in a patch's record drives the terminal. `--json` prints the record as it came. + +- **Which patch.** A UUID names it. A PURL, CVE or GHSA id is searched like `get`'s; a package name is matched against the installed packages by the shared target grammar and each match is searched (a name matching more than eight installed packages asks for a PURL). One patch found is shown. With several, a terminal (stdin and stderr, no `--yes`) gets a menu of them; otherwise the best ranked ([the ranking](#which-patch-gets-selected)) that the account can read is shown (a paid patch ranked above a free one does not stand in its way; the best ranked when it can read none) and the others are named on stderr. No patch found is `no_patches`, exit 1. +- **Output (stdout).** The package purl, its worst severity and tier; the patch UUID, publish date and license; `Fixes:` with one line per advisory (severity, CVE or advisory id, summary); `Measured by Socket:` with the measurement lines (see "Human output conventions"), each with the unpatched package's numbers where they were measured; `N files changed: +A -R` with one line per file; then the unified diff of each file (three lines of context). File content is read from the patch view (`include_before_blobs`) or, on the public proxy, by `beforeHash` / `afterHash` from the blob endpoint. A file over 16 MiB, or whose content cannot be read, is listed with the reason and no diff; a file that is not UTF-8 text is `Binary file changed (N -> M bytes)`. Diff lines are for reading: control characters are spelled in caret notation (`^[`), so file content never drives the terminal, and a line over 400 characters is cut with the count of what was left out. +- **Navigation.** On a terminal (stdin, stdout and stderr), `show` opens the patch full-screen, on the terminal's alternate screen, as the page a row of `list` opens (one reader of the patch and one screen serve both, so the two never differ): one page holding the summary (the fixes and the `Measured by Socket:` lines) and then the diff of every selected file, under the package as a title that stays put. The arrow keys (or `j`/`k`) scroll, PgUp/PgDn page, Home/End (`g`/`G`) go to the ends, `n` and `p` step to the next and the previous file (the key line names the file in view and the position), the left and right arrows shift long lines sideways, and `q`, Esc or Ctrl-C leave. The page is redrawn to fit whenever the terminal changes size, lines are cut rather than wrapped (a tab runs to the next 4-column stop and a wide character takes its two columns), and leaving it puts the terminal back as it was and prints the summary, which is what stays in the scrollback. `--file` limits the page to those files' diffs. With `--no-pager` or `--yes`, when a stream is not a terminal, when the terminal shows no escape sequences (`TERM=dumb`, a console without VT processing), under `SOCKET_DEBUG` (whose lines would land in the frame), on Windows, or when the terminal cannot be set up for it, nothing goes full-screen: the summary and every selected diff print at once, as a pipe gets them. There is no other way a patch is read on a terminal: no file menu and no external pager. +- **`--json`.** One document: `{"command": "show", "status": "success", "patch": {"uuid", "purl", "tier", "publishedAt", "license", "description", "vulnerabilities", "statistics", "files": [{"path", "beforeHash", "afterHash", "added", "removed", "binary"}]}}`. `statistics` is the service's object or `null`; `added` / `removed` are `null` for a file with no diff. No file content is included. A failure is `{"command": "show", "status": "error", "error": {"code", "message"}}` with exit 1; codes: `offline_unsupported`, `patch_lookup_failed`, `no_patches`, `patch_not_found`, `patch_fetch_failed`, `file_not_in_patch`. +- `--silent` prints nothing on success. + ### Scan modes (v5.0) -**Mode resolution (`resolve_mode_flags`, MAJOR in v5.0).** `--mode`, or `--sync` (agent mode), picks the mode. With neither, `scan` and `get` keep the mode the project's patch state already records (`mode_from_project_state`, #1088; both stores are read from the project the resolved manifest belongs to, so a `--manifest-path` into another project consults that project's ledger): a non-empty vendor ledger (`.socket/vendor/state.json`; also an unreadable or malformed one, so the vendored flow reports it) means **vendored**, a manifest holding patches the ledger does not already cover (by key or base purl), or an unreadable or malformed manifest (so the agent flow reports it), means **agent** — a record the ledger covers, as `get --save-only` then `vendor` leaves, is vendored state — and a project with neither runs **hosted** mode — JSON and human alike (see the hosted paragraph below and [`scan` and `get` JSON](#scan-and-get-json-v50-major)). A project holding both agent and vendored state is a usage error (exit 2, code `mode_ambiguous`, naming the three `--mode` values) and writes nothing. So is a vendor ledger beside hosted pins in the project's lockfiles (#1437), the mixed state a partial `--mode hosted` takeover or per-package `get --mode` leaves: hosted mode keeps no ledger, so its pins are its state, and keeping vendored mode would take every pin over. A human-mode run that kept vendored or agent mode says so on stderr (`Note: using --mode vendored because … already holds vendored patches; pass --mode explicitly to switch modes`); `--json` and `--silent` print no note. **Switching modes is always explicit**: the in-place vendored → hosted takeover (see **Staged takeover**) runs only under `--mode hosted`, the hosted → vendored takeover only under `--mode vendored`, and a bare `scan`/`get` never converts a project. With hosted/vendored PATH arguments and no `--mode`, each project directory takes its mode from its own state. The one exception to the state-derived default: a `--prune` or `--global`/`--global-prefix` scan with no mode has no project lockfile to rewire, so it is **report-only** — discovery, the table, the `updates` array and the `redirectState` block below, plus the `--prune` GC — and, in human mode, ends with the hint `To apply these patches in place, run:` / ` socket-patch scan --mode agent [PATHS]` / ` socket-patch get `. Its per-patch listing is headed `Patches available:` (`Patches to apply:` belongs to a run that applies them), and its `--dry-run` prints the same listing and hint as the run it previews, with the `--prune` GC as a read-only preview: a report-only preview never says `Would download and apply N patches`. A global scan's hint carries the run's scope, so it can be run verbatim: `-g` (`scan --mode agent -g` / `get -g <…>`), or `--global-prefix ` when a prefix was given (the directory shell-quoted when it needs it). An explicit `--mode hosted` or `--mode vendored` with `--global`/`--global-prefix` is a usage error (exit 2: global installs have no project lockfile to redirect, or to wire vendored artifacts into); `get` enforces the same rule with the same wording. +**Mode resolution (`resolve_mode_flags`, MAJOR in v5.0).** `--mode`, or `--sync` (agent mode), picks the mode. With neither, `scan` and `get` keep the mode the project's patch state already records (`mode_from_project_state`, #1088; both stores are read from the project the resolved manifest belongs to, so a `--manifest-path` into another project consults that project's ledger): a non-empty vendor ledger (`.socket/vendor/state.json`; also an unreadable or malformed one, so the vendored flow reports it) means **vendored**, a manifest holding patches the ledger does not already cover (by key or base purl), or an unreadable or malformed manifest (so the agent flow reports it), means **agent** — a record the ledger covers, as `get --save-only` then `vendor` leaves, is vendored state — and a project with neither runs **hosted** mode — JSON and human alike (see the hosted paragraph below and [`scan` and `get` JSON](#scan-and-get-json-v50-major)). A project holding both agent and vendored state is a usage error (exit 2, code `mode_ambiguous`, naming the three `--mode` values) and writes nothing. So is a vendor ledger beside hosted pins in the project's lockfiles (#1437), the mixed state a partial `--mode hosted` takeover or per-package `get --mode` leaves: hosted mode keeps no ledger, so its pins are its state, and keeping vendored mode would take every pin over. A human-mode run that kept vendored or agent mode says so on stderr (`Note: using --mode vendored because … already holds vendored patches; pass --mode explicitly to switch modes`); `--json` and `--silent` print no note. **Switching modes is always explicit**: the in-place vendored → hosted takeover (see **Staged takeover**) runs only under `--mode hosted`, the hosted → vendored takeover only under `--mode vendored`, and a bare `scan`/`get` never converts a project. With hosted/vendored PATH arguments and no `--mode`, each project directory takes its mode from its own state. The one exception to the state-derived default: a `--prune` or `--global`/`--global-prefix` scan with no mode has no project lockfile to rewire, so it is **report-only** — discovery, one row per package a patch is available for, the `updates` array and the `redirectState` block below, plus the `--prune` GC — and, in human mode, ends with the hint `To apply these patches in place, run:` / ` socket-patch scan --mode agent [PATHS]` / ` socket-patch get `. Its rows are headed `Patches available:` (under `--verbose` each patch is listed in full instead; `Patches to apply:` heads that listing in a run that applies them), and its `--dry-run` prints the same listing and hint as the run it previews, with the `--prune` GC as a read-only preview: a report-only preview never says `Would download and apply N patches`. A global scan's hint carries the run's scope, so it can be run verbatim: `-g` (`scan --mode agent -g` / `get -g <…>`), or `--global-prefix ` when a prefix was given (the directory shell-quoted when it needs it). An explicit `--mode hosted` or `--mode vendored` with `--global`/`--global-prefix` is a usage error (exit 2: global installs have no project lockfile to redirect, or to wire vendored artifacts into); `get` enforces the same rule with the same wording. **Global scope never touches the project's state (v5.0).** A `--global`/`--global-prefix` run that starts inside a project acts on the global installs only. The `--cwd` project's hosted pins and vendor ledger are not its target: `rollback` and `remove` run no hosted or vendored leg (they restore the global copies and drop their manifest records; `rollback` keeps the manifest records of purls the project vendors), a pre-v5 hosted ledger is never retired, and the project's vendor ledger does not own the global copies, so `apply` and `scan --mode agent` patch the global copy of a purl the project vendors (no `vendored` skip, no `vendored_ownership_retained` warning). One global store is the project's own install: a NuGet project restores into the global packages folder, so when the global run's NuGet folder is one the project restores into, the project's vendored NuGet packages there stay the ledger's (#489). `apply` and `scan --mode agent` skip them as `vendored` (scan adds `vendored_ownership_retained`), and `rollback` and `remove` leave them patched, each reported as a `skipped` / `vendored` event (human: ` [skip] (vendored: …)`); `rollback` keeps their manifest records, as above. The project's folders are the ones its restores recorded (`obj/project.assets.json` `packageFolders`), plus the global packages folder while a project under it has no restore yet, so a project that restores into `RestorePackagesPath` leaves the global folder's copies to the global run. The standalone `vendor` command acts only on the project, so every form of it (plain, `--revert`, `--check`) is a usage error under global scope: exit 2, human `Error: cannot be used with vendor[ --revert| --check]: global installs have no project lockfile to …`, JSON `{status: "error", error: {code: "global_scope_unsupported", message}}`, checked before the project is read or locked (#498). @@ -364,7 +378,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Throttling: bounded retry, then a reported failure.** Every patch-API JSON call (the batch query, the per-package patch lists, patch views and VEX record fetches, hosted package references) retries an HTTP `429` or `503` answer up to 3 times (`SOCKET_API_MAX_RETRIES=`, `0`-`10`; `0` = no retry). The wait honors `Retry-After` (delta-seconds or HTTP-date); a `Retry-After` over 30 s is not waited out — the answer is final at once — and one under the jittered first backoff step (`0`, a past date) waits that step instead. Without one it backs off 0.5 s / 1 s / 2 s (each step up to 8 s, with jitter in its upper half). All retries in one run share a 60 s wall-clock window that opens with the run's first retry: a retry whose wait would end after it closes is refused and the answer is final. Parallel requests wait in parallel, so each still gets its retries while the run adds at most about 60 s. Nothing else is retried (401/403 still drive the proxy fallback on the first answer; the public proxy's permanent `503 "Patch API is not configured"` is never retried on any path — the batch query still degrades to the per-package path at once, and a per-package lookup or patch view answering it is the same non-throttle failure it always was, which on the legacy per-package path leaves that package unanswered, see above), and a retried answer folds exactly where the first attempt's would have, so output is identical to an unthrottled run's. A request still throttled after that is a failure in the channel its siblings use: a failed batch is the human `Warning: API batch of failed: ` line and, under `--json`, a run-level `warnings[]` entry `{code: "api_batch_failed", detail: "API batch of failed: "}` (additive; `status` stays `success`, exit 0 — the other batches' packages are reported); a failed per-package patch-list query in the agent / hosted / vendored flows is the human `Warning: could not fetch details for : ` line and, under `--json`, `{code: "patch_details_failed", detail: "could not fetch details for : "}`. When every batch (or every patch-list query) fails, the existing all-failed error envelope and exit 1 apply. The error names the exhausted retry: `Rate limit exceeded (HTTP 429, gave up after 3 retries). Please try again later.` / `API request failed with status 503: (gave up after 3 retries)` (or `(Retry-After s exceeds the 30 s retry cap)` / `(the run's 60 s retry window has closed)`); with retries off it is the pre-retry text. On the token-less legacy per-package proxy path (a proxy without `POST /patch/batch`), a package still throttled (429 / over-capacity 503) after its retries is an unanswered package (see "No patches" needs an answer above): the batch's answered packages are used and it is reported as `patch_lookup_failed` (`partialFailure`, exit 1); when it leaves no package of its batch answered, the batch fails through the batch-failure channel above. Only a PURL the service itself refuses (its own `400`) is skipped individually. Pinned by `tests/scan_api_retry_e2e.rs` and the core crate's `tests/api_retry_e2e.rs`. -**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the table (flagged ` [NOT INSTALLED]`, plus a stderr note), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. +**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the rows of what a hosted or vendored run patches (an agent or report-only run, which patches installed copies, gets a stderr note that they are not installed), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **Server artifact acquisition (v5.0)**: vendoring downloads the patched artifact for the selected UUID, including on a fresh checkout with no installed package. The CLI no longer downloads pristine packages, stages patch blobs, applies patches to vendor copies, or constructs archives. Backend lock and package-identity checks still run before acquisition; git and custom-registry Cargo sources are refused with `vendor_source_unsupported`. Healthy committed artifacts are reused offline. A changed UUID downloads a fresh server artifact; an unhealthy artifact at the recorded UUID uses the exact redownload procedure below, except that a directory copy whose ledger entry has no file inventory (vendored before v5.0) is rebuilt by its backend from a fresh verified download, and a missing or stale Bun workspace mirror over a healthy canonical tarball is rewritten from that tarball by the backend; those cases report the backend's own failure codes. @@ -376,7 +390,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ `scan --sync` is sugar for `--mode agent --prune` — the canonical single-flag agent-mode bot invocation. `scan --json --sync` discovers, applies, and reconciles state in one pass. -**`scan --ecosystems` scopes the crawl (v5.0)**: without `--prune`/`--sync`, a `scan` given `--ecosystems`/`-e` runs only the named ecosystems' crawlers — everything the run counts, queries and shows (`scannedPackages`, the batch query, `packages[]`, the table, `updates[]`, `wiringLive`, the `gem_bundle_config_path_ignored` warning) was already narrowed to them, so the skipped crawls could only be filtered away. The one visible difference: `lockfileOnlyPackages` (and the human "not yet installed" note) counts only the selected ecosystems' lockfile-only entries (a skipped crawl cannot vouch for another ecosystem's uninstalled lockfile entries). A GC run (`--prune`, or `--sync`, which implies it — in every mode, hosted included) still crawls every ecosystem, because the prune judges each manifest entry against the FULL installed set (see `scan --prune` above); its output, `lockfileOnlyPackages` included, is unchanged. Without `--ecosystems` nothing changes. Pinned by `tests/scan/scan_ecosystems_scope_e2e.rs`. +**`scan --ecosystems` scopes the crawl (v5.0)**: without `--prune`/`--sync`, a `scan` given `--ecosystems`/`-e` runs only the named ecosystems' crawlers — everything the run counts, queries and shows (`scannedPackages`, the batch query, `packages[]`, the rows, `updates[]`, `wiringLive`, the `gem_bundle_config_path_ignored` warning) was already narrowed to them, so the skipped crawls could only be filtered away. The one visible difference: `lockfileOnlyPackages` (and the human "not yet installed" note) counts only the selected ecosystems' lockfile-only entries (a skipped crawl cannot vouch for another ecosystem's uninstalled lockfile entries). A GC run (`--prune`, or `--sync`, which implies it — in every mode, hosted included) still crawls every ecosystem, because the prune judges each manifest entry against the FULL installed set (see `scan --prune` above); its output, `lockfileOnlyPackages` included, is unchanged. Without `--ecosystems` nothing changes. Pinned by `tests/scan/scan_ecosystems_scope_e2e.rs`. **Path-scoped scans (`scan [PATHS]...`, v5.0)**: what a PATH means depends on the mode. @@ -396,7 +410,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Vendored entries and the rest of the CLI.** Because nothing is in the manifest, vendored patches are invisible to `apply` (nothing to apply in place) but fully visible to `list` (listed from the ledger, labeled `Mode: vendored (recorded in .socket/vendor/state.json)` in human mode, exit 0 on a vendored-only project), `vex` (attested from the embedded records while a lockfile still wires the artifact — see "Manifest-less VEX"), `repair` (health-checked and rebuilt from the ledger), and `scan --prune` (lockfile-driven reconcile). They are exempt from standalone `vendor`'s manifest reconcile (`reconcile_dropped` never touches `detached` entries) and exit via `remove ` (which reverts them), `vendor --revert`, or `rollback`, whose vendored leg reverts every in-scope ledger entry (unscoped and identifier-scoped runs; path-scoped runs reach them only when an installed copy matches). -`scan --mode hosted` swaps the in-place apply for the registry-redirect pipeline: discover → resolve hosted-patch references (grant token + integrity + per-dep registry override) → rewrite ONLY the patched dependencies' lockfile / registry-config entries to point at the hosted packages. A dep counts as **redirected** only when its hosted-artifact URL (or per-dep registry index URL) actually landed in a project file — a granted reference whose rewriter found nothing to edit is neither counted nor attested. **No ledger (v5.0)**: hosted mode writes ONLY the lockfile / registry-config edits — `.socket/vendor/redirect-state.json` is never written (on success or failure), and a pre-v5 one on disk is ignored (never read for planning, never quarantined, left byte-identical). The lockfiles are the only record of a hosted patch: `list`, `vex`, `rollback`, `remove`, `vendor` and `repair` all discover the hosted pins from them (a hosted URL counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin), and commit-ready output is just the lockfile / config changes. Cargo and golang are confirmed only by their rewriter's own report (`confirmed_cargo_uuids` / `confirmed_golang_uuids`): a golang dep counts only when its go.mod `replace M V => patch.socket.dev/gopatch/ ` and both go.sum lines are in place (a re-run restores the zip line `go mod tidy` drops while no package of the module is loaded, so a later import still builds), never because the patch-server origin or leftover go.sum lines appear somewhere. Gradle is confirmed the same way (`confirmed_gradle_uuids`): only when the final files hold the owned script, the index row, the live apply line in every build's settings file and the suffixed version in every lock entry of the GA (see [Gradle builds](#gradle-builds-v50)). A golang module that go.mod does not require and go.sum has no zip (`h1:` of the module tree) line for at the patched version is outside the build graph and is refused with `redirect_golang_not_in_module_graph` (nothing written); with a `go.work` in effect the build graph is the workspace's (every `use` member's go.mod, go.sum and `go.work.sum`), so a member raising the module refuses the pin with `redirect_golang_version_mismatch`, and a `go.work` that overrides, ignores or rejects the replace refuses it with `redirect_golang_workspace_conflict` before anything is written. Run in the directory holding the `go.work`, a module the workspace shares (no root `go.mod`, or the root module is a `use` member and another member lists it or `go.work` already holds the Socket replace) is pinned in `go.work` and its two sum lines go into `go.work.sum`, the members' files untouched; a member's own `replace` of it, which the go.work pin would override, refuses it (`redirect_golang_workspace_conflict`); a `/go.mod`-only line doesn't count, since go writes one for every version MVS reads (#509). In a go < 1.17 graph, where `require` holds only lower bounds, the build selects the highest of the required version and go.sum's zip-line versions, and a patch for a lower version warns `redirect_golang_version_mismatch` (nothing written). Only the exact module `patch.socket.dev/gopatch/` is socket-owned; any other module path is refused with `redirect_golang_untrusted_module_path`. A vendored golang module is taken over like cargo and the npm family: its vendor wiring, committed copy and ledger entry are reverted first (`redirect_takeover_reverted_vendored`). A vendored PyPI package (requirements.txt, Poetry, Pipenv, uv, Hatch, PDM, pylock) is taken over the same way: its vendored wiring is restored to the recorded registry entry, its ledger entry and wheel are removed, and it is redirected in the same commit. The Python rewriters treat any non-registry source as user-authored, so without the revert they refused socket-patch's own vendored source and left the project vendored. A vendored Composer package is taken over the same way: its `composer.lock` entry is restored to the recorded pre-vendor entry, its ledger entry and committed copy are removed, and it is redirected in the same commit, so the lock matches a direct hosted scan and `rollback` can restore it from packagist. Without the revert the rewriter edited the vendored entry in place and kept its patch-uuid `dist.reference`, which `rollback` refused. A vendored Composer entry the takeover cannot revert (its vendored ledger entry is missing) is left vendored with `redirect_composer_vendored_entry`, never repointed in place. A takeover revert that leaves vendored wiring in place is refused with `redirect_vendored_revert_failed`. That covers a drift-skipped record (`vendor_lock_entry_drifted`) and a reverted file that still references the artifact (`vendor_revert_residual_reference`). The ledger entry and artifact are kept, and the package stays vendored and skipped. `--dry-run` predicts the same refusal from the same signals instead of previewing `redirect_would_revert_vendored`. The hosted requirements.txt rewriter only rewrites an existing pin in the root `requirements.txt`, so a vendored requirements.txt package whose wiring is a pin in a `-r` include or a `(transitive)` line vendored mode appended is kept vendored, wet and `--dry-run` alike, with `redirect_requirements_takeover_unreachable` (a top-level `warnings[]` entry, and the `errorCode` of the package's `skipped` event). Its wiring, ledger entry and wheel are kept, so it stays vendored and patched (exit 0). The uv and Poetry rewriters are covered the same way: a vendored uv package whose recorded pre-vendor `uv.lock` entry is at another version than the patch (earlier releases pinned such an entry down to the patch's version, where vendored uv now refuses the patch with `pypi_uv_lock_package_missing`; the revert brings the lock's own version back, and hosted mode only pins the version the lock resolves) is kept vendored with `redirect_uv_takeover_version_unreachable`, and a vendored Poetry package on a Poetry 0.x lock (which hosted mode refuses outright) is kept vendored with `redirect_poetry_lock_unsupported`. **Staged takeover (v5.0)**: the takeover is atomic. Each purl's vendored revert is staged in memory (the run's group commit, the same journaled commit vendored mode uses), the hosted rewrite plans against the reverted project, and a staged purl the rewrite does not pin is retracted: every staged revert is undone, that purl keeps its vendored wiring, ledger entry and artifact byte-identical, and the rest are staged and rewritten again. A retracted purl is a `skipped` event whose `errorCode` is the cause: its existing skip reason (unavailable wheel metadata, …), the rewriter warning that names the package (`redirect_yarn_berry_missing_checksum`, `redirect_pypi_platform_wheel`, …), `redirect_requirements_takeover_unreachable`, the rewrite's lock-level refusal (`redirect_yarn_berry_mixed_line_endings`, `redirect_bun_lock_unsupported`, a Gradle planner refusal, …) or `redirect_takeover_not_pinned`; that warning is reported in `warnings[]`, followed by `redirect_takeover_kept_vendored` naming the package. Exit 0: the package stays vendored and patched, never unpatched in both modes. The reverts, the hosted pins and the vendored ledger then reach the disk in one commit, and the reverted artifacts are deleted only after it: a refusal or write failure before the commit writes nothing, a failed commit puts back the files it replaced, and a commit interrupted after its journal was written is finished by the next command that takes the apply lock. `--dry-run` runs the same steps and drops the staged state instead of committing, so its `verified` events and warnings are the wet run's `applied` events and warnings. A hosted run with no takeover stages its writes the same way but commits them without the journal (it writes nothing under `.socket/`): a file that fails to be replaced puts back the ones already replaced, so a failed run leaves no lock half-redirected. Re-runs over already-rewritten output plan from the current lock text and are idempotent (exit 0, lock unchanged). **Lock (v5.0)**: the hosted engine acquires `<.socket>/apply.lock` before its first wet write (the staged takeover reverts) — not on `--dry-run`, and not when the run would write nothing (zero redirects, all skipped) — so previews and no-op runs never create `.socket/`; contention is `lock_held` and a lock-file I/O fault (a read-only project root, a file squatting on `.socket/`) is `lock_io` — both exit 1, refused BEFORE any project file is written, and rendered like every other lock holder: human `Error (): ` on stderr (+ the `--lock-timeout` hint for a live holder); JSON prints the envelope with `status: "error"` and `error: {code: "lock_held" | "lock_io", message}` (no `redirect` payload: nothing was rewritten). **Takeover symlink pre-check (v5.0)**: a vendored→hosted takeover whose recorded wiring file is a symlink is refused up front with `redirect_symlinked_file_unsupported` — wet and `--dry-run` alike, before any revert — so "nothing was written" holds. **Human mode (v5.0)**: hosted `scan` prints the results table and update detection like the other modes, then rewrites without a prompt (scan never prompts); `--dry-run` previews through the engine, and a detail fetch that leaves nothing to redirect enters the engine as a no-op (`Redirected 0 packages; rewrote 0 files.`, no lock, no `.socket/`). The detail fetch prints the same progress counter and per-package `Warning: could not fetch details for …` lines as the agent arm. An EMPTY hosted discovery prints `No patches available for installed packages.` and exits 0 without entering the engine; a discovery whose every offer is paid-tier for an org without paid access prints the table's paid nudge, then `No downloadable patches (paid subscription required).`, and exits 0 without entering the engine (parity with the agent/vendored arms). Under `--json` (v5.0, MAJOR) the outcome is recorded into the scan envelope: one event per selected patch, sorted by purl, each with `details.mode: "hosted"` — `applied` for a confirmed pin (`verified` under `--dry-run`), `skipped` with the skip reason as `errorCode` (and its detail as `reason`), or `skipped` / `redirect_unconfirmed` for a patch that was granted but no lockfile entry pinning it could be rewritten (the human output's `Not hosted : …` line) — plus a `redirect: {mode: "hosted", rewrittenFiles}` payload (the files rewritten, or that would be). A `skipped` event does not change `status` or the exit code (the hosted exit policy is an open decision, #704). Rewriter warnings carry stable `redirect_*` codes (e.g. `redirect_npm_no_lockfile`, `redirect_gradle_manual_snippet`, `redirect_golang_unsupported`); new codes are additive (MINOR). v5.0 additive codes: `redirect_composer_no_lockfile` / `redirect_gem_no_gemfile` (composer / gem: neither manifest nor lock present — once per run, after the intake gates), `redirect_pypi_no_lockfile` (pypi: a granted patch reached the PyPI rewriters but the project has no root `requirements.txt`, `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock`, PEP 751 / PEP 723 lock or Hatch configuration — once per run, beside each patch's `redirect_unconfirmed` row; #638), `redirect_gem_bundle_gemfile_unsupported` (gem: `BUNDLE_GEMFILE` — `BUNDLE_GEMFILE:` in the bundler app config, which outranks the environment variable as in `Bundler::Settings`, else the environment variable — names a manifest other than the project's `Gemfile` / `gems.rb`, so no gem is redirected or attested; a value naming one of those two selects that pair even when the other spelling is present), `redirect_gem_bundle_lockfile_unsupported` (gem: bundler 4's custom lockfile — the `BUNDLE_LOCKFILE` environment variable, else `BUNDLE_LOCKFILE:` in the bundler app config, else in the global config — names a lock other than the loaded pair's own `Gemfile.lock` / `gems.locked`, so no gem is redirected or attested rather than pinning a lock bundler ignores), `redirect_gem_twin_manifest_ambiguous` (gem: a `Gemfile` + `gems.rb` twin under default discovery; bundler 1.x loads the `Gemfile` and bundler ≥ 2 loads `gems.rb`, and a lock's `BUNDLED WITH` records which bundler wrote it, not which one installs it, so neither pair is wired or attested — remove the unused spelling or set `BUNDLE_GEMFILE` to the one in use), `redirect_gem_mirror_overrides_source` (gem: Bundler's all-source, exact patch-source or patch-hostname mirror can route the gem's Socket `source:` to an unpatched upstream gem. Intake reads the app config (`BUNDLE_APP_CONFIG`, where a set-but-empty value selects `/config`, honoring `BUNDLE_IGNORE_CONFIG`) and all `BUNDLE_MIRROR__...` variables visible to the scan; app config overrides the environment per encoded key, then `mirror.all` takes precedence over exact source, which takes precedence over hostname. URI matching follows Bundler's whole-URI case folding, default-port/trailing-slash normalization and single slash key alias, not URL prefixes. An exact-source fallback-timeout key without a mirror URL shadows the hostname mirror and fetches that source directly; a configured URL is conservatively refused even if a timeout could bypass an unreachable mirror at install time. Like `redirect_gem_bundle_gemfile_unsupported`, the gate leaves the Gemfile pair byte-identical and confirms no gem redirect. On an embedded `scan --vex`, rediscovered older hosted gem pins may attest only from verified installed bytes: a missing tree is not excused by the lockfile, and `--vex-no-verify` omits those hosted gems with `mirror_overrides_source` rather than trusting their intercepted source. Agent/vendored evidence, unrelated ecosystems and standalone VEX behavior are unchanged. Details identify the setting form and its app/environment origin without printing mirror values or source URLs, which may contain credentials. Remove the applicable all/source/hostname setting (including any slash alias) from that origin and reuse its existing mirror URL under `mirror.https://rubygems.org` to clear the refusal; an environment setting must be unset in the scan/install environment. User-global Bundler config and mirrors set only in a later install environment are not inspected; keep those mirrors scoped to the upstream source too), `redirect_maven_no_pom` (no `pom.xml` and no Gradle build), `redirect_nuget_lock_unparseable` (a present-but-corrupt `packages.lock.json` — warned once, nothing mutated; an absent lock still proceeds; a leading UTF-8 BOM, which dotnet reads past, is not corrupt and is kept on rewrite), `redirect_nuget_lock_other_version` (the lock also resolves the patched id at another version in some target framework: the exact-id `packageSourceMapping` would route that framework to a feed that serves only the patched version, so the dep is skipped with nothing written; only lock entries at the patched version are ever re-pinned, and `resolved` is never rewritten), `redirect_nuget_mapping_set_aside` (v5.0 #462: another source's `packageSourceMapping` also named the patched id exactly — Visual Studio's mapping UI writes such lists — which ties with the Socket source so NuGet would take the package from whichever feed answers first; that pattern, or its whole `` when it was the only one, is commented out in a `` comment while the patch is wired, and `remove` / `rollback` put it back byte-exact), `redirect_nuget_mapping_conflict` (such a pattern sits in markup that cannot go in a comment; the dep is skipped, nothing written). v5.0 #354: when the rewriter creates the `packageSourceMapping`, its `*` catch-all also names the sources NuGet merges in from the user config and every parent directory's config (honoring ``), since NuGet drops every source no pattern names; a fresh config only seeds `nuget.org` when those inherited configs have it (a parent that cleared it for a mirror keeps that choice); when an inherited config already has a `packageSourceMapping` (NuGet merges those too), no catch-all is written at all — only the Socket pattern — so a source the parent restricts is never widened; the exclusivity set-aside exempts only the source the run wires, so a `socket-patch-*` lookalike key or a stale uuid naming the id is set aside too, `redirect_cargo_lock_pkg_ambiguous` (several same-name+version `[[package]]` blocks and none carries the index `source` — transactional skip), `redirect_cargo_dep_overridden` (the crate does not resolve to crates.io because the user overrides it — its one `Cargo.lock` block carries a git / other-registry `source`, as a `[patch]` git or registry override in the root manifest or any cargo config leaves it, or has no `source` while the root `Cargo.toml` / project `.cargo/config*` holds a `[patch]` path entry for it; with no `Cargo.lock`, the same `[patch.crates-io]` / `[patch."https://github.com/rust-lang/crates.io-index"]` entry for the crate, by key or `package = "…"`, in the root `Cargo.toml` or the project `.cargo/config*` — transactional skip, nothing rewritten: a Socket pin would silently replace the user's fork and the then-unused `[patch]` entry breaks `cargo --locked`). Also additive: `redirect_cargo_directory_source` (#455: a cargo config replaces crates.io with an on-disk source through its `[source.crates-io] replace-with` chain — a directory source, as a `cargo vendor` project has, or a `cargo local-registry` — so the project builds every crates.io crate offline from it and a Socket registry pin would break `cargo build --frozen --offline`. The configs read are the ones cargo reads for a build in the scanned directory: the project's own `.cargo/config*`, every parent directory's (a monorepo root) and `$CARGO_HOME`'s. Every cargo dependency is skipped with nothing written, one warning each naming the crate and the config that set the replacement, and the detail points at agent mode, which patches the copy cargo builds in place. A replacement with a registry mirror is not an offline source and is still redirected). Also additive: `redirect_gem_version_not_locked` (gem: no `GEM` section of the lock lists the crawled `name (version)`, for example a version another project installed into the shared gem home; the gem is skipped with nothing written, so the user's declared constraint and the locked version are never overwritten), `redirect_gem_no_lockfile` (gem: the project has a `Gemfile` / `gems.rb` but no `Gemfile.lock` / `gems.locked`, so nothing records which version it resolves and the crawled version may be another project's copy in the shared gem home; the gem is skipped with nothing written, never pinned over the user's constraint or appended as a new dependency, and the detail asks for `bundle lock` (or `bundle install`) and a re-run). Also v5.0: a registry override of the wrong kind (or none at all) warns the arm's missing-override code for nuget/gem/golang. Refusals stay fail-closed with a diagnosis that names the actual cause: a yarn-berry lock entry resolving through a non-`npm:` protocol keeps `redirect_yarn_berry_unsupported_protocol` with the entry's ACTUAL protocol in the detail — except socket-patch's OWN vendored wiring (a `file:` range into `.socket/vendor/`), which gets the distinct `redirect_yarn_berry_vendored_entry` code whose detail names the retirement path (`remove ` per package, or `vendor --revert` which unwinds every vendored package, then re-run `scan --mode hosted`). Both leave the entry byte-identical; neither changes exit code or status. **yarn berry line endings (v5.0)**: yarn writes a NEW `yarn.lock` with the OS line ending (`os.EOL` — CRLF on Windows) and keeps an existing lock's majority ending on every later write, and a `core.autocrlf` checkout turns an LF lock CRLF on any OS — so a uniformly CRLF lock is rewritten in its own ending: every untouched byte (a leading BOM included) round-trips (and `rollback`'s upstream restore keeps the lock's own ending). A lock that MIXES CRLF and LF (or holds a bare CR) has no single ending to keep — yarn's own `--immutable` check rejects it too (YN0028) — so it is refused untouched with `redirect_yarn_berry_mixed_line_endings` (the detail names `yarn install`, which normalizes it). The root `package.json`, which the rewrite re-renders to add `resolutions`, gets the same gate: a mixed one is refused untouched with the same code — the decision vendored mode takes with `vendor_yarn_berry_mixed_line_endings`, from the same shared berry gate set. This replaces v4's `redirect_yarn_berry_crlf_unsupported`, which refused every CRLF lock and is no longer emitted. A vendored→hosted takeover of a yarn-berry entry is checked against these project gates (mixed `yarn.lock` / `package.json` line endings, unsupported `cacheKey`, a non-zero `.yarnrc.yml` `compressionLevel`) on the project as it is before any revert, because the revert re-renders `package.json` in its majority ending — wet and `--dry-run` alike. A refused purl keeps its vendored wiring, ledger entry and artifact byte-identical, is skipped with the gate's code (reported in `warnings[]`, followed by `redirect_takeover_kept_vendored`) and is never announced as `redirect_takeover_reverted_vendored`. +`scan --mode hosted` swaps the in-place apply for the registry-redirect pipeline: discover → resolve hosted-patch references (grant token + integrity + per-dep registry override) → rewrite ONLY the patched dependencies' lockfile / registry-config entries to point at the hosted packages. A dep counts as **redirected** only when its hosted-artifact URL (or per-dep registry index URL) actually landed in a project file — a granted reference whose rewriter found nothing to edit is neither counted nor attested. **No ledger (v5.0)**: hosted mode writes ONLY the lockfile / registry-config edits — `.socket/vendor/redirect-state.json` is never written (on success or failure), and a pre-v5 one on disk is ignored (never read for planning, never quarantined, left byte-identical). The lockfiles are the only record of a hosted patch: `list`, `vex`, `rollback`, `remove`, `vendor` and `repair` all discover the hosted pins from them (a hosted URL counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin), and commit-ready output is just the lockfile / config changes. Cargo and golang are confirmed only by their rewriter's own report (`confirmed_cargo_uuids` / `confirmed_golang_uuids`): a golang dep counts only when its go.mod `replace M V => patch.socket.dev/gopatch/ ` and both go.sum lines are in place (a re-run restores the zip line `go mod tidy` drops while no package of the module is loaded, so a later import still builds), never because the patch-server origin or leftover go.sum lines appear somewhere. Gradle is confirmed the same way (`confirmed_gradle_uuids`): only when the final files hold the owned script, the index row, the live apply line in every build's settings file and the suffixed version in every lock entry of the GA (see [Gradle builds](#gradle-builds-v50)). A golang module that go.mod does not require and go.sum has no zip (`h1:` of the module tree) line for at the patched version is outside the build graph and is refused with `redirect_golang_not_in_module_graph` (nothing written); with a `go.work` in effect the build graph is the workspace's (every `use` member's go.mod, go.sum and `go.work.sum`), so a member raising the module refuses the pin with `redirect_golang_version_mismatch`, and a `go.work` that overrides, ignores or rejects the replace refuses it with `redirect_golang_workspace_conflict` before anything is written. Run in the directory holding the `go.work`, a module the workspace shares (no root `go.mod`, or the root module is a `use` member and another member lists it or `go.work` already holds the Socket replace) is pinned in `go.work` and its two sum lines go into `go.work.sum`, the members' files untouched; a member's own `replace` of it, which the go.work pin would override, refuses it (`redirect_golang_workspace_conflict`); a `/go.mod`-only line doesn't count, since go writes one for every version MVS reads (#509). In a go < 1.17 graph, where `require` holds only lower bounds, the build selects the highest of the required version and go.sum's zip-line versions, and a patch for a lower version warns `redirect_golang_version_mismatch` (nothing written). Only the exact module `patch.socket.dev/gopatch/` is socket-owned; any other module path is refused with `redirect_golang_untrusted_module_path`. A vendored golang module is taken over like cargo and the npm family: its vendor wiring, committed copy and ledger entry are reverted first (`redirect_takeover_reverted_vendored`). A vendored PyPI package (requirements.txt, Poetry, Pipenv, uv, Hatch, PDM, pylock) is taken over the same way: its vendored wiring is restored to the recorded registry entry, its ledger entry and wheel are removed, and it is redirected in the same commit. The Python rewriters treat any non-registry source as user-authored, so without the revert they refused socket-patch's own vendored source and left the project vendored. A vendored Composer package is taken over the same way: its `composer.lock` entry is restored to the recorded pre-vendor entry, its ledger entry and committed copy are removed, and it is redirected in the same commit, so the lock matches a direct hosted scan and `rollback` can restore it from packagist. Without the revert the rewriter edited the vendored entry in place and kept its patch-uuid `dist.reference`, which `rollback` refused. A vendored Composer entry the takeover cannot revert (its vendored ledger entry is missing) is left vendored with `redirect_composer_vendored_entry`, never repointed in place. A takeover revert that leaves vendored wiring in place is refused with `redirect_vendored_revert_failed`. That covers a drift-skipped record (`vendor_lock_entry_drifted`) and a reverted file that still references the artifact (`vendor_revert_residual_reference`). The ledger entry and artifact are kept, and the package stays vendored and skipped. `--dry-run` predicts the same refusal from the same signals instead of previewing `redirect_would_revert_vendored`. The hosted requirements.txt rewriter only rewrites an existing pin in the root `requirements.txt`, so a vendored requirements.txt package whose wiring is a pin in a `-r` include or a `(transitive)` line vendored mode appended is kept vendored, wet and `--dry-run` alike, with `redirect_requirements_takeover_unreachable` (a top-level `warnings[]` entry, and the `errorCode` of the package's `skipped` event). Its wiring, ledger entry and wheel are kept, so it stays vendored and patched (exit 0). The uv and Poetry rewriters are covered the same way: a vendored uv package whose recorded pre-vendor `uv.lock` entry is at another version than the patch (earlier releases pinned such an entry down to the patch's version, where vendored uv now refuses the patch with `pypi_uv_lock_package_missing`; the revert brings the lock's own version back, and hosted mode only pins the version the lock resolves) is kept vendored with `redirect_uv_takeover_version_unreachable`, and a vendored Poetry package on a Poetry 0.x lock (which hosted mode refuses outright) is kept vendored with `redirect_poetry_lock_unsupported`. **Staged takeover (v5.0)**: the takeover is atomic. Each purl's vendored revert is staged in memory (the run's group commit, the same journaled commit vendored mode uses), the hosted rewrite plans against the reverted project, and a staged purl the rewrite does not pin is retracted: every staged revert is undone, that purl keeps its vendored wiring, ledger entry and artifact byte-identical, and the rest are staged and rewritten again. A retracted purl is a `skipped` event whose `errorCode` is the cause: its existing skip reason (unavailable wheel metadata, …), the rewriter warning that names the package (`redirect_yarn_berry_missing_checksum`, `redirect_pypi_platform_wheel`, …), `redirect_requirements_takeover_unreachable`, the rewrite's lock-level refusal (`redirect_yarn_berry_mixed_line_endings`, `redirect_bun_lock_unsupported`, a Gradle planner refusal, …) or `redirect_takeover_not_pinned`; that warning is reported in `warnings[]`, followed by `redirect_takeover_kept_vendored` naming the package. Exit 0: the package stays vendored and patched, never unpatched in both modes. The reverts, the hosted pins and the vendored ledger then reach the disk in one commit, and the reverted artifacts are deleted only after it: a refusal or write failure before the commit writes nothing, a failed commit puts back the files it replaced, and a commit interrupted after its journal was written is finished by the next command that takes the apply lock. `--dry-run` runs the same steps and drops the staged state instead of committing, so its `verified` events and warnings are the wet run's `applied` events and warnings. A hosted run with no takeover stages its writes the same way but commits them without the journal (it writes nothing under `.socket/`): a file that fails to be replaced puts back the ones already replaced, so a failed run leaves no lock half-redirected. Re-runs over already-rewritten output plan from the current lock text and are idempotent (exit 0, lock unchanged). **Lock (v5.0)**: the hosted engine acquires `<.socket>/apply.lock` before its first wet write (the staged takeover reverts) — not on `--dry-run`, and not when the run would write nothing (zero redirects, all skipped) — so previews and no-op runs never create `.socket/`; contention is `lock_held` and a lock-file I/O fault (a read-only project root, a file squatting on `.socket/`) is `lock_io` — both exit 1, refused BEFORE any project file is written, and rendered like every other lock holder: human `Error (): ` on stderr (+ the `--lock-timeout` hint for a live holder); JSON prints the envelope with `status: "error"` and `error: {code: "lock_held" | "lock_io", message}` (no `redirect` payload: nothing was rewritten). **Takeover symlink pre-check (v5.0)**: a vendored→hosted takeover whose recorded wiring file is a symlink is refused up front with `redirect_symlinked_file_unsupported` — wet and `--dry-run` alike, before any revert — so "nothing was written" holds. **Human mode (v5.0)**: hosted `scan` runs discovery and update detection like the other modes, then rewrites without a prompt (scan never prompts) and prints its result line with one row per package it switched (see "Human output conventions"); `--dry-run` previews through the engine, and a detail fetch that leaves nothing to redirect enters the engine as a no-op (`Redirected 0 packages; rewrote 0 files.`, no lock, no `.socket/`). The detail fetch prints the same progress counter and per-package `Warning: could not fetch details for …` lines as the agent arm. An EMPTY hosted discovery prints `No patches available for installed packages.` and exits 0 without entering the engine; a discovery whose every offer is paid-tier for an org without paid access prints `No downloadable patches: every patch found requires a paid Socket plan.`, and exits 0 without entering the engine (the closing lines count what a paid plan would fix and name the plan page) (parity with the agent/vendored arms). Under `--json` (v5.0, MAJOR) the outcome is recorded into the scan envelope: one event per selected patch, sorted by purl, each with `details.mode: "hosted"` — `applied` for a confirmed pin (`verified` under `--dry-run`), `skipped` with the skip reason as `errorCode` (and its detail as `reason`), or `skipped` / `redirect_unconfirmed` for a patch that was granted but no lockfile entry pinning it could be rewritten (the human output's `Not hosted : …` line; more than three such packages share one line that names the first three) — plus a `redirect: {mode: "hosted", rewrittenFiles}` payload (the files rewritten, or that would be). A `skipped` event does not change `status` or the exit code (the hosted exit policy is an open decision, #704). Rewriter warnings carry stable `redirect_*` codes (e.g. `redirect_npm_no_lockfile`, `redirect_gradle_manual_snippet`, `redirect_golang_unsupported`); new codes are additive (MINOR). v5.0 additive codes: `redirect_composer_no_lockfile` / `redirect_gem_no_gemfile` (composer / gem: neither manifest nor lock present — once per run, after the intake gates), `redirect_pypi_no_lockfile` (pypi: a granted patch reached the PyPI rewriters but the project has no root `requirements.txt`, `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock`, PEP 751 / PEP 723 lock or Hatch configuration — once per run, beside each patch's `redirect_unconfirmed` row; #638), `redirect_gem_bundle_gemfile_unsupported` (gem: `BUNDLE_GEMFILE` — `BUNDLE_GEMFILE:` in the bundler app config, which outranks the environment variable as in `Bundler::Settings`, else the environment variable — names a manifest other than the project's `Gemfile` / `gems.rb`, so no gem is redirected or attested; a value naming one of those two selects that pair even when the other spelling is present), `redirect_gem_bundle_lockfile_unsupported` (gem: bundler 4's custom lockfile — the `BUNDLE_LOCKFILE` environment variable, else `BUNDLE_LOCKFILE:` in the bundler app config, else in the global config — names a lock other than the loaded pair's own `Gemfile.lock` / `gems.locked`, so no gem is redirected or attested rather than pinning a lock bundler ignores), `redirect_gem_twin_manifest_ambiguous` (gem: a `Gemfile` + `gems.rb` twin under default discovery; bundler 1.x loads the `Gemfile` and bundler ≥ 2 loads `gems.rb`, and a lock's `BUNDLED WITH` records which bundler wrote it, not which one installs it, so neither pair is wired or attested — remove the unused spelling or set `BUNDLE_GEMFILE` to the one in use), `redirect_gem_mirror_overrides_source` (gem: Bundler's all-source, exact patch-source or patch-hostname mirror can route the gem's Socket `source:` to an unpatched upstream gem. Intake reads the app config (`BUNDLE_APP_CONFIG`, where a set-but-empty value selects `/config`, honoring `BUNDLE_IGNORE_CONFIG`) and all `BUNDLE_MIRROR__...` variables visible to the scan; app config overrides the environment per encoded key, then `mirror.all` takes precedence over exact source, which takes precedence over hostname. URI matching follows Bundler's whole-URI case folding, default-port/trailing-slash normalization and single slash key alias, not URL prefixes. An exact-source fallback-timeout key without a mirror URL shadows the hostname mirror and fetches that source directly; a configured URL is conservatively refused even if a timeout could bypass an unreachable mirror at install time. Like `redirect_gem_bundle_gemfile_unsupported`, the gate leaves the Gemfile pair byte-identical and confirms no gem redirect. On an embedded `scan --vex`, rediscovered older hosted gem pins may attest only from verified installed bytes: a missing tree is not excused by the lockfile, and `--vex-no-verify` omits those hosted gems with `mirror_overrides_source` rather than trusting their intercepted source. Agent/vendored evidence, unrelated ecosystems and standalone VEX behavior are unchanged. Details identify the setting form and its app/environment origin without printing mirror values or source URLs, which may contain credentials. Remove the applicable all/source/hostname setting (including any slash alias) from that origin and reuse its existing mirror URL under `mirror.https://rubygems.org` to clear the refusal; an environment setting must be unset in the scan/install environment. User-global Bundler config and mirrors set only in a later install environment are not inspected; keep those mirrors scoped to the upstream source too), `redirect_maven_no_pom` (no `pom.xml` and no Gradle build), `redirect_nuget_lock_unparseable` (a present-but-corrupt `packages.lock.json` — warned once, nothing mutated; an absent lock still proceeds; a leading UTF-8 BOM, which dotnet reads past, is not corrupt and is kept on rewrite), `redirect_nuget_lock_other_version` (the lock also resolves the patched id at another version in some target framework: the exact-id `packageSourceMapping` would route that framework to a feed that serves only the patched version, so the dep is skipped with nothing written; only lock entries at the patched version are ever re-pinned, and `resolved` is never rewritten), `redirect_nuget_mapping_set_aside` (v5.0 #462: another source's `packageSourceMapping` also named the patched id exactly — Visual Studio's mapping UI writes such lists — which ties with the Socket source so NuGet would take the package from whichever feed answers first; that pattern, or its whole `` when it was the only one, is commented out in a `` comment while the patch is wired, and `remove` / `rollback` put it back byte-exact), `redirect_nuget_mapping_conflict` (such a pattern sits in markup that cannot go in a comment; the dep is skipped, nothing written). v5.0 #354: when the rewriter creates the `packageSourceMapping`, its `*` catch-all also names the sources NuGet merges in from the user config and every parent directory's config (honoring ``), since NuGet drops every source no pattern names; a fresh config only seeds `nuget.org` when those inherited configs have it (a parent that cleared it for a mirror keeps that choice); when an inherited config already has a `packageSourceMapping` (NuGet merges those too), no catch-all is written at all — only the Socket pattern — so a source the parent restricts is never widened; the exclusivity set-aside exempts only the source the run wires, so a `socket-patch-*` lookalike key or a stale uuid naming the id is set aside too, `redirect_cargo_lock_pkg_ambiguous` (several same-name+version `[[package]]` blocks and none carries the index `source` — transactional skip), `redirect_cargo_dep_overridden` (the crate does not resolve to crates.io because the user overrides it — its one `Cargo.lock` block carries a git / other-registry `source`, as a `[patch]` git or registry override in the root manifest or any cargo config leaves it, or has no `source` while the root `Cargo.toml` / project `.cargo/config*` holds a `[patch]` path entry for it; with no `Cargo.lock`, the same `[patch.crates-io]` / `[patch."https://github.com/rust-lang/crates.io-index"]` entry for the crate, by key or `package = "…"`, in the root `Cargo.toml` or the project `.cargo/config*` — transactional skip, nothing rewritten: a Socket pin would silently replace the user's fork and the then-unused `[patch]` entry breaks `cargo --locked`). Also additive: `redirect_cargo_directory_source` (#455: a cargo config replaces crates.io with an on-disk source through its `[source.crates-io] replace-with` chain — a directory source, as a `cargo vendor` project has, or a `cargo local-registry` — so the project builds every crates.io crate offline from it and a Socket registry pin would break `cargo build --frozen --offline`. The configs read are the ones cargo reads for a build in the scanned directory: the project's own `.cargo/config*`, every parent directory's (a monorepo root) and `$CARGO_HOME`'s. Every cargo dependency is skipped with nothing written, one warning each naming the crate and the config that set the replacement, and the detail points at agent mode, which patches the copy cargo builds in place. A replacement with a registry mirror is not an offline source and is still redirected). Also additive: `redirect_gem_version_not_locked` (gem: no `GEM` section of the lock lists the crawled `name (version)`, for example a version another project installed into the shared gem home; the gem is skipped with nothing written, so the user's declared constraint and the locked version are never overwritten), `redirect_gem_no_lockfile` (gem: the project has a `Gemfile` / `gems.rb` but no `Gemfile.lock` / `gems.locked`, so nothing records which version it resolves and the crawled version may be another project's copy in the shared gem home; the gem is skipped with nothing written, never pinned over the user's constraint or appended as a new dependency, and the detail asks for `bundle lock` (or `bundle install`) and a re-run). Also v5.0: a registry override of the wrong kind (or none at all) warns the arm's missing-override code for nuget/gem/golang. Refusals stay fail-closed with a diagnosis that names the actual cause: a yarn-berry lock entry resolving through a non-`npm:` protocol keeps `redirect_yarn_berry_unsupported_protocol` with the entry's ACTUAL protocol in the detail — except socket-patch's OWN vendored wiring (a `file:` range into `.socket/vendor/`), which gets the distinct `redirect_yarn_berry_vendored_entry` code whose detail names the retirement path (`remove ` per package, or `vendor --revert` which unwinds every vendored package, then re-run `scan --mode hosted`). Both leave the entry byte-identical; neither changes exit code or status. **yarn berry line endings (v5.0)**: yarn writes a NEW `yarn.lock` with the OS line ending (`os.EOL` — CRLF on Windows) and keeps an existing lock's majority ending on every later write, and a `core.autocrlf` checkout turns an LF lock CRLF on any OS — so a uniformly CRLF lock is rewritten in its own ending: every untouched byte (a leading BOM included) round-trips (and `rollback`'s upstream restore keeps the lock's own ending). A lock that MIXES CRLF and LF (or holds a bare CR) has no single ending to keep — yarn's own `--immutable` check rejects it too (YN0028) — so it is refused untouched with `redirect_yarn_berry_mixed_line_endings` (the detail names `yarn install`, which normalizes it). The root `package.json`, which the rewrite re-renders to add `resolutions`, gets the same gate: a mixed one is refused untouched with the same code — the decision vendored mode takes with `vendor_yarn_berry_mixed_line_endings`, from the same shared berry gate set. This replaces v4's `redirect_yarn_berry_crlf_unsupported`, which refused every CRLF lock and is no longer emitted. A vendored→hosted takeover of a yarn-berry entry is checked against these project gates (mixed `yarn.lock` / `package.json` line endings, unsupported `cacheKey`, a non-zero `.yarnrc.yml` `compressionLevel`) on the project as it is before any revert, because the revert re-renders `package.json` in its majority ending — wet and `--dry-run` alike. A refused purl keeps its vendored wiring, ledger entry and artifact byte-identical, is skipped with the gate's code (reported in `warnings[]`, followed by `redirect_takeover_kept_vendored`) and is never announced as `redirect_takeover_reverted_vendored`. **Attribution gate (v5.0).** A hosted run never leaves wiring that lockfile discovery calls contested: before the rewrite writes any lockfile, the same discovery `vex`, `list`, `rollback`, `remove` and `vendor` read runs over the project as the rewrite would leave it. A candidate whose pin discovery reads but cannot attribute to one package version (a requirements `-r` include resolving the same version from the registry beside a rewired `Pipfile.lock`, #567; a Maven pin in a ``, #260) is left out of the rewrite and reported as a `skipped` event with `errorCode` `redirect_unattributable` (nothing written for it; exit code unchanged). Unchanged: a pin in a file discovery does not read (a pre-2.6 bundler `Gemfile`, locked by the next `bundle install`) keeps the rewriter's verdict, and so does a deliberate partial redirect the run already reports (a bundled or `bun patch`-ed copy left on the registry, a yarn `npm:` alias entry left on the registry with `redirect_yarn_classic_alias_skipped` / `redirect_yarn_berry_alias_skipped` while the package's direct entry is pinned, a dep withheld from the vlt rewrite while a sibling lock takes it), and so does a vendored→hosted takeover: its vendored wiring is reverted in the run's staged overlay before the rewrite plans, and it is redirected when the rewriters pin it (otherwise it is retracted and stays vendored), in a `--dry-run` preview the same. A pin whose own pnpm or yarn lock also installs an unpatched copy of the same `name@version` (a pnpm `file:` directory or tarball dependency; a yarn `file:` / URL / berry `portal:` / `link:` dependency declared under another name) is written too, with a `redirect_copy_unpatched` warning naming that entry, and is not attested. A lockless NuGet / Cargo pin (an exclusive Socket source mapping without `packages.lock.json`, a Cargo registry pin without `Cargo.lock`) is still written, with a `redirect_pin_lockless` warning: no lockfile records its version, so `vex` cannot attest it and `rollback` / `remove` / `vendor` refuse it until the lockfile exists (whether such pins should be written at all is an open decision). The rollout's recorded view uses the same discovery: a uuid a file merely mentions (a stale `package.json` field, an inactive `pdm.lock`, a comment) is not a pin and does not count as already patched. @@ -712,7 +726,7 @@ Recognition rules that hold for every ecosystem: * **Patch hosts.** A hosted reference counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin, with no userinfo. The URL must be one every client reads alike: a backslash, whitespace or a control character anywhere in it (after the lock format's own `\/` unescape and the trim of surrounding whitespace) makes it no reference, because URL parsers disagree about the host of a URL such as `https://patch.socket.dev\@evil.example/…`. Its path must be one the patch server serves a patch under: `patch//…`, `patch-registry//…` (`` one of `npm`, `pypi`, `cargo`, `golang`, `gem`, `composer`, `maven`, `nuget`) or `gopatch/…`, first in the path on Socket's own server and under any path prefix on a `--patch-server-url` deployment, with no percent-encoded `/` or `\` (`%2f`, `%5c`) anywhere in it. The uuid is the LAST canonical-uuid segment below that level, because grant tokens may themselves be uuid-shaped. A URL on a patch host that fails these rules is not a hosted pin (`vex` does not attest it; `list`, `rollback`, `remove` and `scan` do not manage it, and a hosted `scan` does not write one), but a uuid in its path still counts as *mentioned* for the liveness gates below, so no ledger record is revived from it. The Go module prefix is fixed. `socket-patch-` registry / repository / source names count only through a pin. For a URL on any other host, see **Patch hosts** above. * **Pins, not definitions.** A registry, index or source *definition* alone (cargo `[registries]`, nuget ``, pom ``, uv index tables, `.npmrc`) never makes a reference, because it survives a reverted pin. Sections the package manager ignores are not read: npm's v2 `dependencies` mirror, a `.cargo/config.toml` shadowed by `.cargo/config`. A Socket pin inside a maven `` is diagnosed, never a reference. * **Contested locks.** When one lock wires a package to a patch and another lock resolves the same `name@version` from a non-Socket source, the build's bytes depend on which package manager runs. The reference is then dropped with a `patched_ref_unattributable` diagnostic naming both files. This applies across npm / pnpm / yarn / bun and across uv / pylock / poetry / pdm / Pipfile.lock / requirements. A PEP 723 script lock is a lock like the others: `uv run` installs its script's dependencies from it, so a script lock that resolves the release from the index contests a project lock's reference and the reverse (both writers rewire script locks, so a re-run clears it). A Python lock also contests itself: another entry of the **same** `uv.lock`, script lock, `pylock*.toml`, `poetry.lock`, `pdm.lock` or `Pipfile.lock` that resolves the wired release from a non-Socket source (a uv marker fork, a Poetry multiple-constraint dependency, a PEP 751 marker split, a PDM extras variant, the other `Pipfile.lock` category) is installed wherever its markers, extras or category select it, so the reference is withheld until `scan` / `vendor` rewires every entry. Requirements and `pyproject.toml` / `hatch.toml` declarations are not lock entries, and a Socket reference there is withheld (`patched_ref_unattributable`, naming the other requirement) while another requirement of the same package can install the same release where the reference does not apply: beside a reference that carries an environment marker, any requirement of the set that is not an exact pin of another release; beside a reference in an extra, a dependency group or a Hatch environment, any requirement of the package in `[project].dependencies` (which `pip install .` reads), or an exact pin of the release in any table not installed together with the reference. A reference and a compatible requirement that pip resolves together (one requirement set, or `[project].dependencies` with the project's extras) resolve to the reference, so an unmarked reference is not contested there. The root `requirements.txt` and its in-root `-r` includes count as one lock here: pip reads them as one requirement set, where a direct reference wins over a compatible `==` pin of the same version in another file of the set (#1086). A PyPI version matches under PEP 440 equality, so a requirements line pinned in any spelling that can only install the wired release (`==1.2.3.0`, `==v1.2.3`, `===1.2.3`) contests it like `==1.2.3` does; a range or wildcard (`~=1.2.3`, `==1.2.*`) does not (#1602). A **bundled** npm copy (`inBundle: true`, or v1 `bundled: true`, beneath a dependency that bundles it; the root project's own bundles install from the lock, #1618) of the same `name@version` contests the reference too, in the same lock, in the other npm lock of a shrinkwrap/package-lock pair, or in any other lock. npm unpacks it from the parent package's tarball, so no rewire reaches it and it stays unpatched. Bun and vlt unpack bundled copies the same way (#469, #471). pnpm unpacks bundled copies too, but its lock cannot tie one to a reference (see **Unattested references** below). For Bun, that is a `bun.lock` entry whose meta is `{ "bundled": true }`, or a `bun.lockb` record that a dependency edge with the `bundled` behavior bit reaches, including one Bun shares with a regular install. Such an entry is never a reference, and it contests the reference the same way. For vlt, the lock records no node for a bundled copy, so the copy is found in the installed store: a real package directory inside a store package's own `node_modules`. yarn classic's `yarn.lock` records nothing about bundled copies either (#758), so for a lock with a Socket wiring they are found in the installed `node_modules`: each package a parent's `bundleDependencies` / `bundledDependencies` names inside the parent's own `node_modules`, the dependencies of those beside them, and everything nested under them. Such a copy contests the reference in `yarn.lock` (the diagnostic names the parent's lock entry and the copy's directory); a lock-only `vex` with no `node_modules` can't see it. Hosted and vendored scans skip these copies with `redirect_bun_bundled_instance_skipped` / `redirect_vlt_bundled_instance_skipped` / `vendor_bundled_instance_skipped`, and a yarn classic hosted scan names one with `redirect_copy_unpatched`. When a bundled copy is the only instance, vendoring refuses with `vendor_lock_entry_not_rewritable`. A reference withheld only because such an unreachable copy installs beside it (a bundled npm / Bun / vlt copy, an npm copy beneath a `hasShrinkwrap` package (#753) or one npm installs from a git / url / `file:` spec, or a yarn classic git or `file:` directory block of the same `name@version`) is still the rewriter's own wiring of exactly one package version: it is never attested, but `rollback`, `remove`, `list` and the hosted → vendored takeover treat it as an ordinary hosted pin and restore its upstream registry entry (#828), rather than refusing it with `hosted_wiring_contested`. Another entry of the **same** npm, Bun or yarn lock that resolves the wired `name@version` from a non-Socket source (for example a workspace member added after the rewire, then `npm install` / `bun install` / `yarn install`; for yarn berry, a registry locator such as `left-pad@npm:1.3.0` beside the hosted `…::__archiveUrl=` one) contests the reference too (#588). The package manager installs both entries, and that copy stays unpatched. Re-running `scan` / `vendor` rewires every copy. -* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactors** (`vex_maven_reactor_root`): a hosted patch in a reactor (a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers) is omitted while a module that resolves the patched version, or may, is reached by no pin and no declaration of the patch, or a declaration may still build the unpatched version: a module's own literal `` overrides a pin above it (#261). The note names the module. A reactor one of whose poms cannot be read is omitted the same way, whatever its root pins. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, another registry or a git repository under its own table; a registry's table by its index URL, or by its name when the project's cargo config defines that registry), re-lock (`cargo update -p "#@"`, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i "#@"` names the dependency that declares it. The commands name the entry by its source, because the bare `@` also fits the copy the lock holds at `+socket.` and cargo refuses it as ambiguous. A source with a character a shell would read inside the quotes is not printed: the command then takes the bare crate name, which cargo answers with the specs it accepts. +* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactors** (`vex_maven_reactor_root`): a hosted patch in a reactor (a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers) is omitted while a module that resolves the patched version, or may, is reached by no pin and no declaration of the patch, or a declaration may still build the unpatched version: a module's own literal `` overrides a pin above it (#261). The note names the module. A reactor one of whose poms cannot be read is omitted the same way, whatever its root pins. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix of the package's own in the reference's own pnpm lock or the root one; a patched peer's hash inside a dependent's key does not count), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, another registry or a git repository under its own table; a registry's table by its index URL, or by its name when the project's cargo config defines that registry), re-lock (`cargo update -p "#@"`, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i "#@"` names the dependency that declares it. The commands name the entry by its source, because the bare `@` also fits the copy the lock holds at `+socket.` and cargo refuses it as ambiguous. A source with a character a shell would read inside the quotes is not printed: the command then takes the bare crate name, which cargo answers with the specs it accepts. * **Shrinkwrap without a twin (#899).** npm >= 12 never reads `npm-shrinkwrap.json`: on a project whose only npm lock is the shrinkwrap it resolves the tree from the registry and writes a fresh `package-lock.json`, so a Socket reference there reaches npm <= 11 only. The reference is still discovered, so `list`, `rollback` and `remove` manage it, but `vex` omits the patch (`vex_npm_shrinkwrap_only`, as a run warning and as the `failed[].reason`). A `package-lock.json` beside it (wired the same way) makes it attestable again. Hosted and vendored runs still rewire the shrinkwrap and warn `redirect_npm_shrinkwrap_only` / `vendor_npm_shrinkwrap_only`. * **Locks the package manager is told not to read.** A reference in a lock the project's own configuration turns off proves nothing about what installs. Read from the project's own rc file only (no user or global config, no environment): npm's `package-lock` or its alias `shrinkwrap` set to `false` / `null` in `.npmrc` (`npm install` then ignores `package-lock.json` and `npm-shrinkwrap.json` and resolves from the registry; only `npm ci` still installs from the lock; a `${VAR}` value counts as off); yarn 1's `--install.no-lockfile`, `--*.no-lockfile` or `--no-lockfile` in `.yarnrc` with any value but `false` (yarn neither reads nor writes `yarn.lock`, `--frozen-lockfile` included); a yarn berry `lockfileFilename` in `.yarnrc.yml` naming another file (yarn 2 and 3 read that file, yarn 4 rejects the setting and installs nothing); and pnpm's `lockfile` setting (**pnpm with its lockfile off** above). A hosted reference of such a lock keeps no lockfile basis: `vex` attests it only from an installed tree whose every copy verifies, and discovery warns `patched_ref_unattributable` naming the setting. A vendored reference stays a reference but is omitted (`vex_lock_not_read`, as a run warning and as the `failed[].reason`), because its basis is the committed artifact and nothing installs it through a lock nothing reads; the pnpm exception is an override that routes the package to the artifact. * **Lockless pins.** With no lock to name a version, a `Cargo.toml` pin (every declaration on `socket-patch-`, that registry defined on the patch host for the same uuid) or an exclusive nuget exact-id mapping is never a reference on its own, so v5.0 does not attest it (nor does `list` show it, or `rollback` / `remove` restore it — restore those files from version control). Only a pre-v5 redirect-ledger record naming a version the pin admits keeps it live. For Cargo, declarations are read as for a locked pin (**Unpinned Cargo declarations**): one that is no pin admits nothing, and its requirement (any version, without one) is excluded from the pin; a `[workspace.dependencies]` template no manifest inherits is no declaration at all. The same holds for a gem wired only in the `Gemfile` (the pre-bundler-2.6 mixed state, lock not converged). @@ -748,7 +762,7 @@ A reverted lockfile plus a leftover ledger or artifact therefore stops attesting | `sbt_resolution_unverified` | An sbt pin the build's local resolution evidence (`target/`, after `sbt update`) does not verify, or a build-wide blocker applies (stale or partial evidence, project definitions that cannot be read statically, a `dependencyOverrides` / `onLoad` / `resolvers` reassignment, a `build.sbt.lock`); the detail names the cause and its remedy, or that it has none. A hosted reference stays, without the lockfile basis (a hosted pin the build provably bypasses is also omitted, `vex_sbt_pin_bypassed`); a vendored pin is not attested (`vex_sbt_resolution_unverified`). | | `vendored_tree_missing` | A `socket-patch-vendor.sbt` pin whose `.socket/vendor/maven2/` file is missing or modified; it is not attested (`vex_sbt_vendored_tree_missing`). | -Human mode also prints `Note:` lines: superseded records, fetch failures, `--offline` withholding fetches, conflict details, and why a claim is dead. While patch records are fetched, a terminal shows a transient `Fetching patch records... (n/N)` status line on stderr (never under `--json` / `--silent`). +Human mode also prints `Note:` lines: superseded records, fetch failures, `--offline` withholding fetches, conflict details, and why a claim is dead. While it works, a terminal shows a transient status line on stderr (never under `--json` / `--silent`): `Reading lockfiles`, `Reading patch records [####----] n/N` (one request per lockfile-wired patch with no local record; the authenticated API is asked for the view without its file contents, which the record does not use), `Finding installed packages`, `Verifying installed patches`. Nothing else prints while that line is up: the run's advisories are held and printed once it is down. **Output.** A manifest-less run honors every `vex` output convention: `--output -` (or `-O -`) prints the document to stdout; `--dry-run` still discovers, fetches records and verifies, but writes nothing and leaves a previous document at the path alone (`[dry-run] Would write …`, `dryRun: true`); an embedded `--vex` under `--dry-run` skips generation with the shared `Skipping VEX generation (--dry-run: nothing was …).` line. @@ -759,9 +773,18 @@ Human (non-`--json`) output is not a stable interface, but these rules hold: * Warning lines carry no machine code: `Warning: ` (and `GC: skipped: .`); error lines keep theirs (`Error (): …`) so a `--silent` run stays grep-able. The stable codes stay in the JSON envelope (`warnings[].code`, `error.code`, `errorCode`). * Hosted mode is called "hosted" in human text (`Switched N packages to hosted patches; rewrote M files.`); JSON keys and codes keep their `redirect*` names. `N` counts the packages this run switched: one whose hosted patch was in place before the run is not counted again, and a run that finds some gets a second sentence (`Switched 1 package to hosted patches; rewrote 1 file. 2 packages were already on hosted patches.`); a run that rewrites nothing says `N packages are already on hosted patches; nothing to rewrite.` `--json` is unchanged: every confirmed pin, new or already in place, is an `applied` event (`verified` on a dry run), and `rollout.counts.already` / `redirect.rewrittenFiles` tell a re-run from a first run. * npm's `allow-remote` notice prints as one line (`Note: set \`allow-remote=all\` in .npmrc …` or `Warning: npm >=12 refuses the hosted patches until …`); the full `redirect_npm_allow_remote` detail is in `--json` and under `--verbose`. -* Hosted and vendored runs that change the project end with one shared `Next steps:` block (commit, reinstall + `socket-patch vex`, then any extra step). A hosted run that rewrote Bundler's files alone words the second step by what it did about the gems Bundler already held (see "Gem stale-install guard"): once it replaced them it is `Run \`socket-patch vex\` to verify the installed patches (the installed gems already hold the patched builds, so there is nothing to reinstall).`, and while a shared gem home still holds unpatched copies it points at the command in that run's warning instead of a reinstall, since a plain `bundle install` keeps the gems it already has. +* Hosted and vendored runs that change the project end with one shared `Next steps:` block (commit, reinstall + `socket-patch vex`, then any extra step: `2. Reinstall from the updated lockfile (e.g. \`npm ci\`), then run \`socket-patch vex\` to verify the installed patches.`). A hosted run that rewrote Bundler's files alone words the second step by what it did about the gems Bundler already held (see "Gem stale-install guard"): once it replaced them it is `Run \`socket-patch vex\` to verify the installed patches (the installed gems already hold the patched builds, so there is nothing to reinstall).`, and while a shared gem home still holds unpatched copies it points at the command in that run's warning instead of a reinstall, since a plain `bundle install` keeps the gems it already has. * An agent-mode run that recorded a patch (`scan --mode agent`, agent-mode `get`) ends with its own `Next steps:` block, on stdout: `1. Commit .socket/ to keep the patches.` and `2. Run \`socket-patch apply\` after every \`bundle install\`, locally and in CI. A fresh install removes the patches.` The second step names the install command of each ecosystem the run patched, read from the project's lockfile where several package managers share one (`pnpm install`, `yarn install`, `bun install`, `vlt install`, else `npm install`; `uv sync`, `poetry install`, `pipenv install`, `pdm install`, else `pip install`; `bundle install`; `composer install`; `cargo fetch`; `dotnet restore`), and says `every dependency install` where there is no single command (Maven, Gradle, sbt). After `get --save-only` it reads `Run \`socket-patch apply\` now, and after every …`. A Go patch is a committed copy plus a `replace`, so the first step also names `go.mod (or go.work)` and a run that patched only Go modules has no second step. The block is not printed by a run that recorded nothing new, a dry run, a failed run, a global (`-g` / `--global-prefix`) run, `--silent` or `--json`. With a `--max-new-patches` cap, the lines about deferred patches follow in the same block. -* `scan` says which advisories a run leaves unpatched. One patch is applied per package version, while the results table lists the ids of every candidate patch. So under its result line (`Switched …`, `Vendored …`, the agent apply's `Summary: …`, the `--dry-run` line), every mode prints one line per package it patched: ` : fixes `, plus `; still unpatched: ` for the advisories only the package's other patches fix (paid ones included). A dry run says `would fix` / `would stay unpatched`; a re-run that finds the patch in place repeats the line. When any package keeps an unpatched advisory, one closing line follows: `Only one patch is applied per package version. Upgrade the package to fix the advisories still unpatched.` A list longer than eight ids ends `(+N more)` unless `--verbose`. Only a patch the run applied (or found applied) gets a line; a patch whose records name no advisory gets none. `--json` carries the same facts on `packages[]` (see [`scan` and `get` JSON](#scan-and-get-json-v50-major)). +* `scan` lists each package it patched once, under the mode's result line (`Switched …`, `Vendored …`, the agent apply's `Applied N patches.`, the `--dry-run` line): ` @ `, worst severity first, then by purl. The name is the package's `name@version` when every row of the project is one ecosystem and its purl otherwise. `` are the first two advisories the patch fixes (a CVE, or the advisory's own id when it has none) and `(+N)` for the rest; `` counts the advisories only the package's other patches fix (paid ones included), since one patch is applied per package version. `--verbose` names every id and adds a `still unpatched: ` line under the row. On a terminal narrower than a row, the row names fewer ids and then drops the measurements rather than wrap. Only a patch the run applied (or found applied, or on a dry run would apply) gets a row. `--json` carries the same facts on `packages[]` (see [`scan` and `get` JSON](#scan-and-get-json-v50-major)). The other per-package listings a scan used to print (the results table, the `Patches to apply:` blocks, `[add]` / `[fetch]` lines, `Patched packages:`) are gone from the default output; `--verbose` keeps the per-patch blocks. `get` keeps its numbered listing and, like `scan`, no longer names the patches again while it downloads and applies them: its nested apply says `Applied N patches.` (the other buckets only when a patch landed in one: `Applied 4 of 6 patches: 1 already patched, 1 failed.`), and `get --save-only` says `Saved N patches to .` (`(1 updated, 1 skipped)` when so); a recorded patch a `get` replaces still gets its `[update] (replacing )` line. `apply` itself prints as before. +* `scan` closes with the totals of the whole invocation, once, under a blank line: `Patched 22 packages in 3 projects, fixing 39 vulnerabilities (5 critical, 15 high).` (`Would patch …` on a dry run; `in N projects` only past one), then, under the `Verified:` line when there is one, `Saved about 44 hours of engineering time (22 package upgrades at ~2 hours each).` (`Would save …` on a dry run), then `18 vulnerabilities left to patch (32%): 14 need a package upgrade, 3 need a paid Socket plan, 1 is in packages this run did not patch.` or `Nothing left to patch.` (`No free patches left to apply.` when a lookup of the run went through the public proxy, which answers for free patches only). The counts are occurrences: a package patched in three project directories counts three times, and so does each advisory its patch fixes there; an advisory is one id as the rows show it. "Left to patch" counts the advisories of every package a patch was offered for that this run did not fix, as a share of those it could have. A package a hosted or vendored run finds installed on the machine but absent from a lockfile that lists the whole dependency graph (npm, Cargo, Go, Bundler, Composer) is not the project's and is not counted; a PyPI package always counts, since a requirements file may pin only direct dependencies. A run given a selection filter with reachability findings adds `Reachable: 9 fixed, 2 left to patch (18%).`, the same two counts for the advisories a finding marks `reachable`. The hours are an estimate, and the line says so: each patched package, in every project directory it is patched in, stands for one upgrade that did not have to be made, taken at two hours (finding a release with the fix, moving to it, getting the build and tests through everything else that release changed, and the review). The figure is an assumption, not a measurement of the project. A run that leaves advisories to a paid plan ends with the upsell line below (once per invocation: a project directory whose every patch is paid prints it under its `No downloadable patches` line instead). Nothing is printed when no patch was offered at all. +* **Measurements.** When stdout is a terminal, `scan`, `get` and `show` ask the patch service what it measured about the patches they list (the patch view's `statistics`): the proof-of-concept exploits of the fixed advisories blocked by the patched package, the package's own tests passing on it, the size of the change, and its run-time cost. `scan` shows them in each row (`exploit blocked, 25/25 tests`) and totals them in its closing lines (`Verified: 24 of 24 exploits blocked, 1208 of 1208 package tests passing.`, with `(measured for 18 of 22 patches)` when some were not measured); `get` adds `Verified:` / `Change:` / `Performance:` lines under each listed patch; `show` prints them with the unpatched package's numbers beside them. They are a courtesy to someone reading: a pipe, a log, `--silent` and `--json` make no such request and print no such line, a patch that was never measured shows none, and a failed or slow request costs the output those numbers and nothing else. `scan` asks in the background while it works (for each package's best-ranked patch as soon as the lookup answers, then for any other patch it selected; at most 100 patches a round), waits at most 0.4 s per project directory for answers still out when its rows are due and 1.5 s before its closing lines, and counts an answer that missed its row in the closing lines all the same. +* **Marks, bars and color.** Color follows `NO_COLOR` / `CLICOLOR` / `CLICOLOR_FORCE` / `TERM=dumb`. Where color is on, the stream is a terminal and the terminal is known to show UTF-8 (a UTF-8 locale; on Windows: Windows Terminal, an editor's terminal, or an xterm-like one; never `TERM=linux`), `scan` and `rollback` open each done line with a green check mark (the rows of a dry run and of a report-only scan, whose patches are on offer and not in place, leave that column blank), the status line draws its progress bar in line glyphs, and `scan`'s closing lines end with a meter of the share patched. Everywhere else the same lines print in ASCII at the same columns (a space for the mark, `[####----]` for the bar, no meter), so a log or a pipe never carries a glyph. +* **Progress.** On a terminal every command shows its waits on one self-rewriting status line that opens with an activity mark (`⠹ Scanning packages`; `|`, `/`, `-`, `\` where glyphs are off). The mark keeps turning for as long as the line shows, whether the command is waiting on the network or busy, so a long step never reads as a hang. `scan` shows `Finding projects` (a hosted or vendored scan looking for its project directories), `Scanning packages`, `Checking 644 packages for patches [####----] 1/2` (lookup batches), `Reading patches [######--] 6/8` (patch records), `Reading patch test results` (the measurements still out when the rows are due), `Looking for other projects` (an agent-mode scan whose search for project directories below outlasts its lookup), then the mode's own steps (`Downloading patches [##------] 2/8` in agent and vendored mode; in hosted mode `Checking 4 hosted patches`, `Resolving hosted artifacts for 3 patches`, `Checking project patches`, `Reading lockfiles`, `Rewriting lockfiles` (`Planning lockfile changes` on a dry run) and `Writing lockfiles`); `rollback` shows `Rolling back packages [###-----] 3/8`. The line is drawn only on a terminal that understands escape sequences, never under `--json`, `--silent`, `TERM=dumb` or `SOCKET_DEBUG`, and it is cleared before anything else prints. A scan leaves one permanent line per project directory, `Found 644 packages (644 npm)`; the count and its per-ecosystem parts are the packages the run goes on to check (after `--ecosystems`, the socket.yml filters and the project's own patches). `Note: N packages from project lockfiles are not yet installed (lockfile-only).` prints only for an agent or report-only scan, which patches installed copies. +* **Agents.** A terminal an AI coding agent runs the command in is not treated as a terminal with a person at it: the run gets what a pipe gets. No status line is drawn (a harness that runs commands on a pseudo-terminal would otherwise read back every redraw of it), no glyphs and no color (`CLICOLOR_FORCE` still forces color, as on a pipe), `list` and `show` print instead of going full-screen (which would wait for keys nobody presses), an arrow-key menu takes its first option with the usual note, rows and warnings are not fitted to the terminal's width, the measurements a terminal gets are not fetched, and the update notice is not shown. An agent is recognized by a variable it sets for the commands it runs, set to anything but `0`, `false`, `no`, `off`, `n` or `f`: the generic `AI_AGENT`, then `CLAUDECODE`, `CLAUDE_CODE`, `CURSOR_AGENT`, `CODEX_SANDBOX`, `CODEX_THREAD_ID`, `CODEX_CI`, `GEMINI_CLI`, `ANTIGRAVITY_AGENT`, `VSCODE_AGENT`, `COPILOT_AGENT`, `COPILOT_CLI`, `OPENCODE`, `OPENCODE_CLIENT`, `AMP_CURRENT_THREAD_ID`, `GOOSE_TERMINAL`, `AUGMENT_AGENT`, `CLINE_ACTIVE`, `ROO_ACTIVE`, `ROO_CODE_TASK_ID`, `QWEN_CODE`, `PI_CODING_AGENT`. A variable an editor sets in every terminal, a person's included, is not one of them, and neither is the bare `AGENT`. `SOCKET_PLAIN` overrides the detection: a truthy value (`1`, `true`, `yes`, `on`, `y`, `t`) asks for the plain output anywhere, and any other value keeps the full terminal output (someone working in a terminal an agent started). Where an agent's variable makes `list`, `show` or a menu print instead of opening, one line on stderr says so and names both the variable and `SOCKET_PLAIN=0` (`Note: CLAUDECODE is set, so this terminal gets the plain output of an AI coding agent's. A person at it can set SOCKET_PLAIN=0 for the interactive output.`). Typed yes/no confirmations are not presentation and do not follow this: they are asked on any terminal on stdin, and `--yes` answers them. `--json` is unchanged, and remains the interface for a program. +* **Several project directories.** A scan of more than one project directory (PATHs, or the directories a bare hosted or vendored scan finds) does the read-only half of all of them together before it scans them one by one: every directory is crawled at once (`Scanning projects [####----] 5/17`), then the patch service is asked once about every package any of their scans would ask about (nothing more: a package the `socket.yml` policy or a selection filter leaves out, a project the policy excludes, and a package the project patches itself are not asked about here either) (`Checking 9214 packages for patches [##------] 3/19`, then `Reading patches [###-----] 40/126`). The run's client remembers those answers, so each directory's own scan, which runs in order as before (its heading, its output, the `--max-new-patches` budget and every write), uses the crawl made for it and finds its lookups answered: a package held by ten directories is asked about once, not ten times. What the project patches itself is read with its crawl and handed to its scan. Nothing is decided ahead: a question that was not answered up front (a failed request, a package only a later step names) is asked by the directory's scan, which reports failures as it always did, and a first request the service refuses leaves every lookup to the scans. A run of one directory, a `--prune` / `--sync` scan, and `--global` are unchanged. `--json` takes one directory, so its request pattern is unchanged too. +* **Startup.** A scan draws its status line before it reads the project. The reads that used to stand between the start and the first progress no longer do: the search for the project directories a bare agent-mode scan does not cover runs during the patch lookup (its warning prints once the lookup is in, in its old place among `--json`'s `warnings[]`); the project's own patches are read beside the crawl; the `node_modules` directories the socket.yml filters judge nested copies by are the ones the crawl just walked; and the walk that finds a hosted or vendored scan's project directories runs on several threads. Where file descriptors are scarce, each of these runs in turn, as before. +* **Repeats are folded.** The packages a scan leaves alone because the project patches them itself are one note, not a warning each: `Note: skipped 21 packages covered by this project's own patches (pnpm-lock.yaml, pnpm-workspace.yaml): @cyclonedx/cdxgen@11.2.5, @google-cloud/bigtable@6.5.1, @google-cloud/profiler@6.0.3 and 18 more.` and, under it, ` --allow-patch-conflicts patches them too; --verbose lists them all.` It names the project files (relative to `--cwd`) and the first three packages; `--verbose` lists every package, with its own files where they are not all of the note's. Packages held back only because a project file could not be read are a `Warning:` of their own that says to fix the file (`Warning: 2 packages not patched, because this project's own patches could not be checked: package.json (not valid JSON: …). Fix that file and run again.`), and under `--allow-patch-conflicts` the packages are one `Warning:` to review the combined result. `--json` is unchanged: one `user_patch_conflict` / `user_patch_override` entry per package in `warnings[]`, and one skipped event each. Lockfile-only packages an agent-mode scan leaves out get one `[skip]` line each up to three, and one line naming the first three past that (`--verbose` lists them all). Hosted mode prints at most three warnings of one code, then `... and N more like these (--verbose lists them all)`; `--json` always has every one. A recorded patch a scan re-applies is named in a `[re-apply]` line only under `--verbose` (it has its row), and the download prints no `[skip] … (already in manifest)` line for it: the result says it (`Applied 0 of 6 patches: 6 already patched.`). An agent-mode dry run that would also re-apply recorded patches says so in its headline (`[dry-run] Would download and apply 5 patches and re-apply 1 already recorded. No changes made.`), so it adds up with the rows under it. `rollback` lists the packages it restored once (`Rolled back 6 packages:`) and then says `Removed 6 patches from manifest.`; the purls are listed again under that line only when it removed a record the block above does not name. +* **`list` on a terminal.** With stdin, stdout and stderr all a terminal (and no `--yes`, `--verbose`, `--json` or `--silent`), `list` shows the project's patches as a full-screen table on the terminal's alternate screen instead of printing each patch's full entry. While it finds and reads the projects a status line shows (`Finding patched projects`, `Reading patches`, `Reading patches in `); what a project has to say on stderr prints once that line is down. The table goes up at once with what the project records (`SEVERITY`, colored by tier; `PACKAGE`, as `name@version` when every row is one ecosystem; `FIXES`, the first two advisory ids and `(+N)`; `MODE`; and `PROJECT` when the rows come from several project directories), and the patch service's account of each patch fills its row in as it arrives (`loading details 12/92` beside the title): `EXPLOITS` and `TESTS` (`2/2`, `34/35`: green when all are blocked or passing, yellow when not), `CHANGE` (`+26 -22` lines), `PERF` (the run-time cost of the patched code), `PUBLISHED`, and the severity and advisories of a hosted pin, which the project records by uuid alone. `--offline` asks the patch service nothing, and only a recorded uuid that is a UUID is ever asked about: a record whose `uuid` is anything else keeps its row and opens as the project's own record. The arrow keys (or `j`/`k`), PgUp/PgDn and Home/End (`g`/`G`) move, Enter opens the selected patch, and `q`, Esc or Ctrl-C leave. The table is redrawn to fit whenever the terminal changes size: columns give way on a narrow terminal (the mode and date first, the measurements next, the advisories last), a name too long is cut with `...`, nothing wraps, and the selected row stays in view. Opening a patch shows it as a page on the same screen: what `show` shows for it (its fixes, measurements, files and the diff of each, with the same keys; see [`show`](#show-inspect-a-patch)), and `q` comes back to the table on the same row. When the patch service cannot be asked (`--offline`, a failed request), the page is the project's own record of the patch, under the reason. Nothing is changed by any of it. Leaving the table puts the terminal back as it was and prints the listing that stays: `Found N patches:` and the table's rows as they stood, in columns cut to the terminal's width. Where no such screen is available (Windows, a terminal that cannot be set up) the rows print and an inline arrow-key menu prints a pick's summary (what `show --stat` prints: the fixes, measurements and changed files, without the diffs). A pipe, a log, a terminal that shows no escape sequences (`TERM=dumb`, a console without VT processing), a run under `SOCKET_DEBUG`, `--yes` and `--verbose` get the full entries, as before, and make no request. * A declined prompt prints `Cancelled; no changes made.`; the paid-plan upsell is `Upgrade to a paid Socket plan to access all patches: https://socket.dev/pricing`. * `-h` lists about eight common options per command; `--help` lists all of them. * **A closed output pipe never ends a run.** When the reader of stdout or stderr goes away (`socket-patch apply | head -1`, `| grep -q …`), the command stops printing to that stream and otherwise carries on: it finishes every write, releases `apply.lock` and exits with the code its work earned (`0` for a successful `apply`), not with SIGPIPE's 141 and not with a panic. This holds for `--json` too (the envelope is simply not delivered). Before, the default SIGPIPE disposition killed the process at the line it was printing, between two of a mutating command's writes and with the lock file left behind. @@ -1989,7 +2012,7 @@ Commands other than `--update` itself may print, on **stderr only**, after all c The notice is preceded by one blank line (it follows the command's own output, often an error). The second line is channel-aware (an npm-managed install is pointed at its npm upgrade command from the table above, not at `--update`). Contract promises: - At most one release-metadata fetch per 24 h (cached in the state file below; a failed fetch also counts), and at most one notice per 24 h while an update is pending. -- Never under `--json`, `--silent`, `--offline`/`SOCKET_OFFLINE`, in CI (`CI`/`GITHUB_ACTIONS` env), when stderr is not a terminal, or when `SOCKET_NO_UPDATE_CHECK` is truthy. Silenced means **zero network I/O**, not just no output. +- Never under `--json`, `--silent`, `--offline`/`SOCKET_OFFLINE`, in CI (`CI`/`GITHUB_ACTIONS` env), when stderr is not a terminal with a person at it (a pipe, or an AI coding agent's terminal), or when `SOCKET_NO_UPDATE_CHECK` is truthy. Silenced means **zero network I/O**, not just no output. - Never changes a command's exit code or stdout; adds at most ~500 ms to a run (the background check is abandoned past that grace budget and retried on a later run). The wait runs concurrently with telemetry's 300 ms exit grace, so the two cost the longer one, not the sum. - State-file corruption, clock skew, or an unwritable cache dir degrade to "never checked" — they can never break a command. - Independent of telemetry: `--no-telemetry` does not affect the update check (it fetches public release metadata with no identifying payload beyond the CLI User-Agent); `SOCKET_OFFLINE` kills both. @@ -2093,6 +2116,7 @@ Empty string means unset at every layer: exported-but-empty flag-bound vars are | `SOCKET_NO_CONFIG` | `false` | Truthy (`1`/`true`/`yes`/`on`): disable the socket-cli persisted-config fallback layer entirely — pure flag+env behavior. Also the test-hermeticity switch (the workspace `.cargo/config.toml` exports it as `1` for every cargo-run process). | | `SOCKET_NO_API_TOKEN` | `false` | Truthy: ignore **ambient** API tokens (the `SOCKET_API_TOKEN` env var and the socket-cli config token); only an explicit `--api-token` flag authenticates. Peer alias: `SOCKET_CLI_NO_API_TOKEN`. | | `SOCKET_NO_UPDATE_CHECK` | `false` | Truthy: disable the passive update notice entirely (see "Passive update notice"). Explicit `--update` still works. Also a test-hermeticity switch (the workspace `.cargo/config.toml` exports it as `1` for every cargo-run process). No `SOCKET_CLI_*` alias (socket-cli has no equivalent today). | +| `SOCKET_PLAIN` | (unset) | Overrides the detection of an AI coding agent's terminal (see "Human output conventions", **Agents**). Truthy (`1`/`true`/`yes`/`on`/`y`/`t`): the plain output a pipe gets, on a terminal too. Any other value: the full terminal output, whatever agent variable is set. Presentation only: no result, exit code or `--json` document depends on it. | ### Persisted configuration (socket-cli `config.json`) @@ -2936,7 +2960,7 @@ The VEX document is JSON-LD, which collides with the standard `--json` envelope `--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. -When verification is enabled (the default) and a patch is omitted, the failed PURLs are surfaced on stderr in plain mode (one `Warning: omitting from VEX: ()` line each, sorted by PURL) or as `skipped` events on the envelope in JSON mode (same order; `errorCode` is the tag). 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. ## Semver policy @@ -2994,6 +3018,7 @@ Every item in this document is locked in by at least one of: - **clap parser snapshots** in `crates/socket-patch-cli/tests/cli_parse_*.rs` — assert flag names, short forms, defaults, aliases, and CSV delimiters by calling `socket_patch_cli::Cli::try_parse_from(...)`. - **Helper unit tests** in `crates/socket-patch-cli/src/**` (`#[cfg(test)] mod tests` blocks) — cover `parse_argv_with_shortcuts`, `forced_identifier_error`, `installed_target_matches`, `select_patches`, `find_patches_to_rollback`, `partition_purls`, the JSON serializers, and the terminal UI in `src/ui/` (`StatusLine` redraw/clear/`println` byte streams, `confirm_with` answers and non-interactive notes, `select_one`'s JSON/empty guards, `plural`, `truncate`, the `color_enabled` truth table, `paint`/`severity`, and `pad`/`strip_ansi` alignment). +- **Human-output tests**: the pure builders are pinned byte for byte in their modules (`src/commands/scan/report.rs` for scan's rows and closing lines, `src/commands/measured.rs` for the measurement wording, `src/ui/diff.rs` for `show`'s diff, `src/ui/` for the style and status line), the commands end to end in `tests/scan/scan_render.rs`, `tests/scan/hosted_render.rs`, `tests/show_e2e.rs` and `tests/get/get_render.rs`, and what a terminal shows (status line, check marks, measurements) in `tests/scan/scan_tty.rs`. - **Async `run()` integration tests** in `tests/cli_parse_list.rs`, `tests/cli_parse_remove.rs` — exercise the no-network error paths and assert JSON shape via `serde_json::from_str::` + per-key assertions. If you add a new flag/subcommand/JSON key, add a test here that locks the new surface in the same PR. diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 203353819..3986f0014 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -309,30 +309,40 @@ pub(crate) fn files_with_both_hashes(patch: &PatchResponse) -> HashMap String { - let mut out = if added + updated > 0 { - format!("Patches saved to {}", manifest_path.display()) + let saved = added + updated; + let mut out = if saved > 0 { + format!( + "Saved {} to {}", + crate::ui::plural(saved, "patch", "patches"), + manifest_path.display() + ) } else { format!("No changes to {}", manifest_path.display()) }; - out.push_str(&format!("\n Added: {added}")); - for (label, n) in [ - ("Updated", updated), - ("Skipped", skipped), - ("Failed", failed), - ] { - if n > 0 { - out.push_str(&format!("\n {label}: {n}")); - } - } + let notes: Vec = [ + (updated, "updated"), + (skipped, "skipped"), + (failed, "failed"), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, what)| format!("{n} {what}")) + .collect(); + if !notes.is_empty() { + out.push_str(&format!(" ({})", notes.join(", "))); + } + out.push('.'); out } @@ -1298,7 +1308,7 @@ pub(crate) async fn fetch_selected_patches( // The narrowing queries the API: show that something is happening // once selection (and get's confirm prompt) is done. let mut status = crate::ui::StatusLine::stderr(params.json, params.silent); - status.set("Preparing download..."); + status.set("Preparing download"); let (selected, warnings, views) = filter_to_installed_releases( selected, params.all_releases, @@ -1309,14 +1319,12 @@ pub(crate) async fn fetch_selected_patches( .await; status.finish(); prefetched.extend(views); - // No leading blank line: the caller's prompt or summary already ended - // its line. - if matches!(store, RecordStore::Manifest(_)) && !quiet { - eprintln!( - "Downloading {}...", - crate::ui::plural(selected.len(), "patch", "patches") - ); - } + // The callers have already listed the patches (`scan`'s rows, `get`'s + // listing), so a downloaded patch is not named again here: the + // download shows on the status line. It shows only across each network + // wait below and is cleared before anything else can print, so a skip + // or error line never lands on it. + let mut progress = crate::ui::StatusLine::stderr(params.json, params.silent); let mut batch = FetchBatch { skipped: 0, @@ -1357,7 +1365,7 @@ pub(crate) async fn fetch_selected_patches( |uuid| async move { (uuid, hold_back_debug(api_client.fetch_patch(uuid)).await) }, )); - for search_result in &selected { + for (done, search_result) in selected.iter().enumerate() { let (purl, uuid) = (search_result.purl.as_str(), search_result.uuid.as_str()); // Refusal FIRST (the dry-run preview's precedence): a preserved @@ -1414,18 +1422,23 @@ pub(crate) async fn fetch_selected_patches( // these turns. let view = match prefetched.remove(uuid) { Some(patch) => Ok(Some(patch)), - None => match views.next().await { - Some((planned, view)) if planned == uuid => view.release(), - // Unreachable (the plan mirrors this loop's checks); a - // live fetch keeps the outcome right regardless. - _ => { - debug_assert!( - false, - "view prefetch plan out of step with the download loop" - ); - api_client.fetch_patch(uuid).await + None => { + progress.progress("Downloading patches", done, selected.len()); + let next = views.next().await; + progress.finish(); + match next { + Some((planned, view)) if planned == uuid => view.release(), + // Unreachable (the plan mirrors this loop's checks); a + // live fetch keeps the outcome right regardless. + _ => { + debug_assert!( + false, + "view prefetch plan out of step with the download loop" + ); + api_client.fetch_patch(uuid).await + } } - }, + } }; let patch = match view { Ok(Some(patch)) => patch, @@ -1466,9 +1479,9 @@ pub(crate) async fn fetch_selected_patches( }, }; if action == PatchAction::Skipped { - if !quiet { - eprintln!("{}", format_record_skip(&patch.purl, "already in manifest")); - } + // No line of its own: the caller has listed the patch, and the + // run's result says it (`Applied 0 of 1 patch: 1 already + // patched.`, `No changes to (1 skipped).`). batch.events.push( PatchEvent::new(EventAction::Skipped, patch.purl.as_str()) .with_uuid(patch.uuid.as_str()) @@ -1542,6 +1555,7 @@ pub(crate) async fn fetch_selected_patches( } _ => PatchEvent::new(EventAction::Downloaded, patch.purl.as_str()), }; + // A replaced record is worth its line; a new one has been listed. if let PatchAction::Updated { old_uuid } = &action { if !quiet { // Defensive: a malformed/short UUID in the store must not @@ -1552,8 +1566,6 @@ pub(crate) async fn fetch_selected_patches( crate::ui::short_uuid(old_uuid) ); } - } else if !quiet { - eprintln!(" [{tag}] {}", normalize_purl(&patch.purl)); } event = event.with_uuid(patch.uuid.as_str()).with_details(details); batch.events.push(tag_mode(event, batch.mode)); @@ -2302,21 +2314,18 @@ pub async fn download_and_apply_patches_into( } env.warnings.extend(warnings); - if !quiet { - eprintln!(); + // The apply below says the run's result. With no apply to follow + // (`--save-only`), the save is the result. + if !quiet && apply_lock.is_none() { eprintln!( "{}", - format_save_summary(&manifest_path, added, updated, batch.skipped, batch.failed) + format_save_line(&manifest_path, added, updated, batch.skipped, batch.failed) ); } // Auto-apply unless --save-only (the lock decision above). let mut apply_report: Option = None; if let Some(lock) = apply_lock { - if !quiet { - eprintln!(); - eprintln!("Applying patches..."); - } // Past the network, about to write to installed packages: a // hot-patch pass is no longer dropped at its time limit. crate::hot_patch::mark_apply_started(); diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index e33ee73e9..f605afd43 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1892,7 +1892,15 @@ pub(crate) async fn run_locked( if !args.common.json && !args.common.silent { let cwd = std::fs::canonicalize(&args.common.cwd) .unwrap_or_else(|_| args.common.cwd.clone()); - let block = format_results_block(&results, &caveats, args.common.dry_run, &cwd); + // A nested apply's caller (`scan`, `get`) has listed the + // packages itself: the block that names them again is left + // out, and the result is one short line. + let compact = args.nested.is_some(); + let block = if compact { + Vec::new() + } else { + format_results_block(&results, &caveats, args.common.dry_run, &cwd) + }; let mut block = block.iter().peekable(); // A nested apply's caller already ended its stdout with a // blank line (its listing or table), so the block's leading @@ -1907,7 +1915,16 @@ pub(crate) async fn run_locked( if args.common.verbose && !results.is_empty() { print_verbose_verification(&results); } - if show_summary { + if show_summary && compact { + println!( + "{}", + format_compact_summary( + &tally_results(&results, &caveats), + targeted, + unmatched.len() + ) + ); + } else if show_summary { let tally = tally_results(&results, &caveats); println!(); if args.common.dry_run { @@ -2471,6 +2488,35 @@ fn format_summary_line(tally: &ApplyTally, targeted: usize, not_found: usize) -> format!("Summary: {}", parts.join(", ")) } +/// [`format_summary_line`] for a nested apply, whose caller (`scan`, `get`) +/// lists the patched packages itself: `Applied 6 patches.`, and the other +/// buckets only when a patch landed in one +/// (`Applied 4 of 6 patches: 1 already patched, 1 failed.`). +fn format_compact_summary(tally: &ApplyTally, targeted: usize, not_found: usize) -> String { + let rest: Vec = [ + (tally.already, "already patched"), + (tally.vendored, "vendored"), + (tally.not_applicable, "not applicable"), + (tally.not_in_effect, "not in effect"), + (tally.failed, "failed"), + (not_found, "not found on disk"), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, what)| format!("{n} {what}")) + .collect(); + if rest.is_empty() { + format!("Applied {}.", plural(tally.applied, "patch", "patches")) + } else { + format!( + "Applied {} of {}: {}.", + tally.applied, + plural(targeted, "patch", "patches"), + rest.join(", ") + ) + } +} + /// The dry-run summary block: what a wet run would do, per package. fn format_dry_run_summary(tally: &ApplyTally, not_found: usize) -> Vec { let mut lines = vec![ @@ -4833,6 +4879,33 @@ mod tests { format_summary_line(&failed, 1, 0), "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 failed, 0 not found on disk" ); + // The compact form names only the buckets a patch landed in. + let all = ApplyTally { + applied: 6, + ..ApplyTally::default() + }; + assert_eq!(format_compact_summary(&all, 6, 0), "Applied 6 patches."); + assert_eq!(format_compact_summary(&one, 1, 0), "Applied 1 patch."); + assert_eq!( + format_compact_summary(&mixed, 4, 1), + "Applied 1 of 4 patches: 2 already patched, 1 not found on disk." + ); + assert_eq!( + format_compact_summary(&failed, 1, 0), + "Applied 0 of 1 patch: 1 failed." + ); + // A patch written but not in effect never reads as applied, and + // one with nothing to patch in this build is named too. + let partial = ApplyTally { + applied: 1, + not_in_effect: 1, + not_applicable: 1, + ..ApplyTally::default() + }; + assert_eq!( + format_compact_summary(&partial, 3, 0), + "Applied 1 of 3 patches: 1 not applicable, 1 not in effect." + ); } #[test] diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 3db169b95..0dbbd5efb 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -42,7 +42,9 @@ pub use crate::commands::agent_download::{ download_and_apply_patches_into, download_and_apply_patches_with, DownloadParams, DownloadRun, }; use crate::commands::apply::ApplyRunReport; -use crate::ecosystem_dispatch::{crawl_ecosystems, find_packages_for_rollback, partition_purls}; +use crate::ecosystem_dispatch::{ + crawl_ecosystems, find_packages_for_rollback, installed_target_matches, partition_purls, +}; use crate::json_envelope::{ usage_error, Command as JsonCommand, Envelope, EnvelopeError, PatchAction as EventAction, PatchEvent, RunWarning, Status, @@ -334,14 +336,16 @@ fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering { /// order [`select_patches`] resolves in, so a package's first entry is the /// one that will be applied. A `by-cve` / `by-ghsa` search can span /// several packages, hence the grouping. Severities are colored when -/// `color` is on. Ends with a blank line. +/// `color` is on. Under a patch's `Fixes:` line come the lines of what +/// Socket `measured` about it ([`super::measured::lines`]), when it did. +/// Ends with a blank line. fn format_search_results( patches: &[&PatchSearchResult], can_access_paid: bool, color: bool, + measured: &super::measured::Measured, ) -> String { - let mut patches: Vec<&PatchSearchResult> = patches.to_vec(); - patches.sort_by(|a, b| natural_cmp(&a.purl, &b.purl).then_with(|| cmp_search_results(a, b))); + let patches = listing_order(patches); let mut out = format!( "Found {}:\n\n", @@ -396,11 +400,53 @@ fn format_search_results( .collect(); out.push_str(&format!(" Fixes: {}\n", fixes.join(", "))); } + for line in measured + .get(&patch.uuid) + .map(super::measured::lines) + .unwrap_or_default() + { + out.push_str(&format!(" {line}\n")); + } out.push('\n'); } out } +/// The order a listing shows `patches` in ([`format_search_results`]): by +/// package, each package's patches best ranked first. +fn listing_order<'a>(patches: &[&'a PatchSearchResult]) -> Vec<&'a PatchSearchResult> { + let mut patches: Vec<&PatchSearchResult> = patches.to_vec(); + patches.sort_by(|a, b| natural_cmp(&a.purl, &b.purl).then_with(|| cmp_search_results(a, b))); + patches +} + +/// The patches of a listing whose measurements are asked for: the first +/// [`MEASURED_LISTED`] in the order the listing shows them +/// ([`listing_order`]), so a long listing has its measurements at the +/// top, not scattered over rows further down. +fn measured_uuids(listed: &[&PatchSearchResult]) -> Vec { + listing_order(listed) + .into_iter() + .take(MEASURED_LISTED) + .map(|p| p.uuid.clone()) + .collect() +} + +/// What Socket measured about the patches a listing is about to show, for +/// [`format_search_results`]: asked for only when someone is watching +/// ([`super::measured::wanted`]), and only for the first +/// [`MEASURED_LISTED`] of a long listing ([`measured_uuids`]). +async fn measure_listed( + common: &GlobalArgs, + api_client: &ApiClient, + listed: &[&PatchSearchResult], +) -> super::measured::Measured { + super::measured::fetch(common, api_client, measured_uuids(listed)).await +} + +/// Most patches of one listing whose measurements are asked for. +const MEASURED_LISTED: usize = 32; + /// The stderr line naming the installed packages a package-name search /// matched (every one of them is searched). fn format_matched_packages(purls: &[String]) -> String { @@ -418,22 +464,6 @@ fn format_matched_packages(purls: &[String]) -> String { } } -/// Every installed purl a package-name `target` selects, deduplicated and -/// sorted (a monorepo can hold the same release in several places). -fn installed_target_matches( - target: &Target, - packages: &[socket_patch_core::crawlers::CrawledPackage], -) -> Vec { - let mut purls: Vec = packages - .iter() - .filter(|pkg| target.matches_package(&pkg.purl)) - .map(|pkg| pkg.purl.clone()) - .collect(); - purls.sort(); - purls.dedup(); - purls -} - /// "Did you mean" for a name that matched nothing exactly: up to five /// installed names the fuzzy ranker puts closest. A suggestion only — a /// near name is never searched or patched. @@ -507,8 +537,8 @@ fn selection_prompted( can_access_paid: bool, common: &GlobalArgs, ) -> bool { - use std::io::IsTerminal; - selection_has_choice(candidates, can_access_paid, common) && std::io::stdin().is_terminal() + selection_has_choice(candidates, can_access_paid, common) + && crate::ui::attended(crate::ui::Stream::Stdin) } /// The "which patch will be installed" block printed before the prompt @@ -1582,9 +1612,15 @@ pub async fn run(args: GetArgs) -> i32 { // stdout itself starts with the result. eprintln!(); } + let measured = measure_listed(&args.common, &api_client, &all).await; print!( "{}", - format_search_results(&all, search_response.can_access_paid_patches, color) + format_search_results( + &all, + search_response.can_access_paid_patches, + color, + &measured + ) ); println!("All available patches require a paid Socket plan."); println!("{}", crate::ui::PAID_UPGRADE); @@ -1676,9 +1712,15 @@ pub async fn run(args: GetArgs) -> i32 { // terminal; stdout itself starts with the result. eprintln!(); } + let measured = measure_listed(&args.common, &api_client, &listed).await; print!( "{}", - format_search_results(&listed, search_response.can_access_paid_patches, color) + format_search_results( + &listed, + search_response.can_access_paid_patches, + color, + &measured + ) ); let mut skip_lines = format_skip_summary(&narrow_skips); if args.common.verbose { @@ -2167,10 +2209,8 @@ async fn save_and_apply_patch( let mut apply_report: Option = None; if let Some(lock) = apply_lock { - if !quiet { - eprintln!(); - eprintln!("Applying patches..."); - } + // One patch, named on the save line above: the apply says its + // result in one line (`Applied 1 patch.`). apply_report = Some( run_nested_apply( nested_apply_args(&args.common, &manifest_path, quiet), @@ -2522,7 +2562,7 @@ async fn run_get_vendored( mod tests { use super::*; use crate::commands::agent_download::{ - base64_decode, files_with_both_hashes, format_record_skip, format_save_summary, + base64_decode, files_with_both_hashes, format_record_skip, format_save_line, nested_apply_args_from_params, severity_rank, write_blob_entry, APPLY_FAILED, }; use socket_patch_core::crawlers::CrawlerOptions; @@ -3151,6 +3191,7 @@ mod tests { description: "desc".into(), license: "MIT".into(), tier: "free".into(), + statistics: None, }; let meta = patch_event_metadata(&patch); assert!(meta.as_object().unwrap().get("severity").is_none()); @@ -3181,6 +3222,7 @@ mod tests { description: "Fixes prototype pollution in minimist".into(), license: "MIT".into(), tier: "free".into(), + statistics: None, }; let meta = patch_event_metadata(&patch); assert_eq!(meta["description"], "Fixes prototype pollution in minimist"); @@ -3222,6 +3264,7 @@ mod tests { description: String::new(), license: String::new(), tier: String::new(), + statistics: None, }; let meta = patch_event_metadata(&patch); let ids: Vec<&str> = meta["vulnerabilities"] @@ -3244,6 +3287,7 @@ mod tests { description: "desc".into(), license: "MIT".into(), tier: "free".into(), + statistics: None, }; let meta = patch_event_metadata(&patch); // `severity` is intentionally omitted (not null) when there @@ -3849,6 +3893,7 @@ mod tests { description: "desc".into(), license: "MIT".into(), tier: "free".into(), + statistics: None, } } @@ -4326,6 +4371,37 @@ mod tests { assert_eq!(natural_cmp("é2", "é10"), Ordering::Less); } + /// A long listing asks for the measurements of the patches at its + /// top: the first of them in the order it shows them, whatever order + /// the search returned them in. Measured in search order, they would + /// land on rows further down and leave the first ones bare. + #[test] + fn a_long_listing_measures_the_patches_it_shows_first() { + let total = MEASURED_LISTED + 8; + // As a search returns them: the reverse of how they are listed. + let found: Vec = (0..total) + .rev() + .map(|i| { + mk_patch( + &format!("uuid-{i:02}"), + &format!("pkg:npm/lodash@4.17.{i}"), + "free", + "2024-01-01", + ) + }) + .collect(); + let found: Vec<&PatchSearchResult> = found.iter().collect(); + let shown: Vec = listing_order(&found) + .iter() + .map(|p| p.uuid.clone()) + .collect(); + assert_eq!(shown[0], "uuid-00"); + assert_eq!(shown[total - 1], format!("uuid-{:02}", total - 1)); + assert_eq!(measured_uuids(&found), shown[..MEASURED_LISTED]); + // A short one measures them all. + assert_eq!(measured_uuids(&found[..3]).len(), 3); + } + #[test] fn search_results_listing_exact_text() { let a = with_vulns( @@ -4337,7 +4413,8 @@ mod tests { ); let mut b = mk_patch("uuid-b", "pkg:npm/lodash@4.17.2", "paid", "2024-01-01"); b.description = String::new(); - let out = format_search_results(&[&a, &b], false, false); + let none = crate::commands::measured::Measured::new(); + let out = format_search_results(&[&a, &b], false, false, &none); assert_eq!( out, "Found 2 patches:\n\n\ @@ -4348,13 +4425,28 @@ mod tests { \x20 Description: desc-uuid-a\n\ \x20 Fixes: CVE-2026-1 (HIGH), CVE-2026-2 (MODERATE)\n\n" ); - let one = format_search_results(&[&a], true, false); + let one = format_search_results(&[&a], true, false, &none); assert!(one.starts_with("Found 1 patch:\n\n"), "{one}"); assert_eq!( - format_search_results(&[], true, false), + format_search_results(&[], true, false, &none), "Found 0 patches:\n\n" ); - let colored = format_search_results(&[&a], true, true); + // What Socket measured about a patch follows its `Fixes:` line. + let measured: crate::commands::measured::Measured = [( + "uuid-a".to_string(), + crate::commands::measured::tests::stats(2, 35, 35), + )] + .into(); + assert_eq!( + format_search_results(&[&a], true, false, &measured), + "Found 1 patch:\n\n\ + \x20 1. pkg:npm/lodash@4.17.10 [FREE]\n\ + \x20 UUID: uuid-a\n\ + \x20 Description: desc-uuid-a\n\ + \x20 Fixes: CVE-2026-1 (HIGH), CVE-2026-2 (MODERATE)\n\ + \x20 Verified: 2 of 2 exploits blocked, 35 of 35 tests passing\n\n" + ); + let colored = format_search_results(&[&a], true, true, &none); assert!( colored.contains("CVE-2026-1 (\x1b[31mHIGH\x1b[0m)"), "{colored:?}" @@ -4482,23 +4574,27 @@ mod tests { } #[test] - fn save_summary_lines() { + fn save_line_says_what_changed_in_one_line() { let m = Path::new(".socket/manifest.json"); assert_eq!( - format_save_summary(m, 2, 0, 0, 0), - "Patches saved to .socket/manifest.json\n Added: 2" + format_save_line(m, 2, 0, 0, 0), + "Saved 2 patches to .socket/manifest.json." + ); + assert_eq!( + format_save_line(m, 1, 1, 1, 1), + "Saved 2 patches to .socket/manifest.json (1 updated, 1 skipped, 1 failed)." ); assert_eq!( - format_save_summary(m, 1, 1, 1, 1), - "Patches saved to .socket/manifest.json\n Added: 1\n Updated: 1\n Skipped: 1\n Failed: 1" + format_save_line(m, 1, 0, 0, 0), + "Saved 1 patch to .socket/manifest.json." ); assert_eq!( - format_save_summary(m, 0, 0, 2, 0), - "No changes to .socket/manifest.json\n Added: 0\n Skipped: 2" + format_save_line(m, 0, 0, 2, 0), + "No changes to .socket/manifest.json (2 skipped)." ); assert_eq!( - format_save_summary(m, 0, 0, 0, 1), - "No changes to .socket/manifest.json\n Added: 0\n Failed: 1" + format_save_line(m, 0, 0, 0, 1), + "No changes to .socket/manifest.json (1 failed)." ); } @@ -4608,11 +4704,11 @@ mod tests { assert!(!selection_prompted(&two, false, &json)); // A single free candidate is auto-picked. assert!(!selection_prompted(&one_plus_paid, false, &plain)); - // Several free candidates prompt exactly when stdin is a terminal. - use std::io::IsTerminal; + // Several free candidates prompt exactly when someone is at the + // terminal on stdin. assert_eq!( selection_prompted(&two, false, &plain), - std::io::stdin().is_terminal() + crate::ui::attended(crate::ui::Stream::Stdin) ); } diff --git a/crates/socket-patch-cli/src/commands/list.rs b/crates/socket-patch-cli/src/commands/list.rs index b0c9c2961..d4d9f2b69 100644 --- a/crates/socket-patch-cli/src/commands/list.rs +++ b/crates/socket-patch-cli/src/commands/list.rs @@ -10,6 +10,7 @@ use crate::args::{apply_env_toggles, GlobalArgs}; use crate::json_envelope::{ Command, Envelope, EnvelopeError, PatchAction, PatchEvent, PatchEventFile, RunWarning, }; +use crate::ui::browser::{Cell, Column, Page, Table, Update}; #[derive(Args)] pub struct ListArgs { @@ -211,6 +212,483 @@ struct Listed { patches: usize, /// How many of them are manifest records (what telemetry counts). manifest_patches: usize, + /// The patches as an interactive run's table shows and opens them + /// (empty otherwise). + rows: Vec, + /// What reading the project had to say on stderr (`Warning: ...`, or + /// the `Error: ...` of a project that could not be listed), held back + /// so it prints once the status line is down. + notes: Vec, +} + +impl Listed { + /// Print the held-back stderr lines. + fn print_notes(&mut self) { + for note in self.notes.drain(..) { + eprintln!("{note}"); + } + } +} + +/// One listed patch, as an interactive run shows it: a row of its table, +/// and what opening it falls back to. +#[derive(Clone)] +struct Browse { + purl: String, + uuid: String, + /// The worst severity among the advisories it fixes, upper-cased; + /// empty when the project's records name none (a hosted pin carries + /// only its uuid: the details are the patch service's). + severity: String, + /// The ids to show for what it fixes: each advisory's CVEs, or its own + /// id when it has none. + ids: Vec, + /// `agent`, `hosted` or `vendored`. + mode: &'static str, + /// The entry as the full listing prints it: what opening the patch + /// shows when the patch service cannot be asked. + detail: String, +} + +/// The worst severity and the ids to show for a set of advisories +/// ([`crate::ui::worst_and_ids`]), cleaned of control characters: they +/// may come from the project's own files. +fn fixes<'a>( + advisories: impl Iterator, +) -> (String, Vec) { + let (worst, ids) = crate::ui::worst_and_ids( + advisories.map(|(id, severity, cves)| (id.as_str(), severity, cves)), + ); + // Two ids that differ only in what is cleaned off are one id. + let mut ids: Vec = ids.iter().map(|id| sanitize(id)).collect(); + ids.sort(); + ids.dedup(); + (sanitize(&worst), ids) +} + +impl Browse { + fn of(entry: &ListEntry<'_>, color: bool) -> Self { + let (severity, ids) = fixes( + entry + .record + .vulnerabilities + .iter() + .map(|(id, v)| (id, v.severity.as_str(), v.cves.as_slice())), + ); + Browse { + purl: sanitize(entry.purl), + uuid: entry.record.uuid.clone(), + severity, + ids, + mode: match entry.source { + Store::Manifest => "agent", + Store::Hosted => crate::commands::HOSTED_MODE_LABEL, + Store::Vendored => crate::commands::VENDORED_MODE_LABEL, + }, + detail: format_entry(entry, color), + } + } + + /// The row's cells, in [`columns`]' order. `name` is how the table + /// names the package ([`names`]). `detail` is the patch as the patch + /// service describes it, once that has arrived: it fills in what was + /// measured about the patch and when it was published, and names the + /// advisories of a patch the project records by uuid alone. + fn cells( + &self, + name: &str, + project: Option<&str>, + detail: Option<&socket_patch_core::api::types::PatchResponse>, + ) -> Vec { + use crate::commands::measured::percent; + let (mut severity, mut ids) = (self.severity.clone(), self.ids.clone()); + if let Some(detail) = detail.filter(|_| ids.is_empty()) { + (severity, ids) = fixes( + detail + .vulnerabilities + .iter() + .map(|(id, v)| (id, v.severity.as_str(), v.cves.as_slice())), + ); + } + let ids = if ids.len() > IDS_SHOWN { + format!( + "{} (+{})", + ids[..IDS_SHOWN].join(", "), + ids.len() - IDS_SHOWN + ) + } else { + ids.join(", ") + }; + // Green when every exploit is blocked / every test passes; yellow + // when some are not. + let ratio = |ratio: socket_patch_core::api::types::PatchRatio| { + Cell::painted( + format!("{}/{}", ratio.count, ratio.total), + Some(if ratio.is_all() { "32" } else { "33" }), + ) + }; + let stats = detail.and_then(|d| d.statistics); + let exploits = stats + .and_then(|s| s.pocs) + .map(|pocs| ratio(pocs.blocked_after)) + .unwrap_or_default(); + let tests = stats + .and_then(|s| s.tests) + .map(|tests| ratio(tests.after)) + .unwrap_or_default(); + let change = stats + .and_then(|s| s.diff) + .map(|diff| format!("+{} -{}", diff.lines_added, diff.lines_removed)) + .unwrap_or_default(); + // The cost of the code the patch touches, or of the package's + // general workload where only that was measured. + let perf = stats + .and_then(|s| s.performance) + .and_then(|p| p.hot_wall_change.or(p.general_wall_change)) + .map(percent) + .unwrap_or_default(); + let published = detail + .map(|d| crate::commands::show::short_date(&d.published_at)) + .unwrap_or_default(); + let mut cells = vec![ + Cell::painted(severity.clone(), crate::ui::severity_code(&severity)), + Cell::plain(name), + Cell::plain(ids), + exploits, + tests, + Cell::plain(change), + Cell::plain(perf), + Cell::plain(published), + Cell::plain(self.mode), + ]; + if let Some(project) = project { + cells.push(Cell::plain(project)); + } + cells + } + + /// The patch as a page of the browser from what the project records + /// about it, under `why` the patch service's own account is missing + /// (the end of a sentence: an error's text, which may run over + /// several lines or end in a period of its own). + fn local_page(&self, why: Option<&str>) -> Page { + let mut lines: Vec = why + .map(|why| { + let why = sanitize(why) + .split_whitespace() + .collect::>() + .join(" "); + vec![ + format!( + "The patch could not be read: {}.", + why.trim_end_matches('.') + ), + String::new(), + "What this project records:".to_string(), + String::new(), + ] + }) + .unwrap_or_default(); + lines.extend(self.detail.lines().map(str::to_string)); + Page { + title: self.purl.clone(), + lines, + marks: Vec::new(), + } + } +} + +/// How many advisory ids a row names before it counts the rest. +const IDS_SHOWN: usize = 2; + +/// The columns of the interactive table, with what each gives way to on +/// a narrow terminal (the highest number first): the mode and the dates +/// before the measurements, the measurements before the advisories. +/// `projects`: the rows come from several project directories, so each +/// says whose it is. +fn columns(projects: bool) -> Vec { + let mut columns: Vec = [ + ("SEVERITY", 0), + ("PACKAGE", 0), + ("FIXES", 1), + ("EXPLOITS", 4), + ("TESTS", 3), + ("CHANGE", 5), + ("PERF", 6), + ("PUBLISHED", 7), + ("MODE", 8), + ] + .into_iter() + .map(|(title, gives_way)| Column { title, gives_way }) + .collect(); + if projects { + columns.push(Column { + title: "PROJECT", + gives_way: 2, + }); + } + columns +} + +/// How the table names each of `rows`' packages +/// ([`crate::ui::package_names`]). +fn names(rows: &[&Browse]) -> Vec { + crate::ui::package_names(&rows.iter().map(|row| row.purl.as_str()).collect::>()) +} + +/// The table an interactive run opens with: what the project's own +/// records say about each patch. The patch service's account of them +/// fills in afterwards ([`Browse::cells`]). +fn table_of(rows: &[(Browse, Option)]) -> Table { + let patches: Vec<&Browse> = rows.iter().map(|(row, _)| row).collect(); + let projects = rows.iter().any(|(_, project)| project.is_some()); + let names = names(&patches); + Table { + title: format!( + "{} in this project", + crate::ui::plural(rows.len(), "patch", "patches") + ), + columns: columns(projects), + rows: rows + .iter() + .zip(&names) + .map(|((row, project), name)| row.cells(name, project.as_deref(), None)) + .collect(), + } +} + +/// Whether this run is someone at a terminal who can be shown a table to +/// browse: a human run on a terminal that can show the full-screen +/// browser ([`crate::ui::full_screen`]), that `--yes` did not ask to run +/// unattended. `--verbose` keeps the full listing. +fn interactive(common: &GlobalArgs) -> bool { + !common.json && !common.silent && !common.yes && !common.verbose && crate::ui::full_screen() +} + +/// Browse `rows` full-screen: the table goes up at once with what the +/// project records, the patch service's account of each patch (what it +/// fixes, what was measured about it, when it was published) fills in as +/// it arrives, and Enter opens a patch as a page: its summary and the +/// diff of every file it changes. Nothing is changed by any of it. +/// +/// Returns the table as it stood when the user left, for the listing +/// that stays on the terminal. `--offline` asks the patch service +/// nothing: the rows keep what the project records, and a patch opens as +/// the project's own entry for it. +async fn browse(rows: Vec<(Browse, Option)>, common: &GlobalArgs) -> Table { + use futures_util::StreamExt as _; + use socket_patch_core::utils::concurrent::api_concurrency_for; + + let table = table_of(&rows); + let names = names(&rows.iter().map(|(row, _)| row).collect::>()); + // The patch service's client is built once the table is up, by + // whichever read needs it first: building it can mean a request (a + // token with no organization named has its organization looked up), + // and the listing itself needs none, so it never waits for one. + // While the browser has the screen, core's advisories are muted: a + // line printed under it would land in the middle of the table. The + // one that explains what the table shows is printed after. + // Both reads go through `show`'s source of patches, so a row and the + // page it opens are read the same way, a refused token included. + let connection = tokio::sync::OnceCell::::new(); + let connect = || async { + if common.offline { + return None; + } + Some( + connection + .get_or_init(|| async { + let overrides = common.api_client_overrides(); + let client = socket_patch_core::api::client::get_api_client_with_overrides( + overrides.clone(), + ) + .await + .0; + crate::commands::show::Source::new(client, overrides) + }) + .await, + ) + }; + socket_patch_core::utils::notice::set_output_mode(true, common.json); + let (updates, received) = std::sync::mpsc::channel::(); + let (opened, mut opening) = tokio::sync::mpsc::unbounded_channel::(); + + // The browser blocks on the keyboard, so it runs off the runtime's + // threads. What it shows beyond the project's own records is read + // here, beside it: the patch service's account of each patch, a few at + // a time, and the page of each patch that is opened. + let mut browser = tokio::task::spawn_blocking(move || { + crate::ui::browser::run(table, received, move |row| { + let _ = opened.send(row); + }) + }); + let details = async { + let Some(source) = connect().await else { + return; + }; + // What the project records as a patch's uuid comes from its own + // files (a manifest anyone can write): only one that is a UUID + // goes into a request to the patch service. + let mut uuids: Vec = rows + .iter() + .map(|(row, _)| row.uuid.clone()) + .filter(|uuid| socket_patch_core::utils::target::is_uuid_shaped(uuid)) + .collect(); + uuids.sort_unstable(); + uuids.dedup(); + if uuids.is_empty() { + return; + } + let total = uuids.len(); + let _ = updates.send(Update::Note(format!("loading details 0/{total}"))); + let mut answers = futures_util::stream::iter(uuids) + .map(|uuid| async move { + let (_, answer) = source.ask(|client| client.fetch_patch_summary(&uuid)).await; + (uuid, answer) + }) + .buffer_unordered(api_concurrency_for( + source.client().uses_public_proxy(), + total, + )); + let mut done = 0; + while let Some((uuid, answer)) = answers.next().await { + done += 1; + // A patch that could not be read keeps its row as it is. + if let Ok(Some(detail)) = answer { + for (index, ((row, project), name)) in rows.iter().zip(&names).enumerate() { + if row.uuid == uuid { + let cells = row.cells(name, project.as_deref(), Some(&detail)); + let _ = updates.send(Update::Row(index, cells)); + } + } + } + let note = if done < total { + format!("loading details {done}/{total}") + } else { + String::new() + }; + let _ = updates.send(Update::Note(note)); + } + }; + // A row opens as the page `show` opens for its patch, read the way + // `show` reads it; only a patch the service cannot be asked about + // opens as the project's own record. + let style = crate::ui::Style::stderr(); + let page = |index: usize| { + let (rows, connect, updates) = (&rows, &connect, &updates); + async move { + let Some((row, _)) = rows.get(index) else { + return; + }; + let page = match connect().await { + Some(source) => { + match crate::commands::show::load_page(source, &row.uuid, style).await { + Ok(page) => page, + Err(why) => row.local_page(Some(&why)), + } + } + None => row.local_page(None), + }; + let _ = updates.send(Update::Page(index, Ok(page))); + } + }; + let mut details = std::pin::pin!(details); + let mut detailed = false; + let mut pages = futures_util::stream::FuturesUnordered::new(); + let left = loop { + tokio::select! { + left = &mut browser => break left, + () = &mut details, if !detailed => detailed = true, + Some(index) = opening.recv() => pages.push(page(index)), + Some(()) = pages.next(), if !pages.is_empty() => {} + } + }; + drop(pages); + // The screen is the terminal's again: advisories print as before, + // and the one the browser withheld that explains its rows is said + // now (a token whose organization could not be found reads the + // public service, which knows free patches only). + socket_patch_core::utils::notice::set_output_mode(common.silent, common.json); + if let Some(reason) = connection + .get() + .and_then(|source| source.client().org_unresolved()) + { + eprintln!("Warning: {reason}"); + } + match left { + Ok(Ok(table)) => table, + // No full-screen browser here (the terminal could not be set up + // for one, or this is not Unix): the inline menu does the job. + Ok(Err(table)) => { + for line in listing_lines(&table) { + println!("{line}"); + } + println!(); + browse_inline(&rows, &table, common).await; + Table { + rows: Vec::new(), + ..table + } + } + // The browser's thread panicked: the terminal is restored by its + // guard, and the listing is still owed. + Err(_) => table_of(&rows), + } +} + +/// The inline stand-in for the full-screen browser: an arrow-key menu of +/// the rows under the printed listing; a pick prints `show`'s summary of +/// the patch (`show --stat`: its fixes, measurements and files, without +/// the diffs, which would push the menu off the screen) and comes back +/// to the menu. +async fn browse_inline(rows: &[(Browse, Option)], table: &Table, common: &GlobalArgs) { + let options: Vec = + crate::ui::browser::table_lines(table, usize::MAX, crate::ui::Style::PLAIN) + .into_iter() + .skip(1) + .map(|line| line.trim_start().to_string()) + .collect(); + let mut at = 0; + while let Ok(picked) = + crate::ui::select_from("Open a patch (Esc to leave)", &options, at, common) + { + at = picked; + let patch = &rows[picked].0; + // A recorded uuid that is not one is no identifier to look up. + let shown = !common.offline + && socket_patch_core::utils::target::is_uuid_shaped(&patch.uuid) + && crate::commands::show::run(crate::commands::show::ShowArgs { + identifier: patch.uuid.clone(), + common: common.clone(), + files: Vec::new(), + stat: true, + no_pager: false, + }) + .await + == 0; + if !shown { + println!("{}", patch.detail); + } + println!(); + } +} + +/// The listing an interactive run leaves on the terminal: the count, +/// then the table's rows as they stood ([`table_lines`]), cut to the +/// terminal's width. +/// +/// [`table_lines`]: crate::ui::browser::table_lines +fn listing_lines(table: &Table) -> Vec { + let mut lines = vec![format!( + "Found {}:", + crate::ui::plural(table.rows.len(), "patch", "patches") + )]; + lines.extend(crate::ui::browser::table_lines( + table, + crate::ui::stdout_width().saturating_sub(1), + crate::ui::Style::stdout(), + )); + lines } /// The listing of a project in an error state. Used for the "manifest not @@ -224,21 +702,25 @@ fn failed_listing( message: String, warnings: Vec, ) -> Listed { + // Errors print even under --silent; `--json` carries them instead. + let mut notes = Vec::new(); let envelope = if args.common.json { let mut env = Envelope::new(Command::List); env.mark_error(EnvelopeError::new(code, message)); env.warnings = warnings; Some(env) } else { - eprintln!("Error: {message}"); + notes.push(format!("Error: {message}")); None }; Listed { code: 1, + notes, envelope, text: None, patches: 0, manifest_patches: 0, + rows: Vec::new(), } } @@ -348,9 +830,24 @@ fn format_listing(entries: &[ListEntry<'_>], color: bool) -> String { pub async fn run(args: ListArgs) -> i32 { use crate::commands::projects_below::{self, CWD_NAME}; apply_env_toggles(&args.common); + // Someone at a terminal browses the patches; everyone else gets them + // printed. + let browsing = interactive(&args.common); + if !browsing && !args.common.yes && !args.common.verbose { + // On a terminal this would have been the table: say why not. + crate::ui::note_agent_terminal(&args.common); + } + // Finding and reading the projects walks the checkout and parses its + // lockfiles: the status line says so while it lasts. What a project + // has to say on stderr is held back until the line is down. + let mut status = crate::ui::StatusLine::stderr(args.common.json, args.common.silent); + status.set("Finding patched projects"); // What `scan` patched from this directory is listed from it: the // project at `--cwd`, then the patched project directories below it. let below = projects_below::patched(&args.common, projects_below::Depth::All).await; + let here_patched = + !below.projects.is_empty() && projects_below::cwd_is_patched(&args.common).await; + status.finish(); let loud = !args.common.json && !args.common.silent; if loud { below.print_notes(); @@ -360,15 +857,21 @@ pub async fn run(args: ListArgs) -> i32 { // when it holds patches itself: listed first, under the heading scan // gives `--cwd`. A project's warnings and errors go to stderr as it is // read, so its heading goes out before it is. - let mut here = !below.projects.is_empty() && projects_below::cwd_is_patched(&args.common).await; - if here && loud { + let mut here = here_patched; + // The headings belong to the printed listing: a browsed one names each + // row's project in a column. + let headed = loud && !browsing; + if here && headed { println!("{}", projects_below::heading(CWD_NAME)); } - let mut own = list_project(&args).await; + status.set("Reading patches"); + let mut own = list_project(&args, browsing).await; + status.finish(); + own.print_notes(); // The listing has the last word on what `--cwd` holds. if !here && !below.projects.is_empty() && (own.patches > 0 || own.code != 0) { here = true; - if loud { + if headed { println!("{}", projects_below::heading(CWD_NAME)); } } @@ -382,10 +885,13 @@ pub async fn run(args: ListArgs) -> i32 { let child = ListArgs { common: project.common(&args.common), }; - if loud { + if headed { println!("{}", projects_below::heading(&project.shown)); } - let listing = list_project(&child).await; + status.set(format!("Reading patches in {}", project.shown)); + let mut listing = list_project(&child, browsing).await; + status.finish(); + listing.print_notes(); if let Some(text) = &listing.text { println!("{text}"); } @@ -440,7 +946,7 @@ pub async fn run(args: ListArgs) -> i32 { println!("{text}"); } } else { - if loud { + if headed { let patches: usize = listed.iter().map(|(_, listing)| listing.patches).sum(); println!( "\n{} in {}.", @@ -471,6 +977,31 @@ pub async fn run(args: ListArgs) -> i32 { ); } } + // Someone at a terminal browses every patch found, in one table, and + // what it showed when they left is the listing that stays. + let shown_own = here || listed.is_empty(); + let several = !listed.is_empty(); + let rows: Vec<(Browse, Option)> = own + .rows + .drain(..) + .filter(|_| shown_own) + .map(|row| (row, several.then(|| CWD_NAME.to_string()))) + .chain(listed.iter_mut().flat_map(|(shown, listing)| { + let shown = shown.to_string(); + listing + .rows + .drain(..) + .map(move |row| (row, Some(shown.clone()))) + })) + .collect(); + if !rows.is_empty() { + let table = browse(rows, &args.common).await; + if !table.rows.is_empty() { + for line in listing_lines(&table) { + println!("{line}"); + } + } + } listed .iter() .fold(own.code, |code, (_, listing)| code.max(listing.code)) @@ -478,7 +1009,11 @@ pub async fn run(args: ListArgs) -> i32 { /// Read the patches of the project at `args.common.cwd`: the manifest's, /// the vendor ledger's and the hosted pins its lockfiles wire. -async fn list_project(args: &ListArgs) -> Listed { +/// +/// `browsing`: the run shows its patches in the full-screen table, so the +/// listing comes back as rows for it instead of text to print (a project +/// with nothing to list still says so in text). +async fn list_project(args: &ListArgs, browsing: bool) -> Listed { let manifest_path = args.common.resolved_manifest_path(); // One load of the three stores, all from the SAME project as the @@ -507,6 +1042,8 @@ async fn list_project(args: &ListArgs) -> Listed { // to consult", surfaced on stderr unless --silent, or in the envelope's // `warnings[]` under --json. let mut warnings: Vec = Vec::new(); + // The human copies of those warnings: printed by the caller. + let mut notes: Vec = Vec::new(); let legacy_redirect = match &loaded.redirect { Ok(state) => state.as_ref(), Err(corrupt) => { @@ -516,7 +1053,7 @@ async fn list_project(args: &ListArgs) -> Listed { corrupt.to_string(), )); } else if !args.common.silent { - eprintln!("Warning: {corrupt}"); + notes.push(format!("Warning: {corrupt}")); } None } @@ -530,7 +1067,7 @@ async fn list_project(args: &ListArgs) -> Listed { if args.common.json { warnings.push(RunWarning::new("hosted_wiring_contested", detail.clone())); } else if !args.common.silent { - eprintln!("Warning: {}", crate::ui::sentence_case(detail)); + notes.push(format!("Warning: {}", crate::ui::sentence_case(detail))); } } // A hosted `resolutions` selector (#1203) or uv override pin (#1445) @@ -566,7 +1103,7 @@ async fn list_project(args: &ListArgs) -> Listed { if args.common.json { warnings.push(RunWarning::new("hosted_resolution_orphaned", detail)); } else if !args.common.silent { - eprintln!("Warning: {}", crate::ui::sentence_case(&detail)); + notes.push(format!("Warning: {}", crate::ui::sentence_case(&detail))); } } // A broken vendor ledger degrades to nothing-to-list here (every path @@ -581,7 +1118,7 @@ async fn list_project(args: &ListArgs) -> Listed { if args.common.json { warnings.push(RunWarning::new("vendor_state_unreadable", detail)); } else if !args.common.silent { - eprintln!("Warning: {detail}"); + notes.push(format!("Warning: {detail}")); } None } @@ -593,7 +1130,10 @@ async fn list_project(args: &ListArgs) -> Listed { let entries = combined_entries(manifest, &hosted, vendor_state); if manifest.is_none() && entries.is_empty() { if let Some(detail) = contested { - return failed_listing(args, "hosted_wiring_contested", detail, warnings); + let mut failed = failed_listing(args, "hosted_wiring_contested", detail, warnings); + // The warnings read before the error come before it. + failed.notes.splice(0..0, notes); + return failed; } } @@ -607,6 +1147,8 @@ async fn list_project(args: &ListArgs) -> Listed { text: None, patches: entries.len(), manifest_patches: manifest.map_or(0, |m| m.patches.len()), + rows: Vec::new(), + notes, }; if args.common.json { let mut env = build_list_envelope(&entries); @@ -614,6 +1156,14 @@ async fn list_project(args: &ListArgs) -> Listed { listed.envelope = Some(env); } else if args.common.silent { // `--silent` is "errors only" (CLI_CONTRACT.md). + } else if browsing && !entries.is_empty() { + // Someone at a terminal browses the patches in a table; a pipe, a + // log and `--verbose` get every entry in full. + let color = crate::ui::stderr_color(); + listed.rows = entries + .iter() + .map(|entry| Browse::of(entry, color)) + .collect(); } else { listed.text = Some(format_listing(&entries, crate::ui::stdout_color())); } @@ -676,6 +1226,273 @@ mod tests { } } + fn browse_row(purl: &str, severity: &str, ids: &[&str], mode: &'static str) -> Browse { + Browse { + purl: purl.to_string(), + uuid: format!("{:08x}-1111-4111-8111-111111111111", purl.len()), + severity: severity.to_string(), + ids: ids.iter().map(|id| id.to_string()).collect(), + mode, + detail: format!("Package: {purl}\n UUID: 1234"), + } + } + + fn text(cells: &[Cell]) -> Vec<&str> { + cells.iter().map(|cell| cell.text.as_str()).collect() + } + + /// The table someone at a terminal browses opens with what the project + /// records: a row per patch with its worst severity (painted), the + /// advisories it fixes and the mode it is patched in. + #[test] + fn the_browsed_table_opens_with_what_the_project_records() { + let manifest = sample_manifest(); + let entries = combined_entries(Some(&manifest), &[], None); + let row = Browse::of(&entries[0], false); + assert_eq!(row.purl, "pkg:npm/minimist@1.2.2"); + assert_eq!(row.severity, "HIGH"); + assert_eq!(row.ids, ["CVE-2024-12345"]); + assert_eq!(row.mode, "agent"); + assert!(row.detail.starts_with("Package: pkg:npm/minimist@1.2.2")); + + let rows = vec![ + (row, None), + ( + browse_row( + "pkg:npm/%40scope/a-much-longer-name@10.0.0", + "CRITICAL", + &["CVE-2026-1", "CVE-2026-2", "CVE-2026-3"], + "vendored", + ), + None, + ), + // A hosted pin records only its uuid: no severity, no ids. + (browse_row("pkg:npm/undici@6.27.0", "", &[], "hosted"), None), + ]; + let table = table_of(&rows); + assert_eq!(table.title, "3 patches in this project"); + assert_eq!( + table.columns.iter().map(|c| c.title).collect::>(), + [ + "SEVERITY", + "PACKAGE", + "FIXES", + "EXPLOITS", + "TESTS", + "CHANGE", + "PERF", + "PUBLISHED", + "MODE" + ] + ); + assert_eq!( + text(&table.rows[0]), + [ + "HIGH", + "minimist@1.2.2", + "CVE-2024-12345", + "", + "", + "", + "", + "", + "agent" + ] + ); + assert_eq!(table.rows[0][0].paint, Some("31")); + assert_eq!( + text(&table.rows[1])[..3], + [ + "CRITICAL", + "@scope/a-much-longer-name@10.0.0", + "CVE-2026-1, CVE-2026-2 (+1)" + ] + ); + assert_eq!(table.rows[1][0].paint, Some("91")); + assert_eq!(text(&table.rows[2])[..3], ["", "undici@6.27.0", ""]); + assert_eq!(table.rows[2][0].paint, None); + // The listing that stays on the terminal is those rows in columns; + // the ones nothing is known for yet take no room. + assert_eq!( + crate::ui::browser::table_lines(&table, 200, crate::ui::Style::PLAIN), + [ + " SEVERITY PACKAGE FIXES MODE", + " HIGH minimist@1.2.2 CVE-2024-12345 agent", + " CRITICAL @scope/a-much-longer-name@10.0.0 CVE-2026-1, CVE-2026-2 (+1) vendored", + " undici@6.27.0 hosted", + ] + ); + + // Rows of several project directories say whose they are, and + // packages of two ecosystems are named by purl. + let mixed = vec![ + ( + browse_row("pkg:npm/undici@6.27.0", "", &[], "hosted"), + Some(".".to_string()), + ), + ( + browse_row("pkg:pypi/requests@2.31.0", "", &[], "hosted"), + Some("services/worker".to_string()), + ), + ]; + let table = table_of(&mixed); + assert_eq!(table.columns.last().map(|c| c.title), Some("PROJECT")); + assert_eq!( + text(&table.rows[1])[1..], + [ + "pkg:pypi/requests@2.31.0", + "", + "", + "", + "", + "", + "", + "hosted", + "services/worker" + ] + ); + } + + /// The patch service's account of a patch fills its row in: what was + /// measured about it (green when every exploit is blocked and every + /// test passes, yellow when not), the size and cost of the change and + /// when it was published. It also names the advisories of a patch the + /// project records by uuid alone. + #[test] + fn a_row_fills_in_from_the_patch_service() { + use socket_patch_core::api::types::{ + PatchDiffSize, PatchPerformance, PatchResponse, PatchStatistics, VulnerabilityResponse, + }; + let detail = |statistics: Option| PatchResponse { + uuid: "11111111-1111-4111-8111-111111111111".to_string(), + purl: "pkg:npm/undici@6.27.0".to_string(), + published_at: "Fri, 14 Nov 2026 07:13:44 GMT".to_string(), + files: HashMap::new(), + vulnerabilities: HashMap::from([ + ( + "GHSA-aaaa-bbbb-cccc".to_string(), + VulnerabilityResponse { + cves: vec!["CVE-2026-84961".to_string()], + summary: "A summary".to_string(), + severity: "high".to_string(), + description: String::new(), + }, + ), + ( + "GHSA-dddd-eeee-ffff".to_string(), + VulnerabilityResponse { + cves: Vec::new(), + summary: "Another".to_string(), + severity: "critical".to_string(), + description: String::new(), + }, + ), + ]), + description: String::new(), + license: "MIT".to_string(), + tier: "free".to_string(), + statistics, + }; + let measured = PatchStatistics { + diff: Some(PatchDiffSize { + lines_added: 26, + lines_removed: 22, + files_changed: 2, + }), + performance: Some(PatchPerformance { + general_wall_change: Some(0.2), + hot_wall_change: Some(0.008), + peak_mem_change: None, + }), + ..crate::commands::measured::tests::stats(2, 34, 35) + }; + + // A hosted pin: everything comes from the patch service. + let pin = browse_row("pkg:npm/undici@6.27.0", "", &[], "hosted"); + let cells = pin.cells("undici@6.27.0", None, Some(&detail(Some(measured)))); + assert_eq!( + text(&cells), + [ + "CRITICAL", + "undici@6.27.0", + "CVE-2026-84961, GHSA-dddd-eeee-ffff", + "2/2", + "34/35", + "+26 -22", + "+0.8%", + "14 Nov 2026", + "hosted" + ] + ); + assert_eq!(cells[0].paint, Some("91")); + assert_eq!(cells[3].paint, Some("32"), "every exploit blocked"); + assert_eq!(cells[4].paint, Some("33"), "a test still failing"); + + // What the project records about a patch stays: the service only + // adds to it. A patch that was never measured shows its date. + let recorded = browse_row("pkg:npm/undici@6.27.0", "LOW", &["CVE-2020-1"], "agent"); + assert_eq!( + text(&recorded.cells("undici@6.27.0", Some("."), Some(&detail(None)))), + [ + "LOW", + "undici@6.27.0", + "CVE-2020-1", + "", + "", + "", + "", + "14 Nov 2026", + "agent", + "." + ] + ); + } + + /// With the patch service out of reach (or `--offline`) a patch opens + /// as what the project records about it, under the reason. + #[test] + fn a_patch_opens_as_the_projects_record_when_the_service_cannot_be_asked() { + let row = browse_row("pkg:npm/undici@6.27.0", "", &[], "hosted"); + let page = row.local_page(None); + assert_eq!(page.title, "pkg:npm/undici@6.27.0"); + assert_eq!( + page.lines, + ["Package: pkg:npm/undici@6.27.0", " UUID: 1234"] + ); + assert!(page.marks.is_empty()); + assert_eq!( + row.local_page(Some("timed out")).lines, + [ + "The patch could not be read: timed out.", + "", + "What this project records:", + "", + "Package: pkg:npm/undici@6.27.0", + " UUID: 1234" + ] + ); + // An error's text is one line of the page whatever its shape: a + // period of its own is not doubled, and a body that runs over + // several lines, or carries an escape sequence, cannot break the + // frame. + for (why, line) in [ + ( + "Rate limit exceeded. Please try again later.", + "The patch could not be read: Rate limit exceeded. Please try again later.", + ), + ( + "status 500:\n upstream\tfailed\r\n", + "The patch could not be read: status 500: upstream failed.", + ), + ( + "bad \u{1b}[31mbody", + "The patch could not be read: bad [31mbody.", + ), + ] { + assert_eq!(row.local_page(Some(why)).lines[0], line); + } + } + /// A manifest with several patches, each carrying multiple /// vulnerabilities and files, all inserted in deliberately /// non-alphabetical order. Used to pin the stable sort order the diff --git a/crates/socket-patch-cli/src/commands/measured.rs b/crates/socket-patch-cli/src/commands/measured.rs new file mode 100644 index 000000000..e3b3584e1 --- /dev/null +++ b/crates/socket-patch-cli/src/commands/measured.rs @@ -0,0 +1,405 @@ +//! What Socket measured about a patch, for human output: whether it +//! blocks the exploits of the advisories it fixes, whether the package's +//! own tests still pass, how large it is and what it costs at run time +//! (the patch view's `statistics`, see [`PatchStatistics`]). +//! +//! The wording is pure and unit-tested; [`fetch`] is the one request. +//! Measurements are a courtesy to someone reading the output: they are +//! asked for only when stdout is a terminal ([`wanted`]), and a patch that +//! was never measured, or whose answer fails, simply shows none. + +use std::collections::HashMap; + +use socket_patch_core::api::client::{hold_back_debug, ApiClient, ApiError, HeldBack}; +use socket_patch_core::api::types::{PatchRatio, PatchStatistics}; + +use crate::args::GlobalArgs; +use crate::ui::plural; + +/// What the patch service measured, by patch uuid. +pub(crate) type Measured = HashMap; + +/// One patch's measurement request: its uuid, and the answer with its +/// `--debug` lines held back until the caller's turn to print. +pub(crate) type Measurement = (String, HeldBack, ApiError>>); + +/// How long a listing waits for its measurements ([`fetch`]). The ones +/// still out by then are left off: a listing is not held up for a +/// courtesy. +const LISTING_WAIT: std::time::Duration = std::time::Duration::from_millis(1500); + +/// Whether this run shows measurements: a human run (neither `--json` nor +/// `--silent`) whose stdout is a terminal. A pipe, a log and a script make +/// no extra request and read the same every time. +pub(crate) fn wanted(common: &GlobalArgs) -> bool { + !common.json && !common.silent && crate::ui::attended(crate::ui::Stream::Stdout) +} + +/// Ask the patch service what it measured about each of `uuids`. +/// Answers come back as they arrive. +/// +/// The requests are a courtesy beside the run's real ones, so they stay +/// out of their way: they keep to the patch API's own window (the public +/// proxy's is small, and one request at a time where file descriptors +/// are scarce), and one that is throttled is given up, not retried. A +/// retry would open the run's one retry window, which the downloads that +/// follow may need. +/// +/// Every request takes a slot of `window` first ([`window`]): a run that +/// asks in several rounds (a scan of many project directories asks once +/// for each) keeps to one window for all of them, not one each. +pub(crate) async fn request( + client: &ApiClient, + uuids: Vec, + window: &Window, +) -> Vec { + use futures_util::StreamExt; + use socket_patch_core::api::retry::{ApiRetryPolicy, RetryHooks}; + use socket_patch_core::utils::concurrent::api_concurrency_for; + let at_once = api_concurrency_for(client.uses_public_proxy(), uuids.len().max(1)); + let client = client + .clone() + .with_api_retry(ApiRetryPolicy::none(), RetryHooks::default()); + let client = &client; + futures_util::stream::iter(uuids) + .map(|uuid| async move { + // Never closed, so the slot is always given. + let _slot = window.acquire().await; + let answer = hold_back_debug(client.fetch_patch_statistics(&uuid)).await; + (uuid, answer) + }) + .buffer_unordered(at_once) + .collect() + .await +} + +/// The measurement requests a run may have out at once, whoever asks: +/// the patch API's own window for `client`'s route. +pub(crate) type Window = std::sync::Arc; + +/// A [`Window`] for `client`'s route. +pub(crate) fn window(client: &ApiClient) -> Window { + use socket_patch_core::utils::concurrent::api_concurrency_for; + std::sync::Arc::new(tokio::sync::Semaphore::new(api_concurrency_for( + client.uses_public_proxy(), + usize::MAX, + ))) +} + +/// Fold `answers` into `measured`, printing each request's `--debug` +/// lines. A failed request, or a patch that was not measured, adds +/// nothing. +pub(crate) fn collect(measured: &mut Measured, answers: Vec) { + for (uuid, answer) in answers { + if let Ok(Some(stats)) = answer.release() { + measured.insert(uuid, stats); + } + } +} + +/// [`request`] and [`collect`] in one step, for a caller that shows the +/// measurements right away. Empty when the run does not show them, and +/// when they are not all in within [`LISTING_WAIT`]. +pub(crate) async fn fetch(common: &GlobalArgs, client: &ApiClient, uuids: Vec) -> Measured { + let mut measured = Measured::new(); + if wanted(common) && !uuids.is_empty() { + let window = window(client); + if let Ok(answers) = + tokio::time::timeout(LISTING_WAIT, request(client, uuids, &window)).await + { + collect(&mut measured, answers); + } + } + measured +} + +/// A relative change as a signed percentage with one decimal: `0.0356` is +/// `+3.6%`, `-0.0446` is `-4.5%`. A change that rounds to nothing is `0%`. +pub(crate) fn percent(change: f64) -> String { + let tenths = (change * 1000.0).round(); + if !tenths.is_finite() || tenths == 0.0 { + return "0%".to_string(); + } + format!("{:+.1}%", tenths / 10.0) +} + +/// `2 of 2 exploits blocked`. +fn exploits_blocked(blocked: PatchRatio) -> String { + format!( + "{} of {} blocked", + blocked.count, + plural(blocked.total as usize, "exploit", "exploits") + ) +} + +/// `35 of 35 tests passing`. +fn tests_passing(passing: PatchRatio) -> String { + format!( + "{} of {} passing", + passing.count, + plural(passing.total as usize, "test", "tests") + ) +} + +/// What was measured about a patch, in a few words for a table row: +/// `exploit blocked, 25/25 tests`. The exploits are the proofs of concept +/// of the advisories the patch fixes, run against the patched package; the +/// tests are the package's own, run on it. A part that was not measured is +/// left out, and an exploit count is spelled out only past one or when the +/// patch does not block them all. +pub(crate) fn evidence(stats: &PatchStatistics) -> String { + let mut parts = Vec::new(); + if let Some(pocs) = stats.pocs { + let blocked = pocs.blocked_after; + parts.push(if !blocked.is_all() { + format!("{}/{} exploits blocked", blocked.count, blocked.total) + } else if blocked.total == 1 { + "exploit blocked".to_string() + } else { + format!("{} exploits blocked", blocked.total) + }); + } + if let Some(tests) = stats.tests { + parts.push(format!("{}/{} tests", tests.after.count, tests.after.total)); + } + parts.join(", ") +} + +/// What was measured about a patch, as labelled lines for a listing (no +/// indent): what it was verified against, how large it is, and what it +/// costs at run time. A line whose part was not measured is left out. +/// +/// ```text +/// Verified: 2 of 2 exploits blocked, 35 of 35 tests passing +/// Change: +9 -2 lines in 2 files, 3 functions +/// Performance: patched code +3.6%, memory +0.1% +/// ``` +/// +/// "Patched code" is the wall time of a workload through the code the +/// patch touches; "runtime" is that of the package's general workload. +pub(crate) fn lines(stats: &PatchStatistics) -> Vec { + lines_with(stats, false) +} + +/// [`lines`], and with `before` what the same exploits and tests did on +/// the unpatched package, where that was measured: +/// `Verified: 2 of 2 exploits blocked (2 of 2 worked before the patch), +/// 35 of 35 tests passing (35 of 35 before the patch)`. +pub(crate) fn lines_with(stats: &PatchStatistics, before: bool) -> Vec { + let mut lines = Vec::new(); + let mut verified = Vec::new(); + if let Some(pocs) = stats.pocs { + let mut part = exploits_blocked(pocs.blocked_after); + if let Some(worked) = pocs.reproduced_before.filter(|_| before) { + part.push_str(&format!( + " ({} of {} worked before the patch)", + worked.count, worked.total + )); + } + verified.push(part); + } + if let Some(tests) = stats.tests { + let mut part = tests_passing(tests.after); + if let Some(passed) = tests.before.filter(|_| before) { + part.push_str(&format!( + " ({} of {} before the patch)", + passed.count, passed.total + )); + } + verified.push(part); + } + if !verified.is_empty() { + lines.push(format!("Verified: {}", verified.join(", "))); + } + let mut change = Vec::new(); + if let Some(diff) = stats.diff { + change.push(format!( + "+{} -{} lines in {}", + diff.lines_added, + diff.lines_removed, + plural(diff.files_changed as usize, "file", "files") + )); + } + if let Some(functions) = stats.functions_changed { + change.push(plural(functions as usize, "function", "functions")); + } + if !change.is_empty() { + lines.push(format!("Change: {}", change.join(", "))); + } + if let Some(perf) = stats.performance { + let cost: Vec = [ + ("runtime", perf.general_wall_change), + ("patched code", perf.hot_wall_change), + ("memory", perf.peak_mem_change), + ] + .into_iter() + .filter_map(|(what, change)| Some(format!("{what} {}", percent(change?)))) + .collect(); + if !cost.is_empty() { + lines.push(format!("Performance: {}", cost.join(", "))); + } + } + lines +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use socket_patch_core::api::types::{ + PatchDiffSize, PatchExploitRuns, PatchPerformance, PatchTestRuns, + }; + + /// Measurements: `exploits` blocked of as many run, `tests` passing of + /// `tests_total`. + pub(crate) fn stats(exploits: u64, tests: u64, tests_total: u64) -> PatchStatistics { + PatchStatistics { + pocs: Some(PatchExploitRuns { + reproduced_before: None, + blocked_after: PatchRatio { + count: exploits, + total: exploits, + }, + }), + tests: Some(PatchTestRuns { + before: None, + after: PatchRatio { + count: tests, + total: tests_total, + }, + }), + ..PatchStatistics::default() + } + } + + #[test] + fn evidence_says_what_was_measured_in_a_few_words() { + assert_eq!(evidence(&stats(1, 25, 25)), "exploit blocked, 25/25 tests"); + assert_eq!( + evidence(&stats(2, 34, 35)), + "2 exploits blocked, 34/35 tests" + ); + let partly = PatchStatistics { + pocs: Some(PatchExploitRuns { + reproduced_before: None, + blocked_after: PatchRatio { count: 1, total: 2 }, + }), + ..PatchStatistics::default() + }; + assert_eq!(evidence(&partly), "1/2 exploits blocked"); + // Measured, but neither exploits nor tests: nothing to say here. + assert_eq!(evidence(&PatchStatistics::default()), ""); + } + + #[test] + fn lines_label_each_measured_part_and_skip_the_rest() { + let full = PatchStatistics { + diff: Some(PatchDiffSize { + lines_added: 9, + lines_removed: 2, + files_changed: 2, + }), + functions_changed: Some(3), + performance: Some(PatchPerformance { + general_wall_change: None, + hot_wall_change: Some(0.03564810053424257), + peak_mem_change: Some(0.00035335689045936394), + }), + ..stats(2, 35, 35) + }; + assert_eq!( + lines(&full), + [ + "Verified: 2 of 2 exploits blocked, 35 of 35 tests passing", + "Change: +9 -2 lines in 2 files, 3 functions", + "Performance: patched code +3.6%, memory 0%", + ] + ); + let small = PatchStatistics { + diff: Some(PatchDiffSize { + lines_added: 5, + lines_removed: 0, + files_changed: 1, + }), + tests: Some(PatchTestRuns { + before: None, + after: PatchRatio { count: 1, total: 1 }, + }), + // Measured with nothing to report: no line. + performance: Some(PatchPerformance::default()), + ..PatchStatistics::default() + }; + assert_eq!( + lines(&small), + [ + "Verified: 1 of 1 test passing", + "Change: +5 -0 lines in 1 file" + ] + ); + assert!(lines(&PatchStatistics::default()).is_empty()); + // With the unpatched package's runs, where they were measured. + let mut both = stats(2, 35, 35); + both.pocs.as_mut().unwrap().reproduced_before = Some(PatchRatio { count: 2, total: 2 }); + both.tests.as_mut().unwrap().before = Some(PatchRatio { + count: 34, + total: 35, + }); + assert_eq!( + lines_with(&both, true), + [ + "Verified: 2 of 2 exploits blocked (2 of 2 worked before the patch), 35 of 35 \ + tests passing (34 of 35 before the patch)" + ] + ); + assert_eq!(lines_with(&both, false), lines(&stats(2, 35, 35))); + assert_eq!( + lines_with(&stats(2, 35, 35), true), + lines(&stats(2, 35, 35)) + ); + } + + #[test] + fn percent_is_signed_with_one_decimal() { + assert_eq!(percent(0.03564810053424257), "+3.6%"); + assert_eq!(percent(-0.044605818765549615), "-4.5%"); + assert_eq!(percent(0.001246555570135153), "+0.1%"); + assert_eq!(percent(0.0002), "0%"); + assert_eq!(percent(-0.0002), "0%"); + assert_eq!(percent(1.5), "+150.0%"); + assert_eq!(percent(f64::NAN), "0%"); + } + + /// The wire shape of the view endpoint's `statistics`, as the service + /// sends it: every part optional, unknown keys ignored. + #[test] + fn statistics_parse_from_the_view_endpoints_shape() { + let stats: PatchStatistics = serde_json::from_str( + r#"{ + "diff": {"linesAdded": 64, "linesRemoved": 34, "filesChanged": 2}, + "functionsChanged": 4, + "tests": {"before": {"count": 106, "total": 106}, + "after": {"count": 106, "total": 106}}, + "pocs": {"reproducedBefore": {"count": 1, "total": 1}, + "blockedAfter": {"count": 1, "total": 1}}, + "performance": {"generalWallChange": null, + "hotWallChange": -0.044605818765549615, + "peakMemChange": 0.001246555570135153}, + "somethingNew": {"a": 1} + }"#, + ) + .expect("the service's statistics parse"); + assert_eq!( + lines(&stats), + [ + "Verified: 1 of 1 exploit blocked, 106 of 106 tests passing", + "Change: +64 -34 lines in 2 files, 4 functions", + "Performance: patched code -4.5%, memory +0.1%", + ] + ); + let sparse: PatchStatistics = serde_json::from_str( + r#"{"diff": null, "functionsChanged": null, "tests": null, "pocs": null, + "performance": null}"#, + ) + .expect("an unmeasured patch parses"); + assert_eq!(sparse, PatchStatistics::default()); + } +} diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index ada46feb8..438e22b38 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -9,12 +9,14 @@ pub mod hosted_bundle; pub(crate) mod hosted_unwind; pub mod list; pub(crate) mod lock_cli; +pub(crate) mod measured; pub(crate) mod projects_below; pub(crate) mod pypi_reinstall; pub mod remove; pub mod repair; pub mod rollback; pub mod scan; +pub mod show; pub mod update; pub(crate) mod user_patches; pub mod vendor; diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 25fb544e7..52349014a 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -370,9 +370,16 @@ fn patched_in_other_scope_warning(purl: &str, path: &Path, common: &GlobalArgs) } /// The wet run's per-package blocks: what was rolled back (naming each -/// physical copy when a package has several) and what failed. -fn format_rollback_results(results: &[RollbackResult], cwd: &Path) -> Vec { - let rolled_back: Vec = results +/// physical copy when a package has several) and what failed. The rolled +/// back packages are counted in their heading and listed by purl; `style` +/// opens each of their lines with a check mark where the terminal shows +/// one. +fn format_rollback_results( + results: &[RollbackResult], + cwd: &Path, + style: crate::ui::Style, +) -> Vec { + let mut rolled_back: Vec = results .iter() .filter(|r| r.success && !r.files_rolled_back.is_empty()) .map(|r| copy_label(results, r, None, cwd)) @@ -383,16 +390,45 @@ fn format_rollback_results(results: &[RollbackResult], cwd: &Path) -> Vec = results + .iter() + .filter(|r| { + r.success && (!r.files_rolled_back.is_empty() || all_files_already_original(r)) + }) + .map(|r| r.package_key.as_str()) + .collect(); lines.push(String::new()); - lines.push("Rolled back packages:".to_string()); - lines.extend(rolled_back); + lines.push(format!( + "Rolled back {}:", + plural(packages.len(), "package", "packages") + )); + // A label opens with two spaces: the mark takes the first. + lines.extend( + rolled_back + .iter() + .map(|label| format!("{}{}", style.check(), &label[1..])), + ); } lines.extend(format_rollback_failures(results, cwd)); lines } +/// Whether the wet run's `Rolled back N packages:` block +/// ([`format_rollback_results`]) already names every purl of `removed`: +/// the manifest removal is then one line, not the same list again. +fn removal_already_listed(results: &[RollbackResult], removed: &[String]) -> bool { + removed.iter().all(|purl| { + results.iter().any(|r| { + r.success + && r.package_key == *purl + && (!r.files_rolled_back.is_empty() || all_files_already_original(r)) + }) + }) +} + /// `--preserve-state`'s closing line (names vendored artifacts only when /// some were preserved). Shared with `remove --preserve-state`. pub(crate) fn format_preserved_note(entries: usize, vendored: usize) -> String { @@ -2793,7 +2829,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let lines = if args.common.dry_run { format_rollback_dry_run_counts(&results, &cwd_abs) } else { - format_rollback_results(&results, &cwd_abs) + format_rollback_results(&results, &cwd_abs, crate::ui::Style::stdout()) }; for line in lines { println!("{line}"); @@ -2871,6 +2907,12 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { println!(" - {purl}"); } } + } else if !removed.is_empty() && removal_already_listed(&results, &removed) { + // The block above just named each of them. + println!( + "\nRemoved {} from manifest.", + plural(removed.len(), "patch", "patches") + ); } else if !removed.is_empty() { println!( "\nRemoved {} from manifest:", @@ -2886,7 +2928,12 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { ); } if gc_bytes_freed > 0 { - println!("\n{}", format_gc_freed(gc_bytes_freed, args.common.dry_run)); + // Under the removal it follows from; on its own + // otherwise. + if removed.is_empty() { + println!(); + } + println!("{}", format_gc_freed(gc_bytes_freed, args.common.dry_run)); } // Only packages that are NOT also handled in place keep // patched bytes. A successful in-place result that verified @@ -3566,7 +3613,7 @@ pub(crate) async fn rollback_patches_inner( // Transient progress on stderr; the result line replaces it. let mut status = StatusLine::stderr(common.json, common.silent); status.set(format!( - "Downloading {}...", + "Downloading {}", plural(missing_blobs.len(), "missing blob", "missing blobs") )); @@ -3661,7 +3708,19 @@ pub(crate) async fn rollback_patches_inner( let mut warnings: Vec<(String, String)> = Vec::new(); let mut superseded_left: Vec = Vec::new(); - for target in &rollback_targets { + // The restores show as counted progress: a large tree of copies takes + // a while. Nothing prints while the line is up: a failure prints here + // only under `--silent`, where there is no line, and the line comes + // down before a gem's native extension is rebuilt, which reports its + // own progress. + let mut restoring = StatusLine::stderr(common.json, common.silent); + let verb = if common.dry_run { + "Checking packages" + } else { + "Rolling back packages" + }; + for (done, target) in rollback_targets.iter().enumerate() { + restoring.progress(verb, done, rollback_targets.len()); let (purl, pkg_path) = (&target.purl, &target.dir); let patch = match filtered_manifest.patches.get(purl) { Some(p) => p, @@ -3714,6 +3773,7 @@ pub(crate) async fn rollback_patches_inner( offline: common.offline, progress: common.gem_build_progress(), }; + restoring.finish(); if let Err(e) = gem_ext::restore_original_build(pkg_path, &env).await { result.success = false; result.error = Some(format!("{}: {e}", gem_ext::RESTORE_FAILED_CODE)); @@ -3773,6 +3833,7 @@ pub(crate) async fn rollback_patches_inner( } results.push(result); } + restoring.finish(); // Redirects the crawler never saw (see `undiscovered_redirects` above): // roll the redirect back from the manifest alone. `package_path` is the @@ -6580,16 +6641,40 @@ mod tests { false, ), ]; + let plain = crate::ui::Style::PLAIN; assert_eq!( - format_rollback_results(&results, Path::new("/p")), + format_rollback_results(&results, Path::new("/p"), plain), vec![ "", - "Rolled back packages:", + "Rolled back 2 packages:", " pkg:npm/nuxt@4.5.0 (node_modules/nuxt)", " pkg:npm/nuxt@4.5.0 (node_modules/vite/node_modules/nuxt)", " pkg:npm/ok@1 (already original)", ] ); + // Where the terminal shows glyphs, a check mark takes the first + // column of each package's line. + let fancy = crate::ui::Style { + color: true, + glyphs: true, + }; + let marked: Vec = format_rollback_results(&results, Path::new("/p"), fancy) + .iter() + .map(|line| crate::ui::strip_ansi(line)) + .collect(); + assert_eq!(marked[2], "✔ pkg:npm/nuxt@4.5.0 (node_modules/nuxt)"); + assert_eq!(marked[4], "✔ pkg:npm/ok@1 (already original)"); + // The manifest removal names its purls only when the block above + // did not. + let removed = |purls: &[&str]| purls.iter().map(|p| p.to_string()).collect::>(); + assert!(removal_already_listed( + &results, + &removed(&["pkg:npm/nuxt@4.5.0", "pkg:npm/ok@1"]) + )); + assert!(!removal_already_listed( + &results, + &removed(&["pkg:npm/nuxt@4.5.0", "pkg:npm/gone@1"]) + )); let mut failed = rb( "pkg:npm/x@1", "/p/x", @@ -6599,10 +6684,10 @@ mod tests { failed.success = false; failed.error = Some("modified".into()); assert_eq!( - format_rollback_results(&[failed], Path::new("/p")), + format_rollback_results(&[failed], Path::new("/p"), plain), vec!["", "Failed to roll back:", " pkg:npm/x@1: modified"] ); - assert!(format_rollback_results(&[], Path::new("/p")).is_empty()); + assert!(format_rollback_results(&[], Path::new("/p"), plain).is_empty()); } #[test] diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 6e834f367..5247005fe 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -1,6 +1,7 @@ //! Discovery-side helpers for `scan`: lockfile / vendored-ledger crawl //! supplements, update detection against the existing manifest, vendor -//! baseline pre-verification, and the table's vuln-ID helper. +//! baseline pre-verification, and what each selected patch fixes and +//! leaves unpatched. use futures_util::StreamExt; use socket_patch_core::api::client::hold_back_debug; @@ -136,8 +137,8 @@ fn lockfile_only_packages<'a>( /// the comparison bridges the two by [`PurlKey`] (encoding, qualifiers, /// PyPI/NuGet name folding, composer release identity: the API may serve /// the padded `@3.0.2.0` for a lock's `3.0.2`). The ONE predicate behind the -/// `notInstalled` flag, the `[NOT INSTALLED]` marker, the -/// `package_not_installed` skip partition and the vendor baseline pre-check. +/// `notInstalled` flag, the `package_not_installed` skip partition and the +/// vendor baseline pre-check. pub(super) fn lockfile_only_contains(purls: &HashSet, api_purl: &str) -> bool { purls.contains(&PurlKey::new(api_purl)) } @@ -180,7 +181,7 @@ pub(crate) struct LedgerSupplement { /// Vendored-ledger packages with no crawled counterpart: on a fresh clone /// the committed artifact IS the dependency, so these stay discoverable -/// (updates[] detection, the table, and `scan --mode vendored` re-vendor/in-sync +/// (updates[] detection, the report, and `scan --mode vendored` re-vendor/in-sync /// runs all keep working before any install). They are NOT "lockfile-only" /// — nothing needs installing; the artifact satisfies the lock. `state` is /// the ledger `run` already loaded (`vendor::load_state`). @@ -450,7 +451,7 @@ pub(super) fn detect_updates( let mut updates = Vec::new(); for pkg in packages { // The candidate is the top-ranked patch — the one the apply path - // resolves to, so `[UPDATE]` and `updates[]` track what scan + // resolves to, so the newer-patches line and `updates[]` track what scan // installs. One divergence: the batch response omits `publishedAt`, // so on a merge-status + severity tie this falls to the tier/uuid // tiebreaks where apply (by-package shape) uses the date. @@ -512,62 +513,6 @@ pub(super) fn detect_updates( updates } -/// The scan table's VULNERABILITIES data for one package, built from the -/// batch results (see [`collect_vuln_ids`]). -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub(super) struct VulnIds { - /// Ids to show first: every CVE, then the GHSAs that only ever appear - /// on patches listing no CVE (those cannot be aliases). Each group is - /// sorted. - pub primary: Vec, - /// Every CVE and GHSA id (CVEs first, each group sorted), for `--verbose`. - pub all: Vec, - /// How many distinct vulnerabilities the ids stand for, for `(+N)`. - pub count: usize, -} - -/// A package's vulnerability ids across all its patches, sorted and -/// deduped so the rendered table is stable. -/// -/// A GHSA id is usually an alias of a CVE listed beside it, but the batch -/// endpoint gives the two lists without their pairing, so listing both made -/// `(+N)` count most vulnerabilities twice. Each vulnerability has at least -/// one of the two ids, so the count is the larger of the distinct CVEs and -/// the distinct GHSAs. That is exact when every GHSA has at most one CVE, -/// and never counts an alias twice. -pub(super) fn collect_vuln_ids(pkg: &BatchPackagePatches) -> VulnIds { - let mut cves: HashSet<&str> = HashSet::new(); - let mut ghsas: HashSet<&str> = HashSet::new(); - let mut ghsa_only: HashSet<&str> = HashSet::new(); - let mut ghsa_beside_cve: HashSet<&str> = HashSet::new(); - for patch in &pkg.patches { - cves.extend(patch.cve_ids.iter().map(String::as_str)); - ghsas.extend(patch.ghsa_ids.iter().map(String::as_str)); - let bucket = if patch.cve_ids.is_empty() { - &mut ghsa_only - } else { - &mut ghsa_beside_cve - }; - bucket.extend(patch.ghsa_ids.iter().map(String::as_str)); - } - // A GHSA listed beside a CVE on any patch may be its alias. - ghsa_only.retain(|g| !ghsa_beside_cve.contains(g)); - let sorted = |set: &HashSet<&str>| { - let mut v: Vec = set.iter().map(|s| (*s).to_string()).collect(); - v.sort(); - v - }; - let cves = sorted(&cves); - let ghsas = sorted(&ghsas); - let primary: Vec = cves.iter().cloned().chain(sorted(&ghsa_only)).collect(); - let count = cves.len().max(ghsas.len()).max(primary.len()); - VulnIds { - primary, - all: cves.into_iter().chain(ghsas).collect(), - count, - } -} - /// What the patch a run selected for one package fixes, and which of the /// advisories the package's patches name it leaves unfixed (see /// [`advisory_coverage`]). @@ -674,7 +619,9 @@ pub(crate) fn advisory_coverage( .collect() } -fn package_coverage( +/// [`advisory_coverage`] for one package. With no patch selected for it +/// nothing is fixed, and every advisory its patches name is unfixed. +pub(super) fn package_coverage( pkg: &BatchPackagePatches, selected: &[&PatchSearchResult], ) -> AdvisoryCoverage { @@ -1776,24 +1723,6 @@ mod tests { ); } - /// Build a single-patch package whose patch carries the given CVE and - /// GHSA identifier lists. - fn batch_with_vulns(purl: &str, cves: &[&str], ghsas: &[&str]) -> BatchPackagePatches { - BatchPackagePatches { - purl: purl.to_string(), - patches: vec![BatchPatchInfo { - uuid: "uuid".to_string(), - purl: purl.to_string(), - tier: "free".to_string(), - cve_ids: cves.iter().map(|s| (*s).to_string()).collect(), - ghsa_ids: ghsas.iter().map(|s| (*s).to_string()).collect(), - severity: None, - title: String::new(), - published_at: None, - }], - } - } - fn strs(v: &[&str]) -> Vec { v.iter().map(|s| (*s).to_string()).collect() } @@ -1939,127 +1868,6 @@ mod tests { assert_eq!(c.unpatched, strs(&["CVE-2", "CVE-3"])); } - #[test] - fn collect_vuln_ids_empty_when_no_vulns() { - let pkg = batch_with_vulns("pkg:npm/foo@1.0", &[], &[]); - assert_eq!(collect_vuln_ids(&pkg), VulnIds::default()); - } - - #[test] - fn collect_vuln_ids_lists_cves_before_ghsas_each_sorted() { - // Deliberately unsorted input; output must be CVEs (sorted) then - // GHSAs (sorted) so the rendered table column is deterministic. - let pkg = batch_with_vulns( - "pkg:npm/foo@1.0", - &["CVE-2024-2", "CVE-2024-1"], - &[ - "GHSA-zzzz-zzzz-zzzz", - "GHSA-aaaa-aaaa-aaaa", - "GHSA-mmmm-mmmm-mmmm", - ], - ); - let ids = collect_vuln_ids(&pkg); - assert_eq!( - ids.all, - strs(&[ - "CVE-2024-1", - "CVE-2024-2", - "GHSA-aaaa-aaaa-aaaa", - "GHSA-mmmm-mmmm-mmmm", - "GHSA-zzzz-zzzz-zzzz", - ]), - ); - // The GHSAs sit beside CVEs, so none is shown first; there are at - // least three vulnerabilities (one GHSA has no CVE of its own). - assert_eq!(ids.primary, strs(&["CVE-2024-1", "CVE-2024-2"])); - assert_eq!(ids.count, 3); - } - - #[test] - fn collect_vuln_ids_drops_ghsa_aliases_of_listed_cves() { - // minimist: one CVE and its GHSA alias are one vulnerability. - let pkg = batch_with_vulns( - "pkg:npm/minimist@1.2.5", - &["CVE-2021-44906"], - &["GHSA-xvch-5gv4-984h"], - ); - let ids = collect_vuln_ids(&pkg); - assert_eq!(ids.primary, strs(&["CVE-2021-44906"])); - assert_eq!(ids.all, strs(&["CVE-2021-44906", "GHSA-xvch-5gv4-984h"])); - assert_eq!(ids.count, 1); - // A GHSA-only advisory has no CVE to alias: it stays. - let pkg = batch_with_vulns("pkg:npm/x@1", &[], &["GHSA-r4q5-vmmm-2653"]); - let ids = collect_vuln_ids(&pkg); - assert_eq!(ids.primary, strs(&["GHSA-r4q5-vmmm-2653"])); - assert_eq!(ids.count, 1); - } - - #[test] - fn collect_vuln_ids_one_cve_plus_alias_plus_ghsa_only() { - // CVE-1 (alias GHSA-a) and a GHSA-only GHSA-b on one patch: two - // vulnerabilities, not three. - let pkg = batch_with_vulns("pkg:npm/foo@1.0", &["CVE-1"], &["GHSA-a", "GHSA-b"]); - let ids = collect_vuln_ids(&pkg); - assert_eq!(ids.count, 2); - assert_eq!(ids.primary, strs(&["CVE-1"])); - } - - #[test] - fn collect_vuln_ids_two_cves_one_ghsa_alias_plus_ghsa_only() { - // GHSA-a aliases both CVEs, GHSA-b has none. The batch data cannot - // tell this from two CVE/GHSA pairs, so the count is the lower - // bound (2) and every id is still listed under --verbose. - let pkg = batch_with_vulns( - "pkg:npm/foo@1.0", - &["CVE-1", "CVE-2"], - &["GHSA-a", "GHSA-b"], - ); - let ids = collect_vuln_ids(&pkg); - assert_eq!(ids.count, 2); - assert_eq!(ids.all, strs(&["CVE-1", "CVE-2", "GHSA-a", "GHSA-b"])); - // On its own patch, the GHSA-only advisory is known and shown. - let pkg = BatchPackagePatches { - purl: "pkg:npm/foo@1.0".to_string(), - patches: vec![ - patch_with("u1", &["CVE-1", "CVE-2"], &["GHSA-a"]), - patch_with("u2", &[], &["GHSA-b"]), - ], - }; - let ids = collect_vuln_ids(&pkg); - assert_eq!(ids.primary, strs(&["CVE-1", "CVE-2", "GHSA-b"])); - assert_eq!(ids.count, 3); - } - - #[test] - fn collect_vuln_ids_ghsa_beside_a_cve_elsewhere_is_not_ghsa_only() { - let pkg = BatchPackagePatches { - purl: "pkg:npm/foo@1.0".to_string(), - patches: vec![ - patch_with("u1", &["CVE-1"], &["GHSA-a"]), - patch_with("u2", &[], &["GHSA-a"]), - ], - }; - let ids = collect_vuln_ids(&pkg); - assert_eq!(ids.primary, strs(&["CVE-1"])); - assert_eq!(ids.count, 1); - } - - #[test] - fn collect_vuln_ids_dedups_across_patches() { - // u2's GHSA is the alias of its one CVE, so it is not counted. - let pkg = BatchPackagePatches { - purl: "pkg:npm/foo@1.0".to_string(), - patches: vec![ - patch_with("u1", &["CVE-2024-1"], &[]), - patch_with("u2", &["CVE-2024-1"], &["GHSA-aaaa-aaaa-aaaa"]), - ], - }; - let ids = collect_vuln_ids(&pkg); - assert_eq!(ids.primary, strs(&["CVE-2024-1"])); - assert_eq!(ids.all, strs(&["CVE-2024-1", "GHSA-aaaa-aaaa-aaaa"])); - assert_eq!(ids.count, 1); - } - #[test] fn detect_updates_flags_merged_patch_superseding_applied_single() { // End-to-end through detect_updates: the manifest holds the diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index b45add765..681e18a42 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -945,7 +945,8 @@ pub(super) async fn run_redirect( rows, prior, references, - coverage: Vec::new(), + plan: Vec::new(), + report: None, }), "scan", ) @@ -1129,7 +1130,7 @@ async fn run_redirect_selected_untracked( Ok(std::collections::HashMap::new()) } else { status.set(format!( - "Resolving hosted artifacts for {}...", + "Resolving hosted artifacts for {}", crate::ui::plural(to_fetch.len(), "patch", "patches") )); let fetched = api_client.fetch_registry_references(&to_fetch).await; @@ -1263,8 +1264,12 @@ async fn run_redirect_selected_untracked( let mut user_patch_warnings: Vec = Vec::new(); if !common.allow_patch_conflicts { - user_patch_warnings = - engine::withhold_user_patched_by_supplement(view, &mut candidates, &mut skipped).await; + user_patch_warnings = crate::ui::busy( + common, + "Checking project patches", + engine::withhold_user_patched_by_supplement(view, &mut candidates, &mut skipped), + ) + .await; } // A NEW row the lockfiles already pin on the patch server these @@ -1350,8 +1355,12 @@ async fn run_redirect_selected_untracked( .await; user_patch_warnings.extend(late); } - if let Err(error) = - crate::commands::user_patches::check(common, candidates.iter().map(&sel_purl)).await + if let Err(error) = crate::ui::busy( + common, + "Checking project patches", + crate::commands::user_patches::check(common, candidates.iter().map(&sel_purl)), + ) + .await { // The shared refusal path keeps this run's envelope and lets // telemetry go out before the JSON error. @@ -1421,7 +1430,12 @@ async fn run_redirect_selected_untracked( // dep), but for the files of a `.mvn/maven.config` to heal, read again // now that the lock is held; everything after the rewrite still runs. let read = if !candidates.is_empty() { - engine::read_candidate_files(&view, &std::collections::BTreeSet::new(), &candidates).await + crate::ui::busy( + common, + "Reading lockfiles", + engine::read_candidate_files(&view, &std::collections::BTreeSet::new(), &candidates), + ) + .await } else if heal_pending && may_heal { engine::read_maven_heal_files(&view) .await @@ -1479,10 +1493,7 @@ async fn run_redirect_selected_untracked( // retry, in dep order (the deps after them were never started). let mut drained: Option> = None; for &(dep, sha256) in &wheel_deps { - status.set(format!( - "Fetching hosted wheel metadata for {}...", - dep.name - )); + status.set(format!("Fetching hosted wheel metadata for {}", dep.name)); let attempt = match drained.as_mut() { Some(drained) => drained.pop_front(), None => match in_flight.next().await { @@ -1521,10 +1532,7 @@ async fn run_redirect_selected_untracked( // be fetched or read drops its patch rather than pin an entry yarn // would rewrite on the next install. for dep in engine::yarn_berry_manifest_targets(&candidates, &read.files) { - status.set(format!( - "Fetching hosted package manifest for {}...", - dep.name - )); + status.set(format!("Fetching hosted package manifest for {}", dep.name)); match socket_patch_core::hosted::npm_manifest::fetch_hosted_npm_manifest( api_client, &dep.artifact_url, @@ -1567,7 +1575,7 @@ async fn run_redirect_selected_untracked( }) .collect(); for (url, sha512, dep) in classic_targets { - status.set(format!("Fetching hosted tarball for {}...", dep.name)); + status.set(format!("Fetching hosted tarball for {}", dep.name)); match socket_patch_core::hosted::npm_manifest::fetch_hosted_classic_artifact( api_client, &url, &sha512, ) @@ -1698,8 +1706,18 @@ async fn run_redirect_selected_untracked( .then(|| (read.clone(), python_metadata.clone())); // A retracted takeover rewrites again without it (see below). let takeover_metadata = takeover.is_staged().then(|| python_metadata.clone()); - let mut done = - engine::rewrite(&view, read, &candidates, python_metadata, rewrite_options()).await; + // The rewrite is planned in memory either way; a dry run stops there. + let rewriting = if common.dry_run { + "Planning lockfile changes" + } else { + "Rewriting lockfiles" + }; + let mut done = crate::ui::busy( + common, + rewriting, + engine::rewrite(&view, read, &candidates, python_metadata, rewrite_options()), + ) + .await; // The rollout gate (§5.2): every write-free check has run — grants, // purl/url, takeover refusals, wheel metadata, and the rewrite above, @@ -1723,8 +1741,12 @@ async fn run_redirect_selected_untracked( let before = candidates.len(); candidates.retain(|c| !deferred.contains(&(sel_purl(c), c.dep.patch_uuid.clone()))); if candidates.len() != before { - done = - engine::rewrite(&view, read, &candidates, python_metadata, rewrite_options()).await; + done = crate::ui::busy( + common, + rewriting, + engine::rewrite(&view, read, &candidates, python_metadata, rewrite_options()), + ) + .await; } } // A staged takeover the rewrite did not pin must not happen: undo every @@ -1846,8 +1868,12 @@ async fn run_redirect_selected_untracked( if common.dry_run { // A preview: the staged reverts never reach the disk. drop(group); - } else if let Err(message) = - commit_hosted_writes(common, group, rewrite, &vendor_state, &takeover_migrated).await + } else if let Err(message) = crate::ui::busy( + common, + "Writing lockfiles", + commit_hosted_writes(common, group, rewrite, &vendor_state, &takeover_migrated), + ) + .await { eprintln!("{}", format_error_line(&message)); if common.json { @@ -2258,10 +2284,11 @@ async fn run_redirect_selected_untracked( emit_scan(&env); } else { if !common.silent { - // Wrap long warnings only on a terminal: logs and pipes keep one - // line per sentence so CI can grep them. + // Wrap long warnings only on a terminal with a person at it: + // logs, pipes and agents keep one line per sentence, so CI can + // grep them and an agent reads whole sentences. let width = - std::io::IsTerminal::is_terminal(&std::io::stderr()).then(crate::ui::stderr_width); + crate::ui::attended(crate::ui::Stream::Stderr).then(crate::ui::stderr_width); for purl in &takeover_migrated { eprintln!("{}", format_takeover_line(purl, common.dry_run)); } @@ -2302,18 +2329,14 @@ async fn run_redirect_selected_untracked( "{}", format_hosted_summary(confirmed.len(), already, human_files.len(), common.dry_run) ); - // Under it, per package on a hosted patch: the advisories that - // patch fixes and the ones it leaves unpatched. - if let Some(gate) = &rollout { + // Under it, one row per package on a hosted patch: what the + // patch fixes and how much it leaves unpatched. The same call + // counts the directory into the invocation's closing totals. + if let Some(gate) = rollout.as_mut() { let pinned: std::collections::HashSet<&str> = confirmed.iter().map(|(_, uuid)| uuid.as_str()).collect(); - for line in super::coverage_lines_for( - &gate.coverage, - &pinned, - common.dry_run, - common.verbose, - ) { - println!("{line}"); + if let Some(report) = gate.report.as_deref_mut() { + report.project(&gate.plan, &pinned).await; } } // Then what the run did to the user's Bundler manifest. @@ -2365,7 +2388,15 @@ async fn run_redirect_selected_untracked( ) { eprintln!("{line}"); } + // A warning repeated for package after package (a lock that + // names none of a shared environment's copies) is shown for the + // first few; `--verbose` and `--json` have them all. + let human_warnings = fold_repeated_warnings(human_warnings, common.verbose); for (code, detail) in &human_warnings { + if *code == REPEATED_WARNINGS { + eprintln!("{detail}"); + continue; + } let detail = if *code == "redirect_npm_allow_remote" && !common.verbose { // One line by default; the full policy text (the // tradeoff, every manual recovery) is in `--json` and @@ -2375,7 +2406,7 @@ async fn run_redirect_selected_untracked( } else if *code == "redirect_pnpm_trust_lockfile" && done.pnpm_rerun_only { pnpm_trust_rerun_reminder() } else { - detail + detail.as_ref() }; eprintln!("{}", format_warning(code, detail, width)); } @@ -3038,6 +3069,15 @@ fn format_unredirected( describe_skip_reason(reason) )); } + // Each of these has a warning of its own below that says why, so a + // long list is named once instead of line by line. + if unconfirmed.len() > UNPINNED_NAMED { + lines.push(format!( + "{unpinned_lead}{}: no lockfile entry pinning them could be rewritten{see}", + join_names(unconfirmed, UNPINNED_NAMED), + )); + return lines; + } for purl in unconfirmed { lines.push(format!( "{unpinned_lead}{purl}: no lockfile entry pinning it could be rewritten{see}" @@ -3046,6 +3086,53 @@ fn format_unredirected( lines } +/// How many unpinned packages [`format_unredirected`] names one per line; +/// past it they share a line that names this many. +const UNPINNED_NAMED: usize = 3; + +/// How many warnings of one code the human output prints before it counts +/// the rest ([`fold_repeated_warnings`]). +const REPEATED_SHOWN: usize = 3; + +/// The pseudo-code of the line [`fold_repeated_warnings`] puts in place of +/// the warnings it leaves out. Never a real warning code: the line prints +/// as it is. +const REPEATED_WARNINGS: &str = ""; + +/// `warnings` (`(code, detail)`, in order) with each code's entries past +/// the first [`REPEATED_SHOWN`] replaced by one line that counts them, +/// placed after the last one shown. `verbose` keeps every warning. +fn fold_repeated_warnings<'a>( + warnings: Vec<(&'a str, &'a str)>, + verbose: bool, +) -> Vec<(&'a str, std::borrow::Cow<'a, str>)> { + use std::borrow::Cow; + let mut seen: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for (code, _) in &warnings { + *seen.entry(code).or_default() += 1; + } + let mut shown: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + let mut out = Vec::new(); + for (code, detail) in warnings { + let total = seen[code]; + let nth = shown.entry(code).or_default(); + *nth += 1; + if verbose || total <= REPEATED_SHOWN + 1 || *nth <= REPEATED_SHOWN { + out.push((code, Cow::Borrowed(detail))); + } + if !verbose && total > REPEATED_SHOWN + 1 && *nth == REPEATED_SHOWN { + out.push(( + REPEATED_WARNINGS, + Cow::Owned(format!( + " ... and {} more like these (--verbose lists them all)", + total - REPEATED_SHOWN + )), + )); + } + } + out +} + /// The human line for a successful (or, on `--dry-run`, planned) /// vendored→hosted migration. fn format_takeover_line(purl: &str, dry_run: bool) -> String { @@ -3147,10 +3234,7 @@ fn format_next_steps( ), _ => crate::ui::next_steps( &commit, - &format!( - "Reinstall from the updated lockfile{hint} so the installed packages pick up the \ - patched artifacts" - ), + &format!("Reinstall from the updated lockfile{hint}"), &extra, ), } @@ -5537,9 +5621,8 @@ mod tests { vec![ "Next steps:".to_string(), " 1. Commit package-lock.json to keep the hosted patches.".to_string(), - " 2. Reinstall from the updated lockfile (e.g. `npm ci`) so the installed \ - packages pick up the patched artifacts, then run `socket-patch vex` to verify \ - the installed patches." + " 2. Reinstall from the updated lockfile (e.g. `npm ci`), then run \ + `socket-patch vex` to verify the installed patches." .to_string(), ] ); diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 9af689aca..0737dbc24 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -12,7 +12,6 @@ use socket_patch_core::api::client::{ build_proxy_fallback_client, get_api_client_with_overrides, hold_back_debug, is_fallback_candidate, ApiClient, ApiError, }; -use socket_patch_core::api::ranking::severity_order; use socket_patch_core::api::types::{BatchPackagePatches, BatchSearchResponse, PatchSearchResult}; use socket_patch_core::crawlers::ruby_crawler::{ config_path_ignored_warning, stale_plugin_registration_warning, @@ -28,13 +27,13 @@ use socket_patch_core::vendor::lock_inventory::unsupported_layout_warnings; use socket_patch_core::vendor::{purl_keys_cover, VendorState}; use socket_patch_core::vex::discover::{LedgerLiveness, WiringMode}; use std::collections::{HashMap, HashSet}; -use std::io::IsTerminal; use std::path::{Path, PathBuf}; use crate::args::{apply_env_toggles, GlobalArgs}; use crate::commands::vex::{generate_vex_from_manifest_path, VexEmbedArgs}; use crate::ecosystem_dispatch::{ - crawl_ecosystems, crawl_ecosystems_with_npm, find_package_paths_for_path_scope, partition_purls, + crawl_ecosystems_with_npm, crawl_ecosystems_with_npm_roots, find_package_paths_for_path_scope, + partition_purls, }; use crate::json_envelope::{ usage_error, Command as JsonCommand, Envelope, EnvelopeError, PatchAction, PatchEvent, @@ -55,6 +54,7 @@ mod gc; pub(crate) mod hosted; pub(crate) mod policy; pub(crate) mod render; +pub(crate) mod report; pub(crate) mod rollout; pub mod rollout_args; mod socket_yml_args; @@ -62,9 +62,8 @@ pub(crate) mod vendor_flow; mod withdrawn; use self::discovery::{ - advisory_coverage, collect_vuln_ids, detect_updates, lockfile_only_contains, - lockfile_supplement, preverify_vendor_baselines, vendored_ledger_supplement, AdvisoryCoverage, - LockfileSupplement, + advisory_coverage, detect_updates, lockfile_only_contains, lockfile_supplement, + preverify_vendor_baselines, vendored_ledger_supplement, AdvisoryCoverage, LockfileSupplement, }; // Shared with `get --mode hosted|vendored` (commands::get): the lockfile // and vendored-ledger crawl supplements. `pub(crate)` re-exports because @@ -132,8 +131,8 @@ fn is_pypi_purl(purl: &str) -> bool { /// Mark each API purl that names a lockfile-only PyPI pin under another /// PEP 440 spelling (`@1.16.0` for a lock's `@1.16`, #604) as lockfile-only -/// too, so the `notInstalled` flag, the `[NOT INSTALLED]` marker and the -/// vendored baseline pre-check treat it as the package it is. A spelling an +/// too, so the `notInstalled` flag, the agent-mode not-installed skip and +/// the vendored baseline pre-check treat it as the package it is. A spelling an /// installed copy already carries is left alone. fn adopt_pypi_equivalents( packages: &[BatchPackagePatches], @@ -772,34 +771,6 @@ fn select_accessible( policy.select(accessible) } -/// The advisory lines ([`render::coverage_lines`]) of the packages whose -/// selected patch is one of `landed`: only a patch the run applied (or, on -/// a dry run, would apply) is said to fix anything. -pub(super) fn coverage_lines_for( - coverage: &[AdvisoryCoverage], - landed: &HashSet<&str>, - dry_run: bool, - verbose: bool, -) -> Vec { - let patched: Vec<&AdvisoryCoverage> = coverage - .iter() - .filter(|c| c.uuids.iter().any(|uuid| landed.contains(uuid.as_str()))) - .collect(); - render::coverage_lines(&patched, dry_run, verbose, ui::stdout_color()) -} - -/// Print [`coverage_lines_for`] on stdout, under the mode's result line. -fn print_coverage( - coverage: &[AdvisoryCoverage], - landed: &HashSet<&str>, - dry_run: bool, - verbose: bool, -) { - for line in coverage_lines_for(coverage, landed, dry_run, verbose) { - println!("{line}"); - } -} - /// The uuids of the patches an agent run left applied: the ones its nested /// apply wrote, the ones it found already in place, and the ones whose /// code is not in the build installed here @@ -820,14 +791,6 @@ fn patched_uuids(outcome: &Envelope) -> HashSet<&str> { .collect() } -/// Print the blank stdout line that opens a paragraph, once: `opened` -/// flips on the first call. -fn open_paragraph(opened: &mut bool) { - if !std::mem::replace(opened, true) { - println!(); - } -} - /// One `search_patches_by_package` query per package with patches, merged /// into one result list — the detail-fetch loop the apply, vendor, redirect /// and human-preview flows share. Returns the merged results plus every @@ -866,11 +829,7 @@ async fn fetch_patch_details( }, )); for i in 0..packages.len() { - status.set(format!( - "Fetching patch details... ({}/{})", - i + 1, - packages.len() - )); + status.progress("Reading patches", i, packages.len()); let Some((pkg, response)) = responses.next().await else { break; }; @@ -1322,9 +1281,13 @@ fn is_info_note(code: &str) -> bool { } /// Print the run-level warnings to stderr: advisories as `Note:` (not -/// under `--silent`), everything else as `Warning:`. User-patch skips are -/// silenced too, matching `user_patches::check`; the envelope keeps them. -fn print_layout_refusals(refusals: &[(String, String)], silent: bool) { +/// under `--silent`), everything else as `Warning:`. The packages the +/// project's own patches cover have one entry each in `refusals` (the +/// envelope's), and print as `project_patches`, the one notice for all of +/// them ([`render::project_patch_notice`]), where the first of them +/// stands; `--silent` mutes it, matching `user_patches::check`. +fn print_layout_refusals(refusals: &[(String, String)], project_patches: &[String], silent: bool) { + let mut project_patches = Some(project_patches); for (code, detail) in refusals { if is_info_note(code) { if !silent { @@ -1334,8 +1297,10 @@ fn print_layout_refusals(refusals: &[(String, String)], silent: bool) { code.as_str(), super::user_patches::CONFLICT | super::user_patches::ALLOWED ) { - if !silent { - eprintln!("Warning: {detail}"); + for line in project_patches.take().unwrap_or_default() { + if !silent { + eprintln!("{line}"); + } } } else { eprintln!("Warning: {detail}"); @@ -1635,7 +1600,12 @@ fn scanned_ecosystems(purls: &[String]) -> Vec { } pub async fn run(args: ScanArgs) -> i32 { - Box::pin(run_scan(args, None, true)).await + // One report per invocation: every project directory's run adds to + // it, and the totals print once, under the last of them. + let mut report = report::Run::new(&args.common); + let code = Box::pin(run_scan(args, None, true, None, &mut report)).await; + report.finish().await; + code } /// The project directories a hosted or vendored scan's PATHs name: each @@ -1713,6 +1683,7 @@ async fn run_project_dirs( invocation: &InvocationPolicy, mode_inferred: bool, dirs: Vec<(PathBuf, bool)>, + report: &mut report::Run, ) -> i32 { let usage = |code: &str, message: &str| { usage_error( @@ -1779,11 +1750,22 @@ async fn run_project_dirs( .collect(), ); } + // The slow, read-only half of every directory's scan, for all of them + // at once (see `ahead`). The directories are then scanned one by one, + // in order, as before: their output and the patch budget stay ordered. + let mut crawled = ahead(&args, &dirs, invocation, report).await.into_iter(); let mut code = 0; for (dir, explicit) in &dirs { if dirs.len() > 1 && !args.common.silent { let shown = crate::commands::projects_below::shown_project_dir(&args.common.cwd, dir); - println!("{}", crate::commands::projects_below::heading(&shown)); + // The heading opens with a blank line; only its text is bold. + let heading = crate::commands::projects_below::heading(&shown); + let text = heading.trim_start_matches('\n'); + println!( + "{}{}", + &heading[..heading.len() - text.len()], + ui::bold(text, ui::stdout_color()) + ); } let mut child = args.clone(); child.paths.clear(); @@ -1792,11 +1774,246 @@ async fn run_project_dirs( if mode_inferred { child.mode = None; } - code = code.max(Box::pin(run_scan(child, Some(invocation), *explicit)).await); + let ahead = crawled.next().flatten(); + code = + code.max(Box::pin(run_scan(child, Some(invocation), *explicit, ahead, report)).await); } code } +/// One project directory's crawl, made ahead of its scan ([`ahead`]): +/// the packages every ecosystem's crawler found, with the options and +/// ecosystem scope they were crawled with. The scan uses it in place of +/// its own crawl when it would crawl the same way. +struct Crawled { + options: socket_patch_core::crawlers::CrawlerOptions, + scope: Option>, + packages: Vec, + skipped_bundle_config_path: Option, + npm: Option, + /// What the project patches itself, read with the crawl: the scan + /// takes it instead of reading the project's files again. + user_patches: Option, +} + +impl Crawled { + /// Whether a crawl with `options` over `scope` would be this one. + fn is_for( + &self, + options: &socket_patch_core::crawlers::CrawlerOptions, + scope: Option<&[String]>, + ) -> bool { + // Destructured, not field-by-field: a new crawler option that + // changes what a crawl finds has to be answered here. + let socket_patch_core::crawlers::CrawlerOptions { + cwd, + global, + global_prefix, + } = options; + self.options.cwd == *cwd + && self.options.global == *global + && self.options.global_prefix == *global_prefix + && self.scope.as_deref() == scope + && self.npm.as_ref().is_none_or(|npm| npm.taken_with(options)) + } +} + +/// How many project directories are crawled at once ahead of their +/// scans. The crawls share the walk pool, so this bounds how much is held +/// in flight, not the load. +const AHEAD_AT_ONCE: usize = 8; + +/// A scan of several project directories spends most of its time +/// waiting: each directory is crawled, then the patch service is asked +/// about its packages, one directory after another. None of that waiting +/// depends on the directory before it, so it is done here for all of +/// them together: every directory is crawled at once, and the patch +/// service is asked once about every package any of them holds (the batch +/// search, then the patches of each package that has any), through the +/// run's client, which remembers the answers +/// ([`report::Run::share_lookups`]). +/// +/// The directories' scans then run one by one as they always did (their +/// output, the per-run patch budget and every write stay in order), each +/// using its crawl from here and finding its questions already answered. +/// Nothing here decides anything: a crawl the scan would have made +/// differently is made again, and a question that was not answered (or +/// not asked: a failed request, a package only a later step names) is +/// asked by the scan, which reports failures as before. +/// +/// Returns each directory's crawl, in `dirs`' order; `None` for a +/// directory (or all of them) left to its scan. +async fn ahead( + args: &ScanArgs, + dirs: &[(PathBuf, bool)], + invocation: &InvocationPolicy, + report: &mut report::Run, +) -> Vec> { + use futures_util::StreamExt as _; + let mut out: Vec> = dirs.iter().map(|_| None).collect(); + // One directory waits for nothing but itself. A pruning scan crawls a + // scope its policy settles, a global one has no project directories, + // and an offline one is refused before it asks anything. Where file + // descriptors are scarce the crawls run one at a time, each in its + // directory's turn, as every other part of a run does there: a crawl + // that runs out of descriptors reads a directory it could not open as + // one that is not there, and comes back short. + if dirs.len() < 2 + || args.prune + || args.sync + || args.common.offline + || args.common.is_global() + || socket_patch_core::crawlers::walk_pool::fd_limit_is_tight() + { + return out; + } + report.share_lookups(); + // The client every directory's scan uses, built as the first of them + // would build it (its advisories print here, once). + let (client, on_proxy) = report + .client(get_api_client_with_overrides( + args.common.api_client_overrides(), + )) + .await; + let client = &client; + let scope = &args.common.ecosystems; + let mut status = StatusLine::stderr(args.common.json, args.common.silent); + + // Every directory's crawl, and the purls its scan may ask about: what + // is installed, and what only its lockfiles and vendor ledger name, + // less what its scan leaves out before it asks (a package the + // socket.yml policy or a selection filter excludes, and one the + // project patches itself): nothing is asked here that the directory's + // own scan would not ask. + status.progress("Scanning projects", 0, dirs.len()); + let mut crawls = futures_util::stream::iter(dirs.iter().enumerate()) + .map(|(index, (dir, explicit))| async move { + let mut common = args.common.clone(); + common.cwd = dir.clone(); + let options = common.crawler_options(); + let (packages, _, skipped_bundle_config_path, npm) = + crawl_ecosystems_with_npm(&options, scope.as_deref()).await; + let ctx = crate::commands::context::ProjectContext::new(&common); + let lockfile_only = lockfile_supplement( + &ctx, + &packages, + scope.as_deref(), + args.mode == Some(ScanMode::Hosted), + ) + .await; + let ledger = + vendored_ledger_supplement(&ctx, &packages, &ctx.loaded().await.vendor).await; + let purls: Vec = packages + .iter() + .chain(&lockfile_only.packages) + .chain(&ledger.packages) + .map(|package| package.purl.clone()) + .collect(); + let user_patches = super::user_patches::inspect(&common).await; + let asks = invocation.asks_about(dir, *explicit); + let purls: Vec = purls + .into_iter() + .filter(|purl| asks(purl)) + .filter(|purl| { + args.common.allow_patch_conflicts || user_patches.conflicts(purl).is_empty() + }) + .collect(); + let purls = with_pypi_equivalents(&purls, &lockfile_only.purls); + let crawled = Crawled { + options, + scope: scope.clone(), + packages, + skipped_bundle_config_path, + npm, + user_patches: Some(user_patches), + }; + (index, crawled, purls) + }) + .buffer_unordered(AHEAD_AT_ONCE); + let mut asked_by: Vec> = dirs.iter().map(|_| Vec::new()).collect(); + let mut done = 0; + while let Some((index, crawled, purls)) = crawls.next().await { + done += 1; + status.progress("Scanning projects", done, dirs.len()); + out[index] = Some(crawled); + asked_by[index] = purls; + } + drop(crawls); + + // One question per package, however many directories hold it. + let mut seen = HashSet::new(); + let purls: Vec = asked_by + .iter() + .flatten() + .filter(|purl| seen.insert(purl.as_str())) + .cloned() + .collect(); + let chunks = batch_chunks( + &purls, + effective_batch_size(args.batch_size, on_proxy), + BATCH_BODY_BYTE_CAP, + ); + let checking = format!( + "Checking {} for patches", + plural(purls.len(), "package", "packages") + ); + let mut found: Vec = Vec::new(); + let mut paid = false; + let Some((first, rest)) = chunks.split_first() else { + status.finish(); + return out; + }; + // The first request goes alone: a refused token (or a service that is + // down) is found by one request, and left to the scans to report. + status.progress(&checking, 0, chunks.len()); + let Ok(answer) = client.search_patches_batch(first).await else { + status.finish(); + return out; + }; + paid |= answer.can_access_paid_patches; + found.extend(answer.packages); + let mut answers = futures_util::stream::iter(rest) + .map(|chunk| client.search_patches_batch(chunk)) + .buffer_unordered(api_concurrency_for(on_proxy, rest.len().max(1))); + let mut done = 1; + while let Some(answer) = answers.next().await { + done += 1; + status.progress(&checking, done, chunks.len()); + if let Ok(answer) = answer { + paid |= answer.can_access_paid_patches; + found.extend(answer.packages); + } + } + drop(answers); + + // The patches of each package that has any. + found.retain(|package| !package.patches.is_empty()); + let mut reads = futures_util::stream::iter(&found) + .map(|package| client.search_patches_by_package(&package.purl)) + .buffer_unordered(api_concurrency_for(on_proxy, found.len().max(1))); + let mut done = 0; + status.progress("Reading patches", done, found.len()); + while reads.next().await.is_some() { + done += 1; + status.progress("Reading patches", done, found.len()); + } + drop(reads); + status.finish(); + + // What was measured about the patches each directory is likely to get + // is asked for now too, so it is in when that directory's rows print. + for asked in &asked_by { + let asked: HashSet<&str> = asked.iter().map(String::as_str).collect(); + let theirs: Vec = found + .iter() + .filter(|package| asked.contains(package.purl.as_str())) + .cloned() + .collect(); + report.measure_likely(client, &theirs, paid); + } + out +} + /// Report a usage error `scan` enforces itself (exit 2): the coded error /// on stdout under `--json`, `Error: ...` on stderr otherwise. fn scan_usage_error(args: &ScanArgs, code: &str, message: &str) -> i32 { @@ -1822,15 +2039,61 @@ fn report_policy_error(err: &socket_patch_core::policy::PolicyError, args: &Scan 1 } +/// A read of the checkout started beside the crawl, for an answer the run +/// needs only once the crawl is in: the reads are independent, and waiting +/// for them one after another was most of a scan's time before its first +/// progress. Dropping it (an early return) cancels the read. +struct Beside(tokio::task::JoinHandle); + +impl Beside { + /// Start `read` now, or not at all where file descriptors are scarce: + /// the crawl already uses what there is, and the caller then makes the + /// read itself, in turn. + fn start(read: impl std::future::Future + Send + 'static) -> Option { + (!socket_patch_core::crawlers::walk_pool::fd_limit_is_tight()) + .then(|| Beside(tokio::spawn(read))) + } + + /// The read's answer. + async fn done(mut self) -> T { + match (&mut self.0).await { + Ok(answer) => answer, + // Only a drop cancels the read, and nothing awaits a dropped + // one: what is left is the read's own panic. + Err(e) => std::panic::resume_unwind(e.into_panic()), + } + } +} + +impl Drop for Beside { + fn drop(&mut self) { + self.0.abort(); + } +} + /// `invocation` is the policy a PATH-list parent already loaded (`None` /// loads it here); `explicit` says whether the user named this root. /// /// The one place a scan's exit code is settled: a run that left packages /// unchecked (the patch API gave no answer for them) is a partial failure /// whatever the mode it went on to run reported, so it never exits 0. -async fn run_scan(args: ScanArgs, invocation: Option<&InvocationPolicy>, explicit: bool) -> i32 { +async fn run_scan( + args: ScanArgs, + invocation: Option<&InvocationPolicy>, + explicit: bool, + ahead: Option, + report: &mut report::Run, +) -> i32 { let mut unchecked = 0usize; - let code = Box::pin(scan_project(args, invocation, explicit, &mut unchecked)).await; + let code = Box::pin(scan_project( + args, + invocation, + explicit, + ahead, + &mut unchecked, + report, + )) + .await; if unchecked > 0 && code == 0 { 1 } else { @@ -1840,11 +2103,15 @@ async fn run_scan(args: ScanArgs, invocation: Option<&InvocationPolicy>, explici /// [`run_scan`]'s body. `unchecked` is set to the number of packages the /// patch API gave no answer for (already reported; see `run_scan`). +/// `report` is the invocation's report: this directory's rows print +/// through it and its counts join the closing totals. async fn scan_project( mut args: ScanArgs, invocation: Option<&InvocationPolicy>, explicit: bool, + ahead: Option, unchecked: &mut usize, + report: &mut report::Run, ) -> i32 { apply_env_toggles(&args.common); @@ -1931,19 +2198,31 @@ async fn scan_project( Ok(dirs) => dirs, Err((code, message)) => return scan_usage_error(&args, code, &message), }; - return Box::pin(run_project_dirs(args, invocation, mode_inferred, dirs)).await; + return Box::pin(run_project_dirs( + args, + invocation, + mode_inferred, + dirs, + report, + )) + .await; } // A bare one names none and finds them: every project in the checkout // at or below `--cwd`. `--json` and `--vex` take one directory, so they // scan `--cwd` alone and say which projects were left. let mut unscanned_projects = None; if discovers_projects(&args, invocation) { + // The search walks the checkout before anything else can print: + // say so at once, or a large one opens with seconds of nothing. + let mut finding = StatusLine::stderr(args.common.json, args.common.silent); + finding.set("Finding projects"); let found = crate::commands::projects_below::discovered( &args.common, &invocation.policy, &invocation.repo_root, ) .await; + finding.finish(); let others: Vec = found .dirs .iter() @@ -1970,6 +2249,7 @@ async fn scan_project( invocation, mode_inferred, found.dirs, + report, )) .await; } @@ -2052,8 +2332,11 @@ async fn scan_project( let socket_dir = args.common.socket_dir(); let overrides = args.common.api_client_overrides(); - let (mut api_client, mut use_public_proxy) = - get_api_client_with_overrides(overrides.clone()).await; + // One client per invocation: the project directories of a run share + // its connection (and its org lookup). + let (mut api_client, mut use_public_proxy) = report + .client(get_api_client_with_overrides(overrides.clone())) + .await; // Sized for the endpoint the run starts on. A mid-run downgrade to the // proxy keeps these chunk boundaries: every chunk is within the proxy's // body cap by construction (`BATCH_BODY_BYTE_CAP`). @@ -2076,7 +2359,7 @@ async fn scan_project( // envelope are unaffected. let human = !args.common.json && !args.common.silent; let mut status = StatusLine::stderr(args.common.json, args.common.silent); - status.set(format!("Scanning {scan_target}...")); + status.set(format!("Scanning {scan_target}")); // Which ecosystems to crawl (see `crawl_scope`). let crawl_scope = crawl_scope(prune, args.common.ecosystems.as_deref()); @@ -2089,12 +2372,53 @@ async fn scan_project( let keep_npm = vendor || (hosted && args.vex.vex.is_some() && !args.common.dry_run) || !path_scope.is_empty(); - let (mut all_crawled, mut eco_counts, skipped_bundle_config_path, npm_crawl) = if keep_npm { - crawl_ecosystems_with_npm(&crawler_options, crawl_scope).await + // Either way the crawl hands back the `node_modules` roots it walked: + // the socket.yml filters below judge a nested project's copies by + // them, and finding them is most of the crawl of a large checkout. + let crawl = async { + if keep_npm { + let (packages, _, skipped, npm) = + crawl_ecosystems_with_npm(&crawler_options, crawl_scope).await; + let roots = npm.as_ref().map(|npm| npm.roots().to_vec()); + (packages, skipped, npm, roots) + } else { + let (packages, _, skipped, roots) = + crawl_ecosystems_with_npm_roots(&crawler_options, crawl_scope).await; + (packages, skipped, None, roots) + } + }; + // The project's own patches (the consent gate below) are read beside + // the crawl ([`Beside`]), and collected where they were always used; + // a run over several project directories read them ahead, with this + // directory's crawl. + let mut ahead = ahead; + let mut patches_read_ahead = ahead + .as_mut() + .and_then(|crawled| crawled.user_patches.take()); + let mut project_patches = if patches_read_ahead.is_some() { + None } else { - let (packages, counts, skipped) = crawl_ecosystems(&crawler_options, crawl_scope).await; - (packages, counts, skipped, None) + Beside::start({ + let common = args.common.clone(); + async move { super::user_patches::inspect(&common).await } + }) }; + // A run over several project directories crawled this one ahead of + // its turn (`ahead`): that crawl stands in for this one when it was + // made the same way. + let (mut all_crawled, skipped_bundle_config_path, npm_crawl, npm_roots) = + match ahead.filter(|crawled| crawled.is_for(&crawler_options, crawl_scope)) { + Some(crawled) => { + let roots = crawled.npm.as_ref().map(|npm| npm.roots().to_vec()); + ( + crawled.packages, + crawled.skipped_bundle_config_path, + crawled.npm.filter(|_| keep_npm), + roots, + ) + } + None => crawl.await, + }; // Lockfile supplement: dependencies the project's lockfile resolves // that have NO installed copy (fresh clone, partial install). They join @@ -2116,49 +2440,14 @@ async fn scan_project( if let Some(others) = &unscanned_projects { let detail = render::unscanned_projects_detail(others, args.common.json); if !args.common.json && !args.common.silent { - eprintln!("Warning: {detail}"); + status.println(format!("Warning: {detail}")); } layout_refusals.push((render::PROJECTS_NOT_SCANNED.to_string(), detail)); } - // A bare agent-mode scan patches the copies the crawl above found, so - // it covers the one project at `--cwd`. It names the project - // directories below whose packages that crawl did not read (#2125): - // without it the run reads as empty, or as a success for the checkout. - // PATHs scope the run to what the user named, and a run for one - // directory of several (`carry`) leaves the rest to its parent. - let mut projects_left = false; - if apply && args.paths.is_empty() && args.rollout.carry.is_none() { - use crate::commands::projects_below; - let left = - projects_below::not_crawled(&args.common, &invocation.policy, &invocation.repo_root) - .await; - if let Some(first) = left.dirs.first() { - let shown: Vec = left - .dirs - .iter() - .map(|dir| projects_below::shown_project_dir(&args.common.cwd, dir)) - .collect(); - // The run for a directory is asked as this one was: only an - // explicit `--mode` converts a project (#1088). - let scan = if args.sync { - "scan --sync" - } else if mode_explicit { - "scan --mode agent" - } else { - "scan" - }; - let command = projects_below::project_command(first, &args.common, scan); - let detail = render::unscanned_agent_projects_detail(&shown, &command); - layout_refusals.push((render::PROJECTS_NOT_SCANNED.to_string(), detail)); - projects_left = true; - } - if left.truncated { - layout_refusals.push(( - projects_below::PROJECTS_BELOW_NOT_SEARCHED.to_string(), - projects_below::NOT_CRAWLED_TRUNCATED.to_string(), - )); - } - } + // Where the warnings of the search for project directories below go + // once it is in (before the package count is judged, below): the + // run-level warnings keep the order they always had. + let projects_left_at = layout_refusals.len(); // A token whose org could not be resolved put the whole run on the // public proxy (the client already warned on stderr): `--json` // consumers get it on the same run-level `warnings[]` channel. @@ -2196,9 +2485,6 @@ async fn scan_project( let mut supplement_purls: HashSet = HashSet::new(); if !lockfile_only.packages.is_empty() { for pkg in &lockfile_only.packages { - if let Some(eco) = Ecosystem::from_purl(&pkg.purl) { - *eco_counts.entry(eco).or_insert(0) += 1; - } supplement_purls.insert(pkg.purl.clone()); } all_crawled.extend(lockfile_only.packages.iter().cloned()); @@ -2210,9 +2496,6 @@ async fn scan_project( let vendor_state = &ctx.loaded().await.vendor; let ledger_supplement = vendored_ledger_supplement(&ctx, &all_crawled, vendor_state).await; for pkg in &ledger_supplement.packages { - if let Some(eco) = Ecosystem::from_purl(&pkg.purl) { - *eco_counts.entry(eco).or_insert(0) += 1; - } supplement_purls.insert(pkg.purl.clone()); } all_crawled.extend(ledger_supplement.packages); @@ -2450,10 +2733,15 @@ async fn scan_project( // The socket.yml root/ecosystem/package filters, after the flags // (which only narrow further) and after the prune-universe capture. if policy.judges_nested_roots() && args.common.ecosystem_selected(Ecosystem::Npm) { - let nm_roots = socket_patch_core::crawlers::NpmCrawler::for_options(&crawler_options) - .get_node_modules_paths(&crawler_options) - .await - .unwrap_or_default(); + // The roots the crawl just walked, or (a crawl that left npm out) + // a walk for them. + let nm_roots = match npm_roots { + Some(roots) => roots, + None => socket_patch_core::crawlers::NpmCrawler::for_options(&crawler_options) + .get_node_modules_paths(&crawler_options) + .await + .unwrap_or_default(), + }; policy .locate_nested_copies(&nm_roots, &filtered_crawled) .await; @@ -2461,12 +2749,18 @@ async fn scan_project( let mut filtered_crawled = policy.admit_crawled_copies(filtered_crawled, &supplement_purls); // Keep the full crawl above for GC: a protected package is still installed. // Protect before querying/selecting, in every mode and in dry-run previews. - let user_patches = super::user_patches::inspect(&args.common).await; + let user_patches = match (patches_read_ahead.take(), project_patches.take()) { + (Some(read), _) => read, + (None, Some(started)) => started.done().await, + (None, None) => super::user_patches::inspect(&args.common).await, + }; let mut user_patch_withheld = 0usize; // Of those, the ones held back only because a project file could not // be read: a broken file, not a patch the project declares. let mut user_patch_unreadable = 0usize; let mut user_patch_skips = Vec::new(); + // The same packages for the human notice: one block, not a line each. + let mut project_patched: Vec = Vec::new(); filtered_crawled.retain(|package| { let sources = user_patches.conflicts(&package.purl); if sources.is_empty() { @@ -2479,6 +2773,11 @@ async fn scan_project( args.common.allow_patch_conflicts, unreadable, ); + project_patched.push(render::Protected { + purl: package.purl.clone(), + sources, + unreadable, + }); if !args.common.allow_patch_conflicts { user_patch_withheld += 1; user_patch_unreadable += usize::from(unreadable); @@ -2503,6 +2802,13 @@ async fn scan_project( )); args.common.allow_patch_conflicts }); + // The index reports its sources under the absolute project root. + let project_patch_notice = render::project_patch_notice( + &project_patched, + args.common.allow_patch_conflicts, + args.common.verbose, + &std::path::absolute(&args.common.cwd).unwrap_or_else(|_| args.common.cwd.clone()), + ); // Agent mode patches the installed jar where it lies. A version whose // directory in the Maven local repository holds only its pom was never @@ -2526,13 +2832,76 @@ async fn scan_project( .await; layout_refusals.extend(gradle.notes.iter().cloned()); + // A bare agent-mode scan patches the copies the crawl found, so it + // covers the one project at `--cwd`, and names the project directories + // below whose packages that crawl did not read (#2125): without it the + // run reads as empty, or as a success for the checkout. PATHs scope + // the run to what the user named, and a run for one directory of + // several (`carry`) leaves the rest to its parent. + // + // Finding them walks the whole checkout, which used to be most of the + // wait before a scan's first progress. Nothing before the patch lookup + // needs the answer unless the crawl came back empty, so the walk runs + // during the lookup, whose wait is the network's, and its warnings + // take their old place among the run's (`projects_left_at`). + let searches_below = apply && args.paths.is_empty() && args.rollout.carry.is_none(); + let search_below = |common: GlobalArgs, policy, repo_root: PathBuf| async move { + crate::commands::projects_below::not_crawled(&common, &policy, &repo_root).await + }; + let projects_left_warnings = |left: &crate::commands::projects_below::NotCrawled| { + use crate::commands::projects_below; + let mut warnings = Vec::new(); + if let Some(first) = left.dirs.first() { + let shown: Vec = left + .dirs + .iter() + .map(|dir| projects_below::shown_project_dir(&args.common.cwd, dir)) + .collect(); + // The run for a directory is asked as this one was: only an + // explicit `--mode` converts a project (#1088). + let scan = if args.sync { + "scan --sync" + } else if mode_explicit { + "scan --mode agent" + } else { + "scan" + }; + let command = projects_below::project_command(first, &args.common, scan); + let detail = render::unscanned_agent_projects_detail(&shown, &command); + warnings.push((render::PROJECTS_NOT_SCANNED.to_string(), detail)); + } + if left.truncated { + warnings.push(( + projects_below::PROJECTS_BELOW_NOT_SEARCHED.to_string(), + projects_below::NOT_CRAWLED_TRUNCATED.to_string(), + )); + } + warnings + }; + let all_purls: Vec = filtered_crawled.iter().map(|p| p.purl.clone()).collect(); let package_count = all_purls.len(); if package_count == 0 { + // An empty crawl is where the projects below matter most: they + // are why nothing was found. + let mut projects_left = false; + if searches_below { + let left = search_below( + args.common.clone(), + invocation.policy.clone(), + invocation.repo_root.clone(), + ) + .await; + projects_left = !left.dirs.is_empty(); + layout_refusals.splice( + projects_left_at..projects_left_at, + projects_left_warnings(&left), + ); + } status.finish(); if human { - print_layout_refusals(&layout_refusals, args.common.silent); + print_layout_refusals(&layout_refusals, &project_patch_notice, args.common.silent); policy.print_warnings(args.common.silent); // Hosted mode already printed its own prune-ignored warning. if prune && !hosted && unwired_vendored.is_empty() { @@ -2665,18 +3034,16 @@ async fn scan_project( .await; } - // Build ecosystem summary + // The ecosystem summary counts the packages this run goes on to check, + // like the total beside it: a filter, the socket.yml policy or the + // project's own patches can each leave some of the crawl out, and + // "Found 5703 packages (5724 npm)" reads as a miscount. let mut eco_parts = Vec::new(); for eco in Ecosystem::all() { - let count = if args.common.ecosystems.is_some() { - // When filtering, count the filtered packages - filtered_crawled - .iter() - .filter(|p| Ecosystem::from_purl(&p.purl) == Some(*eco)) - .count() - } else { - eco_counts.get(eco).copied().unwrap_or(0) - }; + let count = filtered_crawled + .iter() + .filter(|p| Ecosystem::from_purl(&p.purl) == Some(*eco)) + .count(); if count > 0 { eco_parts.push(format!("{count} {}", eco.display_name())); } @@ -2692,12 +3059,25 @@ async fn scan_project( plural(package_count, "package", "packages") )); if human { - if lockfile_only_count > 0 { + // Hosted and vendored mode patch from the lockfile, so a package + // not yet installed is patched like any other. An agent or + // report-only scan patches installed copies, and leaves these out. + if lockfile_only_count > 0 && !hosted && !vendor { eprintln!("{}", render::lockfile_only_note(lockfile_only_count)); } - print_layout_refusals(&layout_refusals, args.common.silent); + print_layout_refusals(&layout_refusals, &project_patch_notice, args.common.silent); policy.print_warnings(args.common.silent); } + // The search for project directories below runs through the lookup. + let mut left_below = searches_below + .then(|| { + Beside::start(search_below( + args.common.clone(), + invocation.policy.clone(), + invocation.repo_root.clone(), + )) + }) + .flatten(); // Query API in batches let mut all_packages_with_patches: Vec = Vec::new(); @@ -2781,10 +3161,14 @@ async fn scan_project( |chunk| hold_back_debug(client.search_patches_batch(chunk)), )); while next < end { - status.set(format!( - "Querying API for patches... (batch {}/{total_batches})", - next + 1 - )); + status.progress( + format_args!( + "Checking {} for patches", + plural(package_count, "package", "packages") + ), + next, + total_batches, + ); // `ordered_concurrent` yields one item per chunk. Should it // ever run dry early, stop: re-entering the outer loop with // `next` unchanged would re-POST the same window forever. @@ -2814,6 +3198,7 @@ async fn scan_project( api_client = build_proxy_fallback_client(&overrides); use_public_proxy = true; fallback_to_proxy = true; + report.fell_back_to(&api_client); let result = api_client.search_patches_batch(chunks[next]).await; fold(next, result, &mut status); next += 1; @@ -2821,7 +3206,7 @@ async fn scan_project( } // Batches are only sorted within each chunk. Sort globally: this list - // drives the table, the `--json` `packages` array and the apply order, + // drives the report, the `--json` `packages` array and the apply order, // which operators diff across runs. all_packages_with_patches.sort_by(|a, b| a.purl.cmp(&b.purl)); // #604: a patch the API returned under an equivalent spelling of a @@ -2859,6 +3244,32 @@ async fn scan_project( } } + // The project directories below that this run did not read, now that + // the lookup is in (and before a lookup that failed ends the run: + // that this run would not have covered them is news either way): usually found by now, else the status says what + // the run is waiting for. + if searches_below { + status.set("Looking for other projects"); + let left = match left_below.take() { + Some(started) => started.done().await, + None => { + search_below( + args.common.clone(), + invocation.policy.clone(), + invocation.repo_root.clone(), + ) + .await + } + }; + let warnings = projects_left_warnings(&left); + if human { + for (_, detail) in &warnings { + status.println(format!("Warning: {detail}")); + } + } + layout_refusals.splice(projects_left_at..projects_left_at, warnings); + } + // If every batch errored, surface a full scan failure rather than // silently reporting zero patches. if total_batches > 0 && batch_error_count == total_batches { @@ -2897,22 +3308,10 @@ async fn scan_project( // failed batch. let lookup_incomplete = batch_error_count > 0 || !unanswered.is_empty(); - let total_patches_found: usize = all_packages_with_patches - .iter() - .map(|p| p.patches.len()) - .sum(); - - if total_patches_found > 0 { - status.finish_with(format!( - "Found {} for {}", - plural(total_patches_found, "patch", "patches"), - plural(all_packages_with_patches.len(), "package", "packages") - )); - } else { - // The result line ("No patches available for installed packages.") - // is printed on stdout below; saying it here too would repeat it. - status.finish(); - } + // The lookup's outcome is the run's result line on stdout below (what + // was patched, or "No patches available for installed packages."), so + // the status only clears. + status.finish(); // Hosted mode: restore the lockfile pins whose patch the server no // longer serves, before the rewrite below re-pins any replacement. @@ -2964,7 +3363,6 @@ async fn scan_project( } } } - let total_patches = free_patches + paid_patches; // Telemetry: record the scan outcome with the per-tier counts and the // ecosystems the crawl actually found (not the `--ecosystems` filter, @@ -3024,7 +3422,7 @@ async fn scan_project( serde_json::json!(can_access_paid_patches), ); // Flag lockfile-only packages (absent means installed), with the - // same predicate as the `[NOT INSTALLED]` marker, and Gradle-cached + // same predicate as the agent-mode not-installed skip, and Gradle-cached // packages with whether the build's lock files name them (an // annotation, never a filter). let mut packages = @@ -3359,9 +3757,9 @@ async fn scan_project( // Only a lookup the service answered in full may say it of // every installed package. if lookup_incomplete { - println!("\n{}", render::NO_PATCHES_AMONG_CHECKED); + println!("{}", render::NO_PATCHES_AMONG_CHECKED); } else { - println!("\nNo patches available for installed packages."); + println!("No patches available for installed packages."); } } return finish_human(0).await; @@ -3369,17 +3767,60 @@ async fn scan_project( // `downloadable_count` (above): a free-tier org whose every offer is // paid-tier has nothing any mode could select, so every human arm stops - // below the table with the same paid-subscription line. - - // The by-package records every arm selects from, fetched before the - // table so its `[UPDATE]` markers are the same UPGRADE rows the - // selection acts on (§5.1). Only `discover_selected`'s own `Err` - // (every query failed) is a fetch failure: queries that succeed with - // no records leave nothing to select, in every arm and in `--json` - // alike (#1062). A failed discovery still prints the table first; its - // exit code is returned below it. + // with the same paid-subscription line. + + // The by-package records every arm selects from. Only + // `discover_selected`'s own `Err` (every query failed) is a fetch + // failure: queries that succeed with no records leave nothing to + // select, in every arm and in `--json` alike (#1062). let mut discovery_failure: Option = None; + let filter = invocation.policy.filter(); + // A hosted or vendored run patches what the lockfile resolves. Where + // that lockfile lists the whole dependency graph, a package it does + // not name is a copy installed on this machine that the project does + // not use (another project's gem in a shared gem home, an extraneous + // `node_modules` entry): the mode reports it, and the report does not + // count it as left to patch. A requirements file may pin only the + // direct dependencies, so PyPI packages always count. + let locked: HashSet = lockfile_only + .entries + .iter() + .map(|entry| PurlKey::new(&entry.purl)) + .collect(); + let complete_locks: HashSet = lockfile_only + .entries + .iter() + .filter_map(|entry| Ecosystem::from_purl(&entry.purl)) + .filter(|eco| *eco != Ecosystem::Pypi) + .collect(); + let in_project = |purl: &str| { + !(hosted || vendor) + || Ecosystem::from_purl(purl).is_none_or(|eco| !complete_locks.contains(&eco)) + || locked.contains(&PurlKey::new(purl)) + }; + // What Socket measured about the patches this run is likely to select, + // asked for now so the answers are in by the time the rows print. + if fetch_details { + report.measure_likely( + &api_client, + &all_packages_with_patches, + can_access_paid_patches, + ); + } + // The report's view of every package with a patch on offer: what the + // selected patch fixes and leaves unpatched. Every mode prints the rows + // of the packages it patched under its result line, and counts the + // rest as left to patch. + let mut plan = Vec::new(); let rows: Vec = if !fetch_details { + plan = report::plan( + &all_packages_with_patches, + &[], + &[], + can_access_paid_patches, + filter, + &in_project, + ); Vec::new() } else { match discover_selected( @@ -3404,6 +3845,16 @@ async fn scan_project( None, ); updates = offer_updates(&rows, &discovered, &recorded, &all_packages_with_patches); + let records: Vec<&PatchSearchResult> = + discovered.offers.unfiltered.values().flatten().collect(); + plan = report::plan( + &all_packages_with_patches, + &writers_of(&rows), + &records, + can_access_paid_patches, + filter, + &in_project, + ); rows } // `discover_selected` already printed the failure to stderr. @@ -3413,140 +3864,32 @@ async fn scan_project( } } }; - // What each package's selected patch fixes and leaves unpatched: every - // mode prints it under its result line, for the packages it patched. - let coverage = advisory_coverage(&all_packages_with_patches, &writers_of(&rows)); - - // Presentational only, so `--silent` skips it wholesale. - if !silent { - let mut updates_available = 0usize; - - // PURLs with a newer patch, from the same `detect_updates` result the - // JSON `updates` array uses, so the table and JSON never disagree. - let update_purls: HashSet<&str> = updates.iter().map(|u| u.purl.as_str()).collect(); - - // Human display only: the decoded PURL (`%40scope` → `@scope`), like - // the "Patches to apply" preview. The PACKAGE column is as wide as - // the longest one (capped); longer ones keep their `@version`. - let shown_purls: Vec = all_packages_with_patches - .iter() - .map(|p| normalize_purl(&p.purl).into_owned()) - .collect(); - let purl_w = render::purl_col_width(shown_purls.iter().map(String::as_str)); - - let mut rows: Vec = Vec::with_capacity(all_packages_with_patches.len()); - for (pkg, shown) in all_packages_with_patches.iter().zip(&shown_purls) { - let display_purl = render::elide_purl(shown, purl_w); - - let pkg_free = pkg.patches.iter().filter(|p| p.tier == "free").count(); - let pkg_paid = pkg.patches.iter().filter(|p| p.tier == "paid").count(); - - let count_str = if pkg_paid > 0 { - if can_access_paid_patches { - format!("{}+{}", pkg_free, pkg_paid) - } else { - format!( - "{}+{}", - pkg_free, - ui::paint(&pkg_paid.to_string(), "33", use_color) - ) - } - } else { - format!("{}", pkg_free) - }; - - // Get highest severity - let severity = pkg - .patches - .iter() - .filter_map(|p| p.severity.as_deref()) - .min_by_key(|s| severity_order(Some(s))) - .unwrap_or("unknown"); - - // Collect vuln IDs (deterministic; see collect_vuln_ids). - let vuln_str = render::vuln_cell(&collect_vuln_ids(pkg), verbose); - - let has_update = update_purls.contains(pkg.purl.as_str()); - if has_update { - updates_available += 1; - } - - let update_marker = if has_update { - ui::paint(" [UPDATE]", "33", use_color) - } else { - String::new() - }; - // Lockfile-only packages can be vendored (fetched pristine) but - // not applied in place. - let not_installed_marker = if lockfile_only_contains(&lockfile_only.purls, &pkg.purl) { - ui::paint(" [NOT INSTALLED]", "33", use_color) - } else { - String::new() - }; - - rows.push(render::table_row( - purl_w, - &display_purl, - &count_str, - &ui::severity(severity, use_color), - &vuln_str, - &format!("{update_marker}{not_installed_marker}"), - )); - } - - // The rule is as wide as the table, but never wraps a terminal. - let header = render::table_header(purl_w); - let cap = std::io::stdout().is_terminal().then(ui::stdout_width); - let rule = render::ruler( - std::iter::once(header.as_str()).chain(rows.iter().map(String::as_str)), - cap, - ); - println!("\n{rule}"); - println!("{header}"); - println!("{rule}"); - for row in &rows { - println!("{row}"); - } - println!("{rule}"); - - // Summary - let with_patches = all_packages_with_patches.len(); - if can_access_paid_patches { - println!( - "\n{}", - render::summary_line(with_patches, total_patches, true) - ); - } else { - println!( - "\n{}", - render::summary_line(with_patches, free_patches, false) - ); - if paid_patches > 0 { - println!( - "{}", - ui::paint(&render::paid_extra_line(paid_patches), "33", use_color), - ); - println!("\n{}", ui::PAID_UPGRADE); - } - } - - if updates_available > 0 { - println!( - "\n{}", - ui::paint(&render::updates_line(updates_available), "33", use_color), - ); - } + report.reads_reachability(filter); + if use_public_proxy { + report.saw_free_patches_only(); } + // And about any selected patch that guess missed. + report.measure(&api_client, &plan); if downloadable_count == 0 { if !silent { - println!("\nNo downloadable patches: every patch found requires a paid Socket plan."); + println!("No downloadable patches: every patch found requires a paid Socket plan."); } + report.upsell(); + report.count(&plan, &HashSet::new()); return finish_human(0).await; } if let Some(code) = discovery_failure { return code; } + // A recorded patch the run replaces with a newer one, from the same + // `detect_updates` result the JSON `updates` array uses. + if !silent && !updates.is_empty() { + println!( + "{}", + ui::paint(&render::updates_line(updates.len()), "33", use_color), + ); + } policy.print_human(silent, verbose); // Hosted mode is a self-contained flow: it reuses the discovery, table @@ -3571,7 +3914,8 @@ async fn scan_project( rows, prior: prior_discovery, references: sweep_references, - coverage, + plan, + report: Some(report), }), "scan", ) @@ -3583,10 +3927,6 @@ async fn scan_project( let report_only = args.mode.is_none(); let selected: Vec = writers_of(&rows); - // The skip / already-recorded lines below open their own paragraph - // under the table's Summary: one blank line before the first of them. - let mut skip_paragraph = false; - // Agent flow (mirrors the JSON arm): vendor-owned and lockfile-only // purls leave the selection as skips. Vendored mode partitions nothing. let selected = if vendor { @@ -3595,12 +3935,15 @@ async fn scan_project( let split = partition_agent_selection(selected, &vendor_owned_purls, &lockfile_only); if !silent { for purl in &split.vendored_purls { - open_paragraph(&mut skip_paragraph); println!("{}", render::vendored_skip_line(&normalize_purl(purl))); } - for purl in &split.not_installed_purls { - open_paragraph(&mut skip_paragraph); - println!("{}", render::not_installed_skip_line(&normalize_purl(purl))); + let not_installed: Vec = split + .not_installed_purls + .iter() + .map(|purl| normalize_purl(purl).into_owned()) + .collect(); + for line in render::not_installed_skip_lines(¬_installed, verbose) { + println!("{line}"); } } split.kept @@ -3645,9 +3988,12 @@ async fn scan_project( selected.into_iter().partition(|p| recorded(p)) }; let reapply = !report_only && !args.common.dry_run; - if !silent { + // A recorded patch the run re-applies (or would) gets its row under the + // result line like every other patched package; naming it here as well + // is for `--verbose`. A report-only run applies nothing, so this line + // is the one place it says the patch is already recorded. + if !silent && (verbose || report_only) { for p in &already_recorded { - open_paragraph(&mut skip_paragraph); println!( "{}", render::already_recorded_line(&normalize_purl(&p.purl), &p.uuid, reapply) @@ -3657,7 +4003,6 @@ async fn scan_project( if selected.is_empty() && (!reapply || already_recorded.is_empty()) { if !silent { - open_paragraph(&mut skip_paragraph); if !stage.deferred_keys().is_empty() { if args.common.dry_run { println!("No new patches would be added this run."); @@ -3672,12 +4017,59 @@ async fn scan_project( println!("{}", render::ALL_ALREADY_RECORDED); } } + // A dry run of an agent project whose patches are all recorded + // would re-apply them; every other run that stops here patched + // nothing. + let landing: HashSet<&str> = if args.common.dry_run && !report_only { + already_recorded.iter().map(|p| p.uuid.as_str()).collect() + } else { + HashSet::new() + }; + report.project(&plan, &landing).await; print_rollout_human(&stage, args.common.dry_run, silent, &[]); return finish_human(0).await; } - // Display detailed summary of selected patches (skipped under --silent). - if !silent && !selected.is_empty() { + // A replacement that fixes less than the recorded patch is said on + // every run; `--verbose` says it under the patch's block below. + let replaces_of = |patch: &PatchSearchResult| { + existing_manifest + .as_ref() + .filter(|_| !vendor) + .and_then(|m| m.patches.get(&patch.purl)) + .filter(|r| r.uuid != patch.uuid) + }; + if !silent && !verbose { + for patch in &selected { + let Some(recorded) = replaces_of(patch) else { + continue; + }; + let block = render::PatchBlock { + patch, + severity: "", + replaces: Some(render::Replaces { + uuid: &recorded.uuid, + vuln_ids: recorded + .vulnerabilities + .keys() + .map(String::as_str) + .collect(), + }), + verbose, + }; + if let Some(warning) = render::replacement_warning(&block) { + eprintln!( + "Warning: {}: {}", + normalize_purl(&patch.purl), + warning.trim_start().trim_start_matches("Warning: ") + ); + } + } + } + + // `--verbose`: each selected patch in full (its tier, every advisory's + // summary, the patch description). + if !silent && verbose && !selected.is_empty() { if vendor { println!("\nPatches to vendor:\n"); } else if report_only { @@ -3694,15 +4086,10 @@ async fn scan_project( // The manifest already records a different patch for this // package: say so, and warn when the new one fixes less. Agent // mode only: vendored mode never writes the manifest. - let replaces = existing_manifest - .as_ref() - .filter(|_| !vendor) - .and_then(|m| m.patches.get(&patch.purl)) - .filter(|r| r.uuid != patch.uuid) - .map(|r| render::Replaces { - uuid: &r.uuid, - vuln_ids: r.vulnerabilities.keys().map(String::as_str).collect(), - }); + let replaces = replaces_of(patch).map(|r| render::Replaces { + uuid: &r.uuid, + vuln_ids: r.vulnerabilities.keys().map(String::as_str).collect(), + }); let block = render::PatchBlock { patch, severity: &severity, @@ -3728,7 +4115,22 @@ async fn scan_project( // read-only preview on a dry run). The preview never says it would // download and apply. if report_only { - // The "Patches available:" listing already ends with a blank line. + // One row per package a patch is available for (the `--verbose` + // listing above names each in full instead), none of them patched. + let offered: HashSet<&str> = selected + .iter() + .chain(&already_recorded) + .map(|p| p.uuid.as_str()) + .collect(); + report.settle().await; + if !silent && !verbose { + println!("Patches available:"); + for row in report.rows_offered(&plan, &offered) { + println!("{row}"); + } + println!(); + } + report.count(&plan, &HashSet::new()); if !silent { for line in render::report_only_hint(&args.common) { println!("{line}"); @@ -3755,45 +4157,48 @@ async fn scan_project( .await; } - // `--dry-run` is a non-mutating preview: stop here, having printed the - // table and the per-patch plan above, before the download/apply and the - // prune GC (which runs as a read-only preview instead). + // `--dry-run` is a non-mutating preview: stop here, before the + // download/apply and the prune GC (which runs as a read-only preview + // instead). if args.common.dry_run { + // What the wet run would patch: the agent selection with the + // recorded patches it re-applies. A vendored preview narrows it to + // its rows less its refusals below. + let preview = if vendor { + // The planning pass above always computed it for a vendored + // run. + let mut preview = vendor_preview + .take() + .expect("the vendored planning pass computed the preview"); + preview.retain_selected(&selected); + Some(preview) + } else { + None + }; + let landing: HashSet<&str> = match &preview { + Some(preview) => preview.landing_uuids(), + None => selected + .iter() + .chain(&already_recorded) + .map(|p| p.uuid.as_str()) + .collect(), + }; if !silent { // Vendored preview: the JSON arm's ledger classification, // rendered as `[skip]` and `[would-refuse]` lines so a preview // never advertises vendoring the wet run would skip or refuse. - let preview = if vendor { - // The planning pass above always computed it for a - // vendored run. - let mut preview = vendor_preview - .take() - .expect("the vendored planning pass computed the preview"); - preview.retain_selected(&selected); - Some(preview) - } else { - None - }; match &preview { Some(preview) => preview.print_human(), None => println!( "{}", - render::dry_run_line(render::Plan::Apply(selected.len())) + render::dry_run_line(render::Plan::Apply { + new: selected.len(), + recorded: already_recorded.len(), + }) ), } - // What the wet run would patch: the vendored preview's rows - // less its refusals, or the agent selection with the recorded - // patches it re-applies. - let landing: HashSet<&str> = match &preview { - Some(preview) => preview.landing_uuids(), - None => selected - .iter() - .chain(&already_recorded) - .map(|p| p.uuid.as_str()) - .collect(), - }; - print_coverage(&coverage, &landing, true, verbose); } + report.project(&plan, &landing).await; print_rollout_human(&stage, true, silent, &[]); return finish_human(0).await; } @@ -3851,7 +4256,8 @@ async fn scan_project( prune, &telemetry_auth, npm_crawl.as_ref(), - &coverage, + &plan, + report, ) .await } else { @@ -3865,9 +4271,9 @@ async fn scan_project( &download_run(&args, &api_client), ) .await; - if !silent { - print_coverage(&coverage, &patched_uuids(&outcome), false, verbose); - } + // Under the apply's result line: one row per package it left + // patched. + report.project(&plan, &patched_uuids(&outcome)).await; // A project run that recorded a patch has something to commit, and // a re-apply to wire up after every install. if code == 0 && !args.common.is_global() { diff --git a/crates/socket-patch-cli/src/commands/scan/policy.rs b/crates/socket-patch-cli/src/commands/scan/policy.rs index 6ce011259..33912308d 100644 --- a/crates/socket-patch-cli/src/commands/scan/policy.rs +++ b/crates/socket-patch-cli/src/commands/scan/policy.rs @@ -53,6 +53,42 @@ pub(crate) struct InvocationPolicy { pub scanned_dirs: std::sync::OnceLock>, } +impl InvocationPolicy { + /// The project at `root_dir` as the policy names it (its path below + /// the repository root), and whether the policy admits it as a whole. + fn root_verdict( + &self, + root_dir: &Path, + explicit: bool, + global: bool, + ) -> (String, Result<(), FilterReason>) { + let root_dir = std::fs::canonicalize(root_dir).unwrap_or_else(|_| root_dir.to_path_buf()); + let project = repo_relative_checked(&self.repo_root, &root_dir).unwrap_or_default(); + let verdict = if global { + Ok(()) + } else { + let markers = dir_markers(&root_dir); + self.policy.admits_root(&Root { + rel_dir: &project, + markers: &markers, + explicit, + }) + }; + (project, verdict) + } + + /// Whether the scan of the project at `root_dir` may ask the patch + /// service about a package: the policy admits the project as a whole + /// and the package. What [`ScanPolicy::for_root`] and + /// [`ScanPolicy::admit_crawled`] decide for a scan, without their + /// report, for the read made ahead of the scans: a package the + /// policy leaves out is not asked about there either. + pub(crate) fn asks_about(&self, root_dir: &Path, explicit: bool) -> impl Fn(&str) -> bool + '_ { + let admitted = self.root_verdict(root_dir, explicit, false).1.is_ok(); + move |purl| admitted && self.policy.admits_purl(purl).is_ok() + } +} + /// Load the policy for `args` (4.5): `--global` scans have no repo and read /// no file; everything else reads the repo root's socket.yml. The /// invocation's selection filter narrows either. @@ -166,18 +202,7 @@ impl ScanPolicy { explicit: bool, global: bool, ) -> Self { - let root_dir = std::fs::canonicalize(root_dir).unwrap_or_else(|_| root_dir.to_path_buf()); - let project = repo_relative_checked(&invocation.repo_root, &root_dir).unwrap_or_default(); - let root_verdict = if global { - Ok(()) - } else { - let markers = dir_markers(&root_dir); - invocation.policy.admits_root(&Root { - rel_dir: &project, - markers: &markers, - explicit, - }) - }; + let (project, root_verdict) = invocation.root_verdict(root_dir, explicit, global); let mut warnings = invocation.warnings.clone(); if !invocation.policy.enabled() { warnings.push(PolicyWarning { diff --git a/crates/socket-patch-cli/src/commands/scan/render.rs b/crates/socket-patch-cli/src/commands/scan/render.rs index 962b48366..109184961 100644 --- a/crates/socket-patch-cli/src/commands/scan/render.rs +++ b/crates/socket-patch-cli/src/commands/scan/render.rs @@ -1,5 +1,6 @@ -//! Pure text builders for `scan`'s human output: the results table, the -//! summary lines, the dry-run line, the per-patch preview, and the hints. +//! Pure text builders for `scan`'s human output: the status notes, the +//! dry-run line, the `--verbose` per-patch preview, and the hints. The +//! rows and the closing totals are `report`'s. //! No I/O and no terminal state (color is decided by the caller and passed //! in), so every string is unit-testable byte for byte. @@ -8,34 +9,13 @@ use std::collections::HashMap; use socket_patch_core::api::types::{PatchSearchResult, VulnerabilityResponse}; use crate::args::GlobalArgs; -use crate::ui::{self, plural, Align}; +use crate::ui::{self, plural}; use socket_patch_core::api::ranking::severity_order; -/// Visible widths of the table's PATCHES and SEVERITY columns. -pub(super) const PATCHES_COL: usize = 8; -pub(super) const SEVERITY_COL: usize = 16; -/// The PACKAGE column grows to the longest PURL, up to this many columns; -/// longer PURLs are middle-elided (keeping `@version`). -pub(super) const MAX_PURL_COL: usize = 60; -/// Vulnerability ids shown per table row before `(+N)` (unless `--verbose`). -const VULN_IDS_SHOWN: usize = 2; /// Per-patch preview limits for API free text (unless `--verbose`). const SUMMARY_MAX: usize = 76; const DESCRIPTION_MAX: usize = 72; -const HEADER_PACKAGE: &str = "PACKAGE"; - -/// Width of the PACKAGE column for these (display) PURLs: the longest, -/// never narrower than the header and never wider than [`MAX_PURL_COL`]. -pub(super) fn purl_col_width<'a>(purls: impl IntoIterator) -> usize { - purls - .into_iter() - .map(|p| p.chars().count()) - .max() - .unwrap_or(0) - .clamp(HEADER_PACKAGE.len(), MAX_PURL_COL) -} - /// Fit a PURL into `max` characters, keeping the `@version` (and any /// `?qualifiers`) tail and eliding the middle of the name: /// `pkg:npm/@typescript-eslint/typescript-estree@6.0.0` at 40 becomes @@ -73,158 +53,7 @@ pub(super) fn elide_purl(purl: &str, max: usize) -> String { format!("{head}{DOTS}{end}{tail}") } -/// The table's column header, aligned like [`table_row`]. -pub(super) fn table_header(purl_w: usize) -> String { - table_row( - purl_w, - HEADER_PACKAGE, - "PATCHES", - "SEVERITY", - "VULNERABILITIES", - "", - ) -} - -/// One table row. Cells may carry color: padding counts visible -/// characters only, so colored and plain rows line up. `count` is -/// right-aligned; `markers` (`[UPDATE]`, ...) trail the vulnerabilities. -pub(super) fn table_row( - purl_w: usize, - purl: &str, - count: &str, - severity: &str, - vulns: &str, - markers: &str, -) -> String { - format!( - "{} {} {} {vulns}{markers}", - ui::pad(purl, purl_w, Align::Left), - ui::pad(count, PATCHES_COL, Align::Right), - ui::pad(severity, SEVERITY_COL, Align::Left), - ) -} - -/// The `=` rule above and below the table: as wide as its widest line, -/// capped at `cap` columns (the terminal width) so it never wraps. -pub(super) fn ruler<'a>(lines: impl IntoIterator, cap: Option) -> String { - let widest = lines.into_iter().map(ui::visible_width).max().unwrap_or(0); - let width = cap.map_or(widest, |c| widest.min(c)).max(1); - "=".repeat(width) -} - -/// The VULNERABILITIES cell: the first two ids plus `(+N)` for the rest of -/// `vulns.count`, every id under `--verbose`, `-` when there are none. -pub(super) fn vuln_cell(vulns: &super::discovery::VulnIds, verbose: bool) -> String { - if verbose { - return if vulns.all.is_empty() { - "-".to_string() - } else { - vulns.all.join(", ") - }; - } - let shown = &vulns.primary[..vulns.primary.len().min(VULN_IDS_SHOWN)]; - let extra = vulns.count.saturating_sub(shown.len()); - match (shown.is_empty(), extra) { - (true, 0) => "-".to_string(), - (true, n) => format!("(+{n})"), - (false, 0) => shown.join(", "), - (false, n) => format!("{} (+{n})", shown.join(", ")), - } -} - -/// Advisory ids one list of a coverage line names before `(+N more)` -/// (unless `--verbose`). -const COVERAGE_IDS_SHOWN: usize = 8; - -fn coverage_ids(ids: &[String], verbose: bool) -> String { - if verbose || ids.len() <= COVERAGE_IDS_SHOWN { - return ids.join(", "); - } - format!( - "{} (+{} more)", - ids[..COVERAGE_IDS_SHOWN].join(", "), - ids.len() - COVERAGE_IDS_SHOWN - ) -} - -/// The lines under a mode's result line, one per patched package: the -/// advisories its patch fixes and the ones it leaves unpatched (other -/// patches of the package name them, and only one is applied). A closing -/// line says why and what fixes them when any package keeps one. `dry_run` -/// puts it in the future tense. A package whose patches name no advisory -/// gets no line; `color` highlights what stays unpatched. -pub(crate) fn coverage_lines( - coverage: &[&super::discovery::AdvisoryCoverage], - dry_run: bool, - verbose: bool, - color: bool, -) -> Vec { - let (fixes, stays) = if dry_run { - ("would fix", "would stay unpatched") - } else { - ("fixes", "still unpatched") - }; - let mut lines = Vec::new(); - let mut incomplete = 0usize; - for c in coverage { - if c.fixes.is_empty() && c.unpatched.is_empty() { - continue; - } - let mut line = format!( - " {}: ", - socket_patch_core::utils::purl::normalize_purl(&c.purl) - ); - if c.fixes.is_empty() { - line.push_str("its patch names no advisory"); - } else { - line.push_str(&format!("{fixes} {}", coverage_ids(&c.fixes, verbose))); - } - if !c.unpatched.is_empty() { - incomplete += 1; - let rest = format!("{stays}: {}", coverage_ids(&c.unpatched, verbose)); - line.push_str(&format!("; {}", ui::paint(&rest, "33", color))); - } - lines.push(line); - } - if incomplete > 0 { - lines.push(format!( - "Only one patch is applied per package version. Upgrade {} to fix the advisories \ - still unpatched.", - if incomplete == 1 { - "the package" - } else { - "those packages" - } - )); - } - lines -} - -/// The line under the table: how many packages have patches and how many -/// of those patches this account can download. -pub(super) fn summary_line(packages: usize, patches: usize, all_accessible: bool) -> String { - let kind = if all_accessible { - ("available patch", "available patches") - } else { - ("free patch", "free patches") - }; - format!( - "Summary: {} with {}", - plural(packages, "package", "packages"), - plural(patches, kind.0, kind.1) - ) -} - -/// The indented follow-up to [`summary_line`] for free accounts. -pub(super) fn paid_extra_line(paid: usize) -> String { - let verb = if paid == 1 { "is" } else { "are" }; - format!( - " + {} {verb} available with a paid Socket plan", - plural(paid, "additional patch", "additional patches") - ) -} - -/// How many table rows carry `[UPDATE]`. +/// How many packages have a newer patch than the one the project records. pub(super) fn updates_line(n: usize) -> String { if n == 1 { "1 package has a newer patch available.".to_string() @@ -281,13 +110,14 @@ pub(crate) fn no_packages_message( /// found: `declared` packages the project patches itself, and `unreadable` /// ones held back only because a project file could not be read. A broken /// file is fixed, not overridden, so only the first line names -/// `--allow-patch-conflicts`. +/// `--allow-patch-conflicts`. The notice above +/// ([`project_patch_notice`]) names the files and the packages. pub(crate) fn user_patch_withheld_lines(declared: usize, unreadable: usize) -> Vec { let mut lines = Vec::new(); if unreadable > 0 { lines.push(format!( "{} not scanned: this project's own patches could not be checked (see the \ - warnings). Fix the file they name and run again.", + warning). Fix the file it names and run again.", plural(unreadable, "package was", "packages were") )); } @@ -298,14 +128,173 @@ pub(crate) fn user_patch_withheld_lines(declared: usize, unreadable: usize) -> V ("were", "them") }; lines.push(format!( - "{} protected by this project's own patches and {was} not scanned (see the \ - warnings). Pass --allow-patch-conflicts to scan {them} anyway.", + "{} protected by this project's own patches and {was} not scanned. Pass \ + --allow-patch-conflicts to scan {them} anyway.", plural(declared, "package is", "packages are") )); } lines } +/// A package the project's own patches cover, as the scan's consent gate +/// found it. +pub(crate) struct Protected { + pub purl: String, + /// The project files that cover it. + pub sources: Vec, + /// Covered only because one of those files could not be read or + /// parsed: nothing the project is known to declare. + pub unreadable: bool, +} + +/// How many packages, and how many files, a project-patch notice names +/// before it folds the rest. +const PROTECTED_NAMED: usize = 3; + +/// The scan's notice of the packages the project's own patches cover: one +/// short block per kind, where there used to be a warning per package (a +/// project file that cannot be read covers every package of its +/// ecosystem, so that was a warning per installed package). +/// +/// - Left alone because the project declares a patch or replacement for +/// them: a `Note:`, the steady state of a project that patches a few +/// dependencies itself. +/// - Left alone because a project file could not be read: a `Warning:` +/// that says to fix the file. +/// - Not left alone, under `--allow-patch-conflicts` (`allowed`): a +/// `Warning:` to review the result. +/// +/// Each names the files (relative to `cwd`) and the first few packages; +/// `--verbose` lists every package under its block with its own files. +pub(crate) fn project_patch_notice( + protected: &[Protected], + allowed: bool, + verbose: bool, + cwd: &std::path::Path, +) -> Vec { + let mut lines = Vec::new(); + if allowed { + let group: Vec<&Protected> = protected.iter().collect(); + notice_block(&mut lines, &group, Kind::Allowed, verbose, cwd); + } else { + let (unreadable, declared): (Vec<&Protected>, Vec<&Protected>) = + protected.iter().partition(|p| p.unreadable); + notice_block(&mut lines, &unreadable, Kind::Unreadable, verbose, cwd); + notice_block(&mut lines, &declared, Kind::Declared, verbose, cwd); + } + lines +} + +/// Which block of [`project_patch_notice`] a group of packages gets. +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Declared, + Unreadable, + Allowed, +} + +/// A project file as the notice names it: relative to `cwd` when it is +/// below it. A source may carry a reason after the path +/// (`package.json (not valid JSON: ...)`), which stays. +fn shown_source(source: &str, cwd: &std::path::Path) -> String { + let base = cwd.to_string_lossy(); + source + .strip_prefix(base.as_ref()) + .and_then(|rest| rest.strip_prefix(['/', '\\'])) + .filter(|rest| !rest.is_empty()) + .unwrap_or(source) + .to_string() +} + +fn notice_block( + lines: &mut Vec, + group: &[&Protected], + kind: Kind, + verbose: bool, + cwd: &std::path::Path, +) { + use socket_patch_core::utils::purl::canonical_purl; + use std::collections::{BTreeMap, BTreeSet}; + + // One entry per package: a crawl finds a release once per installed + // copy. + let mut packages: BTreeMap> = BTreeMap::new(); + for package in group { + packages + .entry(canonical_purl(&package.purl)) + .or_default() + .extend(package.sources.iter().map(|s| shown_source(s, cwd))); + } + if packages.is_empty() { + return; + } + let names = ui::package_names(&packages.keys().map(String::as_str).collect::>()); + let sources: Vec = packages + .values() + .flatten() + .cloned() + .collect::>() + .into_iter() + .collect(); + let files = ui::folded(&sources, PROTECTED_NAMED); + let count = plural(names.len(), "package", "packages"); + let (it, lists) = if names.len() == 1 { + ("it", "") + } else { + ("them", "; --verbose lists them all") + }; + // Every name fits, or `--verbose` lists them below: the fold is for + // the long lists only. + let named = if verbose && names.len() > PROTECTED_NAMED { + String::new() + } else { + format!(": {}", ui::folded(&names, PROTECTED_NAMED)) + }; + let more = if names.len() > PROTECTED_NAMED && !verbose { + lists + } else { + "" + }; + match kind { + Kind::Declared => { + lines.push(format!( + "Note: skipped {count} covered by this project's own patches ({files}){named}." + )); + lines.push(format!(" --allow-patch-conflicts patches {it} too{more}.")); + } + Kind::Unreadable => { + let fix = if sources.len() == 1 { + "that file" + } else { + "those files" + }; + lines.push(format!( + "Warning: {count} not patched, because this project's own patches could not \ + be checked: {files}. Fix {fix} and run again." + )); + } + Kind::Allowed => { + lines.push(format!( + "Warning: --allow-patch-conflicts: {count} covered by this project's own \ + patches ({files}) may get a Socket patch too{named}. Review and test the \ + combined result." + )); + } + } + if verbose && names.len() > PROTECTED_NAMED { + for (name, own) in names.iter().zip(packages.values()) { + // A package's files are worth a line's width only where they + // are not the block's. + if own.len() == sources.len() { + lines.push(format!(" {name}")); + } else { + let own: Vec = own.iter().cloned().collect(); + lines.push(format!(" {name} ({})", own.join(", "))); + } + } + } +} + /// What a bare scan's search for project directories left out, one line /// each: roots under an ignored path, and a walk that gave up. /// `filter_paths`: the run's selection filter skips roots by path too (and @@ -467,8 +456,9 @@ pub(super) fn unwired_vendored_detail(purls: &[String]) -> String { /// What the dry-run line says the run would do. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Plan { - /// Agent mode: download `n` patches and apply them in place. - Apply(usize), + /// Agent mode: download `new` patches and apply them in place, and + /// re-apply the `recorded` ones the manifest already holds. + Apply { new: usize, recorded: usize }, /// Vendored mode: of `total` selected patches, `refused` would be /// refused by the vendored preflight (listed as `[would-refuse]` /// lines) and `in_sync` are held by the ledger at this uuid (listed as @@ -488,7 +478,13 @@ pub(super) enum Plan { /// to vendor either (#1850). pub(super) fn dry_run_line(plan: Plan) -> String { let what = match plan { - Plan::Apply(n) => format!("download and apply {}", plural(n, "patch", "patches")), + Plan::Apply { new, recorded: 0 } => { + format!("download and apply {}", plural(new, "patch", "patches")) + } + Plan::Apply { new, recorded } => format!( + "download and apply {} and re-apply {recorded} already recorded", + plural(new, "patch", "patches") + ), Plan::Vendor { total, refused, @@ -565,6 +561,28 @@ pub(super) fn not_installed_skip_line(purl: &str) -> String { ) } +/// How many not-installed packages [`not_installed_skip_lines`] names one +/// per line; past it they share one line that names this many. +const NOT_INSTALLED_NAMED: usize = 3; + +/// The `[skip]` lines for the lockfile-only packages an agent-mode scan +/// leaves out: one [`not_installed_skip_line`] each, or (past three of +/// them, unless `--verbose`) one line for them all. A fresh clone locks +/// every package and installs none, and the remedy is the same for each. +pub(super) fn not_installed_skip_lines(purls: &[String], verbose: bool) -> Vec { + if verbose || purls.len() <= NOT_INSTALLED_NAMED { + return purls.iter().map(|p| not_installed_skip_line(p)).collect(); + } + vec![format!( + " [skip] {} with patches are not installed ({}, +{} more); run your package \ + manager's install first, or `socket-patch scan --mode vendored` to vendor them from \ + the lockfile", + plural(purls.len(), "package", "packages"), + purls[..NOT_INSTALLED_NAMED].join(", "), + purls.len() - NOT_INSTALLED_NAMED, + )] +} + /// Line for a selection the manifest already records: `[re-apply]` on a /// wet agent run (the nested apply re-applies it), `[skip]` in a preview. pub(super) fn already_recorded_line(purl: &str, uuid: &str, reapply: bool) -> String { @@ -792,17 +810,6 @@ mod tests { // ---- table ------------------------------------------------------------ - #[test] - fn purl_col_width_tracks_longest_within_bounds() { - assert_eq!(purl_col_width([]), HEADER_PACKAGE.len()); - assert_eq!(purl_col_width(["a"]), HEADER_PACKAGE.len()); - assert_eq!(purl_col_width(["pkg:npm/minimist@1.2.5"]), 22); - let long = "x".repeat(100); - assert_eq!(purl_col_width([long.as_str()]), MAX_PURL_COL); - // Chars, not bytes. - assert_eq!(purl_col_width(["pkg:npm/日本語@1.0.0"]), 17); - } - #[test] fn elide_purl_keeps_version() { let purl = "pkg:npm/@typescript-eslint/typescript-estree@6.0.0"; @@ -841,132 +848,8 @@ mod tests { assert_eq!(out.chars().count(), 30); } - #[test] - fn table_colored_and_plain_rows_align_identically() { - let w = 24; - let vulns_at = w + 2 + PATCHES_COL + 2 + SEVERITY_COL + 2; - let header = table_header(w); - assert_eq!(header.find("VULNERABILITIES"), Some(vulns_at)); - assert_eq!( - header.find("PATCHES").map(|i| i + "PATCHES".len()), - Some(w + 2 + PATCHES_COL) - ); - let row = |on: bool, sev: &str, paid: bool| { - let count = if paid { - format!("0+{}", ui::paint("2", "33", on)) - } else { - "1".to_string() - }; - table_row( - w, - "pkg:npm/minimist@1.2.5", - &count, - &ui::severity(sev, on), - "CVE-2021-44906", - &ui::paint(" [UPDATE]", "33", on), - ) - }; - for sev in ["CRITICAL", "HIGH", "MODERATE", "LOW", "unknown"] { - for paid in [false, true] { - let plain = row(false, sev, paid); - assert_eq!(ui::strip_ansi(&row(true, sev, paid)), plain); - assert_eq!(plain.find("CVE-"), Some(vulns_at), "{plain:?}"); - assert!(plain.ends_with("CVE-2021-44906 [UPDATE]"), "{plain:?}"); - let count_end = w + 2 + PATCHES_COL; - let want = if paid { "0+2" } else { "1" }; - assert_eq!(&plain[count_end - want.len()..count_end], want); - } - } - } - - #[test] - fn table_row_exact_string() { - assert_eq!( - table_row(10, "pkg:a@1", "1", "HIGH", "CVE-1", " [UPDATE]"), - "pkg:a@1 1 HIGH CVE-1 [UPDATE]" - ); - } - - #[test] - fn ruler_fits_widest_line_and_cap() { - assert_eq!(ruler(["abc", "abcdef"], None), "======"); - assert_eq!(ruler(["abc", "abcdef"], Some(4)), "===="); - assert_eq!(ruler(["\x1b[31mab\x1b[0m"], None), "=="); - assert_eq!(ruler([], None), "="); - } - - fn vids(primary: &[&str], all: &[&str], count: usize) -> super::super::discovery::VulnIds { - super::super::discovery::VulnIds { - primary: primary.iter().map(|s| s.to_string()).collect(), - all: all.iter().map(|s| s.to_string()).collect(), - count, - } - } - - #[test] - fn vuln_cell_caps_unless_verbose() { - let four = ["CVE-1", "CVE-2", "CVE-3", "CVE-4"]; - assert_eq!( - vuln_cell(&vids(&four, &four, 4), false), - "CVE-1, CVE-2 (+2)" - ); - assert_eq!( - vuln_cell(&vids(&four, &four, 4), true), - "CVE-1, CVE-2, CVE-3, CVE-4" - ); - assert_eq!( - vuln_cell(&vids(&four[..2], &four[..2], 2), false), - "CVE-1, CVE-2" - ); - assert_eq!(vuln_cell(&vids(&four[..1], &four[..1], 1), false), "CVE-1"); - assert_eq!(vuln_cell(&vids(&[], &[], 0), false), "-"); - assert_eq!(vuln_cell(&vids(&[], &[], 0), true), "-"); - } - - #[test] - fn vuln_cell_counts_vulnerabilities_not_ids() { - // 1 CVE + its alias + a GHSA-only advisory: two vulnerabilities. - let v = vids(&["CVE-1"], &["CVE-1", "GHSA-a", "GHSA-b"], 2); - assert_eq!(vuln_cell(&v, false), "CVE-1 (+1)"); - assert_eq!(vuln_cell(&v, true), "CVE-1, GHSA-a, GHSA-b"); - let v = vids(&["CVE-1", "CVE-2", "GHSA-c"], &[], 5); - assert_eq!(vuln_cell(&v, false), "CVE-1, CVE-2 (+3)"); - } - // ---- summary lines ------------------------------------------------------- - #[test] - fn summary_line_singular_and_plural() { - assert_eq!( - summary_line(1, 1, true), - "Summary: 1 package with 1 available patch" - ); - assert_eq!( - summary_line(2, 4, true), - "Summary: 2 packages with 4 available patches" - ); - assert_eq!( - summary_line(1, 0, false), - "Summary: 1 package with 0 free patches" - ); - assert_eq!( - summary_line(3, 1, false), - "Summary: 3 packages with 1 free patch" - ); - } - - #[test] - fn paid_extra_line_agrees_in_number() { - assert_eq!( - paid_extra_line(1), - " + 1 additional patch is available with a paid Socket plan" - ); - assert_eq!( - paid_extra_line(3), - " + 3 additional patches are available with a paid Socket plan" - ); - } - #[test] fn updates_line_agrees_in_number() { assert_eq!(updates_line(1), "1 package has a newer patch available."); @@ -1090,9 +973,22 @@ mod tests { #[test] fn dry_run_line_counts_refusals() { assert_eq!( - dry_run_line(Plan::Apply(1)), + dry_run_line(Plan::Apply { + new: 1, + recorded: 0 + }), "[dry-run] Would download and apply 1 patch. No changes made." ); + // The rows under the line also list a recorded patch the wet run + // re-applies: the line says so, so the two counts add up. + assert_eq!( + dry_run_line(Plan::Apply { + new: 5, + recorded: 1 + }), + "[dry-run] Would download and apply 5 patches and re-apply 1 already recorded. No \ + changes made." + ); assert_eq!( dry_run_line(vendor(2, 0, 0)), "[dry-run] Would download and vendor 2 patches. No changes made." @@ -1121,104 +1017,154 @@ mod tests { ); } - fn coverage( - purl: &str, - fixes: &[&str], - unpatched: &[&str], - ) -> crate::commands::scan::discovery::AdvisoryCoverage { - let strs = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::>(); - crate::commands::scan::discovery::AdvisoryCoverage { + #[test] + fn user_patch_withheld_lines_separate_broken_files_from_declared_patches() { + assert_eq!( + user_patch_withheld_lines(0, 2), + [ + "2 packages were not scanned: this project's own patches could not be checked \ + (see the warning). Fix the file it names and run again." + ] + ); + assert_eq!( + user_patch_withheld_lines(3, 0), + [ + "3 packages are protected by this project's own patches and were not scanned. \ + Pass --allow-patch-conflicts to scan them anyway." + ] + ); + let both = user_patch_withheld_lines(1, 1); + assert_eq!(both.len(), 2); + assert!( + both[0].starts_with("1 package was not scanned: "), + "{both:?}" + ); + assert!( + both[1].starts_with("1 package is protected by this project's own patches and was "), + "{both:?}" + ); + assert!(user_patch_withheld_lines(0, 0).is_empty()); + } + + fn protected(purl: &str, sources: &[&str], unreadable: bool) -> Protected { + Protected { purl: purl.to_string(), - uuids: vec!["u".to_string()], - fixes: strs(fixes), - unpatched: strs(unpatched), - fixed_ids: strs(fixes), - unfixed_ids: strs(unpatched), + sources: sources.iter().map(|s| s.to_string()).collect(), + unreadable, } } + /// The reported flood: one long warning per package the project + /// patches itself. They are one note now: the count, the files, the + /// first few names, and the flag. #[test] - fn coverage_lines_name_fixed_and_unpatched_advisories_per_package() { - let complete = coverage("pkg:npm/%40scope/a@1.0.0", &["CVE-1"], &[]); - let partial = coverage("pkg:pypi/urllib3@1.26.18", &["CVE-2"], &["CVE-3", "CVE-4"]); - let silent = coverage("pkg:npm/b@1.0.0", &[], &[]); - let unnamed = coverage("pkg:npm/c@1.0.0", &[], &["CVE-5"]); - // Every advisory fixed: one line, no closing note. A package whose - // patches name no advisory has nothing to say. + fn project_patch_notice_is_one_block_not_a_warning_per_package() { + let cwd = std::path::Path::new("/work/app"); + let lock = "/work/app/pnpm-lock.yaml"; + let workspace = "/work/app/pnpm-workspace.yaml"; + let few = [ + protected("pkg:npm/next-auth@4.24.15", &[lock, workspace], false), + // A second installed copy of the same release is the same + // package. + protected("pkg:npm/next-auth@4.24.15", &[lock, workspace], false), + protected("pkg:npm/%40rmp135/sql-ts@1.18.1", &[workspace], false), + ]; assert_eq!( - coverage_lines(&[&complete, &silent], false, false, false), - [" pkg:npm/@scope/a@1.0.0: fixes CVE-1"] + project_patch_notice(&few, false, false, cwd), + [ + "Note: skipped 2 packages covered by this project's own patches \ + (pnpm-lock.yaml, pnpm-workspace.yaml): @rmp135/sql-ts@1.18.1, \ + next-auth@4.24.15.", + " --allow-patch-conflicts patches them too.", + ] ); assert_eq!( - coverage_lines(&[&complete, &partial], false, false, false), + project_patch_notice(&few[..1], false, false, cwd), [ - " pkg:npm/@scope/a@1.0.0: fixes CVE-1", - " pkg:pypi/urllib3@1.26.18: fixes CVE-2; still unpatched: CVE-3, CVE-4", - "Only one patch is applied per package version. Upgrade the package to fix \ - the advisories still unpatched.", + "Note: skipped 1 package covered by this project's own patches \ + (pnpm-lock.yaml, pnpm-workspace.yaml): next-auth@4.24.15.", + " --allow-patch-conflicts patches it too.", ] ); - // A dry run says it in the future tense; the note is for both - // packages. + + let many: Vec = (0..33) + .map(|i| protected(&format!("pkg:npm/dep-{i:02}@1.0.0"), &[workspace], false)) + .collect(); assert_eq!( - coverage_lines(&[&partial, &unnamed], true, false, false), + project_patch_notice(&many, false, false, cwd), [ - " pkg:pypi/urllib3@1.26.18: would fix CVE-2; would stay unpatched: CVE-3, CVE-4", - " pkg:npm/c@1.0.0: its patch names no advisory; would stay unpatched: CVE-5", - "Only one patch is applied per package version. Upgrade those packages to \ - fix the advisories still unpatched.", + "Note: skipped 33 packages covered by this project's own patches \ + (pnpm-workspace.yaml): dep-00@1.0.0, dep-01@1.0.0, dep-02@1.0.0 and 30 more.", + " --allow-patch-conflicts patches them too; --verbose lists them all.", ] ); - assert!(coverage_lines(&[], false, false, false).is_empty()); - } - - #[test] - fn coverage_lines_bound_a_long_id_list_unless_verbose() { - let ids: Vec = (1..=11).map(|i| format!("CVE-2024-{i:04}")).collect(); - let ids: Vec<&str> = ids.iter().map(String::as_str).collect(); - let many = coverage("pkg:npm/a@1.0.0", &["CVE-1"], &ids); - let line = &coverage_lines(&[&many], false, false, false)[0]; - assert!( - line.ends_with("CVE-2024-0007, CVE-2024-0008 (+3 more)"), - "{line}" + // `--verbose` lists every one, each with its own files. + let verbose = project_patch_notice(&many, false, true, cwd); + assert_eq!(verbose.len(), 2 + 33, "{verbose:#?}"); + assert_eq!( + verbose[..3], + [ + "Note: skipped 33 packages covered by this project's own patches \ + (pnpm-workspace.yaml).", + " --allow-patch-conflicts patches them too.", + " dep-00@1.0.0", + ] ); - let line = &coverage_lines(&[&many], false, true, false)[0]; - assert!(line.ends_with("CVE-2024-0010, CVE-2024-0011"), "{line}"); - // Color wraps only the unpatched clause. - let line = &coverage_lines(&[&many], false, true, true)[0]; - assert!( - line.starts_with(" pkg:npm/a@1.0.0: fixes CVE-1; \u{1b}[33mstill unpatched: "), - "{line:?}" + // A package says which files cover it where they are not all of + // the block's. + let mut uneven = many; + uneven[1].sources.push(lock.to_string()); + let verbose = project_patch_notice(&uneven, false, true, cwd); + assert_eq!( + verbose[2..5], + [ + " dep-00@1.0.0 (pnpm-workspace.yaml)", + " dep-01@1.0.0", + " dep-02@1.0.0 (pnpm-workspace.yaml)", + ] ); + assert!(project_patch_notice(&[], false, false, cwd).is_empty()); } + /// A file that could not be read is a warning of its own, with the + /// reason and the remedy, and it never offers the override. Under the + /// override everything is one warning to review the result. Packages of + /// two ecosystems are named by purl, and a file outside `--cwd` by its + /// whole path. #[test] - fn user_patch_withheld_lines_separate_broken_files_from_declared_patches() { + fn project_patch_notice_separates_unreadable_files_and_the_override() { + let cwd = std::path::Path::new("/work/app"); + let broken = "/work/app/package.json (not valid JSON: expected value at line 1)"; + let mixed = [ + protected("pkg:npm/a@1.0.0", &[broken], true), + protected("pkg:npm/b@2.0.0", &[broken], true), + protected("pkg:cargo/serde@1.0.0", &["/work/Cargo.toml"], false), + protected( + "pkg:npm/c@3.0.0", + &["/work/app/patches/c+3.0.0.patch"], + false, + ), + ]; assert_eq!( - user_patch_withheld_lines(0, 2), + project_patch_notice(&mixed, false, false, cwd), [ - "2 packages were not scanned: this project's own patches could not be checked \ - (see the warnings). Fix the file they name and run again." + "Warning: 2 packages not patched, because this project's own patches could \ + not be checked: package.json (not valid JSON: expected value at line 1). Fix \ + that file and run again.", + "Note: skipped 2 packages covered by this project's own patches \ + (/work/Cargo.toml, patches/c+3.0.0.patch): pkg:cargo/serde@1.0.0, \ + pkg:npm/c@3.0.0.", + " --allow-patch-conflicts patches them too.", ] ); assert_eq!( - user_patch_withheld_lines(3, 0), + project_patch_notice(&mixed[2..], true, false, cwd), [ - "3 packages are protected by this project's own patches and were not scanned \ - (see the warnings). Pass --allow-patch-conflicts to scan them anyway." + "Warning: --allow-patch-conflicts: 2 packages covered by this project's own \ + patches (/work/Cargo.toml, patches/c+3.0.0.patch) may get a Socket patch too: \ + pkg:cargo/serde@1.0.0, pkg:npm/c@3.0.0. Review and test the combined result.", ] ); - let both = user_patch_withheld_lines(1, 1); - assert_eq!(both.len(), 2); - assert!( - both[0].starts_with("1 package was not scanned: "), - "{both:?}" - ); - assert!( - both[1].starts_with("1 package is protected by this project's own patches and was "), - "{both:?}" - ); - assert!(user_patch_withheld_lines(0, 0).is_empty()); } #[test] diff --git a/crates/socket-patch-cli/src/commands/scan/report.rs b/crates/socket-patch-cli/src/commands/scan/report.rs new file mode 100644 index 000000000..918bf3f0e --- /dev/null +++ b/crates/socket-patch-cli/src/commands/scan/report.rs @@ -0,0 +1,1717 @@ +//! `scan`'s human report: one row per package a run patched, and the +//! closing totals of the whole invocation (`Patched 22 packages in 3 +//! projects, fixing 39 vulnerabilities ...`, what Socket measured about +//! those patches, then what is left to patch). +//! +//! The counts are occurrences: a package patched in three project +//! directories counts three times, and so does each advisory its patch +//! fixes there. A "vulnerability" is one advisory id as the rows show it +//! (a CVE, or the advisory's own id when it has none). +//! +//! Everything that builds text is pure (style and width are passed in), so +//! each line is unit-tested byte for byte. Only [`Run`] prints, and only +//! it talks to the network: on a terminal it asks the patch service what +//! it measured about the selected patches, in the background, while the +//! run does its work. + +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; + +use socket_patch_core::api::client::ApiClient; +use socket_patch_core::api::ranking::{cmp_batch_infos, severity_order}; +use socket_patch_core::api::types::{BatchPackagePatches, PatchSearchResult, PatchStatistics}; +use socket_patch_core::policy::filter::{Reachability, SelectionFilter}; +use socket_patch_core::utils::purl_key::PurlKey; + +use crate::args::GlobalArgs; +use crate::commands::measured::{self, evidence, Measured, Measurement}; +use crate::ui::{self, plural, Style}; + +/// Advisory ids a row names before `(+N)` (unless `--verbose`). +const IDS_SHOWN: usize = 2; +/// Columns of the closing meter. +const METER_CELLS: usize = 40; +/// How long a project directory's rows wait for measurements still on +/// their way once the directory's own work is done. They are a courtesy: +/// past this the rows print without them, and the answers that come in +/// later still count in the closing lines. +const ROWS_WAIT: Duration = Duration::from_millis(400); +/// Most patches whose measurements one request round asks for (a project +/// directory makes two: the likely selection, then what was selected). +const MEASURED_PER_ROUND: usize = 100; +/// How long the closing lines wait for the last measurements. +const CLOSING_WAIT: Duration = Duration::from_millis(1500); +/// The engineering hours one package upgrade is taken to cost, for the +/// closing lines' estimate of the work patching saved: finding a release +/// with the fix, moving to it, getting the build and the tests through +/// everything else that changed in it, and the review. An assumption, not +/// a measurement: the line that uses it says "about" and states it. +const UPGRADE_HOURS: usize = 2; +/// The package column is as wide as the longest name, up to this many +/// columns; a longer name keeps its `@version` and loses its middle. +const MAX_NAME_COL: usize = 44; + +/// One package with a patch on offer, as the report counts and shows it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Package { + /// The package purl as the batch lookup spells it. + pub(crate) purl: String, + /// The patches the run selected for it (one per release variant); + /// empty when none could be selected. + pub(crate) uuids: Vec, + /// The worst severity among the advisories the selection fixes, or + /// among the package's patches when nothing was selected. + pub(crate) severity: Option, + /// The ids to show for what the selection fixes. + pub(crate) fixes: Vec, + /// The ids to show for what it leaves: advisories only the package's + /// other patches fix. Every advisory of a package with no selection. + pub(crate) unpatched: Vec, + /// How many of `fixes` are critical, and how many high. + pub(crate) fixed_critical: usize, + pub(crate) fixed_high: usize, + /// How many of `fixes` / `unpatched` a reachability finding of the + /// run's selection filter marks reachable (0 without a filter). + pub(crate) fixed_reachable: usize, + pub(crate) unpatched_reachable: usize, + /// Every patch of the package needs a paid plan this account lacks. + pub(crate) paid_only: bool, + /// The run patches what the project's lockfile resolves, and the + /// lockfile does not name this package: a copy installed on this + /// machine that the project does not use. It is not the project's to + /// patch, so it is never counted as left. + pub(crate) outside_project: bool, +} + +impl Package { + /// Whether one of the package's selected patches is in `landed`. + fn landed(&self, landed: &HashSet<&str>) -> bool { + self.uuids.iter().any(|uuid| landed.contains(uuid.as_str())) + } + + /// What was measured about the package's selected patch. + fn measured<'a>(&self, measured: &'a Measured) -> Option<&'a PatchStatistics> { + self.uuids.iter().find_map(|uuid| measured.get(uuid)) + } +} + +/// What the detail records say about one advisory id of a package: its +/// worst severity and every id it is known by (itself, its CVEs, the +/// advisory they alias). +#[derive(Default)] +struct IdFacts<'a> { + severity: Option<&'a str>, + aliases: Vec<&'a str>, +} + +/// The facts of every advisory id `records` name, by the id uppercased. +fn id_facts<'a>(records: &[&'a PatchSearchResult]) -> HashMap> { + let mut facts: HashMap> = HashMap::new(); + for record in records { + for (advisory, vuln) in &record.vulnerabilities { + let group: Vec<&str> = std::iter::once(advisory.as_str()) + .chain(vuln.cves.iter().map(String::as_str)) + .collect(); + for id in &group { + let entry = facts.entry(id.to_ascii_uppercase()).or_default(); + let worse = entry.severity.is_none_or(|known| { + severity_order(Some(&vuln.severity)) < severity_order(Some(known)) + }); + if worse { + entry.severity = Some(vuln.severity.as_str()); + } + for alias in &group { + if !entry.aliases.contains(alias) { + entry.aliases.push(alias); + } + } + } + } + } + facts +} + +/// The report's view of every package in `packages` (the batch lookup's +/// packages with patches, in its order). `selected` is the patch the run +/// chose for each package that got one, `records` every patch record the +/// run fetched (they pair an advisory with its CVEs and its severity), and +/// `filter` the run's selection filter, whose reachability findings mark +/// advisories reachable. `in_project` says whether the project the run +/// patches uses a package (see [`Package::outside_project`]). +pub(crate) fn plan( + packages: &[BatchPackagePatches], + selected: &[PatchSearchResult], + records: &[&PatchSearchResult], + can_access_paid_patches: bool, + filter: Option<&SelectionFilter>, + in_project: &dyn Fn(&str) -> bool, +) -> Vec { + fn by_package<'a>( + patches: &[&'a PatchSearchResult], + ) -> HashMap> { + let mut map: HashMap> = HashMap::new(); + for patch in patches { + map.entry(PurlKey::new(&patch.purl)) + .or_default() + .push(patch); + } + map + } + let selected: Vec<&PatchSearchResult> = selected.iter().collect(); + let selected_of = by_package(&selected); + let records_of = by_package(records); + let filter = filter.filter(|f| f.has_findings()); + packages + .iter() + .map(|pkg| { + let key = PurlKey::new(&pkg.purl); + let chosen = selected_of.get(&key).map_or(&[][..], Vec::as_slice); + let coverage = super::discovery::package_coverage(pkg, chosen); + // The selection's own records come first: they are the ones + // that say what a fixed id is. + let known: Vec<&PatchSearchResult> = chosen + .iter() + .chain(records_of.get(&key).into_iter().flatten()) + .copied() + .collect(); + let facts = id_facts(&known); + let severity_of = |id: &str| facts.get(&id.to_ascii_uppercase())?.severity; + let reachable = |id: &&String| { + let Some(filter) = filter else { + return false; + }; + let aliases: Vec = match facts.get(&id.to_ascii_uppercase()) { + Some(known) => known.aliases.iter().map(|a| a.to_string()).collect(), + None => vec![id.to_string()], + }; + filter.reachability(&pkg.purl, &aliases) == Some(Reachability::Reachable) + }; + let fixed_at = |rank: u8| { + coverage + .fixes + .iter() + .filter(|id| severity_of(id).is_some_and(|s| severity_order(Some(s)) == rank)) + .count() + }; + // The severity of what the selection fixes: its records' own + // advisories, else what the lookup said of the selected patches + // (of every patch, when none was selected). + let listed = |selected_only: bool| { + pkg.patches + .iter() + .filter(|p| !selected_only || chosen.iter().any(|c| c.uuid == p.uuid)) + .filter_map(|p| p.severity.as_deref()) + .min_by_key(|s| severity_order(Some(s))) + }; + let severity = chosen + .iter() + .flat_map(|p| p.vulnerabilities.values()) + .map(|v| v.severity.as_str()) + .min_by_key(|s| severity_order(Some(s))) + .or_else(|| listed(!chosen.is_empty())); + Package { + purl: pkg.purl.clone(), + severity: severity.map(str::to_string), + fixed_critical: fixed_at(0), + fixed_high: fixed_at(1), + fixed_reachable: coverage.fixes.iter().filter(reachable).count(), + unpatched_reachable: coverage.unpatched.iter().filter(reachable).count(), + paid_only: !can_access_paid_patches + && !pkg.patches.is_empty() + && pkg.patches.iter().all(|p| p.tier != "free"), + outside_project: !in_project(&pkg.purl), + uuids: coverage.uuids, + fixes: coverage.fixes, + unpatched: coverage.unpatched, + } + }) + .collect() +} + +/// What a run did, in the units the closing report counts. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct Counts { + /// Packages whose patch landed (or, on a dry run, would). + pub(crate) patched: usize, + /// Advisories those patches fix, and how many of them are critical, + /// high, and reachable. + pub(crate) fixed: usize, + pub(crate) fixed_critical: usize, + pub(crate) fixed_high: usize, + pub(crate) fixed_reachable: usize, + /// Advisories left on patched packages: only another patch of the + /// package fixes them, and one patch is applied per package version. + pub(crate) left_upgrade: usize, + /// Advisories of packages whose every patch needs a paid plan. + pub(crate) left_paid: usize, + /// Advisories of the other packages the run did not patch. + pub(crate) left_unpatched: usize, + /// How many of the three `left_*` counts are reachable. + pub(crate) left_reachable: usize, + /// Patched packages whose patch was measured, and what the + /// measurements add up to: exploits blocked of those run against the + /// patches, and package tests passing of those run on them. + pub(crate) measured: usize, + pub(crate) exploits_blocked: u64, + pub(crate) exploits: u64, + pub(crate) tests_passing: u64, + pub(crate) tests: u64, + /// Some lookup of the run saw free patches only (the public proxy): + /// "nothing left" then speaks for the free patches alone. + pub(crate) free_only: bool, +} + +impl Counts { + /// The counts of one project directory: `plan` judged by the patches + /// that landed there (`landed`, by uuid). What was measured about + /// them is added once every answer is in ([`Self::verify`]). + pub(crate) fn of(plan: &[Package], landed: &HashSet<&str>) -> Self { + let mut counts = Counts::default(); + for pkg in plan { + if pkg.landed(landed) { + counts.patched += 1; + counts.fixed += pkg.fixes.len(); + counts.fixed_critical += pkg.fixed_critical; + counts.fixed_high += pkg.fixed_high; + counts.fixed_reachable += pkg.fixed_reachable; + counts.left_upgrade += pkg.unpatched.len(); + counts.left_reachable += pkg.unpatched_reachable; + } else if pkg.outside_project { + // Not the project's package: nothing of it is left to + // patch here. + } else { + let advisories = pkg.fixes.len() + pkg.unpatched.len(); + if pkg.paid_only { + counts.left_paid += advisories; + } else { + counts.left_unpatched += advisories; + } + counts.left_reachable += pkg.fixed_reachable + pkg.unpatched_reachable; + } + } + counts + } + + /// Add what was `measured` about the patches of the patched packages + /// (`patched`: each one's selected uuids). + pub(crate) fn verify(&mut self, patched: &[Vec], measured: &Measured) { + for uuids in patched { + let Some(stats) = uuids.iter().find_map(|uuid| measured.get(uuid)) else { + continue; + }; + self.measured += 1; + if let Some(pocs) = stats.pocs { + self.exploits_blocked += pocs.blocked_after.count; + self.exploits += pocs.blocked_after.total; + } + if let Some(tests) = stats.tests { + self.tests_passing += tests.after.count; + self.tests += tests.after.total; + } + } + } + + fn add(&mut self, other: &Counts) { + self.patched += other.patched; + self.fixed += other.fixed; + self.fixed_critical += other.fixed_critical; + self.fixed_high += other.fixed_high; + self.fixed_reachable += other.fixed_reachable; + self.left_upgrade += other.left_upgrade; + self.left_paid += other.left_paid; + self.left_unpatched += other.left_unpatched; + self.left_reachable += other.left_reachable; + } + + /// Advisories with a patch on offer that the run did not fix. + pub(crate) fn left(&self) -> usize { + self.left_upgrade + self.left_paid + self.left_unpatched + } +} + +/// `left` as a share of `fixed + left`, for the closing lines: a whole +/// percentage that never rounds a remainder away (`<1%`) or the fixed +/// part to nothing (`>99%`). `None` when nothing was fixed, where the +/// share says nothing the count does not. +fn percent_left(fixed: usize, left: usize) -> Option { + if fixed == 0 || left == 0 { + return None; + } + let total = fixed + left; + let rounded = (left * 100 + total / 2) / total; + Some(match rounded { + 0 => "<1%".to_string(), + 100 => ">99%".to_string(), + n => format!("{n}%"), + }) +} + +/// How a row names its package: `name@version` when every row of the +/// project is of one ecosystem (the scan line above names it), the full +/// purl otherwise, where a bare name could be either's. +fn display_names(packages: &[&Package]) -> Vec { + let purls: Vec<&str> = packages.iter().map(|p| p.purl.as_str()).collect(); + ui::package_names(&purls) +} + +/// A row's advisory cell at `shown` ids: `CVE-1, CVE-2 (+3)`; every id +/// when `shown` is `None` (`--verbose`); `3 fixed` when there is no room +/// for an id. Empty for a patch that names no advisory. +fn ids_cell(ids: &[String], shown: Option) -> String { + match shown { + None => ids.join(", "), + Some(_) if ids.is_empty() => String::new(), + Some(0) => format!("{} fixed", ids.len()), + Some(n) if ids.len() <= n => ids.join(", "), + Some(n) => format!("{} (+{})", ids[..n].join(", "), ids.len() - n), + } +} + +/// The rows of one project directory: each package of `plan` whose patch +/// is in `landed`, worst severity first, then by name. +/// +/// ```text +/// CRITICAL shell-quote@1.10.0 CVE-2026-102422 exploit blocked, 25/25 tests +/// HIGH undici@8.10.0 CVE-2026-84961, CVE-2026-85024 2 exploits blocked, 35/35 tests 3 unpatched +/// ``` +/// +/// A row names its first two advisory ids and counts the rest, then says +/// what was `measured` about its patch, then how many advisories of the +/// package stay unpatched. On a terminal `cap` columns wide it names +/// fewer ids, and then drops the measurements, rather than wrap. +/// `--verbose` names every id, and lists the unpatched ones on a line of +/// their own. Where the terminal shows one, `style` opens each row of a +/// patch that is in place (`done`) with a check mark; the rows of a dry +/// run and of a report, whose patches are only on offer, keep the column +/// and leave it blank. +pub(crate) fn rows( + plan: &[Package], + landed: &HashSet<&str>, + measured: &Measured, + verbose: bool, + style: Style, + cap: Option, + done: bool, +) -> Vec { + let mut patched: Vec<&Package> = plan.iter().filter(|p| p.landed(landed)).collect(); + if patched.is_empty() { + return Vec::new(); + } + patched.sort_by(|a, b| { + severity_order(a.severity.as_deref()) + .cmp(&severity_order(b.severity.as_deref())) + .then_with(|| a.purl.cmp(&b.purl)) + }); + let color = style.color; + let names = display_names(&patched); + let name_w = names + .iter() + .map(|n| n.chars().count()) + .max() + .unwrap_or(0) + .min(MAX_NAME_COL); + // One spelling whatever the source's (`HIGH` from the service, + // `moderate` from an advisory database). + let severities: Vec = patched + .iter() + .map(|p| p.severity.as_deref().unwrap_or("unknown").to_uppercase()) + .collect(); + let sev_w = severities + .iter() + .map(|s| s.chars().count()) + .max() + .unwrap_or(0); + let evidence: Vec = patched + .iter() + .map(|p| p.measured(measured).map(evidence).unwrap_or_default()) + .collect(); + + // One row: the cells that are there, each padded to its column only + // while a later cell follows it. + let build = |shown: Option, with_evidence: bool| -> Vec { + let ids: Vec = patched + .iter() + .map(|p| ids_cell(&p.fixes, shown)) + .map(|ids| match ids.is_empty() { + true => ids, + false => ui::dim(&ids, color), + }) + .collect(); + // The columns after the name: the ids, then the measurements. One + // that is empty in every row is left out, not left blank. + let columns: Vec<(&[String], usize)> = [Some(&ids), with_evidence.then_some(&evidence)] + .into_iter() + .flatten() + .map(|cells| { + let width = cells.iter().map(|c| ui::visible_width(c)).max(); + (cells.as_slice(), width.unwrap_or(0)) + }) + .filter(|(_, width)| *width > 0) + .collect(); + (0..patched.len()) + .map(|i| { + let mut row = format!( + "{} {} {}", + if done { style.check() } else { " ".to_string() }, + ui::pad(&ui::severity(&severities[i], color), sev_w), + ui::pad(&super::render::elide_purl(&names[i], name_w), name_w), + ); + for (cells, width) in &columns { + row.push_str(" "); + row.push_str(&ui::pad(&cells[i], *width)); + } + if !patched[i].unpatched.is_empty() { + let note = format!("{} unpatched", patched[i].unpatched.len()); + row.push_str(" "); + row.push_str(&ui::paint(¬e, "33", color)); + } + row.trim_end().to_string() + }) + .collect() + }; + + if verbose { + let mut out = Vec::new(); + for (row, pkg) in build(None, true).into_iter().zip(&patched) { + out.push(row); + if !pkg.unpatched.is_empty() { + let rest = format!("still unpatched: {}", pkg.unpatched.join(", ")); + out.push(format!(" {}", ui::paint(&rest, "33", color))); + } + } + return out; + } + let fits = + |rows: &[String]| cap.is_none_or(|cap| rows.iter().all(|row| ui::visible_width(row) < cap)); + // What a narrow terminal gives up, in order: the second id, the + // measurements, then the ids altogether (a count stays). + [(2, true), (1, true), (2, false), (1, false), (0, false)] + .into_iter() + .map(|(shown, with_evidence)| build(Some(shown.min(IDS_SHOWN)), with_evidence)) + .find(|rows| fits(rows)) + // Too narrow even for the counts: the widest form reads best + // wrapped. + .unwrap_or_else(|| build(Some(IDS_SHOWN), true)) +} + +/// The closing meter: how much of what could be patched was, as a bar and +/// a percentage (`━━━━━━──── 63% patched`). Drawn only where the terminal +/// shows glyphs: the sentence above it already says the share. +fn meter(fixed: usize, left: usize, style: Style) -> Option { + if !style.glyphs || fixed == 0 || left == 0 { + return None; + } + let total = fixed + left; + // The share the "left" sentence leaves, so the two always add up. + let percent = 100 - ((left * 100 + total / 2) / total).clamp(1, 99); + let filled = (METER_CELLS * percent / 100).clamp(1, METER_CELLS - 1); + Some(format!( + "{}{} {}", + ui::paint(&"━".repeat(filled), "32", style.color), + ui::paint(&"━".repeat(METER_CELLS - filled), "33", style.color), + ui::dim(&format!("{percent}% patched"), style.color), + )) +} + +/// The closing lines of a run: what it patched, what was measured about +/// those patches, what is left to patch, and (with reachability findings) +/// the last again for the reachable advisories alone. Empty when the run +/// found nothing to count. +/// +/// ```text +/// Patched 22 packages in 3 projects, fixing 39 vulnerabilities (5 critical, 21 high) in 4.2s. +/// Verified: 24 of 24 exploits blocked, 1208 of 1208 package tests passing. +/// Saved about 44 hours of engineering time (22 package upgrades at ~2 hours each). +/// 18 vulnerabilities left to patch (32%): 14 need a package upgrade, 4 are in packages this run did not patch. +/// Reachable: 9 fixed, 2 left to patch (18%). +/// ``` +/// +/// Where the terminal shows glyphs, the lines of what was done open with a +/// check mark (the others are indented to match) and a meter closes them. +pub(crate) fn closing( + counts: &Counts, + projects: usize, + dry_run: bool, + reachability: bool, + elapsed: Option, + style: Style, +) -> Vec { + let left = counts.left(); + if counts.patched == 0 && left == 0 { + return Vec::new(); + } + let color = style.color; + let num = |n: usize, one: &str, many: &str| { + format!( + "{} {}", + ui::bold(&n.to_string(), color), + if n == 1 { one } else { many } + ) + }; + // With glyphs every line has a two-column gutter: a check mark for + // what was done, blank otherwise. + let done = |line: String| { + if style.glyphs && !dry_run { + format!("{} {line}", style.check()) + } else if style.glyphs { + format!(" {line}") + } else { + line + } + }; + let plain = |line: String| { + if style.glyphs { + format!(" {line}") + } else { + line + } + }; + let mut lines = Vec::new(); + if counts.patched > 0 { + let verb = if dry_run { "Would patch" } else { "Patched" }; + let mut line = format!( + "{} {}", + ui::paint(verb, "1;32", color), + num(counts.patched, "package", "packages") + ); + if projects > 1 { + line.push_str(&format!(" in {}", num(projects, "project", "projects"))); + } + if counts.fixed > 0 { + line.push_str(&format!( + ", fixing {}", + num(counts.fixed, "vulnerability", "vulnerabilities") + )); + let mut tiers = Vec::new(); + if counts.fixed_critical > 0 { + tiers.push(format!("{} critical", counts.fixed_critical)); + } + if counts.fixed_high > 0 { + tiers.push(format!("{} high", counts.fixed_high)); + } + if !tiers.is_empty() { + line.push_str(&format!(" ({})", tiers.join(", "))); + } + } + if let Some(elapsed) = elapsed { + line.push_str(&format!(" in {:.1}s", elapsed.as_secs_f64())); + } + line.push('.'); + lines.push(done(line)); + } + // What Socket measured about the patches that landed: the exploits of + // the advisories they fix, run against the patched packages, and the + // packages' own tests, run on them. + let mut verified = Vec::new(); + if counts.exploits > 0 { + verified.push(format!( + "{} of {} blocked", + ui::bold(&counts.exploits_blocked.to_string(), color), + plural(counts.exploits as usize, "exploit", "exploits"), + )); + } + if counts.tests > 0 { + verified.push(format!( + "{} of {} passing", + ui::bold(&counts.tests_passing.to_string(), color), + plural(counts.tests as usize, "package test", "package tests"), + )); + } + if !verified.is_empty() { + let all = + counts.exploits_blocked == counts.exploits && counts.tests_passing == counts.tests; + let mut line = format!("Verified: {}", verified.join(", ")); + if counts.measured < counts.patched { + line.push_str(&format!( + " (measured for {} of {})", + counts.measured, + plural(counts.patched, "patch", "patches") + )); + } + line.push('.'); + lines.push(if all { done(line) } else { plain(line) }); + } + // What the patches stood in for: an upgrade of each patched package, + // in every project it is patched in. An estimate, and it says so. + if counts.patched > 0 { + let hours = counts.patched * UPGRADE_HOURS; + lines.push(plain(format!( + "{} about {} of engineering time ({} at ~{UPGRADE_HOURS} hours{}).", + if dry_run { "Would save" } else { "Saved" }, + num(hours, "hour", "hours"), + plural(counts.patched, "package upgrade", "package upgrades"), + if counts.patched == 1 { "" } else { " each" }, + ))); + } + if left == 0 { + // The public proxy answers for free patches only: what a paid + // plan would fix is unknown there, so the line claims no more than + // the lookup saw. + let nothing = if counts.free_only { + "No free patches left to apply." + } else { + "Nothing left to patch." + }; + lines.push(plain(nothing.to_string())); + } else { + let mut why = Vec::new(); + if counts.left_upgrade > 0 { + why.push(format!( + "{} a package upgrade", + plural(counts.left_upgrade, "needs", "need") + )); + } + if counts.left_paid > 0 { + why.push(format!( + "{} a paid Socket plan", + plural(counts.left_paid, "needs", "need") + )); + } + if counts.left_unpatched > 0 { + why.push(format!( + "{} in packages {}", + plural(counts.left_unpatched, "is", "are"), + if dry_run { + "a run would not patch" + } else { + "this run did not patch" + }, + )); + } + let share = percent_left(counts.fixed, left) + .map(|p| format!(" ({p})")) + .unwrap_or_default(); + lines.push(plain(format!( + "{} {}{share}: {}.", + ui::paint(&left.to_string(), "1;33", color), + match (left == 1, dry_run) { + (true, false) => "vulnerability left to patch", + (false, false) => "vulnerabilities left to patch", + (true, true) => "vulnerability would be left to patch", + (false, true) => "vulnerabilities would be left to patch", + }, + why.join(", ") + ))); + } + if reachability { + let share = percent_left(counts.fixed_reachable, counts.left_reachable) + .map(|p| format!(" ({p})")) + .unwrap_or_default(); + lines.push(plain(format!( + "Reachable: {} {}, {} left to patch{share}.", + ui::bold(&counts.fixed_reachable.to_string(), color), + if dry_run { "would be fixed" } else { "fixed" }, + ui::bold(&counts.left_reachable.to_string(), color), + ))); + } + if let Some(meter) = meter(counts.fixed, left, style) { + lines.push(plain(meter)); + } + lines +} + +/// The report of one `scan` invocation: every project directory's run +/// prints its rows through it and adds its counts, and the invocation +/// prints the totals once, when the last directory is done. +pub(crate) struct Run { + /// Neither `--json` nor `--silent`: the report prints. + human: bool, + /// The run shows measurements ([`measured::wanted`]). + measures: bool, + dry_run: bool, + verbose: bool, + started: Instant, + counts: Counts, + /// Project directories a patch landed in. + projects: usize, + /// Some directory's selection filter holds reachability findings. + reachability: bool, + /// What the patch service measured about the selected patches, as far + /// as its answers have been collected ([`Self::settle`]). + measured: Measured, + /// The measurement requests still out ([`Self::measure`]). + measuring: Vec>>, + /// The window every round of measurement requests shares, with the + /// route it is for (`true`: the public proxy). + window: Option<(bool, measured::Window)>, + /// The patches whose measurements have been asked for. + requested: HashSet, + /// The selected uuids of every package a patch landed in, for the + /// closing lines' measurements. + patched: Vec>, + /// The API client the first project directory built, with whether it + /// is on the public proxy ([`Self::client`]). + client: Option<(ApiClient, bool)>, + /// The paid-plan line has printed ([`Self::upsell`]). + upsold: bool, + /// The run covers several project directories: its client remembers + /// what the patch service answers ([`Self::share_lookups`]). + shares_lookups: bool, + /// Some project directory's lookup ran on the public proxy. + free_only: bool, +} + +impl Run { + pub(crate) fn new(common: &GlobalArgs) -> Self { + Run { + human: !common.json && !common.silent, + measures: measured::wanted(common), + dry_run: common.dry_run, + verbose: common.verbose, + started: Instant::now(), + counts: Counts::default(), + projects: 0, + reachability: false, + measured: Measured::new(), + measuring: Vec::new(), + window: None, + requested: HashSet::new(), + patched: Vec::new(), + client: None, + upsold: false, + shares_lookups: false, + free_only: false, + } + } + + /// The run scans several project directories, which hold many of the + /// same packages: its client remembers what the patch service answers + /// about a package, so each is asked about once for the whole run + /// (and can be asked about ahead of its directory's turn). A run of + /// one directory asks each question once anyway and is left as it is. + pub(crate) fn share_lookups(&mut self) { + self.shares_lookups = true; + self.client = self + .client + .take() + .map(|(client, proxy)| (client.remembering_lookups(), proxy)); + } + + /// A project directory's lookup ran on the public proxy, which answers + /// for free patches only: the closing lines then say "no free patches + /// left", never "nothing left". + pub(crate) fn saw_free_patches_only(&mut self) { + self.free_only = true; + } + + /// Print the paid-plan line (stdout), once per invocation: where a + /// project directory finds only paid patches, else under the closing + /// lines of a run that leaves advisories to a paid plan. + pub(crate) fn upsell(&mut self) { + if self.human && !std::mem::replace(&mut self.upsold, true) { + println!("{}", ui::PAID_UPGRADE); + } + } + + /// The invocation's API client, built by the first project directory + /// that needs one (`build`) and shared by the rest: one connection and + /// one org lookup for the whole run, not one per directory. + pub(crate) async fn client(&mut self, build: F) -> (ApiClient, bool) + where + F: std::future::Future, + { + match &self.client { + Some(client) => client.clone(), + None => { + let (mut client, proxy) = build.await; + if self.shares_lookups { + client = client.remembering_lookups(); + } + self.client = Some((client.clone(), proxy)); + (client, proxy) + } + } + } + + /// A directory's run moved to the public proxy (the API refused its + /// token): the directories after it start there, and are spared the + /// refusal and its warning. + pub(crate) fn fell_back_to(&mut self, proxy: &ApiClient) { + let mut proxy = proxy.clone(); + if self.shares_lookups { + proxy = proxy.remembering_lookups(); + } + self.client = Some((proxy, true)); + } + + /// A project directory's selection filter: once one holds + /// reachability findings, the closing lines also count the reachable + /// advisories on their own. + pub(crate) fn reads_reachability(&mut self, filter: Option<&SelectionFilter>) { + self.reachability |= filter.is_some_and(SelectionFilter::has_findings); + } + + /// Ask the patch service what it measured about the patch each of + /// `packages` is likely to get: the best ranked one this account can + /// download. Called as soon as the lookup answers, so the requests run + /// beside the rest of the directory's work and are in by the time its + /// rows print; [`Self::measure`] then asks about any selection this + /// guess missed. + pub(crate) fn measure_likely( + &mut self, + client: &ApiClient, + packages: &[BatchPackagePatches], + can_access_paid_patches: bool, + ) { + let likely = packages.iter().filter_map(|pkg| { + pkg.patches + .iter() + .filter(|p| can_access_paid_patches || p.tier == "free") + .min_by(|a, b| cmp_batch_infos(a, b)) + .map(|p| p.uuid.clone()) + }); + self.request(client, likely.collect()); + } + + /// Ask the patch service what it measured about the patches `plan` + /// selected, in the background: the answers are collected by + /// [`Self::settle`], when the directory's rows are about to print. + /// + /// Only for someone watching (a human run whose stdout is a terminal): + /// a log, a pipe and `--json` make no such request. A failed or late + /// answer costs its row the measurements and nothing else. + pub(crate) fn measure(&mut self, client: &ApiClient, plan: &[Package]) { + let selected = plan + .iter() + .filter(|pkg| !pkg.outside_project) + .filter_map(|pkg| pkg.uuids.first()) + .cloned(); + self.request(client, selected.collect()); + } + + /// Start one round of measurement requests: those of `uuids` not + /// asked for yet, up to [`MEASURED_PER_ROUND`]. + fn request(&mut self, client: &ApiClient, uuids: Vec) { + if !self.measures { + return; + } + let uuids: Vec = uuids + .into_iter() + .filter(|uuid| self.requested.insert(uuid.clone())) + .take(MEASURED_PER_ROUND) + .collect(); + if uuids.is_empty() { + return; + } + // One window for every round of the run: the rounds of a scan of + // many directories are all out at once. + let proxy = client.uses_public_proxy(); + let window = match &self.window { + Some((route, window)) if *route == proxy => window.clone(), + _ => { + let window = measured::window(client); + self.window = Some((proxy, window.clone())); + window + } + }; + let client = client.clone(); + self.measuring.push(tokio::spawn(async move { + measured::request(&client, uuids, &window).await + })); + } + + /// Collect the measurements asked for so far, waiting a moment + /// ([`ROWS_WAIT`]) for the ones still on their way. Those stay out, and + /// a later call collects them. + pub(crate) async fn settle(&mut self) { + self.collect(ROWS_WAIT).await; + } + + /// [`Self::settle`], waiting up to `wait` in all. The wait shows on + /// the status line: it stands between the lookup and the rows, where + /// nothing else is on screen. + async fn collect(&mut self, wait: Duration) { + let _status = (!self.measuring.is_empty()).then(|| { + let mut status = ui::StatusLine::stderr(!self.human, false); + status.set("Reading patch test results"); + status + }); + let deadline = tokio::time::Instant::now() + wait; + for mut task in std::mem::take(&mut self.measuring) { + match tokio::time::timeout_at(deadline, &mut task).await { + Ok(Ok(answers)) => measured::collect(&mut self.measured, answers), + // The task itself failed: nothing to wait for. + Ok(Err(_)) => {} + Err(_) => self.measuring.push(task), + } + } + } + + /// Report one project directory: print the rows of the packages whose + /// patch is in `landed` (stdout), and count the directory into the + /// totals. + pub(crate) async fn project(&mut self, plan: &[Package], landed: &HashSet<&str>) { + self.settle().await; + for row in self.rows(plan, landed) { + println!("{row}"); + } + self.count(plan, landed); + } + + /// The rows [`Self::project`] prints, for a caller that prints them + /// itself: none under `--json` or `--silent`. They carry the mark of + /// a patch in place unless this is a dry run. + pub(crate) fn rows(&self, plan: &[Package], landed: &HashSet<&str>) -> Vec { + self.rows_marked(plan, landed, !self.dry_run) + } + + /// The rows of the packages a patch is on offer for (`offered`), for + /// a run that reports and patches nothing: no row carries the mark of + /// a patch in place. + pub(crate) fn rows_offered(&self, plan: &[Package], offered: &HashSet<&str>) -> Vec { + self.rows_marked(plan, offered, false) + } + + fn rows_marked(&self, plan: &[Package], landed: &HashSet<&str>, done: bool) -> Vec { + if !self.human { + return Vec::new(); + } + let cap = ui::attended(ui::Stream::Stdout).then(ui::stdout_width); + rows( + plan, + landed, + &self.measured, + self.verbose, + Style::stdout(), + cap, + done, + ) + } + + /// Count one project directory into the totals: `plan`, judged by the + /// patches that landed there. Once per directory. + pub(crate) fn count(&mut self, plan: &[Package], landed: &HashSet<&str>) { + let counts = Counts::of(plan, landed); + self.counts.add(&counts); + self.projects += usize::from(counts.patched > 0); + self.patched.extend( + plan.iter() + .filter(|pkg| pkg.landed(landed)) + .map(|pkg| pkg.uuids.clone()), + ); + } + + /// Print the closing lines (stdout), under a blank line. The elapsed + /// time is for someone watching: it prints on a terminal only, so a + /// log of the same run reads the same every time. + pub(crate) async fn finish(&mut self) { + if !self.human { + return; + } + // The last measurements: the ones that missed their rows still + // count here. Whatever is out after that is given up. + self.collect(CLOSING_WAIT).await; + for task in self.measuring.drain(..) { + task.abort(); + } + let mut counts = self.counts; + counts.verify(&self.patched, &self.measured); + counts.free_only = self.free_only; + let elapsed = ui::attended(ui::Stream::Stdout).then(|| self.started.elapsed()); + let lines = closing( + &counts, + self.projects, + self.dry_run, + self.reachability, + elapsed, + Style::stdout(), + ); + if !lines.is_empty() { + println!(); + } + for line in lines { + println!("{line}"); + } + if counts.left_paid > 0 { + self.upsell(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::commands::measured::tests::stats; + use socket_patch_core::api::types::{BatchPatchInfo, VulnerabilityResponse}; + + const FANCY: Style = Style { + color: true, + glyphs: true, + }; + const COLOR: Style = Style { + color: true, + glyphs: false, + }; + const PLAIN: Style = Style::PLAIN; + + fn none() -> Measured { + Measured::new() + } + + fn strs(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + fn info( + uuid: &str, + tier: &str, + severity: &str, + cves: &[&str], + ghsas: &[&str], + ) -> BatchPatchInfo { + BatchPatchInfo { + uuid: uuid.to_string(), + purl: String::new(), + tier: tier.to_string(), + cve_ids: strs(cves), + ghsa_ids: strs(ghsas), + severity: Some(severity.to_string()), + title: String::new(), + published_at: None, + } + } + + /// A patch record for `purl` fixing `advisories`: `(id, severity, cves)`. + fn record(purl: &str, uuid: &str, advisories: &[(&str, &str, &[&str])]) -> PatchSearchResult { + PatchSearchResult { + uuid: uuid.to_string(), + purl: purl.to_string(), + published_at: String::new(), + description: String::new(), + license: String::new(), + tier: "free".to_string(), + vulnerabilities: advisories + .iter() + .map(|(id, severity, cves)| { + ( + id.to_string(), + VulnerabilityResponse { + cves: strs(cves), + summary: String::new(), + severity: severity.to_string(), + description: String::new(), + }, + ) + }) + .collect(), + } + } + + fn pkg(purl: &str, uuid: &str, severity: &str, fixes: &[&str], unpatched: &[&str]) -> Package { + Package { + purl: purl.to_string(), + uuids: strs(&[uuid]), + severity: Some(severity.to_string()), + fixes: strs(fixes), + unpatched: strs(unpatched), + ..Package::default() + } + } + + fn landed<'a>(uuids: &[&'a str]) -> HashSet<&'a str> { + uuids.iter().copied().collect() + } + + const UNDICI: &str = "pkg:npm/undici@8.10.0"; + const CVE_1: &str = "CVE-2024-0001"; + const CVE_2: &str = "CVE-2024-0002"; + const CVE_3: &str = "CVE-2024-0003"; + const CVE_4: &str = "CVE-2024-0004"; + const CVE_9: &str = "CVE-2024-0009"; + const GHSA_A: &str = "GHSA-aaaa-aaaa-aaaa"; + const GHSA_B: &str = "GHSA-bbbb-bbbb-bbbb"; + const GHSA_C: &str = "GHSA-cccc-cccc-cccc"; + + /// undici with three patches: the selected one fixes a critical and a + /// high advisory, a second fixes a third advisory, and a paid one a + /// fourth. A package nothing was selected for counts whole as left. + fn undici_plan(filter: Option<&SelectionFilter>, paid_access: bool) -> Vec { + let packages = vec![ + BatchPackagePatches { + purl: UNDICI.to_string(), + patches: vec![ + info("u1", "free", "CRITICAL", &[CVE_1, CVE_2], &[GHSA_A, GHSA_B]), + info("u2", "free", "LOW", &[CVE_3], &[GHSA_C]), + info("u3", "paid", "HIGH", &[CVE_4], &[]), + ], + }, + BatchPackagePatches { + purl: "pkg:npm/devalue@5.9.0".to_string(), + patches: vec![info("d1", "paid", "HIGH", &[CVE_9], &[])], + }, + ]; + let chosen = record( + UNDICI, + "u1", + &[(GHSA_A, "CRITICAL", &[CVE_1]), (GHSA_B, "HIGH", &[CVE_2])], + ); + let other = record(UNDICI, "u2", &[(GHSA_C, "LOW", &[CVE_3])]); + plan( + &packages, + std::slice::from_ref(&chosen), + &[&chosen, &other], + paid_access, + filter, + &|_| true, + ) + } + + #[test] + fn plan_counts_what_the_selection_fixes_and_what_it_leaves() { + let plan = undici_plan(None, false); + assert_eq!( + plan[0], + Package { + purl: UNDICI.to_string(), + uuids: strs(&["u1"]), + severity: Some("CRITICAL".to_string()), + fixes: strs(&[CVE_1, CVE_2]), + unpatched: strs(&[CVE_3, CVE_4]), + fixed_critical: 1, + fixed_high: 1, + fixed_reachable: 0, + unpatched_reachable: 0, + paid_only: false, + outside_project: false, + } + ); + // Nothing selected: its patches' worst severity, every id left, + // and (for an account without paid access) a paid plan needed. + assert_eq!( + plan[1], + Package { + purl: "pkg:npm/devalue@5.9.0".to_string(), + severity: Some("HIGH".to_string()), + unpatched: strs(&[CVE_9]), + paid_only: true, + ..Package::default() + } + ); + assert!(!undici_plan(None, true)[1].paid_only); + + let counts = Counts::of(&plan, &landed(&["u1"])); + assert_eq!( + counts, + Counts { + patched: 1, + fixed: 2, + fixed_critical: 1, + fixed_high: 1, + left_upgrade: 2, + left_paid: 1, + ..Counts::default() + } + ); + assert_eq!(counts.left(), 3); + // A selected patch that did not land fixes nothing: the package + // counts whole as left, in a package the run did not patch. + let nothing = Counts::of(&plan, &landed(&[])); + assert_eq!( + nothing, + Counts { + left_unpatched: 4, + left_paid: 1, + ..Counts::default() + } + ); + } + + /// A package the project's lockfile does not name is not the + /// project's: unpatched, it is not counted as left. + #[test] + fn a_package_outside_the_project_is_never_left_to_patch() { + let packages = vec![BatchPackagePatches { + purl: "pkg:gem/rack@3.0.0".to_string(), + patches: vec![info("r1", "free", "HIGH", &[CVE_1, CVE_2], &[])], + }]; + let chosen = record("pkg:gem/rack@3.0.0", "r1", &[(GHSA_A, "HIGH", &[CVE_1])]); + let plan = plan( + &packages, + std::slice::from_ref(&chosen), + &[&chosen], + true, + None, + &|purl| !purl.starts_with("pkg:gem/"), + ); + assert!(plan[0].outside_project); + assert_eq!(Counts::of(&plan, &landed(&[])), Counts::default()); + // Patched all the same (an agent run patches the copy on disk), it + // counts like any other. + assert_eq!(Counts::of(&plan, &landed(&["r1"])).patched, 1); + } + + /// What was measured about the patches that landed adds up; a patch + /// that did not land, or was not measured, adds nothing. + #[test] + fn counts_add_up_the_measurements_of_the_patches_that_landed() { + let plan = vec![ + pkg(UNDICI, "u", "HIGH", &[CVE_1], &[]), + pkg("pkg:npm/nuxt@4.5.0", "n", "HIGH", &[CVE_2], &[]), + pkg("pkg:npm/devalue@5.9.0", "d", "HIGH", &[CVE_3], &[]), + pkg("pkg:npm/skipped@1.0.0", "k", "HIGH", &[CVE_4], &[]), + ]; + let measured: Measured = [ + ("u".to_string(), stats(2, 35, 35)), + ("n".to_string(), stats(1, 104, 106)), + ("k".to_string(), stats(9, 9, 9)), + ] + .into(); + let mut counts = Counts::of(&plan, &landed(&["u", "n", "d"])); + counts.verify(&[strs(&["u"]), strs(&["n"]), strs(&["d"])], &measured); + assert_eq!( + (counts.patched, counts.measured), + (3, 2), + "devalue was not measured" + ); + assert_eq!((counts.exploits_blocked, counts.exploits), (3, 3)); + assert_eq!((counts.tests_passing, counts.tests), (139, 141)); + } + + /// A finding marks an advisory reachable by the advisory's id or by a + /// CVE alias, whichever of them the row shows. + #[test] + fn plan_marks_reachable_advisories_through_their_aliases() { + let filter = SelectionFilter::parse( + format!( + r#"{{"version": 1, "reachability": [ + {{"advisory": "{GHSA_A}", "state": "reachable"}}, + {{"advisory": "{CVE_2}", "state": "unreachable"}}, + {{"advisory": "{GHSA_C}", "state": "reachable"}}, + {{"advisory": "{CVE_9}", "state": "reachable"}} + ]}}"# + ) + .as_bytes(), + ) + .expect("valid filter"); + let plan = undici_plan(Some(&filter), true); + // The first CVE is GHSA-a (reachable); the second is unreachable. + assert_eq!(plan[0].fixed_reachable, 1); + // The third is GHSA-c (reachable); no finding names the fourth. + assert_eq!(plan[0].unpatched_reachable, 1); + assert_eq!(plan[1].unpatched_reachable, 1); + let counts = Counts::of(&plan, &landed(&["u1"])); + assert_eq!((counts.fixed_reachable, counts.left_reachable), (1, 2)); + // A filter with no finding marks nothing. + let bare = SelectionFilter::parse(br#"{"version": 1}"#).expect("valid filter"); + assert_eq!(undici_plan(Some(&bare), true)[0].fixed_reachable, 0); + } + + #[test] + fn rows_list_each_patched_package_once_worst_first() { + let plan = vec![ + pkg( + UNDICI, + "u", + "HIGH", + &["CVE-84961", "CVE-85024"], + &["a", "b", "c"], + ), + pkg( + "pkg:npm/shell-quote@1.10.0", + "s", + "CRITICAL", + &["CVE-102422"], + &[], + ), + pkg( + "pkg:npm/nuxt@4.5.0", + "n", + "HIGH", + &["CVE-1", "CVE-2", "CVE-3", "CVE-4"], + &["x"], + ), + pkg("pkg:npm/skipped@1.0.0", "k", "CRITICAL", &["CVE-7"], &[]), + ]; + let all = landed(&["u", "s", "n"]); + assert_eq!( + rows(&plan, &all, &none(), false, PLAIN, None, true), + vec![ + " CRITICAL shell-quote@1.10.0 CVE-102422", + " HIGH nuxt@4.5.0 CVE-1, CVE-2 (+2) 1 unpatched", + " HIGH undici@8.10.0 CVE-84961, CVE-85024 3 unpatched", + ] + ); + // Nothing landed: no rows at all. + assert!(rows(&plan, &landed(&[]), &none(), false, PLAIN, None, true).is_empty()); + // Color wraps the cells without moving a column. + let colored = rows(&plan, &all, &none(), false, COLOR, None, true); + let plain: Vec = colored.iter().map(|r| ui::strip_ansi(r)).collect(); + assert_eq!(plain, rows(&plan, &all, &none(), false, PLAIN, None, true)); + assert!(colored[0].contains("\x1b[91mCRITICAL\x1b[0m")); + assert!(colored[2].contains("\x1b[33m3 unpatched\x1b[0m")); + } + + #[test] + fn rows_name_fewer_ids_rather_than_wrap_a_terminal() { + let plan = vec![ + pkg( + UNDICI, + "u", + "HIGH", + &["CVE-2026-84961", "CVE-2026-85024"], + &["a"], + ), + pkg( + "pkg:npm/nuxt@4.5.0", + "n", + "HIGH", + &["CVE-1", "CVE-2", "CVE-3"], + &[], + ), + ]; + let all = landed(&["u", "n"]); + let at = |cap| rows(&plan, &all, &none(), false, PLAIN, Some(cap), true); + assert_eq!( + at(80), + vec![ + " HIGH nuxt@4.5.0 CVE-1, CVE-2 (+1)", + " HIGH undici@8.10.0 CVE-2026-84961, CVE-2026-85024 1 unpatched", + ] + ); + assert_eq!( + at(60), + vec![ + " HIGH nuxt@4.5.0 CVE-1 (+2)", + " HIGH undici@8.10.0 CVE-2026-84961 (+1) 1 unpatched", + ] + ); + assert_eq!( + at(44), + vec![ + " HIGH nuxt@4.5.0 3 fixed", + " HIGH undici@8.10.0 2 fixed 1 unpatched", + ] + ); + for cap in [80, 60, 44] { + assert!(at(cap).iter().all(|row| row.chars().count() < cap), "{cap}"); + } + // Narrower than the counts: the full form, wrapped by the terminal. + assert_eq!(at(10), rows(&plan, &all, &none(), false, PLAIN, None, true)); + } + + #[test] + fn rows_verbose_name_every_id_and_what_stays_unpatched() { + let plan = vec![pkg( + UNDICI, + "u", + "HIGH", + &["CVE-1", "CVE-2", "CVE-3"], + &["CVE-8", "CVE-9"], + )]; + assert_eq!( + rows(&plan, &landed(&["u"]), &none(), true, PLAIN, Some(20), true), + vec![ + " HIGH undici@8.10.0 CVE-1, CVE-2, CVE-3 2 unpatched", + " still unpatched: CVE-8, CVE-9", + ] + ); + } + + #[test] + fn rows_spell_the_purl_when_ecosystems_mix_and_elide_long_names() { + let plan = vec![ + pkg("pkg:npm/requests@1.0.0", "a", "LOW", &[], &[]), + pkg("pkg:pypi/requests@2.31.0", "b", "LOW", &["CVE-1"], &[]), + ]; + assert_eq!( + rows( + &plan, + &landed(&["a", "b"]), + &none(), + false, + PLAIN, + None, + true + ), + vec![ + " LOW pkg:npm/requests@1.0.0", + " LOW pkg:pypi/requests@2.31.0 CVE-1", + ] + ); + // A scoped npm name is decoded, and an unknown severity says so. + let scoped = vec![Package { + purl: "pkg:npm/%40scope/a@1.0.0".to_string(), + uuids: strs(&["a"]), + ..Package::default() + }]; + assert_eq!( + rows(&scoped, &landed(&["a"]), &none(), false, PLAIN, None, true), + vec![" UNKNOWN @scope/a@1.0.0"] + ); + // A patch that names no advisory leaves no gap where its ids + // would be: the measurements follow the name. + let measured: Measured = [("a".to_string(), stats(1, 25, 25))].into(); + assert_eq!( + rows( + &scoped, + &landed(&["a"]), + &measured, + false, + PLAIN, + None, + true + ), + vec![" UNKNOWN @scope/a@1.0.0 exploit blocked, 25/25 tests"] + ); + // The severity reads the same whatever the source's spelling. + let lower = vec![pkg("pkg:npm/a@1.0.0", "a", "moderate", &["CVE-1"], &[])]; + assert_eq!( + rows(&lower, &landed(&["a"]), &none(), false, PLAIN, None, true), + vec![" MODERATE a@1.0.0 CVE-1"] + ); + let long = format!("pkg:npm/@typescript-eslint/{}@6.0.0", "x".repeat(60)); + let long = vec![pkg(&long, "a", "HIGH", &["CVE-1"], &[])]; + let row = &rows(&long, &landed(&["a"]), &none(), false, PLAIN, None, true)[0]; + assert!( + row.contains("...") && row.contains("@6.0.0 CVE-1"), + "{row}" + ); + assert_eq!( + row.chars().count(), + " HIGH ".len() + MAX_NAME_COL + " CVE-1".len() + ); + } + + fn counts( + patched: usize, + fixed: usize, + upgrade: usize, + paid: usize, + unpatched: usize, + ) -> Counts { + Counts { + patched, + fixed, + left_upgrade: upgrade, + left_paid: paid, + left_unpatched: unpatched, + ..Counts::default() + } + } + + #[test] + fn closing_totals_the_run() { + let c = Counts { + fixed_critical: 5, + fixed_high: 21, + ..counts(22, 39, 14, 3, 1) + }; + assert_eq!( + closing(&c, 3, false, false, None, PLAIN), + vec![ + "Patched 22 packages in 3 projects, fixing 39 vulnerabilities (5 critical, 21 high).", + "Saved about 44 hours of engineering time (22 package upgrades at ~2 hours each).", + "18 vulnerabilities left to patch (32%): 14 need a package upgrade, 3 need a paid \ + Socket plan, 1 is in packages this run did not patch.", + ] + ); + // One project is not counted out loud; the time is the caller's. + assert_eq!( + closing( + &counts(1, 1, 0, 0, 0), + 1, + false, + false, + Some(Duration::from_millis(4249)), + PLAIN + ), + vec![ + "Patched 1 package, fixing 1 vulnerability in 4.2s.", + "Saved about 2 hours of engineering time (1 package upgrade at ~2 hours).", + "Nothing left to patch.", + ] + ); + // A patch that names no advisory still patched its package. + assert_eq!( + closing(&counts(2, 0, 0, 0, 0), 2, false, false, None, PLAIN), + vec![ + "Patched 2 packages in 2 projects.", + "Saved about 4 hours of engineering time (2 package upgrades at ~2 hours each).", + "Nothing left to patch." + ] + ); + // Nothing patched: only what is left, with no share of nothing. + assert_eq!( + closing(&counts(0, 0, 0, 4, 1), 0, false, false, None, PLAIN), + vec![ + "5 vulnerabilities left to patch: 4 need a paid Socket plan, 1 is in packages \ + this run did not patch." + ] + ); + // Nothing found at all: no lines. + assert!(closing(&Counts::default(), 0, false, false, None, PLAIN).is_empty()); + } + + #[test] + fn closing_dry_run_and_reachability() { + let c = Counts { + fixed_reachable: 9, + left_reachable: 2, + ..counts(22, 39, 1, 0, 2) + }; + assert_eq!( + closing(&c, 3, true, true, None, PLAIN), + vec![ + "Would patch 22 packages in 3 projects, fixing 39 vulnerabilities.", + "Would save about 44 hours of engineering time (22 package upgrades at ~2 hours \ + each).", + "3 vulnerabilities would be left to patch (7%): 1 needs a package upgrade, 2 are \ + in packages a run would not patch.", + "Reachable: 9 would be fixed, 2 left to patch (18%).", + ] + ); + let none_left = Counts { + fixed_reachable: 4, + ..counts(5, 6, 0, 0, 0) + }; + assert_eq!( + closing(&none_left, 1, false, true, None, PLAIN)[2..], + [ + "Nothing left to patch.", + "Reachable: 4 fixed, 0 left to patch." + ] + ); + } + + #[test] + fn closing_colors_the_numbers_only() { + let lines = closing(&counts(2, 3, 1, 0, 0), 1, false, false, None, COLOR); + assert_eq!( + lines[0], + "\x1b[1;32mPatched\x1b[0m \x1b[1m2\x1b[0m packages, fixing \x1b[1m3\x1b[0m vulnerabilities." + ); + let plain: Vec = lines.iter().map(|l| ui::strip_ansi(l)).collect(); + assert_eq!( + plain, + closing(&counts(2, 3, 1, 0, 0), 1, false, false, None, PLAIN) + ); + } + + #[test] + fn rows_show_the_measurements_and_give_them_up_before_wrapping() { + let plan = vec![ + pkg( + UNDICI, + "u", + "HIGH", + &["CVE-2026-84961", "CVE-2026-85024"], + &["a"], + ), + pkg("pkg:npm/nuxt@4.5.0", "n", "HIGH", &["CVE-1"], &[]), + ]; + let all = landed(&["u", "n"]); + let measured: Measured = [("u".to_string(), stats(2, 35, 35))].into(); + let at = |cap| rows(&plan, &all, &measured, false, PLAIN, cap, true); + // A package whose patch was not measured has no such cell. + assert_eq!( + at(None), + vec![ + " HIGH nuxt@4.5.0 CVE-1", + " HIGH undici@8.10.0 CVE-2026-84961, CVE-2026-85024 2 exploits blocked, \ + 35/35 tests 1 unpatched", + ] + ); + // Narrower: the second id goes first, then the measurements. + assert_eq!( + at(Some(90))[1], + " HIGH undici@8.10.0 CVE-2026-84961 (+1) 2 exploits blocked, 35/35 tests \ + 1 unpatched" + ); + assert_eq!( + at(Some(80))[1], + " HIGH undici@8.10.0 CVE-2026-84961, CVE-2026-85024 1 unpatched" + ); + // Where the terminal shows glyphs, a check mark takes the first + // column and nothing else moves. + let fancy = rows(&plan, &all, &measured, false, FANCY, None, true); + let stripped: Vec = fancy.iter().map(|r| ui::strip_ansi(r)).collect(); + let marked: Vec = at(None).iter().map(|r| format!("✔{}", &r[1..])).collect(); + assert_eq!(stripped, marked); + assert!(fancy[0].starts_with("\x1b[32m✔\x1b[0m "), "{:?}", fancy[0]); + // A patch that is only on offer (a dry run, a report) is not + // marked as in place: the column is blank and nothing else moves. + let offered = rows(&plan, &all, &measured, false, FANCY, None, false); + let stripped: Vec = offered.iter().map(|r| ui::strip_ansi(r)).collect(); + assert_eq!(stripped, at(None)); + assert!(!offered.iter().any(|row| row.contains('✔')), "{offered:?}"); + } + + #[test] + fn closing_says_what_was_measured_and_draws_the_meter() { + let c = Counts { + fixed_critical: 5, + fixed_high: 15, + measured: 22, + exploits_blocked: 24, + exploits: 24, + tests_passing: 1208, + tests: 1208, + ..counts(22, 39, 23, 0, 0) + }; + let plain = closing(&c, 3, false, false, None, PLAIN); + assert_eq!( + plain, + vec![ + "Patched 22 packages in 3 projects, fixing 39 vulnerabilities (5 critical, 15 high).", + "Verified: 24 of 24 exploits blocked, 1208 of 1208 package tests passing.", + "Saved about 44 hours of engineering time (22 package upgrades at ~2 hours each).", + "23 vulnerabilities left to patch (37%): 23 need a package upgrade.", + ] + ); + // With glyphs: a check mark on what was done, the rest indented to + // match, and the meter of the share patched. + let fancy: Vec = closing(&c, 3, false, false, None, FANCY) + .iter() + .map(|l| ui::strip_ansi(l)) + .collect(); + assert_eq!( + fancy, + vec![ + format!("✔ {}", plain[0]), + format!("✔ {}", plain[1]), + format!(" {}", plain[2]), + format!(" {}", plain[3]), + format!(" {} 63% patched", "━".repeat(METER_CELLS)), + ] + ); + // Not every patch measured, and not every test passing: said, and + // not check-marked. + let partly = Counts { + measured: 18, + tests_passing: 1200, + ..c + }; + let lines: Vec = closing(&partly, 3, false, false, None, FANCY) + .iter() + .map(|l| ui::strip_ansi(l)) + .collect(); + assert_eq!( + lines[1], + " Verified: 24 of 24 exploits blocked, 1200 of 1208 package tests passing \ + (measured for 18 of 22 patches)." + ); + // Nothing left: no meter to draw. + let done = closing(&counts(2, 3, 0, 0, 0), 1, false, false, None, FANCY); + assert_eq!(done.len(), 3); + assert_eq!(ui::strip_ansi(&done[2]), " Nothing left to patch."); + // A lookup that saw free patches only speaks for those alone. + let free = Counts { + free_only: true, + ..counts(2, 3, 0, 0, 0) + }; + assert_eq!( + closing(&free, 1, false, false, None, PLAIN)[2], + "No free patches left to apply." + ); + } + + #[test] + fn percent_left_never_rounds_to_all_or_nothing() { + assert_eq!(percent_left(39, 18).as_deref(), Some("32%")); + assert_eq!(percent_left(1, 1).as_deref(), Some("50%")); + assert_eq!(percent_left(999, 1).as_deref(), Some("<1%")); + assert_eq!(percent_left(1, 999).as_deref(), Some(">99%")); + assert_eq!(percent_left(0, 5), None); + assert_eq!(percent_left(5, 0), None); + } +} diff --git a/crates/socket-patch-cli/src/commands/scan/rollout.rs b/crates/socket-patch-cli/src/commands/scan/rollout.rs index f27f81b1f..6b0ed4f9a 100644 --- a/crates/socket-patch-cli/src/commands/scan/rollout.rs +++ b/crates/socket-patch-cli/src/commands/scan/rollout.rs @@ -50,10 +50,14 @@ pub(crate) struct Gate<'a> { /// The withdrawn-pin sweep's reference answers: the redirect asks the /// endpoint only about the selected uuids these do not cover. pub(crate) references: Option, - /// What each selected patch fixes and leaves unpatched, for the human - /// lines under the summary (empty under `--json`, which carries it on + /// The report's view of every package with a patch on offer: what + /// the selected patch fixes and leaves unpatched, for the rows under + /// the summary line (empty under `--json`, which carries it on /// `packages[]`). - pub(crate) coverage: Vec, + pub(crate) plan: Vec, + /// The invocation's report, which prints those rows and counts this + /// directory into its closing totals (`None` under `--json`). + pub(crate) report: Option<&'a mut super::report::Run>, } /// Scan's discovery, made BEFORE the apply lock, with the paths it read. diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index 59ff28fc7..48545aed0 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -951,29 +951,13 @@ async fn run_vendor_interactive_path( telemetry_auth: &TelemetryAuth, // The npm half of scan's crawl, for the vendor engine to reuse. prior: Option<&NpmCrawlSnapshot>, - // What each selected patch fixes and leaves unpatched. - coverage: &[super::discovery::AdvisoryCoverage], + // The report's view of every package with a patch on offer, and the + // invocation's report. + plan: &[super::report::Package], + report: &mut super::report::Run, ) -> i32 { - // Under the engine's summary line: the advisory lines of the packages - // it vendored or found already vendored. - let verbose = args.common.verbose; - let closing_lines = move |vendored: &[&str]| -> Vec { - let keys: HashSet = vendored.iter().map(|purl| PurlKey::new(purl)).collect(); - let landed: HashSet<&str> = coverage - .iter() - .filter(|c| keys.contains(&PurlKey::new(&c.purl))) - .flat_map(|c| c.uuids.iter().map(String::as_str)) - .collect(); - super::coverage_lines_for(coverage, &landed, false, verbose) - }; - // The download phase is quiet about its own header in vendored mode - // (only the manifest-mode download prints it), so this arm does. - if !args.common.silent && !selected.is_empty() { - eprintln!( - "Downloading {}...", - plural(selected.len(), "patch", "patches") - ); - } + // The download shows on the status line; the packages it fetched are + // the rows under the summary line. let download = boxed_download_patch_records(selected, params, api_client, prefetched, prior).await; let (dl_code, records) = (download.code, download.records); @@ -982,6 +966,27 @@ async fn run_vendor_interactive_path( // The vendor step is a silent no-op on an empty record set (it can't // know why it is empty); this arm can. let nothing_to_vendor = records.is_empty(); + // The measurements asked for when the patches were selected: in by + // now, so the rows below show them. + report.settle().await; + + // Under the engine's summary line: one row per package it vendored or + // found already vendored. The engine calls this once it knows which; + // those packages are then counted into the report below. + let landed_purls: std::sync::Mutex> = Default::default(); + let landed_of = |keys: &HashSet| -> HashSet<&str> { + plan.iter() + .filter(|p| keys.contains(&PurlKey::new(&p.purl))) + .flat_map(|p| p.uuids.iter().map(String::as_str)) + .collect() + }; + let rows_report = &*report; + let closing_lines = |vendored: &[&str]| -> Vec { + let keys: HashSet = vendored.iter().map(|purl| PurlKey::new(purl)).collect(); + let rows = rows_report.rows(plan, &landed_of(&keys)); + *landed_purls.lock().unwrap_or_else(|e| e.into_inner()) = keys; + rows + }; let code = match boxed_vendor_step(VendorStep { common: &args.common, records, @@ -1009,6 +1014,8 @@ async fn run_vendor_interactive_path( return 1; } }; + let landed_purls = landed_purls.into_inner().unwrap_or_else(|e| e.into_inner()); + report.count(plan, &landed_of(&landed_purls)); // GC after the vendor step (see the JSON arm). if prune { let gc = run_apply_gc( @@ -1161,7 +1168,8 @@ pub(super) fn boxed_vendor_interactive_path<'a>( prune: bool, telemetry_auth: &'a TelemetryAuth, prior: Option<&'a NpmCrawlSnapshot>, - coverage: &'a [super::discovery::AdvisoryCoverage], + plan: &'a [super::report::Package], + report: &'a mut super::report::Run, ) -> std::pin::Pin + 'a>> { Box::pin(run_vendor_interactive_path( args, @@ -1177,7 +1185,8 @@ pub(super) fn boxed_vendor_interactive_path<'a>( prune, telemetry_auth, prior, - coverage, + plan, + report, )) } diff --git a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs index 7c65359b6..24bc86af1 100644 --- a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs +++ b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs @@ -177,7 +177,17 @@ pub(super) async fn sweep( .collect::>() .into_iter() .collect(); - let references = match api_client.fetch_registry_references(&uuids).await { + // A network round trip between the lookup and the patch records. + let asked = crate::ui::busy( + common, + format!( + "Checking {}", + crate::ui::plural(uuids.len(), "hosted patch", "hosted patches") + ), + api_client.fetch_registry_references(&uuids), + ) + .await; + let references = match asked { Ok(references) => references, Err(e) => { out.warn( diff --git a/crates/socket-patch-cli/src/commands/show.rs b/crates/socket-patch-cli/src/commands/show.rs new file mode 100644 index 000000000..693482833 --- /dev/null +++ b/crates/socket-patch-cli/src/commands/show.rs @@ -0,0 +1,1008 @@ +//! `socket-patch show`: look inside one patch before (or after) applying +//! it. Read-only: it asks the patch service and prints, and never touches +//! the project. +//! +//! What it shows: the package and patch, the advisories the patch fixes, +//! what Socket measured about it (exploits blocked, tests passing, size, +//! run-time cost), the files it changes with their line counts, and the +//! unified diff of each file. +//! +//! There is one way a patch is read ([`Source`], [`Shown::read`]) and one +//! screen it is read on: on a terminal `show` opens the patch as a page of the +//! full-screen browser ([`ui::browser`]), the same page a row of `list` +//! opens ([`load_page`]). Anywhere else (a pipe, `--no-pager`, `--yes`) +//! the same text is printed at once, like `git show`. + +use base64::Engine as _; +use clap::Args; +use socket_patch_core::api::client::{ + build_proxy_fallback_client, get_api_client_with_overrides, is_fallback_candidate, ApiClient, + ApiClientEnvOverrides, ApiError, +}; +use socket_patch_core::api::ranking::{cmp_search_results, severity_order}; +use socket_patch_core::api::types::{PatchFileResponse, PatchResponse, PatchSearchResult}; +use socket_patch_core::utils::concurrent::{api_concurrency_for, ordered_concurrent}; +use socket_patch_core::utils::purl::normalize_purl; +use socket_patch_core::utils::target::{Target, TargetKind}; + +use crate::args::{apply_env_toggles, GlobalArgs}; +use crate::ecosystem_dispatch::{crawl_ecosystems, installed_target_matches}; +use crate::ui::diff::{file_diff, FileDiff}; +use crate::ui::{self, plural, select_one, Style}; + +/// The largest file content read for a diff. A larger file is listed with +/// its hashes, undiffed. +const MAX_FILE_BYTES: usize = 16 * 1024 * 1024; +/// Most installed packages a name may match before `show` asks for a purl. +const MAX_NAME_MATCHES: usize = 8; + +#[derive(Args)] +pub struct ShowArgs { + /// The patch to show: a patch UUID, or a PURL, package name, CVE ID + /// or GHSA ID that has one. + pub identifier: String, + + #[command(flatten)] + pub common: GlobalArgs, + + /// Show the diff of these files only (a path of the patch, or the end + /// of one). Repeat for several + #[arg(long = "file", value_name = "PATH")] + pub files: Vec, + + /// Show the summary and the list of changed files, without the diffs + #[arg(long, default_value_t = false)] + pub stat: bool, + + /// Print everything at once instead of opening the patch full-screen + /// (what a pipe gets) + #[arg(long = "no-pager", default_value_t = false)] + pub no_pager: bool, +} + +/// One file of the patch, with what the patch does to it. +struct ShownFile { + path: String, + before_hash: String, + after_hash: String, + /// `None`: a side's content could not be read (the reason). + diff: Result, +} + +/// Report a failure: the coded error on stdout under `--json`, +/// `Error: ...` on stderr otherwise. Returns the exit code, 1. +fn fail(common: &GlobalArgs, code: &str, message: &str) -> i32 { + if common.json { + ui::print_json(&serde_json::json!({ + "command": "show", + "status": "error", + "error": { "code": code, "message": message }, + })); + } else { + eprintln!("Error: {message}"); + } + 1 +} + +/// `publishedAt` as a date: the service sends an HTTP date (`Fri, 27 Mar +/// 2026 19:12:42 GMT`), fixtures an RFC 3339 one. Anything else is shown +/// as it came. +pub(crate) fn short_date(published_at: &str) -> String { + let s = published_at.trim(); + if let Some((_, rest)) = s.split_once(", ") { + let words: Vec<&str> = rest.split_whitespace().take(3).collect(); + if words.len() == 3 { + return words.join(" "); + } + } + match s.split_once('T') { + Some((date, _)) if date.len() == 10 => date.to_string(), + _ => s.to_string(), + } +} + +/// A file's content from its base64 field of the view, when it is there +/// and decodes. +fn decoded(content: Option<&String>) -> Option> { + let content = content.filter(|c| !c.is_empty())?; + base64::engine::general_purpose::STANDARD + .decode(content) + .ok() +} + +/// Read blob `hash` whole, up to [`MAX_FILE_BYTES`]. +async fn read_blob(client: &ApiClient, hash: &str) -> Result, String> { + let mut body = client + .fetch_blob(hash) + .await + .map_err(|e| e.to_string())? + .ok_or_else(|| "the patch service does not have its content".to_string())?; + let mut bytes = Vec::new(); + while let Some(chunk) = body.chunk().await.map_err(|e| e.to_string())? { + bytes.extend_from_slice(chunk.as_ref()); + if bytes.len() > MAX_FILE_BYTES { + return Err("the file is too large to diff".to_string()); + } + } + Ok(bytes) +} + +/// One side of a file: from the view when it carries it, else by hash. +/// `Ok(None)` for a side that does not exist (a file the patch adds). +async fn side( + client: &ApiClient, + inline: Option<&String>, + hash: Option<&String>, +) -> Result>, String> { + if let Some(bytes) = decoded(inline) { + return Ok(Some(bytes)); + } + match hash.filter(|h| !h.is_empty()) { + Some(hash) => read_blob(client, hash).await.map(Some), + None => Ok(None), + } +} + +/// Every file of `patch` with its diff, by path. Content the view does not +/// carry is read by hash, a few files at a time. +async fn shown_files(client: &ApiClient, patch: &PatchResponse, style: Style) -> Vec { + let mut files: Vec<(&String, &PatchFileResponse)> = patch.files.iter().collect(); + files.sort_by(|a, b| a.0.cmp(b.0)); + let mut out = Vec::with_capacity(files.len()); + let mut diffs = std::pin::pin!(ordered_concurrent( + files, + api_concurrency_for(client.uses_public_proxy(), patch.files.len()), + |(path, file)| async move { + let before = side( + client, + file.before_blob_content.as_ref(), + file.before_hash.as_ref(), + ); + let after = side(client, file.blob_content.as_ref(), file.after_hash.as_ref()); + let diff = match (before.await, after.await) { + (Ok(before), Ok(Some(after))) => Ok(file_diff( + &ui::printable(path), + before.as_deref(), + &after, + style, + )), + (Ok(_), Ok(None)) => Err("the patch carries no content for it".to_string()), + (Err(e), _) | (_, Err(e)) => Err(e), + }; + ShownFile { + path: path.clone(), + before_hash: file.before_hash.clone().unwrap_or_default(), + after_hash: file.after_hash.clone().unwrap_or_default(), + diff, + } + }, + )); + use futures_util::StreamExt; + while let Some(file) = diffs.next().await { + out.push(file); + } + out +} + +/// `+12 -3`, `binary`, or why there is no diff. +fn change_label(file: &ShownFile, color: bool) -> String { + match &file.diff { + Ok(diff) if diff.binary => "binary".to_string(), + Ok(diff) => format!( + "{} {}", + ui::paint(&format!("+{}", diff.added), "32", color), + ui::paint(&format!("-{}", diff.removed), "31", color) + ), + Err(why) => format!("({})", ui::printable(why)), + } +} + +/// The summary above the diffs: the package and patch, what it fixes, +/// what was measured about it, and the files it changes. +/// +/// ```text +/// pkg:npm/undici@8.10.0 HIGH [PAID] +/// Patch 8be53d06-7bd4-40cc-ab8f-36dc6248985a, published 03 Aug 2026, MIT +/// +/// Fixes: +/// HIGH CVE-2026-84961 undici vulnerable to TLS certificate validation bypass... +/// +/// Measured by Socket: +/// Verified: 2 of 2 exploits blocked (2 of 2 worked before the patch), ... +/// +/// Files changed (2): +9 -2 +/// lib/dispatcher/client.js +5 -2 +/// ``` +fn summary(patch: &PatchResponse, files: &[ShownFile], style: Style) -> Vec { + let color = style.color; + // What the service says is text to read, never to act on: a control + // character in a summary, a license or a path is left out, so nothing + // in a patch's record can move the cursor or retitle the terminal. + let patch = &printable_patch(patch); + let mut vulns: Vec<_> = patch.vulnerabilities.iter().collect(); + vulns.sort_by(|a, b| { + severity_order(Some(&a.1.severity)) + .cmp(&severity_order(Some(&b.1.severity))) + .then_with(|| a.0.cmp(b.0)) + }); + // The worst severity, as the row of `list` and the patch menu have it. + let (worst, _) = ui::worst_and_ids( + vulns + .iter() + .map(|(id, v)| (id.as_str(), v.severity.as_str(), v.cves.as_slice())), + ); + let mut head = ui::bold(&normalize_purl(&patch.purl), color); + if !worst.is_empty() { + head.push_str(&format!(" {}", ui::severity(&worst, color))); + } + head.push_str(&format!(" [{}]", patch.tier.to_uppercase())); + let mut about = format!("Patch {}", patch.uuid); + if !patch.published_at.trim().is_empty() { + about.push_str(&format!(", published {}", short_date(&patch.published_at))); + } + if !patch.license.trim().is_empty() { + about.push_str(&format!(", {}", patch.license.trim())); + } + let mut lines = vec![head, ui::dim(&about, color)]; + let description = ui::truncate(&patch.description, 200); + if !description.is_empty() { + lines.push(description); + } + + if !vulns.is_empty() { + lines.push(String::new()); + lines.push("Fixes:".to_string()); + let labels: Vec = vulns + .iter() + .map(|(id, vuln)| { + if vuln.cves.is_empty() { + (*id).clone() + } else { + let mut cves = vuln.cves.clone(); + cves.sort(); + cves.join(", ") + } + }) + .collect(); + let severity_w = vulns + .iter() + .map(|(_, v)| v.severity.chars().count()) + .max() + .unwrap_or(0); + let label_w = labels.iter().map(|l| l.chars().count()).max().unwrap_or(0); + for ((_, vuln), label) in vulns.iter().zip(&labels) { + let line = format!( + " {} {} {}", + ui::pad( + &ui::severity(&vuln.severity.to_uppercase(), color), + severity_w + ), + ui::pad(label, label_w), + ui::truncate(&vuln.summary, 100), + ); + lines.push(line.trim_end().to_string()); + } + } + + let measured = patch + .statistics + .as_ref() + .map(|stats| super::measured::lines_with(stats, true)) + .unwrap_or_default(); + if !measured.is_empty() { + lines.push(String::new()); + lines.push("Measured by Socket:".to_string()); + lines.extend(measured.iter().map(|line| format!(" {line}"))); + } + + let (added, removed) = files + .iter() + .filter_map(|f| f.diff.as_ref().ok()) + .fold((0, 0), |(a, r), d| (a + d.added, r + d.removed)); + lines.push(String::new()); + lines.push(format!( + "{} changed: {} {}", + plural(files.len(), "file", "files"), + ui::paint(&format!("+{added}"), "32", color), + ui::paint(&format!("-{removed}"), "31", color), + )); + let path_w = files + .iter() + .map(|f| ui::printable(&f.path).chars().count()) + .max() + .unwrap_or(0); + for file in files { + lines.push(format!( + " {} {}", + ui::pad(&ui::printable(&file.path), path_w), + change_label(file, color) + )); + } + lines +} + +/// `patch` with every piece of text it carries made printable +/// ([`ui::printable`]), for showing. `--json` prints the record as it +/// came: JSON escapes what it carries. +fn printable_patch(patch: &PatchResponse) -> PatchResponse { + let text = |s: &str| ui::printable(s); + PatchResponse { + uuid: text(&patch.uuid), + purl: text(&patch.purl), + published_at: text(&patch.published_at), + description: text(&patch.description), + license: text(&patch.license), + tier: text(&patch.tier), + vulnerabilities: patch + .vulnerabilities + .iter() + .map(|(id, vuln)| { + let mut vuln = vuln.clone(); + vuln.cves = vuln.cves.iter().map(|cve| text(cve)).collect(); + vuln.summary = text(&vuln.summary); + vuln.severity = text(&vuln.severity); + (text(id), vuln) + }) + .collect(), + ..patch.clone() + } +} + +/// The diff of one file as text: its lines, or why there is none. +fn diff_text(file: &ShownFile) -> String { + match &file.diff { + Ok(diff) => diff.lines.join("\n"), + Err(why) => { + let path = ui::printable(&file.path); + format!( + "--- a/{path}\n+++ b/{path}\nNo diff: {} (before {}, after {}).", + ui::printable(why), + ui::printable(&file.before_hash), + ui::printable(&file.after_hash) + ) + } + } +} + +/// The patch service as one run reads patches from it: the run's own +/// client and, for a read the service refuses that client's token (401 / +/// 403), the public service, which has the free patches. The public +/// client is built once, on the first refusal. +pub(crate) struct Source { + client: ApiClient, + overrides: ApiClientEnvOverrides, + public: std::sync::OnceLock, +} + +impl Source { + pub(crate) fn new(client: ApiClient, overrides: ApiClientEnvOverrides) -> Source { + Source { + client, + overrides, + public: std::sync::OnceLock::new(), + } + } + + /// The run's own client. + pub(crate) fn client(&self) -> &ApiClient { + &self.client + } + + /// Ask the service with `read`: the client that answered, and its + /// answer. A refusal the public service cannot make good (it has no + /// such patch, or cannot be reached) stays the answer: it is the + /// cause, and the public service's "no such patch" would hide it. + pub(crate) async fn ask<'s, T, F, Fut>( + &'s self, + read: F, + ) -> (&'s ApiClient, Result, ApiError>) + where + F: Fn(&'s ApiClient) -> Fut, + Fut: std::future::Future, ApiError>>, + { + let answer = read(&self.client).await; + let refused = matches!(&answer, Err(e) if is_fallback_candidate(e)); + if refused && !self.client.uses_public_proxy() { + let public = self + .public + .get_or_init(|| build_proxy_fallback_client(&self.overrides)); + if let Ok(Some(found)) = read(public).await { + return (public, Ok(Some(found))); + } + } + (&self.client, answer) + } +} + +/// A patch as the patch service has it, with the diff of each file it +/// changes: everything `show` prints and everything the page shows. +struct Shown { + patch: PatchResponse, + files: Vec, +} + +/// Why a patch could not be read: the code `--json` reports it under, and +/// the reason as the end of a sentence (`Error: `). +struct Unread { + code: &'static str, + message: String, +} + +impl Shown { + /// Read patch `uuid` and the content of its files from the patch + /// service ([`Source::ask`]): the one way a patch is read, for `show` + /// and for the page a `list` row opens. `style` colors the diff + /// lines. + async fn read(source: &Source, uuid: &str, style: Style) -> Result { + let (client, view) = source + .ask(|client| client.fetch_patch_with_sources(uuid)) + .await; + let patch = match view { + Ok(Some(patch)) => patch, + Ok(None) => { + return Err(Unread { + code: "patch_not_found", + message: format!("no patch found with UUID {uuid}"), + }) + } + Err(e) => { + let message = match &e { + ApiError::Forbidden(_) => format!( + "patch {uuid} needs a paid Socket plan, or access this token does not \ + have ({e})" + ), + _ => e.to_string(), + }; + return Err(Unread { + code: "patch_fetch_failed", + message, + }); + } + }; + let files = shown_files(client, &patch, style).await; + Ok(Shown { patch, files }) + } + + /// The patch as a page of the full-screen browser: under the package + /// as its title, what the patch fixes and what was measured about it + /// (the summary), then the diff of each of `selected`, with a mark at + /// each so the reader can step from file to file. + fn page(&self, selected: &[&ShownFile], style: Style) -> ui::browser::Page { + let summary = summary(&self.patch, &self.files, style); + let title = summary.first().map(|head| ui::strip_ansi(head)); + let mut lines: Vec = summary.into_iter().skip(1).collect(); + let mut marks = Vec::new(); + for file in selected { + lines.push(String::new()); + marks.push((lines.len(), ui::printable(&file.path))); + lines.extend(diff_text(file).lines().map(str::to_string)); + } + ui::browser::Page { + title: title.unwrap_or_default(), + lines, + marks, + } + } +} + +/// Patch `uuid` as the page `show` opens for it, every file's diff +/// included ([`Shown::read`], [`Shown::page`]): what a row of `list` +/// opens. `Err` is why there is none, as the end of a sentence. Nothing +/// is printed: the caller has the screen. +pub(crate) async fn load_page( + source: &Source, + uuid: &str, + style: Style, +) -> Result { + // The uuid comes from a project's own files: only one that is a UUID + // goes into a request to the patch service. + if !socket_patch_core::utils::target::is_uuid_shaped(uuid) { + return Err("the project records no valid patch UUID for it".to_string()); + } + let shown = Shown::read(source, uuid, style) + .await + .map_err(|unread| unread.message)?; + let all: Vec<&ShownFile> = shown.files.iter().collect(); + Ok(shown.page(&all, style)) +} + +/// The files `--file` selects: each spec names a path of the patch, or +/// the end of one at a `/`. `Err` names the first spec that selects none. +fn select_files<'a>( + files: &'a [ShownFile], + specs: &[String], +) -> Result, String> { + if specs.is_empty() { + return Ok(files.iter().collect()); + } + let matches = |path: &str, spec: &str| { + let spec = spec.trim_start_matches("./"); + path == spec || path.ends_with(&format!("/{spec}")) + }; + for spec in specs { + if !files.iter().any(|f| matches(&f.path, spec)) { + return Err(format!( + "`{spec}` is not a file of this patch; it changes: {}", + files + .iter() + .map(|f| f.path.as_str()) + .collect::>() + .join(", ") + )); + } + } + Ok(files + .iter() + .filter(|f| specs.iter().any(|spec| matches(&f.path, spec))) + .collect()) +} + +/// One line of the patch menu: `8be53d06 pkg:npm/undici@8.10.0 HIGH +/// CVE-2026-84961, CVE-2026-85024`. +fn candidate_label(patch: &PatchSearchResult) -> String { + let (severity, ids) = ui::worst_and_ids( + patch + .vulnerabilities + .iter() + .map(|(id, vuln)| (id.as_str(), vuln.severity.as_str(), vuln.cves.as_slice())), + ); + format!( + "{} {} {severity} {}", + ui::short_uuid(&patch.uuid), + normalize_purl(&patch.purl), + ids.join(", ") + ) +} + +/// The patches a target names, best first, and whether the account may +/// read the paid ones among them. +struct Found { + patches: Vec, + can_access_paid: bool, +} + +/// Why the patches a target names could not be looked up. +enum Lookup { + /// The patch service's own answer. A refusal of the token among them + /// is what the public service may make good. + Service(ApiError), + /// The target itself: a name no installed package has, or too many. + Target(String), +} + +impl Lookup { + fn message(&self) -> String { + match self { + Lookup::Service(e) => e.to_string(), + Lookup::Target(message) => message.clone(), + } + } +} + +/// The patches `target` names, best first: an advisory's or a purl's by +/// search, a name's by searching each installed package it matches. +async fn candidates(args: &ShowArgs, target: &Target, client: &ApiClient) -> Result { + let searched = match target.kind() { + TargetKind::Cve => client.search_patches_by_cve(target.as_str()).await, + TargetKind::Ghsa => client.search_patches_by_ghsa(target.as_str()).await, + TargetKind::Purl => client.search_patches_by_package(target.as_str()).await, + TargetKind::Uuid | TargetKind::Name => { + let only = args.common.ecosystems.as_deref().filter(|l| !l.is_empty()); + let (packages, _, _) = crawl_ecosystems(&args.common.crawler_options(), only).await; + let matched = installed_target_matches(target, &packages); + if matched.is_empty() { + return Err(Lookup::Target(format!( + "no installed package is named `{target}`; pass a PURL (pkg:npm/{target}@1.2.3) \ + or a patch UUID" + ))); + } + if matched.len() > MAX_NAME_MATCHES { + return Err(Lookup::Target(format!( + "`{target}` names {} installed packages; pass the PURL of one", + matched.len() + ))); + } + let mut found = Found { + patches: Vec::new(), + can_access_paid: true, + }; + for purl in &matched { + let answer = client + .search_patches_by_package(purl) + .await + .map_err(Lookup::Service)?; + found.patches.extend(answer.patches); + found.can_access_paid &= answer.can_access_paid_patches; + } + found.patches.sort_by(cmp_search_results); + return Ok(found); + } + }; + searched + .map(|answer| Found { + patches: answer.patches, + can_access_paid: answer.can_access_paid_patches, + }) + .map_err(Lookup::Service) +} + +/// The patch to show of several that match, when nobody is asked: the +/// best ranked one the account can read, so a paid patch ranked first +/// does not stand in the way of a free one; the best ranked when it can +/// read none. +fn best_readable(many: &[PatchSearchResult], can_access_paid: bool) -> usize { + many.iter() + .position(|patch| can_access_paid || patch.tier != "paid") + .unwrap_or(0) +} + +pub async fn run(args: ShowArgs) -> i32 { + apply_env_toggles(&args.common); + let common = &args.common; + if common.offline { + return fail( + common, + "offline_unsupported", + "show reads the patch from the patch service and cannot run with \ + --offline/SOCKET_OFFLINE", + ); + } + let target = Target::parse(&args.identifier); + let overrides = common.api_client_overrides(); + let (mut client, _) = get_api_client_with_overrides(overrides.clone()).await; + let mut status = ui::StatusLine::stderr(common.json, common.silent); + + // Which patch: the UUID given, or the pick among the ones found. + let uuid = if target.kind() == TargetKind::Uuid { + args.identifier.clone() + } else { + status.set(format!("Finding patches for {target}...")); + let mut found = candidates(&args, &target, &client).await; + // A refused token still reaches the free patches: the public + // service is asked, and its answer stands in when it has any. + // When it has none, the refusal stays the answer: it is the + // cause. Any other failure (the service down, a name that + // matches nothing) is reported as it is. + if let Err(Lookup::Service(refusal)) = &found { + if !client.uses_public_proxy() && is_fallback_candidate(refusal) { + let proxy = build_proxy_fallback_client(&overrides); + if let Ok(free) = candidates(&args, &target, &proxy).await { + if !free.patches.is_empty() { + (client, found) = (proxy, Ok(free)); + } + } + } + } + status.finish(); + let found = match found { + Ok(found) => found, + Err(lookup) => return fail(common, "patch_lookup_failed", &lookup.message()), + }; + match found.patches.as_slice() { + [] => { + return fail( + common, + "no_patches", + &format!("no patches found for {} {target}", target.kind()), + ) + } + [only] => only.uuid.clone(), + many => { + let menu = !common.json + && !common.silent + && !common.yes + && ui::attended(ui::Stream::Stdin) + && ui::attended(ui::Stream::Stderr); + let labels: Vec = many.iter().map(candidate_label).collect(); + if menu { + match select_one("Which patch?", &labels, common) { + Ok(picked) => many[picked].uuid.clone(), + Err(_) => return 0, + } + } else { + let shown = best_readable(many, found.can_access_paid); + if !common.json && !common.silent { + eprintln!( + "{} match {target}; showing the best ranked. The others:", + plural(many.len(), "patch", "patches") + ); + for (_, label) in labels.iter().enumerate().filter(|(i, _)| *i != shown) { + eprintln!(" {label}"); + } + } + many[shown].uuid.clone() + } + } + } + }; + + status.set(format!("Reading patch {}...", ui::short_uuid(&uuid))); + let style = if common.json { + Style::PLAIN + } else { + Style::stdout() + }; + let source = Source::new(client, overrides); + let shown = Shown::read(&source, &uuid, style).await; + status.finish(); + let shown = match shown { + Ok(shown) => shown, + Err(unread) => return fail(common, unread.code, &unread.message), + }; + let (patch, files) = (&shown.patch, &shown.files); + // Before any form of output: a `--file` the patch does not change is + // an error under `--json` and `--silent` too. + let selected = match select_files(files, &args.files) { + Ok(selected) => selected, + Err(message) => return fail(common, "file_not_in_patch", &message), + }; + + if common.json { + ui::print_json(&serde_json::json!({ + "command": "show", + "status": "success", + "patch": { + "uuid": patch.uuid, + "purl": patch.purl, + "tier": patch.tier, + "publishedAt": patch.published_at, + "license": patch.license, + "description": patch.description, + "vulnerabilities": patch.vulnerabilities, + "statistics": patch.statistics, + "files": files.iter().map(|file| serde_json::json!({ + "path": file.path, + "beforeHash": file.before_hash, + "afterHash": file.after_hash, + "added": file.diff.as_ref().ok().map(|d| d.added), + "removed": file.diff.as_ref().ok().map(|d| d.removed), + "binary": file.diff.as_ref().is_ok_and(|d| d.binary), + })).collect::>(), + }, + })); + return 0; + } + if common.silent { + return 0; + } + + // Someone at a terminal reads the patch on the page a row of `list` + // opens: the summary and every selected diff, which scrolls, steps + // from file to file and follows the terminal's size. Where there is + // no such screen (a pipe, `--no-pager`, `--yes`, a terminal that + // shows no escape sequences or cannot be set up), the same text + // prints below. + let wanted = !args.stat && !args.no_pager && !common.yes && !selected.is_empty(); + let reads = wanted && ui::full_screen(); + if wanted && !reads { + // On a terminal this would have been the page: say why not. + ui::note_agent_terminal(common); + } + let read = reads && ui::browser::read(shown.page(&selected, style)); + // The summary is what stays on the terminal either way. + for line in summary(patch, files, style) { + println!("{line}"); + } + if args.stat || selected.is_empty() || read { + return 0; + } + println!(); + for file in &selected { + println!("{}", diff_text(file)); + } + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::commands::measured::tests::stats; + use socket_patch_core::api::types::VulnerabilityResponse; + use std::collections::HashMap; + + fn file(path: &str, before: Option<&str>, after: &str) -> ShownFile { + ShownFile { + path: path.to_string(), + before_hash: "b".repeat(64), + after_hash: "a".repeat(64), + diff: Ok(file_diff( + path, + before.map(str::as_bytes), + after.as_bytes(), + Style::PLAIN, + )), + } + } + + fn patch() -> PatchResponse { + let vuln = |cves: &[&str], severity: &str, summary: &str| VulnerabilityResponse { + cves: cves.iter().map(|c| c.to_string()).collect(), + summary: summary.to_string(), + severity: severity.to_string(), + description: String::new(), + }; + PatchResponse { + uuid: "8be53d06-7bd4-40cc-ab8f-36dc6248985a".to_string(), + purl: "pkg:npm/%40scope/undici@8.10.0".to_string(), + published_at: "Mon, 03 Aug 2026 19:12:42 GMT".to_string(), + files: HashMap::new(), + vulnerabilities: [ + ( + "GHSA-b".to_string(), + vuln(&["CVE-2026-85024"], "MODERATE", "DoS in WebSocket"), + ), + ( + "GHSA-a".to_string(), + vuln(&["CVE-2026-84961"], "HIGH", "TLS validation bypass"), + ), + ("GHSA-c".to_string(), vuln(&[], "low", "")), + ] + .into(), + description: String::new(), + license: "MIT".to_string(), + tier: "paid".to_string(), + statistics: Some(stats(2, 35, 35)), + } + } + + #[test] + fn summary_names_the_patch_its_fixes_measurements_and_files() { + let files = vec![ + file("lib/a.js", Some("one\ntwo\n"), "one\nTWO\nthree\n"), + file("lib/new.js", None, "x\n"), + ShownFile { + path: "big.bin".to_string(), + before_hash: String::new(), + after_hash: String::new(), + diff: Err("the file is too large to diff".to_string()), + }, + ]; + assert_eq!( + summary(&patch(), &files, Style::PLAIN), + vec![ + "pkg:npm/@scope/undici@8.10.0 HIGH [PAID]", + "Patch 8be53d06-7bd4-40cc-ab8f-36dc6248985a, published 03 Aug 2026, MIT", + "", + "Fixes:", + " HIGH CVE-2026-84961 TLS validation bypass", + " MODERATE CVE-2026-85024 DoS in WebSocket", + " LOW GHSA-c", + "", + "Measured by Socket:", + " Verified: 2 of 2 exploits blocked, 35 of 35 tests passing", + "", + "3 files changed: +3 -1", + " lib/a.js +2 -1", + " lib/new.js +1 -0", + " big.bin (the file is too large to diff)", + ] + ); + // An advisory that names no severity leaves none in the title: + // the same rule as the row of `list` this page opens from. + let blank = PatchResponse { + vulnerabilities: [( + "GHSA-c".to_string(), + VulnerabilityResponse { + cves: Vec::new(), + summary: String::new(), + severity: " ".to_string(), + description: String::new(), + }, + )] + .into(), + ..patch() + }; + assert_eq!( + summary(&blank, &files[..1], Style::PLAIN)[0], + "pkg:npm/@scope/undici@8.10.0 [PAID]" + ); + // No advisories, no measurements: those sections are left out. + let bare = PatchResponse { + vulnerabilities: HashMap::new(), + statistics: None, + published_at: String::new(), + license: String::new(), + ..patch() + }; + assert_eq!( + summary(&bare, &files[..1], Style::PLAIN), + vec![ + "pkg:npm/@scope/undici@8.10.0 [PAID]", + "Patch 8be53d06-7bd4-40cc-ab8f-36dc6248985a", + "", + "1 file changed: +2 -1", + " lib/a.js +2 -1", + ] + ); + } + + #[test] + fn file_specs_select_by_path_or_its_end() { + let files = vec![ + file("lib/a.js", Some("a\n"), "b\n"), + file("lib/web/a.js", Some("a\n"), "b\n"), + file("README.md", Some("a\n"), "b\n"), + ]; + let paths = |specs: &[&str]| { + let specs: Vec = specs.iter().map(|s| s.to_string()).collect(); + select_files(&files, &specs) + .map(|fs| fs.iter().map(|f| f.path.clone()).collect::>()) + }; + assert_eq!(paths(&[]).unwrap().len(), 3); + assert_eq!(paths(&["README.md"]).unwrap(), ["README.md"]); + assert_eq!(paths(&["./lib/a.js"]).unwrap(), ["lib/a.js"]); + // The end of a path, at a `/`: both `a.js`, never `xa.js`. + assert_eq!(paths(&["a.js"]).unwrap(), ["lib/a.js", "lib/web/a.js"]); + assert_eq!(paths(&["web/a.js", "README.md"]).unwrap().len(), 2); + let err = paths(&["b.js"]).unwrap_err(); + assert!( + err.starts_with("`b.js` is not a file of this patch; it changes: lib/a.js, "), + "{err}" + ); + assert!(paths(&["js"]).is_err()); + } + + #[test] + fn diff_text_says_why_a_file_has_no_diff() { + let unread = ShownFile { + path: "lib/a.js".to_string(), + before_hash: "bb".to_string(), + after_hash: "aa".to_string(), + diff: Err("the file is too large to diff".to_string()), + }; + assert_eq!( + diff_text(&unread), + "--- a/lib/a.js\n+++ b/lib/a.js\nNo diff: the file is too large to diff \ + (before bb, after aa)." + ); + assert_eq!( + diff_text(&file("f", Some("a\n"), "b\n")), + "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-a\n+b" + ); + } + + #[test] + fn short_date_reads_both_timestamp_shapes() { + assert_eq!(short_date("Fri, 27 Mar 2026 19:12:42 GMT"), "27 Mar 2026"); + assert_eq!(short_date("2024-01-01T00:00:00Z"), "2024-01-01"); + assert_eq!(short_date("yesterday"), "yesterday"); + } + + /// Nobody asked which of several patches: the best ranked one the + /// account can read is shown, so a paid patch ranked first does not + /// fail the run when a free one is there. + #[test] + fn the_patch_shown_of_several_is_one_the_account_can_read() { + let patch = |tier: &str| PatchSearchResult { + uuid: String::new(), + purl: "pkg:npm/x@1.0.0".to_string(), + published_at: String::new(), + description: String::new(), + license: String::new(), + tier: tier.to_string(), + vulnerabilities: HashMap::new(), + }; + let many = [patch("paid"), patch("paid"), patch("free"), patch("free")]; + assert_eq!(best_readable(&many, true), 0); + assert_eq!(best_readable(&many, false), 2); + assert_eq!(best_readable(&many[..2], false), 0); + assert_eq!(best_readable(&many[2..], false), 0); + } + + #[test] + fn candidate_label_names_the_patch_in_one_line() { + let found = PatchSearchResult { + uuid: "8be53d06-7bd4-40cc-ab8f-36dc6248985a".to_string(), + purl: "pkg:npm/undici@8.10.0".to_string(), + published_at: String::new(), + description: String::new(), + license: String::new(), + tier: "paid".to_string(), + vulnerabilities: patch().vulnerabilities, + }; + assert_eq!( + candidate_label(&found), + "8be53d06 pkg:npm/undici@8.10.0 HIGH CVE-2026-84961, CVE-2026-85024, GHSA-c" + ); + } +} diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index a5a84cbb6..c6d4701ab 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4514,16 +4514,10 @@ fn print_vendor_closing( cmds.join(" and ") ) } else if installs.is_empty() { - "Reinstall from the updated lockfile so the installed packages pick up the \ - vendored artifacts" - .to_string() + "Reinstall from the updated lockfile".to_string() } else { let cmds: Vec = installs.iter().map(|c| format!("`{c}`")).collect(); - format!( - "Run {} to update the installed tree (vendoring rewires the lockfile \ - only; the current install keeps the unpatched bytes until reinstalled)", - cmds.join(" and ") - ) + format!("Run {} to update the installed tree", cmds.join(" and ")) }; let mut extra = Vec::new(); if wired_flavors.contains("bun") && common.cwd.join("bun.lockb").exists() { diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index d5926d63c..33b987da0 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -183,6 +183,7 @@ impl VexEmbedArgs { flag_prefix: "--vex-", npm_prior: None, hosted_uuids: Vec::new(), + warnings_printed: Default::default(), } } } @@ -253,6 +254,10 @@ pub(crate) struct VexBuildParams { /// command, else built at most once when the plan must fetch records. /// Telemetry reads its route when it exists. pub api_client: RunApiClient, + /// How many of the run's advisories a human run has printed so far + /// ([`flush_warnings`]): they are held while the run works (a status + /// line is up) and printed folded, each once. + pub warnings_printed: std::sync::atomic::AtomicUsize, } impl VexBuildParams { @@ -375,6 +380,7 @@ pub async fn run(args: VexArgs) -> i32 { "org_looks_like_path", detail, ); + print_warnings(&args.common, &run_warnings); } let params = VexBuildParams { @@ -393,6 +399,7 @@ pub async fn run(args: VexArgs) -> i32 { npm_prior: None, hosted_uuids: Vec::new(), api_client: RunApiClient::new(), + warnings_printed: Default::default(), }; // One project for the whole document (#745): the ledgers and the @@ -855,9 +862,18 @@ async fn generate_vex( // every copy, so an agent record is attested only when EVERY copy // verifies; the first copy alone would vouch for a later install's // unpatched nested duplicate. + // The lookup and the checks below walk and hash the installed + // tree: the status line says so while they last. A run whose + // lookup prints its own lines (`quiet` off) shows it for the + // checks alone. + let mut verifying = crate::ui::StatusLine::stderr(common.json, common.silent); + if quiet { + verifying.set("Finding installed packages"); + } let copies = find_manifest_package_copies_reusing(&purls, common, quiet, params.npm_prior.as_ref()) .await; + verifying.set("Verifying installed patches"); // The record check: every copy of each purl; for Maven, every copy // a build consumes (`~/.m2` unless the Gradle build never reads it, // each Gradle cache, the read-only cache), re-hashed @@ -888,6 +904,7 @@ async fn generate_vex( Some(&vendor), ) .await; + verifying.finish(); // Hosted lockfile basis: a DISCOVERED Socket-host reference whose // lock pins the artifact attests from that wiring when no installed // tree exists yet (a lockfile-only CI checkout) — the evidence the @@ -1344,9 +1361,11 @@ async fn generate_vex( outcome .failed .sort_by(|a, b| (&a.purl, &a.reason).cmp(&(&b.purl, &b.reason))); + // The advisories first (they say why), then what was left out. + flush_warnings(common, params, warnings); if !common.silent && !common.json { - for f in &outcome.failed { - eprintln!("{}", format_omission_warning(&f.purl, &f.reason)); + for line in omission_lines(&outcome.failed, common.verbose) { + eprintln!("{line}"); } } @@ -1854,21 +1873,102 @@ fn vendored_out_of_sync_detail(purl: &str, copies: &[&Path], notes: &str) -> Str ) } -/// Record a run-level advisory the way `update`/`vendor` do: stderr -/// (`Warning: `) in human mode, and into `warnings` so the `--json` -/// envelope — which silences stderr — carries it in `warnings[]` instead. -/// Under `--silent` only the envelope copy survives (warnings are not -/// errors). -fn note_warning(warnings: &mut Vec, common: &GlobalArgs, code: &str, detail: String) { - if !common.silent && !common.json { - eprintln!("Warning: {detail}"); - } +/// Record a run-level advisory: into `warnings`, which the `--json` +/// envelope carries in `warnings[]`. A human run prints it later, folded +/// with the others of its kind ([`flush_warnings`]): nothing prints while +/// the run works, so its status line stays whole, and forty advisories of +/// one kind are not forty lines. Under `--silent` only the envelope copy +/// survives (warnings are not errors). +fn note_warning(warnings: &mut Vec, _common: &GlobalArgs, code: &str, detail: String) { warnings.push(RunWarning { code: code.to_string(), detail, }); } +/// How many advisories of one kind, and how many names, a human run +/// prints before it folds the rest (`--verbose` prints every one). +const SHOWN_OF_A_KIND: usize = 1; +const NAMES_SHOWN: usize = 3; + +/// The human lines of `warnings`: each kind's first advisory in full, +/// then one line for the rest of that kind, naming the packages they are +/// about where each opens with one (`pkg:npm/glob@10.3.16: ...`). +/// `verbose` prints every advisory. +fn warning_lines(warnings: &[RunWarning], verbose: bool) -> Vec { + let mut kinds: Vec<(&str, Vec<&RunWarning>)> = Vec::new(); + for warning in warnings { + match kinds.iter_mut().find(|(code, _)| *code == warning.code) { + Some((_, of_kind)) => of_kind.push(warning), + None => kinds.push((&warning.code, vec![warning])), + } + } + let mut lines = Vec::new(); + for (_, of_kind) in kinds { + let shown = if verbose { + of_kind.len() + } else { + SHOWN_OF_A_KIND + }; + lines.extend( + of_kind + .iter() + .take(shown) + .map(|warning| format!("Warning: {}", warning.detail)), + ); + let rest = &of_kind[shown.min(of_kind.len())..]; + if rest.is_empty() { + continue; + } + // The package each of the rest is about, when it says so up front. + let purls: Vec<&str> = rest + .iter() + .filter_map(|warning| { + let (purl, _) = warning.detail.split_once(": ")?; + purl.starts_with("pkg:").then_some(purl) + }) + .collect(); + let like = if rest.len() == 1 { "this" } else { "these" }; + lines.push(if purls.len() == rest.len() { + format!( + " ... and {} more like {like}: {} (--verbose lists them all)", + rest.len(), + crate::ui::folded(&crate::ui::package_names(&purls), NAMES_SHOWN) + ) + } else { + format!( + " ... and {} more like {like} (--verbose lists them all)", + rest.len() + ) + }); + } + lines +} + +/// Print `warnings` to stderr the way a human run shows them +/// ([`warning_lines`]); nothing under `--json` (the envelope carries +/// them) or `--silent`. +fn print_warnings(common: &GlobalArgs, warnings: &[RunWarning]) { + if common.silent || common.json { + return; + } + for line in warning_lines(warnings, common.verbose) { + eprintln!("{line}"); + } +} + +/// Print the advisories recorded since the last flush ([`print_warnings`]). +/// Called where the run is about to print anyway: before its omissions, +/// and when generation ends. +fn flush_warnings(common: &GlobalArgs, params: &VexBuildParams, warnings: &[RunWarning]) { + use std::sync::atomic::Ordering; + let printed = params + .warnings_printed + .swap(warnings.len(), Ordering::Relaxed) + .min(warnings.len()); + print_warnings(common, &warnings[printed..]); +} + /// True when `s` opens with an RFC 3986/3987 scheme /// (`ALPHA *(ALPHA / DIGIT / "+" / "-" / ".") ":"`). A purl passes the same /// test (`pkg:` is a scheme), so one check covers both halves of the help @@ -1960,6 +2060,7 @@ async fn generate_vex_with_cleanup( .await; match result { Ok(mut summary) => { + flush_warnings(common, params, &warnings); summary.warnings = warnings; Ok(summary) } @@ -1981,6 +2082,7 @@ async fn generate_vex_with_cleanup( } } } + flush_warnings(common, params, &warnings); e.warnings = warnings; Err(e) } @@ -2085,7 +2187,12 @@ async fn generate_vex_from_manifest_path_inner( // too: discovery is what gates the ledgers (core discover rule 11); // without it the raw-text fallbacks would decide a uuid a lockfile // mentions, attesting a commented-out or rejected pin. - let discovery = crate::commands::discover_wiring(common, &common.project_root()).await; + let discovery = crate::ui::busy( + common, + "Reading lockfiles", + crate::commands::discover_wiring(common, &common.project_root()), + ) + .await; for diag in &discovery.diagnostics { note_warning(warnings, common, diag.code, diag.detail.clone()); } @@ -2363,12 +2470,16 @@ fn emit_envelope_error( println!("{}", env.to_pretty_json()); } else { eprintln!("Error: {message}"); - // The per-patch "Warning: omitting ..." lines already named each - // omission; `--silent` muted them, so list them with the error. + // The "Warning: omitting ..." lines already named the omissions; + // `--silent` muted them, so list them with the error. if args.common.silent { for f in failures { eprintln!(" omitted: {} ({})", f.purl, f.reason); } + } else if let Some(hint) = + nothing_attested_hint(failures).filter(|_| code == "no_applicable_patches") + { + eprintln!("{hint}"); } } } @@ -2468,6 +2579,10 @@ fn omission_phrase(reason: &str) -> &'static str { "the lockfiles wire this package to different patches, so which one the build \ installs cannot be determined" } + "vex_pnpm_bundled_copy" => { + "another package bundles its own copy, which no Socket wiring reaches (the \ + warning above names it)" + } _ => "the patch could not be verified", } } @@ -2481,6 +2596,78 @@ fn format_omission_warning(purl: &str, reason: &str) -> String { ) } +/// The stderr lines for the patches left out of the document: one per +/// reason, with the count and the first few packages (a project that has +/// not installed its patched packages yet leaves every one of them out +/// for the same reason). A reason with one patch keeps the per-patch +/// line, and `verbose` prints that line for every patch. `failed` is +/// sorted by purl; the reasons come largest first. +fn omission_lines(failed: &[FailedPatch], verbose: bool) -> Vec { + if verbose { + return failed + .iter() + .map(|f| format_omission_warning(&f.purl, &f.reason)) + .collect(); + } + let mut reasons: Vec<(&str, Vec<&str>)> = Vec::new(); + for f in failed { + match reasons.iter_mut().find(|(reason, _)| *reason == f.reason) { + Some((_, purls)) => purls.push(&f.purl), + None => reasons.push((&f.reason, vec![&f.purl])), + } + } + reasons.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then(a.0.cmp(b.0))); + reasons + .into_iter() + .map(|(reason, purls)| match purls.as_slice() { + [purl] => format_omission_warning(purl, reason), + _ => format!( + "Warning: omitting {} packages from VEX: {} ({reason}): {}{}", + purls.len(), + omission_phrase(reason), + crate::ui::folded(&crate::ui::package_names(&purls), NAMES_SHOWN), + if purls.len() > NAMES_SHOWN { + " (--verbose lists them all)" + } else { + "" + } + ), + }) + .collect() +} + +/// What to do about a document nothing could go into, said under the +/// error, when patches were left out for a reason with a remedy: the +/// patched packages are not installed yet (the usual case right after a +/// hosted or vendored scan), or not installed at all. +fn nothing_attested_hint(failed: &[FailedPatch]) -> Option { + let count = |reason: &str| failed.iter().filter(|f| f.reason == reason).count(); + let of = |n: usize| { + if n == failed.len() { + "The".to_string() + } else { + format!("{n} of the") + } + }; + let not_applied = count("not_applied"); + if not_applied > 0 { + return Some(format!( + "{} patched packages are not installed yet: the installed copies still hold their \ + original files. Reinstall from the lockfile (hosted or vendored patches) or run \ + `socket-patch apply` (agent-mode patches), then run `socket-patch vex` again.", + of(not_applied) + )); + } + let missing = count("package_not_found"); + (missing > 0).then(|| { + format!( + "{} patched packages are not installed here. Run your package manager's install, \ + then `socket-patch vex` again.", + of(missing) + ) + }) +} + /// Human `reason` string for an omission event; the routing tag rides /// `errorCode`. fn omission_reason_message(reason: &str) -> String { @@ -2662,6 +2849,145 @@ mod tests { assert_eq!(format_vex_emitted(12), "Emitted 12 VEX statements"); } + fn failed(purl: &str, reason: &str) -> FailedPatch { + FailedPatch { + purl: purl.to_string(), + reason: reason.to_string(), + } + } + + /// The reported flood: a project that has not installed its patched + /// packages yet got one line per package. The patches left out are one + /// line per reason, largest first, with the count and the first few + /// names; a reason with one patch keeps its line, and `--verbose` + /// prints the line of every patch. + #[test] + fn omissions_are_one_line_per_reason() { + let mut patches: Vec = (0..82) + .map(|i| failed(&format!("pkg:npm/dep-{i:02}@1.0.0"), "not_applied")) + .collect(); + patches.push(failed( + "pkg:npm/%40scope/glob@10.3.16", + "vex_pnpm_bundled_copy", + )); + patches.push(failed("pkg:npm/tar@7.4.3", "vex_pnpm_bundled_copy")); + patches.push(failed("pkg:npm/gone@1.0.0", "package_not_found")); + assert_eq!( + omission_lines(&patches, false), + [ + "Warning: omitting 82 packages from VEX: the patched files still hold the \ + original content (not_applied): dep-00@1.0.0, dep-01@1.0.0, dep-02@1.0.0 and \ + 79 more (--verbose lists them all)", + "Warning: omitting 2 packages from VEX: another package bundles its own copy, \ + which no Socket wiring reaches (the warning above names it) \ + (vex_pnpm_bundled_copy): @scope/glob@10.3.16, tar@7.4.3", + "Warning: omitting pkg:npm/gone@1.0.0 from VEX: the package is not installed \ + (package_not_found)", + ] + ); + let verbose = omission_lines(&patches, true); + assert_eq!(verbose.len(), 85); + assert_eq!( + verbose[0], + "Warning: omitting pkg:npm/dep-00@1.0.0 from VEX: the patched files still hold the \ + original content (not_applied)" + ); + assert!(omission_lines(&[], false).is_empty()); + // Packages of two ecosystems are named by purl. + assert_eq!( + omission_lines( + &[ + failed("pkg:npm/a@1.0.0", "not_applied"), + failed("pkg:pypi/b@2.0.0", "not_applied"), + ], + false + ), + [ + "Warning: omitting 2 packages from VEX: the patched files still hold the original \ + content (not_applied): pkg:npm/a@1.0.0, pkg:pypi/b@2.0.0" + ] + ); + } + + /// Advisories of one kind print once in full, then as one line naming + /// the packages the rest are about; `--verbose` prints every one. + #[test] + fn advisories_of_one_kind_fold_into_two_lines() { + let warning = |code: &str, detail: &str| RunWarning { + code: code.to_string(), + detail: detail.to_string(), + }; + let mut warnings = vec![warning("org_looks_like_path", "the org looks like a path")]; + warnings.extend( + [ + "glob@10.3.16", + "glob@10.4.5", + "minimatch@3.1.2", + "tar@6.2.1", + "tar@7.4.3", + ] + .map(|package| { + warning( + "vex_pnpm_bundled_copy", + &format!("pkg:npm/{package}: patch is wired, but npm@11.19.0 bundles a copy"), + ) + }), + ); + warnings.push(warning("vex_lock_not_read", "yarn.lock could not be read")); + warnings.push(warning("vex_lock_not_read", "bun.lock could not be read")); + assert_eq!( + warning_lines(&warnings, false), + [ + "Warning: the org looks like a path", + "Warning: pkg:npm/glob@10.3.16: patch is wired, but npm@11.19.0 bundles a copy", + " ... and 4 more like these: glob@10.4.5, minimatch@3.1.2, tar@6.2.1 and 1 more \ + (--verbose lists them all)", + "Warning: yarn.lock could not be read", + " ... and 1 more like this (--verbose lists them all)", + ] + ); + let verbose = warning_lines(&warnings, true); + assert_eq!(verbose.len(), 8); + assert!(verbose.iter().all(|line| line.starts_with("Warning: "))); + assert!(warning_lines(&[], false).is_empty()); + } + + /// Under "nothing to attest", the remedy for the patches that only + /// need installing. + #[test] + fn nothing_attested_says_how_to_get_the_patches_installed() { + let all = [ + failed("pkg:npm/a@1.0.0", "not_applied"), + failed("pkg:npm/b@1.0.0", "not_applied"), + ]; + assert_eq!( + nothing_attested_hint(&all).as_deref(), + Some( + "The patched packages are not installed yet: the installed copies still hold \ + their original files. Reinstall from the lockfile (hosted or vendored patches) \ + or run `socket-patch apply` (agent-mode patches), then run `socket-patch vex` \ + again." + ) + ); + let some = [ + failed("pkg:npm/a@1.0.0", "not_applied"), + failed("pkg:npm/b@1.0.0", "vex_pnpm_bundled_copy"), + ]; + assert!(nothing_attested_hint(&some) + .unwrap() + .starts_with("1 of the patched packages are not installed yet")); + assert!( + nothing_attested_hint(&[failed("pkg:npm/a@1.0.0", "package_not_found")]) + .unwrap() + .starts_with("The patched packages are not installed here.") + ); + assert_eq!( + nothing_attested_hint(&[failed("pkg:npm/a@1.0.0", "hash_mismatch")]), + None + ); + assert_eq!(nothing_attested_hint(&[]), None); + } + #[test] fn omission_warning_names_phrase_and_tag() { assert_eq!( @@ -3002,6 +3328,7 @@ mod npm_prior_tests { npm_prior: prior, hosted_uuids: Vec::new(), api_client: RunApiClient::new(), + warnings_printed: Default::default(), }; let manifest_path = common.resolved_manifest_path(); match generate_vex_from_manifest_path(common, ¶ms, &manifest_path).await { diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index a269fbcf5..2cdf01a1f 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -114,15 +114,22 @@ pub(crate) const REDIRECT_UNWIRED: &str = "redirect_unwired"; /// candidate for that package attests. pub(crate) const WIRING_CONFLICT: &str = "wiring_conflict"; -/// Ceiling on concurrent patch-view fetches (one GET per uuid; the view -/// carries blob content, so it is heavy). +/// Ceiling on concurrent patch-view fetches from the public proxy (one +/// GET per uuid; its view carries blob content, so it is heavy). The +/// authenticated API is asked for the view without that content, which +/// the record does not use, so there the patch API's own window applies. const FETCH_CONCURRENCY: usize = 10; /// The in-flight cap for the record fetch: `SOCKET_API_CONCURRENCY` applies /// here like every other patch-API window, with [`FETCH_CONCURRENCY`] as /// this window's own ceiling on top (a view is heavy). fn fetch_concurrency(use_public_proxy: bool) -> usize { - api_concurrency(use_public_proxy).min(FETCH_CONCURRENCY) + let window = api_concurrency(use_public_proxy); + if use_public_proxy { + window.min(FETCH_CONCURRENCY) + } else { + window + } } /// Everything `vex` reads, loaded once by the caller (which owns the @@ -1315,17 +1322,25 @@ async fn fetch_records( let mut views = std::pin::pin!(ordered_concurrent( pending.iter(), fetch_concurrency(use_public_proxy), - |uuid| async move { (uuid, hold_back_debug(client.fetch_patch(uuid)).await) }, + // The record is built from the view's hashes and + // advisories: its file contents are never read here. + |uuid| async move { + ( + uuid, + hold_back_debug(client.fetch_patch_summary(uuid)).await, + ) + }, )); loop { - status.set(format!( - "Fetching {}... ({done}/{total})", + status.progress( if total == 1 { - "the patch record" + "Reading the patch record" } else { - "patch records" - } - )); + "Reading patch records" + }, + done, + total, + ); let Some((uuid, result)) = views.next().await else { break; }; @@ -1442,18 +1457,24 @@ mod tests { use socket_patch_core::utils::concurrent::API_CONCURRENCY_ENV; let orig = std::env::var(API_CONCURRENCY_ENV).ok(); std::env::remove_var(API_CONCURRENCY_ENV); - // A view is heavy, so this window's own ceiling binds by default - // on the authenticated API (whose cap is above it). - assert_eq!(fetch_concurrency(false), FETCH_CONCURRENCY); + // The authenticated API serves the view without its file contents, + // so the patch API's own window applies there. + assert_eq!(fetch_concurrency(false), api_concurrency(false)); + assert!(fetch_concurrency(false) > FETCH_CONCURRENCY); assert_eq!(fetch_concurrency(true), 4); std::env::set_var(API_CONCURRENCY_ENV, "1"); assert_eq!(fetch_concurrency(false), 1); assert_eq!(fetch_concurrency(true), 1); - // Turned up past this window's own ceiling, the ceiling holds. + // The proxy's view is heavy: its window never passes this one's + // own ceiling, however far the setting is turned up. std::env::set_var(API_CONCURRENCY_ENV, "32"); - assert_eq!(fetch_concurrency(false), FETCH_CONCURRENCY); + assert_eq!( + fetch_concurrency(true), + api_concurrency(true).min(FETCH_CONCURRENCY) + ); + assert_eq!(fetch_concurrency(false), 32); match orig { Some(v) => std::env::set_var(API_CONCURRENCY_ENV, v), diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index d98b38bcc..672ddb155 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -129,6 +129,24 @@ pub async fn find_cargo_copies( found } +/// Every installed purl a package-name `target` selects, deduplicated and +/// sorted (a monorepo can hold the same release in several places). +/// `packages` is a crawl's result. Shared by the commands that take a +/// package name and look it up among what is installed (`get`, `show`). +pub(crate) fn installed_target_matches( + target: &socket_patch_core::utils::target::Target, + packages: &[socket_patch_core::crawlers::CrawledPackage], +) -> Vec { + let mut purls: Vec = packages + .iter() + .filter(|pkg| target.matches_package(&pkg.purl)) + .map(|pkg| pkg.purl.clone()) + .collect(); + purls.sort(); + purls.dedup(); + purls +} + /// Partition PURLs by ecosystem, filtering by the `--ecosystems` flag if set. pub fn partition_purls( purls: &[String], @@ -1074,8 +1092,13 @@ pub struct NpmCrawlSnapshot { } impl NpmCrawlSnapshot { + /// The `node_modules` roots the crawl walked. + pub(crate) fn roots(&self) -> &[PathBuf] { + &self.roots + } + /// Whether this snapshot was crawled with exactly `options`. - fn taken_with(&self, options: &CrawlerOptions) -> bool { + pub(crate) fn taken_with(&self, options: &CrawlerOptions) -> bool { // Destructured, not field-by-field: a new crawler option that // changes what the crawler walks has to be answered here, and the // compiler is what asks. Everything this snapshot stands in for @@ -1473,6 +1496,26 @@ pub async fn crawl_ecosystems( (packages, counts, skipped_config_path) } +/// [`crawl_ecosystems`], also handing back the `node_modules` roots the +/// npm crawl walked (exactly [`NpmCrawler::get_node_modules_paths`]'s +/// answer for the same options and tree), so a caller that needs them +/// right after the crawl does not walk the tree a second time. `None` when +/// `only` leaves npm out. +pub(crate) async fn crawl_ecosystems_with_npm_roots( + options: &CrawlerOptions, + only: Option<&[String]>, +) -> ( + Vec, + HashMap, + Option, + Option>, +) { + let (packages, counts, skipped_config_path, npm_roots) = + crawl_every_ecosystem(options, only).await; + let npm_roots = counts.contains_key(&Ecosystem::Npm).then_some(npm_roots); + (packages, counts, skipped_config_path, npm_roots) +} + /// [`crawl_ecosystems`], also handing back the npm half of the crawl as /// an [`NpmCrawlSnapshot`] (its packages are the leading `counts[Npm]` /// entries of the package list). diff --git a/crates/socket-patch-cli/src/lib.rs b/crates/socket-patch-cli/src/lib.rs index ca3263bd9..7466821ad 100644 --- a/crates/socket-patch-cli/src/lib.rs +++ b/crates/socket-patch-cli/src/lib.rs @@ -143,6 +143,17 @@ pub enum Commands { /// Apply patches for a package, advisory, or patch UUID Get(commands::get::GetArgs), + /// Show what is inside a patch: its fixes, measurements and diff + /// + /// Reads the patch from the patch service and changes nothing. Prints + /// the advisories the patch fixes, what Socket measured about it + /// (exploits blocked, tests passing, size, run-time cost), the files it + /// changes and the diff of each. On a terminal the patch opens + /// full-screen, as the page a row of `list` opens: the arrow keys + /// scroll, n and p step between files, q leaves. Piped, or with + /// --no-pager, everything prints at once. + Show(commands::show::ShowArgs), + /// Show this project's patches in every mode List(commands::list::ListArgs), @@ -223,6 +234,7 @@ impl Commands { Commands::Vendor(a) => &a.common, Commands::Rollback(a) => &a.common, Commands::Get(a) => &a.common, + Commands::Show(a) => &a.common, Commands::List(a) => &a.common, Commands::Remove(a) => &a.common, Commands::Repair(a) => &a.common, diff --git a/crates/socket-patch-cli/src/main.rs b/crates/socket-patch-cli/src/main.rs index c47d772ab..dae704f9a 100644 --- a/crates/socket-patch-cli/src/main.rs +++ b/crates/socket-patch-cli/src/main.rs @@ -155,6 +155,7 @@ async fn run(own_args: Vec, hot_patch_command: Option commands::vendor::run(args).await, Commands::Rollback(args) => commands::rollback::run(args).await, Commands::Get(args) => commands::get::run(args).await, + Commands::Show(args) => commands::show::run(args).await, Commands::List(args) => commands::list::run(args).await, Commands::Remove(args) => commands::remove::run(args).await, Commands::Repair(args) => commands::repair::run(args).await, diff --git a/crates/socket-patch-cli/src/ui/browser.rs b/crates/socket-patch-cli/src/ui/browser.rs new file mode 100644 index 000000000..693576fa9 --- /dev/null +++ b/crates/socket-patch-cli/src/ui/browser.rs @@ -0,0 +1,1738 @@ +//! The full-screen browser of `list` and `show`: a table of rows to pick +//! from, and a page to read when one is opened (a patch: what it fixes, +//! what was measured about it, the diff of each file). +//! +//! It draws on the terminal's alternate screen, so the scrollback is left +//! exactly as it was, and it redraws the whole frame whenever the terminal +//! changes size: nothing on screen depends on how the terminal re-wrapped +//! what was drawn before, which is what an inline menu cannot survive. +//! +//! The table can be shown before everything about its rows is known: the +//! caller sends what it learns afterwards ([`Update`]) and the rows fill +//! in where they stand. Opening a row asks the caller for its page, which +//! arrives the same way. +//! +//! Everything that decides what is on screen is pure ([`State`]: the keys, +//! the scrolling, the frames), so it is tested byte for byte; the terminal +//! handling around it is Unix-only, and elsewhere [`run`] and [`read`] +//! hand their input back for the caller's inline fallback. + +#![cfg_attr(not(unix), allow(dead_code))] + +use std::sync::mpsc::Receiver; + +use super::Style; + +/// One cell of a table row. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct Cell { + pub text: String, + /// The SGR color the text is painted in, where color is on. + pub paint: Option<&'static str>, +} + +impl Cell { + pub(crate) fn plain(text: impl Into) -> Cell { + Cell { + text: text.into(), + paint: None, + } + } + + pub(crate) fn painted(text: impl Into, paint: Option<&'static str>) -> Cell { + Cell { + text: text.into(), + paint, + } + } +} + +/// One column of the table. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Column { + pub title: &'static str, + /// When the terminal is too narrow for every column, the one with the + /// highest number goes first; `0` always stays. + pub gives_way: u8, +} + +/// The rows to pick from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Table { + pub title: String, + pub columns: Vec, + /// One cell per column in each row. + pub rows: Vec>, +} + +/// What opening a row shows: lines to scroll through (they may carry +/// color), under a title that stays put. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct Page { + pub title: String, + pub lines: Vec, + /// Places to jump between (the first line of each file's diff), as + /// `(line, name)` in line order. + pub marks: Vec<(usize, String)>, +} + +/// What the caller learned since the table went up. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Update { + /// The cells of row `.0`, replacing the ones it had. + Row(usize, Vec), + /// What is still being loaded, shown beside the title; empty once + /// nothing is. + Note(String), + /// The page of row `.0`, asked for when it was opened, or why there + /// is none. + Page(usize, Result), +} + +/// What a key press asks for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Key { + Up, + Down, + PageUp, + PageDown, + First, + Last, + Left, + Right, + /// The next and the previous mark of a page. + Next, + Prev, + Open, + /// Leave the page for the table, or the table for the shell. + Back, + /// A key with no use here. + Other, +} + +/// The key a terminal sent as `bytes` (one read: an escape sequence +/// arrives whole). The arrows and their `less` letters move, Enter opens, +/// `n`/`p` step through a page's marks, and `q`, a bare Esc, Backspace +/// and Ctrl-C go back. +fn decode(bytes: &[u8]) -> Key { + match bytes { + [b'\r'] | [b'\n'] => Key::Open, + [b'q'] | [b'Q'] | [0x1b] | [0x03] | [0x04] | [0x7f] | [0x08] => Key::Back, + [b'k'] | [0x1b, b'[', b'A'] | [0x1b, b'O', b'A'] => Key::Up, + [b'j'] | [0x1b, b'[', b'B'] | [0x1b, b'O', b'B'] => Key::Down, + [b'l'] | [0x1b, b'[', b'C'] | [0x1b, b'O', b'C'] => Key::Right, + [b'h'] | [0x1b, b'[', b'D'] | [0x1b, b'O', b'D'] => Key::Left, + [b'b'] | [0x1b, b'[', b'5', b'~'] => Key::PageUp, + [b' '] | [b'f'] | [0x1b, b'[', b'6', b'~'] => Key::PageDown, + [b'g'] | [0x1b, b'[', b'H'] | [0x1b, b'O', b'H'] | [0x1b, b'[', b'1', b'~'] => Key::First, + [b'G'] | [0x1b, b'[', b'F'] | [0x1b, b'O', b'F'] | [0x1b, b'[', b'4', b'~'] => Key::Last, + [b'n'] | [b'\t'] => Key::Next, + [b'p'] | [b'N'] | [0x1b, b'[', b'Z'] => Key::Prev, + _ => Key::Other, + } +} + +/// The keys in `bytes`, what a terminal sent since the last read, and +/// the bytes at its end that are the start of a key not all here yet. +/// +/// A read is not a key press: a held key or a slow link delivers several +/// at once, and an escape sequence can arrive in two reads. Each key is +/// cut off and decoded on its own ([`decode`]). An Esc at the very end is +/// left over rather than taken for the Esc key, since it may be the first +/// byte of an arrow: the caller waits a moment for the rest. +fn keys(bytes: &[u8]) -> (Vec, &[u8]) { + let mut keys = Vec::new(); + let mut at = 0; + while at < bytes.len() { + let rest = &bytes[at..]; + let len = match rest { + [0x1b] => break, + // CSI: parameters, then one final byte. + [0x1b, b'[', after @ ..] => { + match after.iter().position(|b| (0x40..=0x7e).contains(b)) { + Some(end) => 2 + end + 1, + None => break, + } + } + // SS3: one byte. + [0x1b, b'O'] => break, + [0x1b, b'O', ..] => 3, + // Esc, then a key of its own. + [0x1b, ..] => 1, + // One character, however many bytes it is. + [first, ..] => match first { + 0xf0..=0xff => 4, + 0xe0..=0xef => 3, + 0xc0..=0xdf => 2, + _ => 1, + } + .min(rest.len()), + [] => break, + }; + keys.push(decode(&rest[..len])); + at += len; + } + (keys, &bytes[at..]) +} + +/// How a wait for input ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Wait { + /// There is input to read. + Ready, + /// The time passed with none. + TimedOut, + /// A signal cut the wait short (the terminal was resized, a child + /// exited): nothing is known yet. + Interrupted, +} + +/// Whether input arrives within `limit`, waiting with `wait` (which is +/// given the time left). A wait a signal cuts short is taken up again +/// for what is left of the time: read as the time having passed, it +/// would take the first byte of an arrow key for the Esc key by itself, +/// and close the page under a terminal being resized. +fn arrives_within( + limit: std::time::Duration, + mut wait: impl FnMut(std::time::Duration) -> std::io::Result, +) -> std::io::Result { + let deadline = std::time::Instant::now() + limit; + loop { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + match wait(left)? { + Wait::Ready => return Ok(true), + Wait::TimedOut => return Ok(false), + Wait::Interrupted if left.is_zero() => return Ok(false), + Wait::Interrupted => {} + } + } +} + +/// How far a sideways step moves a page. +const SIDEWAYS: usize = 8; + +/// Where the table stands: the selected row and the first row on screen. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +struct View { + selected: usize, + top: usize, +} + +impl View { + /// How many rows a terminal `height` lines tall shows: all of it but + /// the title, the column titles and the key line; one at least. + fn visible(height: usize) -> usize { + height.saturating_sub(3).max(1) + } + + /// The view after `key` on a table of `rows` rows. + fn after(self, key: Key, rows: usize, height: usize) -> View { + let last = rows.saturating_sub(1); + let page = View::visible(height); + let selected = match key { + Key::Up => self.selected.saturating_sub(1), + Key::Down => (self.selected + 1).min(last), + Key::PageUp => self.selected.saturating_sub(page), + Key::PageDown => (self.selected + page).min(last), + Key::First => 0, + Key::Last => last, + _ => self.selected, + }; + View { + selected, + top: self.top, + } + .in_window(rows, height) + } + + /// The view scrolled so the selected row is on screen, and so a + /// terminal that grew shows as many rows as it now can. + fn in_window(self, rows: usize, height: usize) -> View { + let visible = View::visible(height); + let selected = self.selected.min(rows.saturating_sub(1)); + let mut top = self.top.min(rows.saturating_sub(visible)); + if selected < top { + top = selected; + } else if selected >= top + visible { + top = selected + 1 - visible; + } + View { selected, top } + } +} + +/// Where a page stands: its first line on screen and how far it is +/// shifted sideways. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +struct Reading { + top: usize, + left: usize, +} + +impl Reading { + /// How many of a page's lines a terminal `height` lines tall shows: + /// all of it but the title and the key line; one at least. + fn visible(height: usize) -> usize { + height.saturating_sub(2).max(1) + } + + /// The furthest a page of `lines` lines scrolls: its last screenful. + fn end(lines: usize, height: usize) -> usize { + lines.saturating_sub(Reading::visible(height)) + } + + /// Where the page stands after `key`. + fn after(self, key: Key, page: &Page, height: usize) -> Reading { + let end = Reading::end(page.lines.len(), height); + let screen = Reading::visible(height); + let top = match key { + Key::Up => self.top.saturating_sub(1), + Key::Down => self.top + 1, + Key::PageUp => self.top.saturating_sub(screen), + Key::PageDown => self.top + screen, + Key::First => 0, + Key::Last => end, + Key::Next => page + .marks + .iter() + .map(|(line, _)| *line) + .find(|line| *line > self.top) + .unwrap_or(self.top), + Key::Prev => page + .marks + .iter() + .map(|(line, _)| *line) + .rev() + .find(|line| *line < self.top) + .unwrap_or(0), + _ => self.top, + }; + let left = match key { + Key::Right => self.left + SIDEWAYS, + Key::Left => self.left.saturating_sub(SIDEWAYS), + _ => self.left, + }; + Reading { + top: top.min(end), + left, + } + } + + /// The mark the top of the screen is in: the last one at or above it. + fn mark(self, page: &Page) -> Option<(usize, &str)> { + page.marks + .iter() + .enumerate() + .rev() + .find(|(_, (line, _))| *line <= self.top) + .map(|(index, (_, name))| (index, name.as_str())) + } +} + +/// `text` on one line of at most `max` characters, column spacing kept. +fn fit(text: &str, max: usize) -> String { + const ELLIPSIS: &str = "..."; + if text.chars().count() <= max { + return text.to_string(); + } + if max <= ELLIPSIS.len() { + return text.chars().take(max).collect(); + } + let kept: String = text.chars().take(max - ELLIPSIS.len()).collect(); + format!("{}{ELLIPSIS}", kept.trim_end()) +} + +/// Columns between the tab stops of a page's lines. +const TAB_STOP: usize = 4; + +/// The part of `line` that falls in columns `skip..skip + take`. Color +/// sequences are kept (they take no column) and closed at the end, so a +/// cut line never colors the one after it; any other escape sequence is +/// dropped, since it could move the cursor. Every character takes the +/// columns a terminal gives it, so a line takes exactly the columns it +/// is given: a tab runs to the next [`TAB_STOP`] (the indentation of +/// code is kept), a wide character takes its two columns (or shows as a +/// space where the window cuts it in half), one that takes none rides on +/// the one before it, and any other control character is a space. +fn window(line: &str, skip: usize, take: usize) -> String { + let end = skip + take; + let mut out = String::new(); + let mut column = 0usize; + let mut colored = false; + let mut chars = line.chars().peekable(); + // Blank columns `from..to`, where they fall in the window. + let blank = |out: &mut String, from: usize, to: usize| { + for _ in from.max(skip)..to.min(end) { + out.push(' '); + } + }; + while let Some(c) = chars.next() { + if c == '\x1b' { + // A CSI sequence: `ESC [`, parameters, one final letter. + let mut sequence = String::from(c); + if chars.peek() == Some(&'[') { + sequence.extend(chars.next()); + for next in chars.by_ref() { + sequence.push(next); + if next.is_ascii_alphabetic() { + break; + } + } + } + if sequence.len() > 2 && sequence.ends_with('m') { + out.push_str(&sequence); + colored = true; + } + continue; + } + let width = if c == '\t' { + TAB_STOP - column % TAB_STOP + } else if c.is_control() { + 1 + } else { + console::measure_text_width(c.encode_utf8(&mut [0; 4])) + }; + if width == 0 { + // A combining mark: part of the character before it, when + // that one is shown. + if column > skip && column <= end { + out.push(c); + } + continue; + } + if column >= end { + break; + } + if c == '\t' || c.is_control() { + blank(&mut out, column, column + width); + } else if column >= skip && column + width <= end { + out.push(c); + } else { + // Cut by an edge of the window: its columns that are inside. + blank(&mut out, column, column + width); + } + column += width; + } + if colored { + out.push_str("\x1b[0m"); + } + out +} + +/// The columns of `table` a line of `room` characters holds, with the +/// width of each, in order. Every column is as wide as its widest cell +/// (or its title), and a column that gives way and has nothing in any row +/// takes no room. When they do not all fit, the columns that give way are +/// left out, most willing first; if the rest still do not fit, the widest +/// of them is cut. +fn layout(table: &Table, room: usize) -> Vec<(usize, usize)> { + let mut shown: Vec<(usize, usize)> = table + .columns + .iter() + .enumerate() + .filter(|(index, column)| { + column.gives_way == 0 + || table + .rows + .iter() + .any(|row| row.get(*index).is_some_and(|cell| !cell.text.is_empty())) + }) + .map(|(index, column)| { + let cells = table + .rows + .iter() + .filter_map(|row| row.get(index)) + .map(|cell| cell.text.chars().count()) + .max() + .unwrap_or(0); + (index, cells.max(column.title.chars().count())) + }) + .collect(); + // Two columns for the selection mark, two between columns. + let total = |shown: &[(usize, usize)]| { + 2 + shown.iter().map(|(_, width)| width).sum::() + 2 * shown.len().saturating_sub(1) + }; + while total(&shown) > room { + let most_willing = shown + .iter() + .enumerate() + .filter(|(_, (index, _))| table.columns[*index].gives_way > 0) + .max_by_key(|(_, (index, _))| table.columns[*index].gives_way) + .map(|(position, _)| position); + match most_willing { + Some(position) => { + shown.remove(position); + } + None => break, + } + } + let over = total(&shown).saturating_sub(room); + if over > 0 { + if let Some(widest) = shown.iter_mut().max_by_key(|(_, width)| *width) { + widest.1 = widest.1.saturating_sub(over).max(1); + } + } + shown +} + +/// One row of the table in `columns`. `strong` marks the selected row. +fn row_line(row: &[Cell], columns: &[(usize, usize)], strong: bool, style: Style) -> String { + let mut line = String::new(); + let mut gap = 0usize; + for (index, width) in columns { + let cell = row.get(*index).cloned().unwrap_or_default(); + let text = fit(&cell.text, *width); + let used = text.chars().count(); + if !text.is_empty() { + // The padding owed since the last cell that had text: a row + // never ends in spaces. + line.push_str(&" ".repeat(gap)); + gap = 0; + let code = match (strong, cell.paint) { + (true, Some(paint)) => format!("1;{paint}"), + (true, None) => "1".to_string(), + (false, Some(paint)) => paint.to_string(), + (false, None) => String::new(), + }; + if code.is_empty() { + line.push_str(&text); + } else { + line.push_str(&super::paint(&text, &code, style.color)); + } + } + gap += width - used + 2; + } + line +} + +/// The column titles of `table` in `columns`, dimmed. +fn title_line(table: &Table, columns: &[(usize, usize)], style: Style) -> String { + let titles: Vec = table + .columns + .iter() + .map(|column| Cell::plain(column.title)) + .collect(); + super::dim( + &row_line(&titles, columns, false, Style::PLAIN), + style.color, + ) +} + +/// The table's column titles and rows as lines of at most `room` +/// characters, for printing once the browser is left (or where there is +/// none): the titles, then a line per row, each indented by two. +pub(crate) fn table_lines(table: &Table, room: usize, style: Style) -> Vec { + let columns = layout(table, room); + let mut lines = vec![format!(" {}", title_line(table, &columns, style))]; + lines.extend( + table + .rows + .iter() + .map(|row| format!(" {}", row_line(row, &columns, false, style))), + ); + lines +} + +/// What the browser shows. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Screen { + Table, + /// Row `.0` was opened and its page is on its way. + Waiting(usize), + /// Row `.0`'s page. + Page(usize, Page, Reading), + /// Row `.0` has no page to show: why. + NoPage(usize, String), +} + +/// What a key press leaves the loop to do. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Step { + /// Nothing changed. + Stay, + Redraw, + /// Ask the caller for row `.0`'s page. + Open(usize), + Leave, +} + +/// Everything that decides what is on screen. +#[derive(Debug, Clone, PartialEq, Eq)] +struct State { + table: Table, + note: String, + view: View, + screen: Screen, + /// A browser of one page (`show`): going back from it leaves. + only_page: bool, + /// The activity mark's frame. + turn: usize, + width: usize, + height: usize, +} + +impl State { + fn of_table(table: Table, width: usize, height: usize) -> State { + State { + table, + note: String::new(), + view: View::default(), + screen: Screen::Table, + only_page: false, + turn: 0, + width, + height, + } + } + + fn of_page(page: Page, width: usize, height: usize) -> State { + State { + table: Table { + title: String::new(), + columns: Vec::new(), + rows: Vec::new(), + }, + note: String::new(), + view: View::default(), + screen: Screen::Page(0, page, Reading::default()), + only_page: true, + turn: 0, + width, + height, + } + } + + /// Something is on its way: the activity mark is turning. + fn waiting(&self) -> bool { + !self.note.is_empty() || matches!(self.screen, Screen::Waiting(_)) + } + + /// Take in what the caller learned. A page that arrives for a row the + /// user has left is dropped: they asked for something else since. + fn apply(&mut self, update: Update) { + match update { + Update::Row(row, cells) => { + if let Some(slot) = self.table.rows.get_mut(row) { + *slot = cells; + } + } + Update::Note(note) => self.note = note, + Update::Page(row, page) => { + if self.screen == Screen::Waiting(row) { + self.screen = match page { + Ok(page) => Screen::Page(row, page, Reading::default()), + Err(why) => Screen::NoPage(row, why), + }; + } + } + } + } + + /// The terminal is now `width` by `height`. + fn resize(&mut self, width: usize, height: usize) { + self.width = width; + self.height = height; + self.view = self.view.in_window(self.table.rows.len(), height); + if let Screen::Page(_, page, reading) = &mut self.screen { + reading.top = reading.top.min(Reading::end(page.lines.len(), height)); + } + } + + fn key(&mut self, key: Key) -> Step { + match &mut self.screen { + Screen::Table => match key { + Key::Back => Step::Leave, + Key::Open if !self.table.rows.is_empty() => { + self.screen = Screen::Waiting(self.view.selected); + Step::Open(self.view.selected) + } + _ => { + let moved = self.view.after(key, self.table.rows.len(), self.height); + if moved == self.view { + Step::Stay + } else { + self.view = moved; + Step::Redraw + } + } + }, + Screen::Page(_, page, reading) => match key { + Key::Back if self.only_page => Step::Leave, + Key::Back => { + self.screen = Screen::Table; + Step::Redraw + } + _ => { + let moved = reading.after(key, page, self.height); + if moved == *reading { + Step::Stay + } else { + *reading = moved; + Step::Redraw + } + } + }, + Screen::Waiting(_) | Screen::NoPage(..) => match key { + Key::Back | Key::Open => { + self.screen = Screen::Table; + Step::Redraw + } + _ => Step::Stay, + }, + } + } + + /// The lines of the frame: never more than the terminal has, and none + /// reaching its last column, so the terminal neither scrolls nor + /// wraps. + fn frame(&self, style: Style) -> Vec { + let room = self.width.saturating_sub(1).max(1); + let height = self.height.max(1); + let glyphs = style.glyphs; + let (mut lines, keys, at): (Vec, &str, String) = match &self.screen { + Screen::Table => { + let columns = layout(&self.table, room); + let mut title = super::bold(&fit(&self.table.title, room), style.color); + // What is loading goes beside the title where there is + // room for some of it. + let left = room.saturating_sub(self.table.title.chars().count() + 5); + if !self.note.is_empty() && left > 3 { + title.push_str(&format!( + " {} {}", + super::status::activity_mark(self.turn, style), + super::dim(&fit(&self.note, left), style.color) + )); + } + // On a terminal too narrow even for the columns that stay, + // a line is cut where the terminal ends. + let mut lines = vec![ + title, + window( + &format!(" {}", title_line(&self.table, &columns, style)), + 0, + room, + ), + ]; + let mark = if glyphs { "❯" } else { ">" }; + for (index, row) in self + .table + .rows + .iter() + .enumerate() + .skip(self.view.top) + .take(View::visible(height)) + { + let selected = index == self.view.selected; + let text = row_line(row, &columns, selected, style); + let line = if selected { + format!("{} {text}", super::paint(mark, "36", style.color)) + } else { + format!(" {text}") + }; + lines.push(window(&line, 0, room)); + } + let keys = if glyphs { + "↑↓ move PgUp/PgDn page Enter open q quit" + } else { + "Up/Down move PgUp/PgDn page Enter open q quit" + }; + let at = format!("{}/{}", self.view.selected + 1, self.table.rows.len()); + (lines, keys, at) + } + Screen::Page(_, page, reading) => { + let mut lines = vec![super::bold(&fit(&page.title, room), style.color)]; + lines.extend( + page.lines + .iter() + .skip(reading.top) + .take(Reading::visible(height)) + .map(|line| window(line, reading.left, room)), + ); + let keys = match (glyphs, page.marks.len() > 1) { + (true, true) => "↑↓ scroll PgUp/PgDn page n/p file ←→ shift q back", + (true, false) => "↑↓ scroll PgUp/PgDn page ←→ shift q back", + (false, true) => "Up/Down scroll PgUp/PgDn page n/p file q back", + (false, false) => "Up/Down scroll PgUp/PgDn page q back", + }; + let last = (reading.top + Reading::visible(height)).min(page.lines.len()); + let mut at = format!("{last}/{}", page.lines.len()); + if let Some((index, name)) = reading.mark(page) { + at = format!("file {}/{} {name} {at}", index + 1, page.marks.len()); + } + (lines, keys, at) + } + Screen::Waiting(row) => { + let lines = vec![format!( + "{} {}", + super::status::activity_mark(self.turn, style), + fit( + &format!("Reading {}", self.row_name(*row)), + room.saturating_sub(2) + ) + )]; + (lines, "q back", String::new()) + } + Screen::NoPage(row, why) => { + let mut lines = vec![ + super::bold(&fit(&self.row_name(*row), room), style.color), + String::new(), + ]; + lines.extend(why.lines().map(|line| window(line, 0, room))); + (lines, "q back", String::new()) + } + }; + if height >= 2 { + // The position always shows; the keys give way on a narrow + // terminal, and then the name of the file before the position. + let line = if keys.chars().count() + 3 + at.chars().count() <= room { + format!("{keys} {at}").trim_end().to_string() + } else if at.is_empty() { + fit(keys, room) + } else if at.chars().count() <= room { + at + } else { + let tail: Vec = at.chars().collect(); + tail[tail.len() - room..].iter().collect() + }; + lines.truncate(height - 1); + // The key line sits on the last line of the screen. + while lines.len() + 1 < height { + lines.push(String::new()); + } + lines.push(super::dim(&line, style.color)); + } + lines.truncate(height); + lines + } + + /// What row `row` is called on the screens that stand in for its + /// page: its first two cells that say anything. + fn row_name(&self, row: usize) -> String { + self.table + .rows + .get(row) + .map(|cells| { + cells + .iter() + .map(|cell| cell.text.as_str()) + .filter(|text| !text.is_empty()) + .take(2) + .collect::>() + .join(" ") + }) + .unwrap_or_default() + } +} + +/// Show `table` full-screen until the user leaves it. `updates` carries +/// what the caller learns meanwhile; `open(row)` is called when a row is +/// opened, and its page is expected as an [`Update::Page`]. +/// +/// `Ok` is the table as it stood when the user left (every row update +/// applied). `Err` hands the table back untouched: the terminal could not +/// be set up for a full-screen browser (or this is not Unix), and nothing +/// was drawn. +pub(crate) fn run( + table: Table, + updates: Receiver, + open: impl FnMut(usize), +) -> Result { + #[cfg(unix)] + { + screen::run(table, updates, open) + } + #[cfg(not(unix))] + { + let _ = (updates, open); + Err(table) + } +} + +/// Show `page` full-screen until the user leaves it. `false`: the +/// terminal could not be set up (or this is not Unix) and nothing was +/// drawn. +pub(crate) fn read(page: Page) -> bool { + #[cfg(unix)] + { + screen::read(page) + } + #[cfg(not(unix))] + { + let _ = page; + false + } +} + +#[cfg(unix)] +mod screen { + //! The terminal side: the alternate screen, unbuffered keys, and the + //! loop that redraws on a key, an update or a size change. + + use std::io::Write; + use std::sync::mpsc::{Receiver, TryRecvError}; + use std::time::Duration; + + use super::{arrives_within, decode, keys, Key, Page, State, Step, Table, Update, Wait}; + + /// Enter the alternate screen and hide the cursor; leave and show. + const ENTER: &str = "\x1b[?1049h\x1b[?25l"; + const LEAVE: &str = "\x1b[?25h\x1b[?1049l"; + + /// How long a wait for a key lasts before the browser looks at the + /// terminal's size and at what the caller sent, and turns its mark. + const TICK: Duration = Duration::from_millis(100); + + /// The terminal as the browser found it, put back on drop: its input + /// settings, the main screen and the cursor. + struct Restore { + original: libc::termios, + } + + impl Restore { + /// Take keys one at a time, unechoed, and the signal keys as plain + /// bytes: Ctrl-C then leaves through this guard, where a signal + /// would kill the process with the terminal still changed. `None` + /// when stdin's settings cannot be read or set. + fn install() -> Option { + // SAFETY: `termios` is plain data that `tcgetattr` fills; both + // calls take a valid descriptor and a valid pointer, and report + // failure by their return value. + unsafe { + let mut original: libc::termios = std::mem::zeroed(); + if libc::tcgetattr(libc::STDIN_FILENO, &mut original) != 0 { + return None; + } + let mut raw = original; + raw.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG); + raw.c_cc[libc::VMIN] = 1; + raw.c_cc[libc::VTIME] = 0; + if libc::tcsetattr(libc::STDIN_FILENO, libc::TCSADRAIN, &raw) != 0 { + return None; + } + let mut err = std::io::stderr().lock(); + let _ = err.write_all(ENTER.as_bytes()); + let _ = err.flush(); + Some(Restore { original }) + } + } + } + + impl Drop for Restore { + fn drop(&mut self) { + let mut err = std::io::stderr().lock(); + let _ = err.write_all(LEAVE.as_bytes()); + let _ = err.flush(); + // SAFETY: restores the settings `install` read from the same + // descriptor. + unsafe { + libc::tcsetattr(libc::STDIN_FILENO, libc::TCSADRAIN, &self.original); + } + } + } + + /// The terminal's size as `(columns, lines)`. + fn size() -> (usize, usize) { + let (lines, columns) = console::Term::stderr().size(); + (usize::from(columns).max(1), usize::from(lines).max(1)) + } + + /// How long a key that is not all here is waited for: the rest of an + /// escape sequence follows its first byte at once, so an Esc with + /// nothing after it for this long is the Esc key. + const REST_OF_KEY: Duration = Duration::from_millis(40); + + /// Wait up to `wait` for stdin to have bytes to read. `Err` when it + /// cannot be waited on. + fn wait_readable(wait: Duration) -> std::io::Result { + // `select`, not `poll`: macOS's `poll` does not report terminal + // devices reliably. + // SAFETY: `fd_set` is plain data the FD_* macros initialise and + // fill; stdin is below FD_SETSIZE; `select` gets valid pointers + // and reports failure by its return value. + let ready = unsafe { + let mut readable: libc::fd_set = std::mem::zeroed(); + libc::FD_ZERO(&mut readable); + libc::FD_SET(libc::STDIN_FILENO, &mut readable); + let mut wait = libc::timeval { + tv_sec: 0, + tv_usec: wait.as_micros() as libc::suseconds_t, + }; + libc::select( + libc::STDIN_FILENO + 1, + &mut readable, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut wait, + ) + }; + if ready < 0 { + let e = std::io::Error::last_os_error(); + return if e.kind() == std::io::ErrorKind::Interrupted { + Ok(Wait::Interrupted) + } else { + Err(e) + }; + } + Ok(if ready > 0 { + Wait::Ready + } else { + Wait::TimedOut + }) + } + + /// Read what stdin has into `bytes`. `Err` when stdin is gone + /// (closed, or no longer a terminal). + fn read_into(bytes: &mut Vec) -> std::io::Result<()> { + let mut chunk = [0u8; 64]; + // SAFETY: reads at most the buffer's length into it. + let read = + unsafe { libc::read(libc::STDIN_FILENO, chunk.as_mut_ptr().cast(), chunk.len()) }; + match read { + n if n > 0 => { + bytes.extend_from_slice(&chunk[..n as usize]); + Ok(()) + } + 0 => Err(std::io::ErrorKind::UnexpectedEof.into()), + _ => { + let e = std::io::Error::last_os_error(); + if e.kind() == std::io::ErrorKind::Interrupted { + Ok(()) + } else { + Err(e) + } + } + } + } + + /// The keys pressed within a [`TICK`], in order: none when no key + /// came. `Err` when stdin is gone. + fn next_keys() -> std::io::Result> { + // A signal that cuts the tick short is the end of the tick: the + // caller looks at the terminal's size again. + if wait_readable(TICK)? != Wait::Ready { + return Ok(Vec::new()); + } + let mut bytes = Vec::new(); + read_into(&mut bytes)?; + let mut pressed = Vec::new(); + loop { + let (found, rest) = keys(&bytes); + pressed.extend(found); + if rest.is_empty() { + return Ok(pressed); + } + // The start of a key: its rest is on its way, or it is the + // Esc key by itself. + let rest = rest.to_vec(); + if !arrives_within(REST_OF_KEY, wait_readable)? { + pressed.push(decode(&rest)); + return Ok(pressed); + } + bytes = rest; + read_into(&mut bytes)?; + } + } + + /// Write one frame over the whole screen, in a single write. + fn draw(lines: &[String]) { + // Home, each line followed by "erase to end of line", then "erase + // below": the frame replaces whatever was there, at any size. + let mut out = String::from("\x1b[H"); + for (index, line) in lines.iter().enumerate() { + if index > 0 { + out.push_str("\r\n"); + } + out.push_str(line); + out.push_str("\x1b[K"); + } + out.push_str("\x1b[J"); + let mut err = std::io::stderr().lock(); + let _ = err.write_all(out.as_bytes()); + let _ = err.flush(); + } + + /// Run `state` on the terminal until the user leaves. + fn browse( + mut state: State, + updates: Option>, + mut open: impl FnMut(usize), + ) -> State { + let style = crate::ui::Style::stderr(); + draw(&state.frame(style)); + loop { + let mut redraw = false; + if let Some(updates) = &updates { + loop { + match updates.try_recv() { + Ok(update) => { + state.apply(update); + redraw = true; + } + Err(TryRecvError::Empty) => break, + // The caller is done sending: nothing is on its + // way any more. + Err(TryRecvError::Disconnected) => { + if !state.note.is_empty() { + state.note.clear(); + redraw = true; + } + break; + } + } + } + } + if redraw { + draw(&state.frame(style)); + redraw = false; + } + match next_keys() { + Ok(pressed) if !pressed.is_empty() => { + for key in pressed { + match state.key(key) { + Step::Leave => return state, + Step::Open(row) => { + open(row); + redraw = true; + } + Step::Redraw => redraw = true, + Step::Stay => {} + } + } + } + Ok(_) => { + let now = size(); + if now != (state.width, state.height) { + state.resize(now.0, now.1); + redraw = true; + } + if state.waiting() { + state.turn = state.turn.wrapping_add(1); + redraw = true; + } + } + Err(_) => return state, + } + if redraw { + draw(&state.frame(style)); + } + } + } + + pub(super) fn run( + table: Table, + updates: Receiver, + open: impl FnMut(usize), + ) -> Result { + let Some(_restore) = Restore::install() else { + return Err(table); + }; + let (width, height) = size(); + let state = State::of_table(table, width, height); + Ok(browse(state, Some(updates), open).table) + } + + pub(super) fn read(page: Page) -> bool { + let Some(_restore) = Restore::install() else { + return false; + }; + let (width, height) = size(); + browse(State::of_page(page, width, height), None, |_| {}); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FANCY: Style = Style { + color: true, + glyphs: true, + }; + + fn columns() -> Vec { + [ + ("SEVERITY", 0), + ("PACKAGE", 0), + ("FIXES", 1), + ("TESTS", 2), + ("CHANGE", 3), + ("MODE", 4), + ] + .into_iter() + .map(|(title, gives_way)| Column { title, gives_way }) + .collect() + } + + fn table(rows: usize) -> Table { + Table { + title: format!("{rows} patches in this project"), + columns: columns(), + rows: (0..rows) + .map(|i| { + vec![ + Cell::painted("HIGH", Some("31")), + Cell::plain(format!("pkg-{i:02}@1.0.0")), + Cell::plain(format!("CVE-2026-{i:04}")), + Cell::plain(""), + Cell::plain(""), + Cell::plain("hosted"), + ] + }) + .collect(), + } + } + + fn page(lines: usize) -> Page { + Page { + title: "pkg:npm/pkg-00@1.0.0 HIGH".to_string(), + lines: (0..lines).map(|i| format!("line {i:03}")).collect(), + marks: vec![(10, "a.js".to_string()), (40, "lib/b.js".to_string())], + } + } + + fn plain(lines: &[String]) -> Vec { + lines.iter().map(|l| crate::ui::strip_ansi(l)).collect() + } + + #[test] + fn keys_decode_to_what_they_ask() { + for (bytes, key) in [ + (&b"\r"[..], Key::Open), + (b"\n", Key::Open), + (b"q", Key::Back), + (b"\x1b", Key::Back), + (b"\x03", Key::Back), + (b"\x7f", Key::Back), + (b"\x1b[A", Key::Up), + (b"\x1bOA", Key::Up), + (b"k", Key::Up), + (b"\x1b[B", Key::Down), + (b"j", Key::Down), + (b"\x1b[C", Key::Right), + (b"\x1b[D", Key::Left), + (b"\x1b[5~", Key::PageUp), + (b"\x1b[6~", Key::PageDown), + (b" ", Key::PageDown), + (b"\x1b[H", Key::First), + (b"g", Key::First), + (b"\x1b[F", Key::Last), + (b"G", Key::Last), + (b"n", Key::Next), + (b"\t", Key::Next), + (b"p", Key::Prev), + (b"\x1b[Z", Key::Prev), + (b"x", Key::Other), + // A sequence the browser does not know is ignored, never read + // as the Esc it begins with. + (b"\x1b[1;5C", Key::Other), + ] { + assert_eq!(decode(bytes), key, "{bytes:?}"); + } + } + + /// A read is not a key press. Several presses that arrive together + /// are each a key, and the start of an escape sequence at the end of + /// a read is left for the next one: it is never taken for the Esc + /// key, which would close the page under a held arrow. + #[test] + fn a_read_is_cut_into_its_keys() { + let all = |bytes: &'static [u8]| { + let (found, rest) = keys(bytes); + (found, rest.to_vec()) + }; + assert_eq!( + all(b"\x1b[B\x1b[B\x1b[B"), + (vec![Key::Down, Key::Down, Key::Down], vec![]) + ); + assert_eq!( + all(b"jj\x1b[6~k\r"), + ( + vec![Key::Down, Key::Down, Key::PageDown, Key::Up, Key::Open], + vec![] + ) + ); + assert_eq!(all(b"\x1bOA\x1bOB"), (vec![Key::Up, Key::Down], vec![])); + // Split after the Esc, after `[`, inside the parameters, after `O`. + assert_eq!(all(b"\x1b[B\x1b"), (vec![Key::Down], b"\x1b".to_vec())); + assert_eq!(all(b"\x1b["), (vec![], b"\x1b[".to_vec())); + assert_eq!(all(b"j\x1b[5"), (vec![Key::Down], b"\x1b[5".to_vec())); + assert_eq!(all(b"\x1bO"), (vec![], b"\x1bO".to_vec())); + // The rest arrives: the key is whole. + assert_eq!(all(b"\x1b[5~"), (vec![Key::PageUp], vec![])); + // Esc followed by a key of its own is Esc, then that key. + assert_eq!(all(b"\x1bq"), (vec![Key::Back, Key::Back], vec![])); + assert_eq!(all(b"\x1bj"), (vec![Key::Back, Key::Down], vec![])); + // A sequence the browser does not know is one key it ignores, and + // a character of several bytes is one key too. + assert_eq!(all(b"\x1b[1;5Cj"), (vec![Key::Other, Key::Down], vec![])); + assert_eq!(all("éj".as_bytes()), (vec![Key::Other, Key::Down], vec![])); + assert_eq!(all(b""), (vec![], vec![])); + } + + /// The wait for the rest of a key rides out a signal: an interrupted + /// wait is taken up again for the time that is left, so a resize in + /// the middle of an arrow key never turns its first byte into Esc. + /// Only the time passing ends the wait with nothing. + #[test] + fn the_wait_for_the_rest_of_a_key_rides_out_signals() { + use std::time::Duration; + let limit = Duration::from_millis(40); + let scripted = |script: &'static [Wait]| { + let mut calls = 0; + let result = arrives_within(limit, |left| { + assert!(left <= limit); + calls += 1; + Ok(script[(calls - 1).min(script.len() - 1)]) + }); + (result.unwrap(), calls) + }; + assert_eq!(scripted(&[Wait::Ready]), (true, 1)); + assert_eq!(scripted(&[Wait::TimedOut]), (false, 1)); + // Interrupted, then the rest arrives: the key is whole. + assert_eq!( + scripted(&[Wait::Interrupted, Wait::Interrupted, Wait::Ready]), + (true, 3) + ); + // Interrupted, then nothing in what was left of the time. + assert_eq!(scripted(&[Wait::Interrupted, Wait::TimedOut]), (false, 2)); + // Signals without end stop at the limit, not never. + let started = std::time::Instant::now(); + let ended = arrives_within(limit, |left| { + std::thread::sleep(left.min(Duration::from_millis(5))); + Ok(Wait::Interrupted) + }); + assert!(!ended.unwrap()); + assert!(started.elapsed() >= limit); + assert!(started.elapsed() < Duration::from_secs(5)); + // A wait that fails is the failure. + assert!(arrives_within(limit, |_| Err(std::io::ErrorKind::Other.into())).is_err()); + } + + #[test] + fn the_view_follows_the_selection_and_stops_at_the_ends() { + // 10 lines: 7 rows in view. + let start = View::default(); + assert_eq!(View::visible(10), 7); + assert_eq!(start.after(Key::Up, 30, 10), start); + let mut view = start; + for _ in 0..6 { + view = view.after(Key::Down, 30, 10); + } + assert_eq!( + view, + View { + selected: 6, + top: 0 + } + ); + // One more scrolls. + let view = view.after(Key::Down, 30, 10); + assert_eq!( + view, + View { + selected: 7, + top: 1 + } + ); + let paged = view.after(Key::PageDown, 30, 10); + assert_eq!( + paged, + View { + selected: 14, + top: 8 + } + ); + let last = paged.after(Key::Last, 30, 10); + assert_eq!( + last, + View { + selected: 29, + top: 23 + } + ); + assert_eq!(last.after(Key::Down, 30, 10), last); + assert_eq!(last.after(Key::PageDown, 30, 10), last); + assert_eq!(last.after(Key::First, 30, 10), View::default()); + // A table shorter than the screen never scrolls. + assert_eq!( + start.after(Key::Last, 3, 10), + View { + selected: 2, + top: 0 + } + ); + } + + /// The reported need: the browser must survive a resize. A smaller + /// terminal keeps the selected row in view; a larger one fills with + /// rows again instead of leaving the old window at the bottom. + #[test] + fn a_resize_keeps_the_selection_in_view_and_fills_the_screen() { + let at_end = View { + selected: 29, + top: 23, + }; + // Shrunk to 6 lines (3 rows): the selection stays on screen. + assert_eq!( + at_end.in_window(30, 6), + View { + selected: 29, + top: 27 + } + ); + // Grown to 40 lines: every row fits, so the table starts at the top. + assert_eq!( + at_end.in_window(30, 40), + View { + selected: 29, + top: 0 + } + ); + // In the middle, shrinking moves the window only as far as needed. + let middle = View { + selected: 12, + top: 8, + }; + assert_eq!( + middle.in_window(30, 6), + View { + selected: 12, + top: 10 + } + ); + // One-line and zero-line terminals still show the selected row. + assert_eq!(middle.in_window(30, 1).top, 12); + assert_eq!(middle.in_window(30, 0).top, 12); + // The page a reader is in is held to its last screenful. + let mut state = State::of_page(page(100), 80, 12); + state.key(Key::Last); + assert!(matches!(&state.screen, Screen::Page(_, _, reading) if reading.top == 90)); + state.resize(80, 40); + assert!(matches!(&state.screen, Screen::Page(_, _, reading) if reading.top == 62)); + } + + #[test] + fn a_table_frame_fits_the_terminal_at_any_size() { + let state = |rows: usize, width: usize, height: usize| { + let mut state = State::of_table(table(rows), width, height); + state.key(Key::Down); + state + }; + assert_eq!( + state(30, 80, 8).frame(Style::PLAIN), + [ + "30 patches in this project", + " SEVERITY PACKAGE FIXES MODE", + " HIGH pkg-00@1.0.0 CVE-2026-0000 hosted", + "> HIGH pkg-01@1.0.0 CVE-2026-0001 hosted", + " HIGH pkg-02@1.0.0 CVE-2026-0002 hosted", + " HIGH pkg-03@1.0.0 CVE-2026-0003 hosted", + " HIGH pkg-04@1.0.0 CVE-2026-0004 hosted", + "Up/Down move PgUp/PgDn page Enter open q quit 2/30", + ] + ); + // Every size: never more lines than the terminal has, and no line + // reaches the last column. + for width in [1, 2, 5, 20, 39, 40, 41, 80, 200] { + for height in [0, 1, 2, 3, 4, 10, 50] { + for style in [Style::PLAIN, FANCY] { + let mut state = State::of_table(table(30), width, height); + for _ in 0..17 { + state.key(Key::Down); + } + let lines = plain(&state.frame(style)); + assert!(lines.len() <= height.max(1), "{width}x{height}: {lines:?}"); + for line in &lines { + assert!( + line.chars().count() <= width.saturating_sub(1).max(1), + "{width}x{height}: {line:?}" + ); + } + assert!( + lines.iter().any(|l| l.contains("pkg-17")) || width < 30 || height < 4, + "{width}x{height}: {lines:?}" + ); + } + } + } + // A narrow terminal gives up the columns that give way, most + // willing first, then cuts what is left; the position stays. + assert_eq!( + state(30, 44, 6).frame(Style::PLAIN), + [ + "30 patches in this project", + " SEVERITY PACKAGE FIXES", + " HIGH pkg-00@1.0.0 CVE-2026-0000", + "> HIGH pkg-01@1.0.0 CVE-2026-0001", + " HIGH pkg-02@1.0.0 CVE-2026-0002", + "2/30", + ] + ); + assert_eq!( + state(30, 22, 5).frame(Style::PLAIN), + [ + "30 patches in this...", + " SEVERITY PACKAGE", + " HIGH pkg-00...", + "> HIGH pkg-01...", + "2/30", + ] + ); + // A short table leaves the key line on the last line. + let short = state(2, 80, 7).frame(Style::PLAIN); + assert_eq!(short.len(), 7); + assert_eq!(short[4..6], ["", ""]); + assert!(short[6].ends_with("2/2")); + // Glyph terminals mark the row with an arrow, name the arrows and + // paint the cells: the selected row in bold. + let fancy = state(30, 80, 8).frame(FANCY); + assert!( + fancy[3].starts_with("\x1b[36m❯\x1b[0m \x1b[1;31mHIGH\x1b[0m"), + "{fancy:?}" + ); + assert!(fancy[2].starts_with(" \x1b[31mHIGH\x1b[0m"), "{fancy:?}"); + assert!(plain(&fancy)[7].starts_with("↑↓ move"), "{fancy:?}"); + } + + /// The table goes up before everything about its rows is known: what + /// the caller learns later fills in where the rows stand, the note + /// says what is still loading, and columns appear as they get content. + #[test] + fn updates_fill_the_rows_in_and_say_what_is_loading() { + let mut state = State::of_table(table(3), 100, 8); + assert!(!state.waiting()); + state.apply(Update::Note("loading details 0/3".to_string())); + assert!(state.waiting()); + assert_eq!( + state.frame(Style::PLAIN)[0], + "3 patches in this project | loading details 0/3" + ); + let mut cells = state.table.rows[1].clone(); + cells[3] = Cell::painted("106/106", Some("32")); + cells[4] = Cell::plain("+26 -22"); + state.apply(Update::Row(1, cells)); + state.apply(Update::Note(String::new())); + assert!(!state.waiting()); + assert_eq!( + state.frame(Style::PLAIN)[..5], + [ + "3 patches in this project", + " SEVERITY PACKAGE FIXES TESTS CHANGE MODE", + "> HIGH pkg-00@1.0.0 CVE-2026-0000 hosted", + " HIGH pkg-01@1.0.0 CVE-2026-0001 106/106 +26 -22 hosted", + " HIGH pkg-02@1.0.0 CVE-2026-0002 hosted", + ] + ); + // A row that is not there is ignored. + state.apply(Update::Row(9, Vec::new())); + assert_eq!(state.table.rows.len(), 3); + // The same rows print as plain lines once the browser is left. + assert_eq!( + table_lines(&state.table, 100, Style::PLAIN)[..2], + [ + " SEVERITY PACKAGE FIXES TESTS CHANGE MODE", + " HIGH pkg-00@1.0.0 CVE-2026-0000 hosted", + ] + ); + } + + /// Opening a row asks for its page and waits for it; the page takes + /// the screen when it arrives, scrolls, steps between its files, and + /// goes back to the table where the user left it. + #[test] + fn a_row_opens_into_a_page_that_scrolls_and_steps_between_files() { + let mut state = State::of_table(table(5), 60, 8); + state.key(Key::Down); + assert_eq!(state.key(Key::Open), Step::Open(1)); + assert!(state.waiting()); + assert_eq!( + state.frame(Style::PLAIN), + [ + "| Reading HIGH pkg-01@1.0.0", + "", + "", + "", + "", + "", + "", + "q back", + ] + ); + // A page for another row is not what was asked for. + state.apply(Update::Page(3, Ok(page(60)))); + assert_eq!(state.screen, Screen::Waiting(1)); + state.apply(Update::Page(1, Ok(page(60)))); + assert_eq!( + state.frame(Style::PLAIN), + [ + "pkg:npm/pkg-00@1.0.0 HIGH", + "line 000", + "line 001", + "line 002", + "line 003", + "line 004", + "line 005", + "Up/Down scroll PgUp/PgDn page n/p file q back 6/60", + ] + ); + // `n` goes to the next file, and the key line names it (the keys + // give way to it at this width). + assert_eq!(state.key(Key::Next), Step::Redraw); + let frame = state.frame(Style::PLAIN); + assert_eq!(frame[1], "line 010"); + assert_eq!(frame[7], "file 1/2 a.js 16/60"); + state.key(Key::Next); + assert_eq!(state.frame(Style::PLAIN)[1], "line 040"); + assert_eq!(state.key(Key::Next), Step::Stay, "no file after the last"); + state.key(Key::Prev); + assert_eq!(state.frame(Style::PLAIN)[1], "line 010"); + // Scrolling stops at the last screenful. + state.key(Key::Last); + let frame = state.frame(Style::PLAIN); + assert_eq!(frame[1], "line 054"); + assert_eq!(frame[6], "line 059"); + assert_eq!(state.key(Key::Down), Step::Stay); + assert_eq!(state.key(Key::PageDown), Step::Stay); + // A wide terminal shows the keys too. + state.resize(120, 8); + assert_eq!( + state.frame(Style::PLAIN)[7], + "Up/Down scroll PgUp/PgDn page n/p file q back file 2/2 lib/b.js 60/60" + ); + // Back to the table, on the row that was opened. + assert_eq!(state.key(Key::Back), Step::Redraw); + assert_eq!(state.screen, Screen::Table); + assert_eq!(state.view.selected, 1); + assert_eq!(state.key(Key::Back), Step::Leave); + } + + #[test] + fn a_row_without_a_page_says_why_and_goes_back() { + let mut state = State::of_table(table(2), 60, 6); + state.key(Key::Open); + state.apply(Update::Page( + 0, + Err("the patch service could not be reached".to_string()), + )); + assert_eq!( + state.frame(Style::PLAIN), + [ + "HIGH pkg-00@1.0.0", + "", + "the patch service could not be reached", + "", + "", + "q back", + ] + ); + assert!(!state.waiting()); + assert_eq!(state.key(Key::Down), Step::Stay); + assert_eq!(state.key(Key::Back), Step::Redraw); + assert_eq!(state.screen, Screen::Table); + // Leaving while the page is on its way drops it when it comes. + state.key(Key::Open); + state.key(Key::Back); + state.apply(Update::Page(0, Ok(page(5)))); + assert_eq!(state.screen, Screen::Table); + } + + /// `show` is a browser of one page: going back from it leaves. + #[test] + fn a_lone_page_leaves_on_back() { + let mut state = State::of_page(page(5), 40, 6); + assert_eq!( + state.frame(Style::PLAIN), + [ + "pkg:npm/pkg-00@1.0.0 HIGH", + "line 000", + "line 001", + "line 002", + "line 003", + "4/5", + ] + ); + assert_eq!(state.key(Key::Down), Step::Redraw); + assert_eq!( + state.key(Key::Down), + Step::Stay, + "the last line is on screen" + ); + assert_eq!(state.key(Key::Back), Step::Leave); + } + + /// A page's lines are cut to the terminal, never wrapped: color + /// sequences pass and are closed, anything that could move the cursor + /// is dropped, and a character that is not one column wide is shown as + /// one that is. + #[test] + fn a_window_of_a_line_takes_exactly_its_columns() { + assert_eq!(window("abcdefghij", 0, 4), "abcd"); + assert_eq!(window("abcdefghij", 8, 4), "ij"); + assert_eq!(window("abcdefghij", 20, 4), ""); + assert_eq!( + window("\x1b[32m+added line\x1b[0m", 0, 6), + "\x1b[32m+added\x1b[0m" + ); + assert_eq!( + window("\x1b[32m+added line\x1b[0m", 7, 4), + "\x1b[32mline\x1b[0m\x1b[0m" + ); + assert_eq!(window("a\x07c", 0, 9), "a c"); + assert_eq!(window("a\x1b[2Jb\x1b[Hc", 0, 9), "abc"); + // A tab runs to the next stop, so code keeps its indentation, + // wherever the window starts. + assert_eq!(window("\tif x {", 0, 12), " if x {"); + assert_eq!(window("+\t\treturn", 0, 20), "+ return"); + assert_eq!(window("ab\tc", 0, 9), "ab c"); + assert_eq!(window("\t\tx", 6, 9), " x"); + assert_eq!(window("\tx", 0, 2), " "); + // A wide character takes its two columns, and shows as a space + // where an edge of the window cuts it in half. + assert_eq!(window("日本語", 0, 9), "日本語"); + assert_eq!(window("日本語", 0, 4), "日本"); + assert_eq!(window("日本語", 0, 3), "日 "); + assert_eq!(window("日本語", 1, 4), " 本 "); + assert_eq!(window("a日b", 0, 4), "a日b"); + // One that takes no column rides on the one before it. + assert_eq!(window("e\u{301}x", 0, 2), "e\u{301}x"); + assert_eq!(window("e\u{301}x", 1, 2), "x"); + // Shifted sideways, a page shows the rest of its long lines. + let mut state = State::of_page( + Page { + title: "t".to_string(), + lines: vec!["0123456789abcdefghij".to_string()], + marks: Vec::new(), + }, + 12, + 4, + ); + assert_eq!(state.frame(Style::PLAIN)[1], "0123456789a"); + state.key(Key::Right); + assert_eq!(state.frame(Style::PLAIN)[1], "89abcdefghi"); + state.key(Key::Left); + assert_eq!(state.key(Key::Left), Step::Stay); + } + + #[test] + fn the_layout_drops_willing_columns_then_cuts_the_widest() { + let table = table(3); + let widths = |room: usize| -> Vec<(&str, usize)> { + layout(&table, room) + .into_iter() + .map(|(index, width)| (table.columns[index].title, width)) + .collect() + }; + // TESTS and CHANGE have nothing in them yet: they take no room. + assert_eq!( + widths(200), + [("SEVERITY", 8), ("PACKAGE", 12), ("FIXES", 13), ("MODE", 6)] + ); + assert_eq!( + widths(40), + [("SEVERITY", 8), ("PACKAGE", 12), ("FIXES", 13)] + ); + assert_eq!(widths(30), [("SEVERITY", 8), ("PACKAGE", 12)]); + assert_eq!(widths(20), [("SEVERITY", 8), ("PACKAGE", 8)]); + assert_eq!(widths(4), [("SEVERITY", 8), ("PACKAGE", 1)]); + } +} diff --git a/crates/socket-patch-cli/src/ui/diff.rs b/crates/socket-patch-cli/src/ui/diff.rs new file mode 100644 index 000000000..27bb4fb37 --- /dev/null +++ b/crates/socket-patch-cli/src/ui/diff.rs @@ -0,0 +1,480 @@ +//! A line diff and its unified rendering, for showing what a patch changes +//! in a file. Pure: bytes in, lines of text out. +//! +//! The diff is Myers' shortest edit script over lines, bounded: a file +//! that changes beyond [`MAX_EDIT_DISTANCE`] lines is shown as replaced +//! whole rather than diffed for as long as it takes. What is rendered is +//! for reading, not for `patch(1)`: control characters in a line are +//! spelled out (file contents come from the network and must not drive the +//! terminal) and a very long line is cut. + +use super::{paint, Style}; + +/// Lines of context around a change. +const CONTEXT: usize = 3; +/// The longest edit script searched for. Past it (a file rewritten +/// wholesale) the two sides are shown as one removal and one addition. +const MAX_EDIT_DISTANCE: usize = 1000; +/// Characters of one line shown before it is cut (a minified bundle is one +/// line of megabytes). +const MAX_LINE_CHARS: usize = 400; + +/// One step of an edit script. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Op { + Keep, + Remove, + Add, +} + +/// The shortest edit script turning `a` into `b` (Myers), or `None` when +/// it is longer than `limit`. +fn shortest_edit(a: &[T], b: &[T], limit: usize) -> Option> { + let (n, m) = (a.len() as isize, b.len() as isize); + let limit = limit.min(a.len() + b.len()) as isize; + // `v[k + offset]`: the furthest x reached on diagonal k = x - y. A + // round d reads diagonals -d-1..=d+1. + let offset = limit + 1; + let mut v = vec![0isize; (2 * limit + 3) as usize]; + // Per round, the diagonals it read, as they were before it. + let mut trace: Vec> = Vec::new(); + let mut found = false; + 'rounds: for d in 0..=limit { + trace.push(v[(offset - d - 1) as usize..=(offset + d + 1) as usize].to_vec()); + let mut k = -d; + while k <= d { + let down = + k == -d || (k != d && v[(k - 1 + offset) as usize] < v[(k + 1 + offset) as usize]); + let mut x = if down { + v[(k + 1 + offset) as usize] + } else { + v[(k - 1 + offset) as usize] + 1 + }; + let mut y = x - k; + while x < n && y < m && a[x as usize] == b[y as usize] { + x += 1; + y += 1; + } + v[(k + offset) as usize] = x; + if x >= n && y >= m { + found = true; + break 'rounds; + } + k += 2; + } + } + if !found { + return None; + } + // Walk the rounds back from the end, emitting the script in reverse. + let mut ops = Vec::new(); + let (mut x, mut y) = (n, m); + for (d, seen) in trace.iter().enumerate().rev() { + let d = d as isize; + // `seen[k + d + 1]` is the round's view of diagonal k. + let at = |k: isize| seen[(k + d + 1) as usize]; + let k = x - y; + let prev_k = if k == -d || (k != d && at(k - 1) < at(k + 1)) { + k + 1 + } else { + k - 1 + }; + let prev_x = at(prev_k); + let prev_y = prev_x - prev_k; + while x > prev_x && y > prev_y { + ops.push(Op::Keep); + x -= 1; + y -= 1; + } + if d > 0 { + ops.push(if x == prev_x { Op::Add } else { Op::Remove }); + } + x = prev_x; + y = prev_y; + } + ops.reverse(); + Some(ops) +} + +/// The edit script turning `a` into `b`: the shortest one, or (past +/// [`MAX_EDIT_DISTANCE`]) every line between their common head and tail +/// removed, then added. +fn edit_script(a: &[T], b: &[T]) -> Vec { + let head = a.iter().zip(b).take_while(|(x, y)| x == y).count(); + let tail = a[head..] + .iter() + .rev() + .zip(b[head..].iter().rev()) + .take_while(|(x, y)| x == y) + .count(); + let (mid_a, mid_b) = (&a[head..a.len() - tail], &b[head..b.len() - tail]); + let middle = shortest_edit(mid_a, mid_b, MAX_EDIT_DISTANCE).unwrap_or_else(|| { + std::iter::repeat_n(Op::Remove, mid_a.len()) + .chain(std::iter::repeat_n(Op::Add, mid_b.len())) + .collect() + }); + std::iter::repeat_n(Op::Keep, head) + .chain(middle) + .chain(std::iter::repeat_n(Op::Keep, tail)) + .collect() +} + +/// What a patch does to one file, ready to print. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct FileDiff { + /// Lines the patch adds, and lines it removes. + pub(crate) added: usize, + pub(crate) removed: usize, + /// Either side is not text: no line diff, one line saying so. + pub(crate) binary: bool, + /// The unified diff: its two header lines, then the hunks. + pub(crate) lines: Vec, +} + +/// Whether `bytes` are text a line diff makes sense of: valid UTF-8 with +/// no NUL. +fn as_text(bytes: &[u8]) -> Option<&str> { + let text = std::str::from_utf8(bytes).ok()?; + (!text.contains('\0')).then_some(text) +} + +/// One line of file content as it is shown: without its line ending, tabs +/// kept, every other control character spelled in caret notation (`^[` for +/// ESC), and cut at [`MAX_LINE_CHARS`] with the count of what was left +/// out. +fn shown(line: &str) -> String { + let line = line.strip_suffix('\n').unwrap_or(line); + let line = line.strip_suffix('\r').unwrap_or(line); + let mut out = String::with_capacity(line.len().min(MAX_LINE_CHARS * 4)); + let mut chars = line.chars(); + for c in chars.by_ref().take(MAX_LINE_CHARS) { + match c { + '\t' => out.push('\t'), + '\x7f' => out.push_str("^?"), + c if (c as u32) < 0x20 => { + out.push('^'); + out.push((c as u8 + 0x40) as char); + } + c if c.is_control() => out.push('?'), + c => out.push(c), + } + } + let rest = chars.count(); + if rest > 0 { + out.push_str(&format!(" ...[+{rest} characters]")); + } + out +} + +/// The unified diff of one file: `before` (absent for a file the patch +/// adds) against `after`, with [`CONTEXT`] lines around each change. +/// `style` colors it: removals red, additions green, hunk headers cyan, +/// the file headers bold. +pub(crate) fn file_diff(path: &str, before: Option<&[u8]>, after: &[u8], style: Style) -> FileDiff { + let color = style.color; + let old_name = match before { + Some(_) => format!("a/{path}"), + None => "/dev/null".to_string(), + }; + let mut lines = vec![ + paint(&format!("--- {old_name}"), "1", color), + paint(&format!("+++ b/{path}"), "1", color), + ]; + let before_bytes = before.unwrap_or_default(); + let (Some(old), Some(new)) = (as_text(before_bytes), as_text(after)) else { + lines.push(format!( + "Binary file changed ({} -> {} bytes)", + before_bytes.len(), + after.len() + )); + return FileDiff { + binary: true, + lines, + ..FileDiff::default() + }; + }; + let a: Vec<&str> = old.split_inclusive('\n').collect(); + let b: Vec<&str> = new.split_inclusive('\n').collect(); + let ops = edit_script(&a, &b); + let (added, removed) = ops.iter().fold((0, 0), |(add, rem), op| match op { + Op::Add => (add + 1, rem), + Op::Remove => (add, rem + 1), + Op::Keep => (add, rem), + }); + + // The script's steps that belong to a hunk: each change with its + // context, hunks closer than two contexts merged. + let changed: Vec = (0..ops.len()).filter(|&i| ops[i] != Op::Keep).collect(); + let mut hunks: Vec<(usize, usize)> = Vec::new(); + for &i in &changed { + let (start, end) = (i.saturating_sub(CONTEXT), (i + CONTEXT + 1).min(ops.len())); + match hunks.last_mut() { + Some(last) if start <= last.1 => last.1 = end, + _ => hunks.push((start, end)), + } + } + // Line numbers (0-based) of each step on either side. + let mut position = Vec::with_capacity(ops.len()); + let (mut x, mut y) = (0usize, 0usize); + for op in &ops { + position.push((x, y)); + match op { + Op::Keep => { + x += 1; + y += 1; + } + Op::Remove => x += 1, + Op::Add => y += 1, + } + } + for (start, end) in hunks { + let steps = &ops[start..end]; + let old_len = steps.iter().filter(|op| **op != Op::Add).count(); + let new_len = steps.iter().filter(|op| **op != Op::Remove).count(); + let (old_at, new_at) = position[start]; + // A side with no lines names the line before it, as `diff -u` does. + let from = |at: usize, len: usize| if len == 0 { at } else { at + 1 }; + lines.push(paint( + &format!( + "@@ -{},{old_len} +{},{new_len} @@", + from(old_at, old_len), + from(new_at, new_len) + ), + "36", + color, + )); + for (i, op) in steps.iter().enumerate() { + let (x, y) = position[start + i]; + let (mark, text, code) = match op { + Op::Keep => (' ', a[x], ""), + Op::Remove => ('-', a[x], "31"), + Op::Add => ('+', b[y], "32"), + }; + let line = format!("{mark}{}", shown(text)); + lines.push(if code.is_empty() { + line + } else { + paint(&line, code, color) + }); + if !text.ends_with('\n') { + lines.push("\\ No newline at end of file".to_string()); + } + } + } + FileDiff { + added, + removed, + binary: false, + lines, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PLAIN: Style = Style::PLAIN; + + /// Apply a script to `a`: what it produces must be `b`. + fn apply<'a>(ops: &[Op], a: &[&'a str], b: &[&'a str]) -> Vec<&'a str> { + let (mut x, mut y) = (0, 0); + let mut out = Vec::new(); + for op in ops { + match op { + Op::Keep => { + assert_eq!(a[x], b[y], "a kept line is the same on both sides"); + out.push(a[x]); + x += 1; + y += 1; + } + Op::Remove => x += 1, + Op::Add => { + out.push(b[y]); + y += 1; + } + } + } + assert_eq!((x, y), (a.len(), b.len()), "the script covers both sides"); + out + } + + fn edits(ops: &[Op]) -> usize { + ops.iter().filter(|op| **op != Op::Keep).count() + } + + #[test] + fn edit_script_is_shortest_and_reproduces_the_target() { + // Myers' own example: ABCABBA -> CBABAC is five edits. + let a: Vec<&str> = "ABCABBA".split("").filter(|s| !s.is_empty()).collect(); + let b: Vec<&str> = "CBABAC".split("").filter(|s| !s.is_empty()).collect(); + let ops = edit_script(&a, &b); + assert_eq!(apply(&ops, &a, &b), b); + assert_eq!(edits(&ops), 5); + + let cases: &[(&[&str], &[&str], usize)] = &[ + (&[], &[], 0), + (&[], &["x"], 1), + (&["x"], &[], 1), + (&["a", "b", "c"], &["a", "b", "c"], 0), + (&["a", "b", "c"], &["a", "x", "c"], 2), + (&["a", "b", "c"], &["a", "c"], 1), + (&["a", "c"], &["a", "b", "c"], 1), + (&["a", "b"], &["c", "d"], 4), + (&["a", "a", "a"], &["a", "a"], 1), + ]; + for (a, b, want) in cases { + let ops = edit_script(a, b); + assert_eq!(apply(&ops, a, b), *b, "{a:?} -> {b:?}"); + assert_eq!(edits(&ops), *want, "{a:?} -> {b:?}"); + } + } + + /// A rewrite past the search bound is still a correct script: the + /// common head and tail kept, the middle replaced. + #[test] + fn a_wholesale_rewrite_falls_back_to_replacing_the_middle() { + let old: Vec = (0..MAX_EDIT_DISTANCE + 50) + .map(|i| format!("old {i}")) + .collect(); + let new: Vec = (0..MAX_EDIT_DISTANCE + 50) + .map(|i| format!("new {i}")) + .collect(); + let mut a: Vec<&str> = vec!["head"]; + a.extend(old.iter().map(String::as_str)); + a.push("tail"); + let mut b: Vec<&str> = vec!["head"]; + b.extend(new.iter().map(String::as_str)); + b.push("tail"); + let ops = edit_script(&a, &b); + assert_eq!(apply(&ops, &a, &b), b); + assert_eq!(ops[0], Op::Keep); + assert_eq!(ops[ops.len() - 1], Op::Keep); + assert_eq!(edits(&ops), old.len() + new.len()); + } + + #[test] + fn file_diff_is_unified_with_context_and_counts() { + let before = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n"; + let after = "one\ntwo\nthree\nfour\nFIVE\nsix\nseven\neight\nnine\nten\neleven\n"; + let diff = file_diff("lib/a.js", Some(before.as_bytes()), after.as_bytes(), PLAIN); + assert_eq!((diff.added, diff.removed, diff.binary), (2, 1, false)); + assert_eq!( + diff.lines, + vec![ + "--- a/lib/a.js", + "+++ b/lib/a.js", + "@@ -2,9 +2,10 @@", + " two", + " three", + " four", + "-five", + "+FIVE", + " six", + " seven", + " eight", + " nine", + " ten", + "+eleven", + ] + ); + // Changes further apart than their contexts get hunks of their own. + let lines: Vec = (1..=30).map(|i| format!("l{i}\n")).collect(); + let old = lines.concat(); + let mut changed = lines.clone(); + changed[1] = "L2\n".to_string(); + changed[27] = "L28\n".to_string(); + let diff = file_diff( + "a", + Some(old.as_bytes()), + changed.concat().as_bytes(), + PLAIN, + ); + let headers: Vec<&String> = diff.lines.iter().filter(|l| l.starts_with("@@")).collect(); + assert_eq!(headers, ["@@ -1,5 +1,5 @@", "@@ -25,6 +25,6 @@"]); + // Nothing changed: the headers alone. + let same = file_diff("a", Some(b"x\n"), b"x\n", PLAIN); + assert_eq!((same.added, same.removed, same.lines.len()), (0, 0, 2)); + } + + #[test] + fn file_diff_of_an_added_file_and_a_missing_final_newline() { + let diff = file_diff("new.txt", None, b"a\nb", PLAIN); + assert_eq!((diff.added, diff.removed), (2, 0)); + assert_eq!( + diff.lines, + vec![ + "--- /dev/null", + "+++ b/new.txt", + "@@ -0,0 +1,2 @@", + "+a", + "+b", + "\\ No newline at end of file", + ] + ); + // The patch adds the missing newline: the old last line says so. + let diff = file_diff("f", Some(b"a\nb"), b"a\nb\n", PLAIN); + assert_eq!( + diff.lines[2..], + [ + "@@ -1,2 +1,2 @@", + " a", + "-b", + "\\ No newline at end of file", + "+b" + ] + ); + } + + #[test] + fn file_diff_of_binary_content_says_so() { + let diff = file_diff("lib.so", Some(&[0u8, 1, 2]), &[0u8, 1, 2, 3], PLAIN); + assert!(diff.binary); + assert_eq!( + diff.lines, + vec![ + "--- a/lib.so", + "+++ b/lib.so", + "Binary file changed (3 -> 4 bytes)" + ] + ); + // Invalid UTF-8 is binary too. + assert!(file_diff("x", Some(b"ok\n"), &[0xff, 0xfe], PLAIN).binary); + } + + /// File content never drives the terminal: an escape sequence is + /// spelled out, and a line of megabytes is cut. + #[test] + fn shown_lines_spell_out_control_characters_and_cut_long_lines() { + assert_eq!(shown("a\tb\r\n"), "a\tb"); + assert_eq!(shown("x\x1b[2Jy\x07\x7f\n"), "x^[[2Jy^G^?"); + assert_eq!(shown("caf\u{e9} \u{6f22}"), "caf\u{e9} \u{6f22}"); + assert_eq!(shown("a\u{9b}b"), "a?b"); + let long = "x".repeat(MAX_LINE_CHARS + 25); + assert_eq!( + shown(&long), + format!("{} ...[+25 characters]", "x".repeat(MAX_LINE_CHARS)) + ); + let diff = file_diff("f", Some(b"a\n"), b"a\x1b[31m\n", PLAIN); + assert_eq!(diff.lines[3..], ["-a", "+a^[[31m"]); + } + + #[test] + fn file_diff_colors_by_kind_of_line() { + let color = Style { + color: true, + glyphs: false, + }; + let diff = file_diff("f", Some(b"a\nb\n"), b"a\nc\n", color); + assert_eq!( + diff.lines, + vec![ + "\x1b[1m--- a/f\x1b[0m", + "\x1b[1m+++ b/f\x1b[0m", + "\x1b[36m@@ -1,2 +1,2 @@\x1b[0m", + " a", + "\x1b[31m-b\x1b[0m", + "\x1b[32m+c\x1b[0m", + ] + ); + } +} diff --git a/crates/socket-patch-cli/src/ui/mod.rs b/crates/socket-patch-cli/src/ui/mod.rs index f4a1b8bab..7263d1303 100644 --- a/crates/socket-patch-cli/src/ui/mod.rs +++ b/crates/socket-patch-cli/src/ui/mod.rs @@ -6,12 +6,18 @@ //! - `text`: wording and shaping shared by several commands. //! - [`color_enabled`], [`paint`], [`severity`], [`pad`]: color policy and //! ANSI-aware column alignment. +//! - [`diff`]: a line diff and its unified rendering. +//! - [`Style`]: how one stream is drawn (color, and the Unicode marks and +//! bars of a terminal known to show them), with [`bar`] as its ASCII +//! fallback. //! - [`init`] / [`quiet`]: the process-wide `--silent`/`--json` switch, //! shared with core's own advisories. //! //! Every piece that writes takes (or wraps) a plain `Write` sink so it can //! be unit-tested against a `Vec`. +pub(crate) mod browser; +pub(crate) mod diff; mod prompt; mod status; mod text; @@ -21,11 +27,12 @@ use std::io::IsTerminal; use crate::args::GlobalArgs; pub(crate) use prompt::confirm; -pub use prompt::{select_one, SelectError}; +pub use prompt::{select_from, select_one, SelectError}; pub(crate) use status::StatusLine; pub(crate) use text::{ - agent_next_steps, manifest_error_message, next_steps, next_steps_installed, plural, - sentence_case, shell_word, short_uuid, sweep_failure, truncate, + agent_next_steps, folded, manifest_error_message, next_steps, next_steps_installed, + package_names, plural, printable, sentence_case, shell_word, short_uuid, sweep_failure, + truncate, worst_and_ids, }; /// [`text::no_patches_message`] for this run: the manifest path is named @@ -178,18 +185,315 @@ fn env_var(k: &str) -> Option { std::env::var(k).ok() } -/// [`color_enabled`] for stdout; a terminal must also render escapes -/// ([`vt`]). +/// One of the process's standard streams, for [`attended`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Stream { + Stdin, + Stdout, + Stderr, +} + +/// Whether `stream` is a terminal with a person at it: a terminal, and +/// not one an AI coding agent runs the command in ([`plain_output`]). +/// +/// Every choice of how to draw for a person asks this, never +/// `is_terminal()` itself: the animated status line, color, marks and +/// bars, the full-screen browser, the arrow-key menus, text fitted to +/// the terminal's width. So an agent gets what a pipe gets, however its +/// harness wires the streams. Some run commands on a pseudo-terminal, +/// where the status line's redraws alone would be most of what the agent +/// reads back, and the browser would wait for keys nobody presses. +/// +/// A typed yes/no question ([`confirm`]) does not ask this: it is a +/// safeguard, not decoration, and the environment is not what waives it +/// (`--yes` is). +pub(crate) fn attended(stream: Stream) -> bool { + let terminal = match stream { + Stream::Stdin => std::io::stdin().is_terminal(), + Stream::Stdout => std::io::stdout().is_terminal(), + Stream::Stderr => std::io::stderr().is_terminal(), + }; + terminal && plain() == Plain::No +} + +/// [`plain_output`] of this process's environment, read once: it does +/// not change during a run. +fn plain() -> Plain { + static PLAIN: std::sync::OnceLock = std::sync::OnceLock::new(); + *PLAIN.get_or_init(|| plain_output(env_var)) +} + +/// Say once, on stderr, why this terminal is not getting the interactive +/// output it would: an agent's variable is set. Called where a command +/// prints instead of opening the full-screen browser or a menu, for +/// someone working in a terminal an agent started, who would otherwise +/// look for the reason in vain. Nothing when stdin or stderr is not a +/// terminal, when `SOCKET_PLAIN` decided, or under `--json` / `--silent`. +pub(crate) fn note_agent_terminal(common: &GlobalArgs) { + static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let Plain::Agent(variable) = plain() else { + return; + }; + if common.json + || common.silent + || !std::io::stdin().is_terminal() + || !std::io::stderr().is_terminal() + || SAID.swap(true, std::sync::atomic::Ordering::Relaxed) + { + return; + } + eprintln!("{}", agent_terminal_note(variable)); +} + +/// The line [`note_agent_terminal`] prints. +fn agent_terminal_note(variable: &str) -> String { + format!( + "Note: {variable} is set, so this terminal gets the plain output of an AI coding \ + agent's. A person at it can set SOCKET_PLAIN=0 for the interactive output." + ) +} + +/// The variables AI coding agents put in the environment of the commands +/// they run: `AI_AGENT` first (any agent may set it, to its name), then +/// each tool's own. Only variables an agent injects into its commands +/// are here. One an editor sets in every terminal, a person's included +/// (`CURSOR_TRACE_ID`, `REPL_ID`), is not, and neither is the bare +/// `AGENT`, which is set for too many other reasons. +pub const AGENT_ENV_VARS: &[&str] = &[ + "AI_AGENT", + // Claude Code + "CLAUDECODE", + "CLAUDE_CODE", + // Cursor + "CURSOR_AGENT", + // OpenAI Codex + "CODEX_SANDBOX", + "CODEX_THREAD_ID", + "CODEX_CI", + // Gemini CLI, Antigravity + "GEMINI_CLI", + "ANTIGRAVITY_AGENT", + // VS Code and GitHub Copilot + "VSCODE_AGENT", + "COPILOT_AGENT", + "COPILOT_CLI", + // OpenCode + "OPENCODE", + "OPENCODE_CLIENT", + // Amp, Goose, Augment, Cline, Roo Code, Qwen Code, Pi + "AMP_CURRENT_THREAD_ID", + "GOOSE_TERMINAL", + "AUGMENT_AGENT", + "CLINE_ACTIVE", + "ROO_ACTIVE", + "ROO_CODE_TASK_ID", + "QWEN_CODE", + "PI_CODING_AGENT", +]; + +/// Why output is kept plain on a terminal too (see [`attended`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Plain { + /// It is not: a terminal has a person at it. + No, + /// `SOCKET_PLAIN` asks for it. + Asked, + /// An agent runs the command: this one of [`AGENT_ENV_VARS`] is set. + Agent(&'static str), +} + +/// Whether, and why, output is kept plain on a terminal, pure over the +/// environment: +/// +/// - `SOCKET_PLAIN` decides when it is set to anything: a truthy value +/// (`1`, `true`, `yes`, `on`, `y`, `t`: the vocabulary of every other +/// `SOCKET_*` toggle) asks for plain output; any other value keeps the +/// terminal output whatever else is set (someone at a terminal an +/// agent started). +/// - Otherwise an agent's variable decides: the first of +/// [`AGENT_ENV_VARS`] set to something other than `0`, `false`, `no`, +/// `off`, `n` or `f`. +pub(crate) fn plain_output(env: impl Fn(&str) -> Option) -> Plain { + let set = |k: &str| { + env(k) + .map(|v| v.trim().to_ascii_lowercase()) + .filter(|v| !v.is_empty()) + }; + if let Some(asked) = set("SOCKET_PLAIN") { + return match asked.as_str() { + "1" | "true" | "yes" | "on" | "y" | "t" => Plain::Asked, + _ => Plain::No, + }; + } + let off = |v: &str| matches!(v, "0" | "false" | "no" | "off" | "n" | "f"); + AGENT_ENV_VARS + .iter() + .find(|name| set(name).is_some_and(|v| !off(&v))) + .map_or(Plain::No, |name| Plain::Agent(name)) +} + +/// Whether the Unicode marks and bars may be drawn, pure over its inputs: +/// only with `color` on (so `NO_COLOR` turns both off) and only on a +/// terminal (a pipe or log gets ASCII, whatever forced its colors), and +/// then only where the terminal is known to show UTF-8: +/// +/// - `TERM=linux` (the kernel console's font holds few glyphs) → off; +/// - Windows → on in Windows Terminal (`WT_SESSION`), in an editor's +/// terminal (`TERM_PROGRAM`) and in an xterm-like one (`TERM=xterm...`: +/// Git Bash, MSYS2); the legacy console → off; +/// - elsewhere → on when the locale is UTF-8 (the first set of `LC_ALL`, +/// `LC_CTYPE`, `LANG`). +/// +/// Everything drawn with them has an ASCII form of the same width, so a +/// wrong guess costs polish, never alignment. +pub(crate) fn glyphs_enabled( + color: bool, + is_tty: bool, + windows: bool, + env: impl Fn(&str) -> Option, +) -> bool { + let set = |k: &str| env(k).filter(|v| !v.is_empty()); + if !color || !is_tty || set("TERM").is_some_and(|t| t == "linux") { + return false; + } + if windows { + return set("WT_SESSION").is_some() + || set("TERM_PROGRAM").is_some() + || set("TERM").is_some_and(|t| t.starts_with("xterm")); + } + ["LC_ALL", "LC_CTYPE", "LANG"] + .into_iter() + .find_map(set) + .is_some_and(|locale| { + let locale = locale.to_ascii_lowercase(); + locale.contains("utf-8") || locale.contains("utf8") + }) +} + +/// Whether someone is at a terminal that can show the full-screen browser +/// ([`browser`]): stdin, stdout and stderr (where it is drawn) are all +/// terminals with a person at them ([`attended`]), and the terminal +/// renders escape sequences (not `TERM=dumb`, not a console without VT +/// processing). The browser is drawn with nothing else, so anywhere this +/// is false a command prints instead. +/// +/// Never under `SOCKET_DEBUG`, as the status line is never live then: +/// core's debug logging writes straight to stderr, where it would land +/// in the middle of a frame and be gone with the screen. +pub(crate) fn full_screen() -> bool { + attended(Stream::Stdin) + && attended(Stream::Stdout) + && attended(Stream::Stderr) + && !socket_patch_core::utils::env_compat::is_debug_enabled() + && vt() == (true, true) + && env_var("TERM").is_none_or(|term| term != "dumb") +} + +/// Await `work` with `label` on a status line of its own, so a step +/// that takes a moment shows as work in progress ([`StatusLine::stderr`] +/// says when a line shows at all). The line is up only while `work` is +/// awaited, and `work` must not print: its result is what the caller +/// reports, once this returns. +pub(crate) async fn busy( + common: &GlobalArgs, + label: impl std::fmt::Display, + work: impl std::future::Future, +) -> T { + let mut status = StatusLine::stderr(common.json, common.silent); + status.set(label); + let done = work.await; + status.finish(); + done +} + +/// How human output is drawn on one stream: with color, and with the +/// Unicode marks and bars ([`glyphs_enabled`]). Every piece has a plain +/// form, which is what a pipe, a log and a test see. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Style { + pub(crate) color: bool, + pub(crate) glyphs: bool, +} + +impl Style { + /// No color and no glyphs: logs, pipes, `NO_COLOR`. + pub(crate) const PLAIN: Style = Style { + color: false, + glyphs: false, + }; + + /// The style of stdout (results). + pub(crate) fn stdout() -> Style { + Style::of(attended(Stream::Stdout), stdout_color()) + } + + /// The style of stderr (status lines, warnings). + pub(crate) fn stderr() -> Style { + Style::of(attended(Stream::Stderr), stderr_color()) + } + + fn of(is_tty: bool, color: bool) -> Style { + Style { + color, + glyphs: glyphs_enabled(color, is_tty, cfg!(windows), env_var), + } + } + + /// The mark that opens the line of something done, one column wide: + /// a green `✔`, or a space where glyphs are off (so the line keeps its + /// indent). + pub(crate) fn check(&self) -> String { + if self.glyphs { + paint("✔", "32", self.color) + } else { + " ".to_string() + } + } + + /// A progress bar `cells` columns wide (plus the brackets of the ASCII + /// form): `done` of `total` filled. + pub(crate) fn bar(&self, done: usize, total: usize, cells: usize) -> String { + if !self.glyphs { + return bar(done, total, cells); + } + let filled = filled_cells(done, total, cells); + format!( + "{}{}", + paint(&"━".repeat(filled), "32", self.color), + paint(&"─".repeat(cells - filled), "2", self.color) + ) + } + + /// The width of [`Self::bar`] at `cells`. + pub(crate) fn bar_width(&self, cells: usize) -> usize { + cells + if self.glyphs { 0 } else { 2 } + } +} + +/// How many of `cells` are filled at `done` of `total`: rounded down, so a +/// bar is full only when the work is done. +fn filled_cells(done: usize, total: usize, cells: usize) -> usize { + if total == 0 { + 0 + } else { + (done.min(total) * cells) / total + } +} + +/// [`color_enabled`] for stdout, where a terminal counts when a person +/// is at it ([`attended`]); any terminal, attended or not, must also +/// render escapes ([`vt`]). pub(crate) fn stdout_color() -> bool { - let tty = std::io::stdout().is_terminal(); - color_enabled(tty, env_var) && (!tty || vt().0) + let terminal = std::io::stdout().is_terminal(); + color_enabled(attended(Stream::Stdout), env_var) && (!terminal || vt().0) } -/// [`color_enabled`] for stderr; a terminal must also render escapes -/// ([`vt`]). +/// [`color_enabled`] for stderr, where a terminal counts when a person +/// is at it ([`attended`]); any terminal, attended or not, must also +/// render escapes ([`vt`]). pub(crate) fn stderr_color() -> bool { - let tty = std::io::stderr().is_terminal(); - color_enabled(tty, env_var) && (!tty || vt().1) + let terminal = std::io::stderr().is_terminal(); + color_enabled(attended(Stream::Stderr), env_var) && (!terminal || vt().1) } /// Columns of the terminal on stderr (status lines, prompts): its size, @@ -222,37 +526,54 @@ pub fn paint(text: &str, code: &str, on: bool) -> String { } } +/// `text` in bold when `on`: the numbers a result line is read for. +pub(crate) fn bold(text: &str, on: bool) -> String { + paint(text, "1", on) +} + +/// `text` dimmed when `on`: detail that supports a line without leading it. +pub(crate) fn dim(text: &str, on: bool) -> String { + paint(text, "2", on) +} + +/// A progress bar of `cells` ASCII characters between brackets, +/// `[######----]`: `done` of `total` filled, never more than all of them. +/// ASCII on purpose: every terminal and every log renders it at one column +/// per character, so a status line holding it can always be rewritten. +pub(crate) fn bar(done: usize, total: usize, cells: usize) -> String { + let filled = filled_cells(done, total, cells); + format!("[{}{}]", "#".repeat(filled), "-".repeat(cells - filled)) +} + /// Color a severity label by tier (`critical` bright red, `high` red, /// `medium`/`moderate` yellow, `low` cyan; anything else plain). The /// text itself is kept verbatim. pub fn severity(s: &str, on: bool) -> String { - let code = match s.to_lowercase().as_str() { + match severity_code(s) { + Some(code) => paint(s, code, on), + None => s.to_string(), + } +} + +/// The SGR color of a severity tier, for output that paints its cells +/// itself; `None` for a label that is not a tier. +pub(crate) fn severity_code(s: &str) -> Option<&'static str> { + Some(match s.to_lowercase().as_str() { "critical" => "91", "high" => "31", // GHSA emits `moderate`; same tier as medium (core `ranking::severity_order`). "medium" | "moderate" => "33", "low" => "36", - _ => return s.to_string(), - }; - paint(s, code, on) -} - -/// Column alignment for [`pad`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Align { - Left, - Right, + _ => return None, + }) } -/// Pad `s` to `width` *visible* characters. SGR color sequences don't -/// count, so a colored cell lines up exactly like the plain one (`{:<16}` -/// counts the invisible bytes and misaligns). Never truncates. -pub(crate) fn pad(s: &str, width: usize, align: Align) -> String { - let fill = " ".repeat(width.saturating_sub(visible_width(s))); - match align { - Align::Left => format!("{s}{fill}"), - Align::Right => format!("{fill}{s}"), - } +/// Pad `s` on the right to `width` *visible* characters. SGR color +/// sequences don't count, so a colored cell lines up exactly like the +/// plain one (`{:<16}` counts the invisible bytes and misaligns). Never +/// truncates. +pub(crate) fn pad(s: &str, width: usize) -> String { + format!("{s}{}", " ".repeat(width.saturating_sub(visible_width(s)))) } /// Characters a terminal would display for `s` (SGR sequences excluded). @@ -323,6 +644,71 @@ mod tests { ); } + /// An agent's terminal is not a terminal with a person at it: any one + /// of the variables agents set for their commands makes the output + /// plain, and `SOCKET_PLAIN` has the last word either way. + #[test] + fn plain_output_follows_the_agent_variables_and_the_override() { + let env = |vars: &'static [(&'static str, &'static str)]| { + move |k: &str| { + vars.iter() + .find(|(name, _)| *name == k) + .map(|(_, v)| v.to_string()) + } + }; + assert_eq!(plain_output(env(&[])), Plain::No); + // Each agent's own variable, by name. + for name in AGENT_ENV_VARS { + let named = move |k: &str| (k == *name).then(|| "1".to_string()); + assert_eq!(plain_output(named), Plain::Agent(name), "{name}"); + } + assert_eq!( + plain_output(env(&[("AI_AGENT", "claude-code_2-1-327_agent")])), + Plain::Agent("AI_AGENT") + ); + // Set to nothing, or to "off", is not set. + for value in ["", " ", "0", "false", "FALSE", "no", "off", "n", "f"] { + let unset = move |k: &str| (k == "CLAUDECODE").then(|| value.to_string()); + assert_eq!(plain_output(unset), Plain::No, "{value:?}"); + } + // A variable set for other reasons, or by an editor in every + // terminal, says nothing. + assert_eq!( + plain_output(env(&[ + ("AGENT", "build-agent-7"), + ("CURSOR_TRACE_ID", "abc"), + ("REPL_ID", "abc"), + ("TERM_PROGRAM", "vscode"), + ])), + Plain::No + ); + // The override. Anything but a truthy value keeps the terminal + // output, an agent or not: a typo never turns the UI off. + for value in ["0", "false", "no", "off", "n", "flase"] { + let kept = move |k: &str| match k { + "SOCKET_PLAIN" => Some(value.to_string()), + "CLAUDECODE" => Some("1".to_string()), + _ => None, + }; + assert_eq!(plain_output(kept), Plain::No, "{value:?}"); + } + for value in ["1", "true", "YES", "on", "y", "t"] { + let asked = move |k: &str| (k == "SOCKET_PLAIN").then(|| value.to_string()); + assert_eq!(plain_output(asked), Plain::Asked, "{value:?}"); + } + // Set to nothing, it decides nothing. + assert_eq!( + plain_output(env(&[("SOCKET_PLAIN", ""), ("CLAUDECODE", "1")])), + Plain::Agent("CLAUDECODE") + ); + // The note names the variable and the way back. + assert_eq!( + agent_terminal_note("CLAUDECODE"), + "Note: CLAUDECODE is set, so this terminal gets the plain output of an AI coding \ + agent's. A person at it can set SOCKET_PLAIN=0 for the interactive output." + ); + } + #[test] fn color_enabled_truth_table() { type Case<'a> = (bool, &'a [(&'a str, &'a str)], bool); @@ -361,6 +747,88 @@ mod tests { } } + #[test] + fn glyphs_need_color_a_terminal_and_a_utf8_locale() { + type Case<'a> = (bool, bool, bool, &'a [(&'a str, &'a str)], bool); + let utf8: &[(&str, &str)] = &[("LANG", "en_US.UTF-8")]; + let cases: &[Case] = &[ + // (color, tty, windows, env, glyphs) + (true, true, false, utf8, true), + (false, true, false, utf8, false), + (true, false, false, utf8, false), + (true, true, false, &[], false), + (true, true, false, &[("LANG", "C")], false), + (true, true, false, &[("LANG", "C.utf8")], true), + // The first locale variable that is set decides. + ( + true, + true, + false, + &[("LC_ALL", "C"), ("LANG", "en_US.UTF-8")], + false, + ), + ( + true, + true, + false, + &[("LC_ALL", ""), ("LC_CTYPE", "ja_JP.UTF-8")], + true, + ), + ( + true, + true, + false, + &[("LANG", "en_US.UTF-8"), ("TERM", "linux")], + false, + ), + // Windows: by terminal, never by locale. + (true, true, true, utf8, false), + (true, true, true, &[("WT_SESSION", "1")], true), + (true, true, true, &[("TERM_PROGRAM", "vscode")], true), + (true, true, true, &[("TERM", "xterm-256color")], true), + (true, true, true, &[("TERM", "cygwin")], false), + ]; + for (color, tty, windows, vars, want) in cases { + assert_eq!( + glyphs_enabled(*color, *tty, *windows, env(vars)), + *want, + "color={color} tty={tty} windows={windows} env={vars:?}" + ); + } + } + + #[test] + fn style_marks_and_bars_have_a_plain_form_of_the_same_width() { + let fancy = Style { + color: true, + glyphs: true, + }; + assert_eq!(Style::PLAIN.check(), " "); + assert_eq!(fancy.check(), "\x1b[32m✔\x1b[0m"); + assert_eq!(visible_width(&fancy.check()), 1); + assert_eq!(Style::PLAIN.bar(1, 4, 8), "[##------]"); + assert_eq!(fancy.bar(1, 4, 8), "\x1b[32m━━\x1b[0m\x1b[2m──────\x1b[0m"); + assert_eq!(visible_width(&fancy.bar(1, 4, 8)), fancy.bar_width(8)); + assert_eq!( + visible_width(&Style::PLAIN.bar(1, 4, 8)), + Style::PLAIN.bar_width(8) + ); + } + + #[test] + fn bar_fills_in_proportion_and_never_overflows() { + assert_eq!(bar(0, 4, 8), "[--------]"); + assert_eq!(bar(1, 4, 8), "[##------]"); + assert_eq!(bar(4, 4, 8), "[########]"); + assert_eq!(bar(9, 4, 8), "[########]"); + // Rounds down: the bar is full only when the work is done. + assert_eq!(bar(7, 8, 4), "[###-]"); + assert_eq!(bar(0, 0, 4), "[----]"); + assert_eq!(bar(3, 3, 0), "[]"); + assert_eq!(bold("7", true), "\x1b[1m7\x1b[0m"); + assert_eq!(dim("x", false), "x"); + } + #[test] fn severity_ramp_is_exact() { assert_eq!(severity("critical", true), "\x1b[91mcritical\x1b[0m"); @@ -378,13 +846,10 @@ mod tests { #[test] fn pad_counts_visible_chars_only() { - let colored = pad(&severity("HIGH", true), 16, Align::Left); - let plain = pad(&severity("HIGH", false), 16, Align::Left); + let colored = pad(&severity("HIGH", true), 16); + let plain = pad(&severity("HIGH", false), 16); assert_eq!(strip_ansi(&colored), plain); assert_eq!(visible_width(&colored), 16); - assert_eq!(pad("0+1", 8, Align::Right), " 0+1"); - let paid = format!("0+{}", paint("1", "33", true)); - assert_eq!(strip_ansi(&pad(&paid, 8, Align::Right)), " 0+1"); - assert_eq!(pad("toolongvalue", 4, Align::Left), "toolongvalue"); + assert_eq!(pad("toolongvalue", 4), "toolongvalue"); } } diff --git a/crates/socket-patch-cli/src/ui/prompt.rs b/crates/socket-patch-cli/src/ui/prompt.rs index 8ff5c978b..1c0d65f9a 100644 --- a/crates/socket-patch-cli/src/ui/prompt.rs +++ b/crates/socket-patch-cli/src/ui/prompt.rs @@ -10,7 +10,8 @@ use crate::args::GlobalArgs; const NON_INTERACTIVE_PROCEED: &str = "Non-interactive mode detected, proceeding automatically."; /// Same, for a prompt whose default is "no". const NON_INTERACTIVE_DECLINE: &str = "Non-interactive mode detected, declining by default."; -/// Same, for [`select_one`], which takes the first option. +/// Same, for [`select_one`], which takes the first option when nobody is +/// at a terminal on stdin (a pipe, or an AI coding agent's terminal). const NON_INTERACTIVE_SELECT_FIRST: &str = "Non-interactive mode detected, selecting the first option."; @@ -120,13 +121,18 @@ pub enum SelectError { JsonModeNeedsExplicit, } +/// How many options a menu shows at once; a longer list scrolls (and +/// pages with the left and right arrows). Fewer on a shorter terminal. +const MENU_ROWS: usize = 12; + /// Prompt the user to select one option from a list (arrow-key menu on /// stderr). Takes the same `common` flags as [`confirm`]. /// /// - `--json`: `Err(JsonModeNeedsExplicit)`. /// - Empty `options`: `Err(Cancelled)` — there is nothing to select, and /// `Ok(0)` would hand callers an out-of-bounds index. -/// - stdin not a terminal: the first option, with +/// - Nobody at a terminal on stdin ([`super::attended`]: a pipe, or an +/// AI coding agent's terminal): the first option, with /// [`NON_INTERACTIVE_SELECT_FIRST`] unless `--silent` or the process is /// quiet ([`super::quiet`]). /// - Interactive: Esc/q/Ctrl-C cancel; the cursor is always restored. @@ -134,6 +140,17 @@ pub fn select_one( prompt: &str, options: &[String], common: &GlobalArgs, +) -> Result { + select_from(prompt, options, 0, common) +} + +/// [`select_one`] with the menu opened on option `start`: a menu shown +/// again after a pick comes back where the user left it. +pub fn select_from( + prompt: &str, + options: &[String], + start: usize, + common: &GlobalArgs, ) -> Result { if common.json { return Err(SelectError::JsonModeNeedsExplicit); @@ -141,10 +158,13 @@ pub fn select_one( if options.is_empty() { return Err(SelectError::Cancelled); } - if !io::stdin().is_terminal() { + // An arrow-key menu needs a person at the keys: an agent's terminal + // takes the first option, as a pipe does. + if !super::attended(super::Stream::Stdin) { if !common.silent && !super::quiet() { eprintln!("{NON_INTERACTIVE_SELECT_FIRST}"); } + super::note_agent_terminal(common); return Ok(0); } let (prompt, options) = fit_menu(prompt, options, super::stderr_width()); @@ -152,7 +172,8 @@ pub fn select_one( let picked = dialoguer::Select::with_theme(&dialoguer::theme::ColorfulTheme::default()) .with_prompt(prompt) .items(&options) - .default(0) + .default(start.min(options.len() - 1)) + .max_length(MENU_ROWS) .interact_opt(); match picked { Ok(Some(idx)) => Ok(idx), @@ -171,11 +192,38 @@ fn fit_menu(prompt: &str, options: &[String], width: usize) -> (String, Vec String { + const ELLIPSIS: &str = "..."; + let flat: String = option + .chars() + .map(|c| { + if c.is_whitespace() || c.is_control() { + ' ' + } else { + c + } + }) + .collect(); + let flat = flat.trim_end(); + if flat.chars().count() <= max { + return flat.to_string(); + } + let kept: String = flat + .chars() + .take(max.saturating_sub(ELLIPSIS.len())) + .collect(); + format!("{}{ELLIPSIS}", kept.trim_end()) +} + /// dialoguer hides the cursor while its menu is up. Its own error paths /// don't show it again, and Ctrl-C (which console turns into a real /// SIGINT) kills the process mid-menu. This guard shows the cursor on diff --git a/crates/socket-patch-cli/src/ui/status.rs b/crates/socket-patch-cli/src/ui/status.rs index f8caca884..11d86c5c4 100644 --- a/crates/socket-patch-cli/src/ui/status.rs +++ b/crates/socket-patch-cli/src/ui/status.rs @@ -1,24 +1,43 @@ -//! A single self-rewriting status line ("Scanning packages...", -//! "Querying API... (batch 3/7)"). +//! A single self-rewriting status line ("Scanning packages", +//! "Reading patches [####----] 8/24"). //! -//! Deterministic by construction: no timer, no background thread, and -//! every byte is written synchronously by a method call, so a `Vec` -//! sink captures exactly what a terminal would receive. +//! Every byte a method writes is written synchronously by that call, so a +//! `Vec` sink captures exactly what a terminal would receive. The one +//! thing that moves by itself is the activity mark of a command's stderr +//! line: on a live terminal a ticker thread turns it, so a long step reads +//! as work whether the command is waiting on the network or busy on the +//! CPU. The ticker and the line's own methods write under one lock, and +//! the ticker only ever redraws the line the last method call left, so it +//! cannot interleave with them or outlive a cleared line. use std::fmt::Display; -use std::io::{self, IsTerminal, Write}; +use std::io::{self, Write}; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; /// Return to column 0 and erase the whole line. const CLEAR: &str = "\r\x1b[2K"; +/// Width of the bar in a [`StatusLine::progress`] line. +const PROGRESS_CELLS: usize = 20; + +/// The activity mark's frames where glyphs are shown, and elsewhere. Each +/// is one column wide. +const TURNS: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; +const TURNS_ASCII: [&str; 4] = ["|", "/", "-", "\\"]; + +/// How often the ticker turns the mark. +const TURN_EVERY: Duration = Duration::from_millis(80); + /// A transient progress line on a terminal, or nothing at all elsewhere. /// /// - **live** (stderr is a terminal that understands escape sequences, /// `TERM` is not `dumb`, not `--json`/`--silent`, not `SOCKET_DEBUG`): /// [`set`](Self::set) redraws the line in place, always clearing first, /// so a shorter message never leaves the tail of a longer one behind. -/// Messages are cut to `width - 1` characters: a line that wraps can't -/// be rewritten by `\r`. +/// Messages are cut to fit: a line that wraps can't be rewritten by +/// `\r`. /// - **not live**: `set` is a no-op and no `\r` or escape sequence is /// ever written. [`finish_with`](Self::finish_with) still writes its /// plain final line when `report` is on, so logs and pipes keep the @@ -27,30 +46,146 @@ const CLEAR: &str = "\r\x1b[2K"; /// Anything else printed while a line is showing must go through /// [`println`](Self::println), which clears the line, prints, and redraws. /// Dropping the value clears a still-visible line. +/// +/// A command's line ([`stderr`](Self::stderr)) opens with an activity +/// mark that keeps turning for as long as the line shows. pub(crate) struct StatusLine { out: W, live: bool, report: bool, width: usize, - current: Option, + /// What the terminal's line holds, shared with the ticker. + shown: Arc>, + /// Turns the mark of a live stderr line; stopped on drop. + ticker: Option, +} + +/// The state both writers of a line draw from. +struct Shown { + /// The visible status, without its mark; `None` once cleared. + line: Option, + /// The line opens with the activity mark. + activity: bool, + /// Which frame of the mark shows. + turn: usize, + /// How a progress bar and the mark are drawn. + style: super::Style, +} + +/// The activity mark at `turn`, painted: the same mark wherever a wait +/// is shown (the status line, the full-screen browser). +pub(crate) fn activity_mark(turn: usize, style: super::Style) -> String { + let frame = if style.glyphs { + TURNS[turn % TURNS.len()] + } else { + TURNS_ASCII[turn % TURNS_ASCII.len()] + }; + super::paint(frame, "36", style.color) +} + +impl Shown { + /// The activity mark and its space, or nothing on a line without one. + fn mark(&self) -> String { + if !self.activity { + return String::new(); + } + format!("{} ", activity_mark(self.turn, self.style)) + } + + /// The bytes that put the current line on the terminal's line, in one + /// write; `None` when nothing shows. + fn frame(&self) -> Option { + self.line + .as_ref() + .map(|line| format!("{CLEAR}{}{line}", self.mark())) + } +} + +/// A lock no panic elsewhere can take away: the state is a line of text. +fn locked(shown: &Mutex) -> MutexGuard<'_, Shown> { + shown + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// The thread that turns a live stderr line's mark. It holds the line's +/// lock for each redraw and draws only what a method call left showing. +struct Ticker { + /// Dropped to wake the thread and end it. + stop: Option>, + thread: Option>, +} + +impl Ticker { + /// Turn the mark of `shown`, writing each redraw with `write`. `None` + /// if the thread cannot start: the mark then stands still, which costs + /// nothing but the motion. + fn start( + shown: Arc>, + mut write: impl FnMut(&[u8]) + Send + 'static, + ) -> Option { + let (stop, stopped) = mpsc::channel::<()>(); + let thread = std::thread::Builder::new() + .name("status-line".to_string()) + .spawn(move || { + // A timeout is a turn; a dropped sender is the end. + while let Err(RecvTimeoutError::Timeout) = stopped.recv_timeout(TURN_EVERY) { + let mut shown = locked(&shown); + if shown.line.is_none() { + continue; + } + shown.turn = shown.turn.wrapping_add(1); + if let Some(frame) = shown.frame() { + write(frame.as_bytes()); + } + } + }) + .ok()?; + Some(Ticker { + stop: Some(stop), + thread: Some(thread), + }) + } +} + +impl Drop for Ticker { + fn drop(&mut self) { + drop(self.stop.take()); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } } impl StatusLine { /// The status line for a command's stderr. It reports (writes /// [`finish_with`](Self::finish_with) lines) unless `json` or /// `silent`, and is live only when it reports on a terminal that - /// understands escape sequences. + /// understands escape sequences and has a person at it + /// ([`super::attended`]: an agent's terminal gets no line, as a pipe + /// gets none). A live line opens with the activity mark, and a ticker + /// keeps it turning. /// /// Under `SOCKET_DEBUG` the line is never live: core's debug logging /// writes straight to stderr and would land on the end of the status. pub(crate) fn stderr(json: bool, silent: bool) -> Self { let human = !json && !silent; let live = human - && io::stderr().is_terminal() + && super::attended(super::Stream::Stderr) && super::vt().1 && !std::env::var("TERM").is_ok_and(|t| t == "dumb") && !socket_patch_core::utils::env_compat::is_debug_enabled(); - StatusLine::new(io::stderr(), live, human, super::stderr_width()) + let mut line = StatusLine::new(io::stderr(), live, human, super::stderr_width()) + .with_style(super::Style::stderr()) + .with_activity(); + if live { + line.ticker = Ticker::start(Arc::clone(&line.shown), |frame| { + let mut err = io::stderr().lock(); + let _ = err.write_all(frame); + let _ = err.flush(); + }); + } + line } } @@ -63,24 +198,101 @@ impl StatusLine { live, report, width, - current: None, + shown: Arc::new(Mutex::new(Shown { + line: None, + activity: false, + turn: 0, + style: super::Style::PLAIN, + })), + ticker: None, } } - /// Show `msg` as the current status (replacing any previous one). + /// Draw progress bars and the mark in `style` (plain unless told). + pub fn with_style(self, style: super::Style) -> Self { + locked(&self.shown).style = style; + self + } + + /// Open the line with the activity mark. + pub fn with_activity(self) -> Self { + locked(&self.shown).activity = true; + self + } + + /// Show `msg` as the current status (replacing any previous one). On + /// a line with the activity mark a trailing `...` is dropped: the + /// turning mark already says the work is going on. pub fn set(&mut self, msg: impl Display) { if !self.live { return; } - let msg: String = msg.to_string(); + let msg = msg.to_string(); + let msg = if locked(&self.shown).activity { + msg.trim_end().trim_end_matches("...").trim_end() + } else { + msg.as_str() + }; let fitted: String = msg .chars() .filter(|c| !c.is_control()) - .take(self.width.saturating_sub(1).max(1)) + .take(self.room()) .collect(); - let _ = write!(self.out, "{CLEAR}{fitted}"); + self.draw(fitted); + } + + /// Characters a status may hold: one short of the width, since a line + /// that wraps can't be rewritten by `\r`, less the activity mark and + /// its space. + fn room(&self) -> usize { + let mark = if locked(&self.shown).activity { 2 } else { 0 }; + self.width.saturating_sub(1 + mark).max(1) + } + + /// Redraw the line as `line`, which already fits. + fn draw(&mut self, line: String) { + let mut shown = locked(&self.shown); + shown.line = Some(line); + if let Some(frame) = shown.frame() { + let _ = self.out.write_all(frame.as_bytes()); + } let _ = self.out.flush(); - self.current = Some(fitted); + } + + /// Show counted work as the current status: `label`, a bar and + /// `done/total`, e.g. `Reading patches [####--------] 8/24`. A `total` + /// of one has nothing to count, so it shows `label` alone (`label...` + /// on a line without the activity mark), and a terminal too narrow for + /// the bar shows the count without it. + pub fn progress(&mut self, label: impl Display, done: usize, total: usize) { + if !self.live { + return; + } + let (activity, style) = { + let shown = locked(&self.shown); + (shown.activity, shown.style) + }; + if total <= 1 { + // The turning mark says "working"; without one the dots do. + return if activity { + self.set(label) + } else { + self.set(format!("{label}...")) + }; + } + let label: String = label + .to_string() + .chars() + .filter(|c| !c.is_control()) + .collect(); + let count = format!("{done}/{total}"); + let with_bar = + label.chars().count() + 1 + style.bar_width(PROGRESS_CELLS) + 1 + count.chars().count(); + if with_bar > self.room() { + return self.set(format!("{label} {count}")); + } + let bar = style.bar(done, total, PROGRESS_CELLS); + self.draw(format!("{label} {bar} {count}")); } /// Print a permanent line (a warning or error) without garbling the @@ -98,10 +310,13 @@ impl StatusLine { .chars() .filter(|&c| c == '\n' || c == '\t' || !c.is_control()) .collect(); - self.clear(); + let shown = locked(&self.shown); + if self.live && shown.line.is_some() { + let _ = write!(self.out, "{CLEAR}"); + } let _ = writeln!(self.out, "{line}"); - if let Some(cur) = &self.current { - let _ = write!(self.out, "{CLEAR}{cur}"); + if let Some(frame) = shown.frame() { + let _ = self.out.write_all(frame.as_bytes()); } let _ = self.out.flush(); } @@ -109,8 +324,11 @@ impl StatusLine { /// Replace the status with a permanent result line (written when /// `report` is on, live or not). pub fn finish_with(&mut self, line: impl Display) { - self.clear(); - self.current = None; + let mut shown = locked(&self.shown); + if self.live && shown.line.is_some() { + let _ = write!(self.out, "{CLEAR}"); + } + shown.line = None; if self.report { let _ = writeln!(self.out, "{line}"); } @@ -119,16 +337,12 @@ impl StatusLine { /// Erase the status, leaving nothing behind. pub fn finish(&mut self) { - self.clear(); - self.current = None; - let _ = self.out.flush(); - } - - /// Erase the visible line (keeps `current` for a redraw). - fn clear(&mut self) { - if self.live && self.current.is_some() { + let mut shown = locked(&self.shown); + if self.live && shown.line.is_some() { let _ = write!(self.out, "{CLEAR}"); } + shown.line = None; + let _ = self.out.flush(); } /// The sink, for tests. @@ -314,6 +528,199 @@ mod tests { assert_eq!(bytes(&s), "\r\x1b[2Ka"); } + #[test] + fn progress_draws_a_bar_and_a_count() { + let mut s = live(); + s.progress("Reading patches", 5, 20); + assert_eq!( + render(bytes(&s).as_bytes()), + vec!["Reading patches [#####---------------] 5/20"] + ); + s.progress("Reading patches", 20, 20); + assert_eq!( + render(bytes(&s).as_bytes()), + vec!["Reading patches [####################] 20/20"] + ); + // One step has nothing to count. + s.progress("Checking 3 packages for patches", 0, 1); + assert_eq!( + render(bytes(&s).as_bytes()), + vec!["Checking 3 packages for patches..."] + ); + // A terminal too narrow for the bar keeps the count; it never + // wraps. + let mut s = StatusLine::new(Vec::new(), true, true, 24); + s.progress("Reading patches", 5, 20); + assert_eq!(render(bytes(&s).as_bytes()), vec!["Reading patches 5/20"]); + let mut s = StatusLine::new(Vec::new(), true, true, 12); + s.progress("Reading patches", 5, 20); + assert_eq!(render(bytes(&s).as_bytes()), vec!["Reading pat"]); + // On a terminal that shows them, the bar is drawn in glyphs, and a + // line printed over it redraws it whole. + let fancy = crate::ui::Style { + color: true, + glyphs: true, + }; + let mut s = StatusLine::new(Vec::new(), true, true, 80).with_style(fancy); + s.progress("Reading patches", 5, 20); + s.println("Warning: w"); + assert_eq!( + render(bytes(&s).as_bytes()), + vec![ + "Warning: w".to_string(), + format!("Reading patches {}{} 5/20", "━".repeat(5), "─".repeat(15)), + ] + ); + // Not live: nothing at all. + let mut s = StatusLine::new(Vec::new(), false, true, 80); + s.progress("Reading patches", 5, 20); + assert!(s.into_inner().is_empty()); + } + + fn working() -> StatusLine> { + StatusLine::new(Vec::new(), true, true, 80).with_activity() + } + + #[test] + fn an_activity_line_opens_with_the_mark_and_keeps_its_room() { + let mut s = working(); + s.set("Scanning packages"); + assert_eq!(bytes(&s), "\r\x1b[2K| Scanning packages"); + s.println("Warning: w"); + assert_eq!( + render(bytes(&s).as_bytes()), + vec!["Warning: w", "| Scanning packages"] + ); + s.finish_with("Found 2 packages"); + assert_eq!( + render(bytes(&s).as_bytes()), + vec!["Warning: w", "Found 2 packages"] + ); + // The mark says the work is going on, so a message's own dots go. + let mut s = working(); + s.set("Fetching patch 5435d265..."); + assert_eq!( + render(bytes(&s).as_bytes()), + vec!["| Fetching patch 5435d265"] + ); + // The mark and its space come out of the line's room: it never + // wraps. + let mut s = StatusLine::new(Vec::new(), true, true, 10).with_activity(); + s.set("Scanning packages"); + assert_eq!(render(bytes(&s).as_bytes()), vec!["| Scannin"]); + // Glyph terminals get the dots. + let fancy = crate::ui::Style { + color: false, + glyphs: true, + }; + let mut s = working().with_style(fancy); + s.set("Scanning packages"); + assert_eq!(render(bytes(&s).as_bytes()), vec!["⠋ Scanning packages"]); + } + + /// What a ticker drew, and the sink it draws into. + fn ticking(s: &mut StatusLine>) -> Arc>> { + let drawn = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&drawn); + s.ticker = Ticker::start(Arc::clone(&s.shown), move |frame| { + sink.lock().unwrap().extend_from_slice(frame) + }); + assert!(s.ticker.is_some()); + drawn + } + + fn frames(drawn: &Mutex>) -> Vec { + String::from_utf8(drawn.lock().unwrap().clone()) + .unwrap() + .split(CLEAR) + .filter(|f| !f.is_empty()) + .map(str::to_string) + .collect() + } + + /// Wait (up to a few seconds: the suite may be busy) for `enough`. + fn wait_for(enough: impl Fn() -> bool) { + for _ in 0..500 { + if enough() { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + panic!("the ticker never drew"); + } + + /// The mark keeps turning while a line shows, whatever the command is + /// doing: nothing here awaits or calls the line between the turns. + #[test] + fn the_ticker_turns_the_mark_of_a_showing_line() { + let mut s = working(); + let drawn = ticking(&mut s); + s.set("Scanning packages"); + wait_for(|| frames(&drawn).len() >= 3); + let seen = frames(&drawn); + // Every redraw is the whole line, cleared first, and the mark + // walks its frames in order. + assert!( + seen.iter().all(|f| f.ends_with(" Scanning packages")), + "{seen:?}" + ); + assert_eq!( + seen[..3], + [ + "/ Scanning packages", + "- Scanning packages", + "\\ Scanning packages" + ] + ); + assert!(!String::from_utf8(drawn.lock().unwrap().clone()) + .unwrap() + .contains('\n')); + // A new status opens on the frame the mark has reached: it does + // not jump back. + let before = frames(&drawn).len(); + s.set("Reading lockfiles"); + wait_for(|| frames(&drawn).len() > before); + assert!( + frames(&drawn) + .last() + .unwrap() + .ends_with(" Reading lockfiles"), + "{:?}", + frames(&drawn) + ); + } + + /// The ticker draws only a line a method call left showing: nothing + /// before the first status, nothing after it is cleared, so a result + /// printed after `finish` can never be overwritten. + #[test] + fn the_ticker_draws_nothing_without_a_showing_line() { + let mut s = working(); + let drawn = ticking(&mut s); + std::thread::sleep(TURN_EVERY * 3); + assert!(drawn.lock().unwrap().is_empty()); + s.set("Scanning packages"); + wait_for(|| !frames(&drawn).is_empty()); + s.finish_with("Found 2 packages"); + let after = drawn.lock().unwrap().len(); + std::thread::sleep(TURN_EVERY * 3); + assert_eq!(drawn.lock().unwrap().len(), after); + // Dropping the line stops the thread. + drop(s); + assert_eq!(Arc::strong_count(&drawn), 1); + } + + /// Off a terminal a command's line has no ticker at all (the test + /// process's stderr is not a terminal, or it is and the line is + /// cleared at once). + #[test] + fn a_line_that_is_not_live_starts_no_ticker() { + let s = StatusLine::stderr(true, false); + assert!(s.ticker.is_none()); + let s = StatusLine::stderr(false, true); + assert!(s.ticker.is_none()); + } + #[test] fn control_chars_in_a_message_cannot_break_the_line() { let mut s = live(); diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index 9453fa173..eb67e05ec 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -10,6 +10,80 @@ pub fn plural(n: usize, one: &str, many: &str) -> String { const ELLIPSIS: &str = "..."; +/// `text` as it may be printed: without its control characters. For +/// text that came from a service or a project's files, which is shown +/// for reading and must never move the cursor, retitle the terminal or +/// write to its clipboard. One-line fields only: a tab or a newline is a +/// control character too. +pub fn printable(text: &str) -> String { + text.chars().filter(|c| !c.is_control()).collect() +} + +/// The worst severity (upper-cased; empty when none is named) and the +/// ids to show for a set of advisories, each given as its id, its +/// severity and its CVEs: an advisory is named by its CVEs, or by its own +/// id when it has none. The ids are sorted, each once. +pub fn worst_and_ids<'a>( + advisories: impl Iterator, +) -> (String, Vec) { + use socket_patch_core::api::ranking::severity_order; + let mut worst: Option<&str> = None; + let mut ids = Vec::new(); + for (id, severity, cves) in advisories { + let severity = severity.trim(); + if !severity.is_empty() + && worst.is_none_or(|w| severity_order(Some(severity)) < severity_order(Some(w))) + { + worst = Some(severity); + } + if cves.is_empty() { + ids.push(id.to_string()); + } else { + ids.extend(cves.iter().cloned()); + } + } + ids.sort(); + ids.dedup(); + (worst.map(str::to_uppercase).unwrap_or_default(), ids) +} + +/// How a listing names the packages `purls` name: `name@version` when +/// they are all of one ecosystem (the lines around them say which), the +/// purl otherwise, where a bare name could be either's. The purl is in +/// its display spelling (`canonical_purl`: no qualifiers, percent-decoded). +/// One rule for `scan`, `list` and `vex`, so a package reads the same in +/// each. +pub fn package_names(purls: &[&str]) -> Vec { + use socket_patch_core::utils::purl::{canonical_purl, purl_parts}; + let parts: Vec<_> = purls.iter().map(|purl| purl_parts(purl)).collect(); + let first = parts.first().and_then(|p| p.as_ref().map(|(ty, _, _)| ty)); + let one_type = first.is_some() + && parts + .iter() + .all(|p| p.as_ref().map(|(ty, _, _)| ty) == first); + purls + .iter() + .zip(&parts) + .map(|(purl, parts)| match parts { + Some((_, name, version)) if one_type => format!("{name}@{version}"), + _ => canonical_purl(purl), + }) + .collect() +} + +/// `items` for a sentence, the first `shown` of them named: `a, b, c and +/// 5 more`. +pub fn folded(items: &[String], shown: usize) -> String { + if items.len() <= shown { + return items.join(", "); + } + format!( + "{} and {} more", + items[..shown].join(", "), + items.len() - shown + ) +} + /// How far back from the cut point a word boundary is still preferred /// over a hard mid-word cut. const WORD_BOUNDARY_WINDOW: usize = 15; @@ -274,6 +348,73 @@ pub(crate) fn shell_word(word: &str) -> String { mod tests { use super::*; + #[test] + fn packages_of_one_ecosystem_are_named_without_it() { + assert_eq!( + package_names(&["pkg:npm/%40scope/a@1.0.0", "pkg:npm/b@2.0.0?x=1"]), + ["@scope/a@1.0.0", "b@2.0.0"] + ); + assert_eq!( + package_names(&["pkg:npm/%40scope/a@1.0.0", "pkg:pypi/b@2.0.0"]), + ["pkg:npm/@scope/a@1.0.0", "pkg:pypi/b@2.0.0"] + ); + assert_eq!(package_names(&["not a purl"]), ["not a purl"]); + assert!(package_names(&[]).is_empty()); + } + + /// One rule for the severity and the ids of a set of advisories, + /// wherever a patch is named in a line: the `list` row, `show`'s + /// title and the patch menu. + #[test] + fn worst_and_ids_names_advisories_by_cve_and_skips_blank_severities() { + let cves = |ids: &[&str]| ids.iter().map(|id| id.to_string()).collect::>(); + let (two, none, shared) = (cves(&["CVE-2", "CVE-1"]), cves(&[]), cves(&["CVE-1"])); + let advisories = [ + ("GHSA-b", "moderate", two.as_slice()), + ("GHSA-a", " High ", none.as_slice()), + ("GHSA-c", "", shared.as_slice()), + ]; + assert_eq!( + worst_and_ids(advisories.into_iter()), + ( + "HIGH".to_string(), + vec![ + "CVE-1".to_string(), + "CVE-2".to_string(), + "GHSA-a".to_string() + ] + ) + ); + // No severity named at all: none is shown, not an empty one. + assert_eq!( + worst_and_ids([("GHSA-c", " ", none.as_slice())].into_iter()), + (String::new(), vec!["GHSA-c".to_string()]) + ); + assert_eq!( + worst_and_ids(std::iter::empty()), + (String::new(), Vec::new()) + ); + } + + #[test] + fn printable_drops_every_control_character() { + assert_eq!(printable("lib/a.js"), "lib/a.js"); + assert_eq!( + printable("a\u{1b}]0;title\u{7}b\u{1b}[2Jc\r\n\td"), + "a]0;titleb[2Jcd" + ); + assert_eq!(printable("é 漢字 \u{9b}31m"), "é 漢字 31m"); + } + + #[test] + fn folded_names_the_first_few_and_counts_the_rest() { + let items: Vec = ["a", "b", "c", "d", "e"].map(String::from).to_vec(); + assert_eq!(folded(&items, 3), "a, b, c and 2 more"); + assert_eq!(folded(&items[..3], 3), "a, b, c"); + assert_eq!(folded(&items[..1], 3), "a"); + assert_eq!(folded(&[], 3), ""); + } + #[test] fn plural_counts() { assert_eq!(plural(0, "package", "packages"), "0 packages"); diff --git a/crates/socket-patch-cli/src/update_notifier.rs b/crates/socket-patch-cli/src/update_notifier.rs index 69fa90bd5..200bcdaef 100644 --- a/crates/socket-patch-cli/src/update_notifier.rs +++ b/crates/socket-patch-cli/src/update_notifier.rs @@ -17,7 +17,6 @@ //! - it can never delay a command beyond the grace budget; //! - state corruption/unwritability is silently absorbed. -use std::io::IsTerminal; use std::time::Duration; use socket_patch_core::update::{ @@ -68,7 +67,7 @@ impl SkipReason { SkipReason::Silent => "--silent", SkipReason::Json => "--json", SkipReason::Ci => "CI environment", - SkipReason::NotATty => "stderr is not a terminal", + SkipReason::NotATty => "stderr is not a terminal with a person at it", SkipReason::NoStateDir => "no resolvable state directory", } } @@ -121,7 +120,7 @@ impl GuardCtx { .is_empty(), // The notice prints on stderr; stdout may be legitimately piped // (`list | jq`) in a perfectly interactive session. - stderr_tty: std::io::stderr().is_terminal(), + stderr_tty: crate::ui::attended(crate::ui::Stream::Stderr), forced: env_truthy("SOCKET_UPDATE_NOTIFIER_FORCE"), state_dir_resolvable: core_update::state::state_dir().is_some(), } diff --git a/crates/socket-patch-cli/tests/cli/list_tty.rs b/crates/socket-patch-cli/tests/cli/list_tty.rs new file mode 100644 index 000000000..452c68fef --- /dev/null +++ b/crates/socket-patch-cli/tests/cli/list_tty.rs @@ -0,0 +1,901 @@ +//! `list` on a terminal: the full-screen table of the project's patches +//! (`src/ui/browser.rs`), driven in a PTY that changes size while the +//! table is up. +//! +//! The table draws on the alternate screen, redraws to fit whenever the +//! terminal's size changes, fills its rows in from the patch service as +//! the answers arrive, and opens a patch as a page. PTY support: macOS + +//! Linux. Skipped on Windows, where `list` uses the inline menu. + +#![cfg(unix)] + +use std::io::Write; +use std::path::Path; +use std::time::{Duration, Instant}; + +use wiremock::matchers::{method, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use crate::common; +use crate::pty_io::PtyOutput; + +const ENTER_SCREEN: &str = "\x1b[?1049h"; +const LEAVE_SCREEN: &str = "\x1b[?1049l"; +const SHOW_CURSOR: &str = "\x1b[?25h"; +/// What every frame starts with: cursor home. +const HOME: &str = "\x1b[H"; +const ORG_SLUG: &str = "test-org"; + +fn uuid(i: usize) -> String { + format!("{i:08x}-1111-4111-8111-111111111111") +} + +/// A manifest of `n` agent-mode patches, enough to scroll. +fn write_manifest(root: &Path, n: usize) { + let patches: serde_json::Map = (0..n) + .map(|i| { + ( + format!("pkg:npm/list-tty-package-{i:02}@1.0.{i}"), + serde_json::json!({ + "uuid": uuid(i), + "exportedAt": "2026-01-01T00:00:00Z", + "files": { "package/index.js": { + "beforeHash": "b".repeat(64), + "afterHash": "a".repeat(64), + }}, + "vulnerabilities": { format!("GHSA-aaaa-bbbb-{i:04}"): { + "cves": [format!("CVE-2026-{:05}", 1000 + i)], + "summary": "A summary", + "severity": if i % 3 == 0 { "critical" } else { "high" }, + "description": "A description", + }}, + "description": "A patch", + "license": "MIT", + "tier": "free", + }), + ) + }) + .collect(); + let socket = root.join(".socket"); + std::fs::create_dir_all(&socket).unwrap(); + std::fs::write( + socket.join("manifest.json"), + serde_json::to_string_pretty(&serde_json::json!({ "patches": patches })).unwrap(), + ) + .unwrap(); +} + +/// A command running on a PTY whose size the test controls. +struct Terminal { + master: Box, + writer: Box, + child: Box, + output: PtyOutput, +} + +fn size(cols: u16, rows: u16) -> portable_pty::PtySize { + portable_pty::PtySize { + rows, + cols, + pixel_width: 0, + pixel_height: 0, + } +} + +impl Terminal { + fn list(cwd: &Path, args: &[&str], cols: u16, rows: u16) -> Terminal { + Terminal::run("list", cwd, args, cols, rows) + } + + fn run(command: &str, cwd: &Path, args: &[&str], cols: u16, rows: u16) -> Terminal { + Terminal::run_with(command, cwd, args, &[], cols, rows) + } + + /// [`Self::run`] with `env` added to the child's environment. + fn run_with( + command: &str, + cwd: &Path, + args: &[&str], + env: &[(&str, &str)], + cols: u16, + rows: u16, + ) -> Terminal { + let pair = portable_pty::native_pty_system() + .openpty(size(cols, rows)) + .expect("openpty"); + let mut cmd = common::hermetic::pty_binary_command(); + cmd.arg(command); + for arg in args { + cmd.arg(arg); + } + cmd.cwd(cwd); + cmd.env("TERM", "xterm-256color"); + // No color, so a frame's lines are its text; glyphs go with color. + cmd.env("NO_COLOR", "1"); + for (name, value) in env { + cmd.env(name, value); + } + let child = pair.slave.spawn_command(cmd).expect("spawn in PTY"); + drop(pair.slave); + let output = PtyOutput::spawn(pair.master.try_clone_reader().expect("clone reader")); + let writer = pair.master.take_writer().expect("take writer"); + Terminal { + master: pair.master, + writer, + child, + output, + } + } + + fn press(&mut self, keys: &[u8]) { + self.writer.write_all(keys).unwrap(); + self.writer.flush().unwrap(); + } + + fn resize(&self, cols: u16, rows: u16) { + self.master.resize(size(cols, rows)).expect("resize"); + } + + /// Wait until `needle` has been drawn `n` times. + fn wait_for(&self, needle: &str, n: usize) { + self.output + .wait_for_count(needle, n, Duration::from_secs(20)); + } + + /// Wait for the child to exit; its code and everything it printed. + fn finish(mut self) -> (i32, String) { + let deadline = Instant::now() + Duration::from_secs(20); + let status = loop { + match self.child.try_wait().expect("try_wait") { + Some(status) => break status, + None if Instant::now() > deadline => { + let _ = self.child.kill(); + break self.child.wait().expect("wait"); + } + None => std::thread::sleep(Duration::from_millis(20)), + } + }; + drop(self.writer); + drop(self.master); + let output = String::from_utf8_lossy(&self.output.finish()).into_owned(); + (status.exit_code() as i32, output) + } +} + +/// The frames drawn in `output`: each one's lines, escape sequences +/// removed. +fn frames(output: &str) -> Vec> { + let escape = regex::Regex::new(r"\x1b\[[0-9;?]*[A-Za-z]").unwrap(); + output + .split(HOME) + .skip(1) + .map(|frame| { + // A frame ends where the browser leaves the screen. + let frame = frame.split(LEAVE_SCREEN).next().unwrap_or(frame); + frame + .split('\n') + // The browser ends its lines with a return and a newline, + // and the terminal adds a return of its own to the newline. + .map(|line| { + escape + .replace_all(line.trim_end_matches('\r'), "") + .into_owned() + }) + .collect() + }) + .collect() +} + +/// The last frame that shows `position` on its key line. +fn frame_at<'a>(frames: &'a [Vec], position: &str) -> &'a Vec { + frames + .iter() + .rev() + .find(|frame| frame.last().is_some_and(|line| line.ends_with(position))) + .unwrap_or_else(|| panic!("no frame at {position}: {frames:#?}")) +} + +/// What the run printed once it left the browser. +fn after_leaving(output: &str) -> String { + let escape = regex::Regex::new(r"\x1b\[[0-9;?]*[A-Za-z]").unwrap(); + let tail = output.rsplit(LEAVE_SCREEN).next().unwrap(); + escape.replace_all(tail, "").replace('\r', "") +} + +/// The reported need: the table must handle the terminal being resized. +/// Shrunk, it redraws within the new size with the selected row still in +/// view and nothing wrapped (the columns that give way are left out); +/// grown, it fills the new size again. Leaving it restores the screen and +/// the cursor, and prints the rows as the listing that stays. +#[test] +fn list_redraws_to_fit_when_the_terminal_is_resized() { + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 30); + // `--offline`: the rows are what the project records. + let mut term = Terminal::list(tmp.path(), &["--offline"], 100, 12); + + term.wait_for(ENTER_SCREEN, 1); + term.wait_for("1/30", 1); + term.press(b"\x1b[B"); + term.wait_for("2/30", 1); + term.press(b"j"); + term.wait_for("3/30", 1); + + // Narrower and shorter than what is drawn. + term.resize(40, 6); + term.wait_for("3/30", 2); + // Move in the small terminal, then grow it past the first size. + term.press(b"\x1b[B"); + term.wait_for("4/30", 1); + term.resize(120, 40); + term.wait_for("4/30", 2); + // The end of the table, then out. + term.press(b"G"); + term.wait_for("30/30", 1); + term.press(b"q"); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + + // Nothing but the status line went out before the browser opened. + let before = output.split(ENTER_SCREEN).next().unwrap(); + assert!(!before.contains("Found 30 patches"), "{before}"); + assert!(!before.contains("Package: pkg:npm/"), "{before}"); + + let frames = frames(&output); + // At 100x12: the title, the column titles, nine rows, the key line. + let first = frame_at(&frames, "1/30"); + assert_eq!(first.len(), 12, "{first:#?}"); + assert_eq!(first[0], "30 patches in this project"); + assert_eq!( + first[1], + " SEVERITY PACKAGE FIXES MODE" + ); + assert_eq!( + first[2], + "> CRITICAL list-tty-package-00@1.0.0 CVE-2026-01000 agent" + ); + assert!( + first[11].starts_with("Up/Down move PgUp/PgDn page Enter open q quit"), + "{first:#?}" + ); + + // At 40x6 the frame is drawn again to fit: six lines, none reaching + // the last column, the columns that give way left out, and the + // selected row among the three in view. + let small = frames + .iter() + .rev() + .find(|frame| frame.len() == 6 && frame.last().is_some_and(|l| l.ends_with("3/30"))) + .unwrap_or_else(|| panic!("no frame for the 40x6 terminal: {frames:#?}")); + for line in small { + assert!(line.chars().count() < 40, "{line:?} wraps at 40 columns"); + } + assert_eq!(small[1], " SEVERITY PACKAGE", "{small:#?}"); + assert_eq!( + small.iter().filter(|line| line.starts_with("> ")).count(), + 1, + "{small:#?}" + ); + assert!( + small + .iter() + .any(|line| line == "> HIGH list-tty-package-02@1.0.2"), + "{small:#?}" + ); + assert_eq!(small[5], "3/30", "the keys give way, the position stays"); + + // At 120x40 every row is on screen again, under the titles. + let large = frames + .iter() + .rev() + .find(|frame| frame.len() == 40 && frame.last().is_some_and(|l| l.ends_with("4/30"))) + .unwrap_or_else(|| panic!("no frame for the 120x40 terminal: {frames:#?}")); + assert!(large[2].contains("list-tty-package-00"), "{large:#?}"); + assert!(large[31].contains("list-tty-package-29"), "{large:#?}"); + assert!(large[5].starts_with("> "), "{large:#?}"); + + // `G` went to the last row. + let last = frame_at(&frames, "30/30"); + assert!( + last.iter() + .any(|line| line.starts_with("> ") && line.contains("list-tty-package-29")), + "{last:#?}" + ); + + // Out: the main screen and the cursor are back, and the rows are the + // listing that stays on the terminal. + assert!(output.contains(LEAVE_SCREEN), "{output}"); + assert!( + output.rfind(SHOW_CURSOR) > output.rfind("\x1b[?25l"), + "the cursor is shown again" + ); + let after = after_leaving(&output); + assert!( + after.starts_with( + "Found 30 patches:\n SEVERITY PACKAGE FIXES MODE\n \ + CRITICAL list-tty-package-00@1.0.0 CVE-2026-01000 agent\n" + ), + "{after:?}" + ); + assert_eq!(after.lines().count(), 32, "{after:?}"); +} + +/// Enter opens the selected patch as a page that takes the screen, and +/// `q` comes back to the table on the same row. With `--offline` the page +/// is what the project records about the patch. +#[test] +fn list_opens_a_patch_as_a_page_and_comes_back() { + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 3); + let mut term = Terminal::list(tmp.path(), &["--offline"], 100, 16); + term.wait_for("1/3", 1); + term.press(b"\x1b[B"); + term.wait_for("2/3", 1); + term.press(b"\r"); + term.wait_for("Package: pkg:npm/list-tty-package-01@1.0.1", 1); + // Back to the table, where it was left; then out. + term.press(b"q"); + term.wait_for("2/3", 2); + term.press(b"q"); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + + let frames = frames(&output); + let page = frames + .iter() + .find(|frame| frame[0] == "pkg:npm/list-tty-package-01@1.0.1") + .unwrap_or_else(|| panic!("no page: {frames:#?}")); + assert_eq!(page.len(), 16, "{page:#?}"); + assert_eq!(page[1], "Package: pkg:npm/list-tty-package-01@1.0.1"); + assert_eq!(page[2], format!(" UUID: {}", uuid(1))); + assert!( + page.iter() + .any(|line| line == " - GHSA-aaaa-bbbb-0001 (CVE-2026-01001)"), + "{page:#?}" + ); + assert!( + page[15].starts_with("Up/Down scroll PgUp/PgDn page q back"), + "{page:#?}" + ); + // The table came back on the row that was opened. + let back = frames.last().unwrap(); + assert_eq!(back[0], "3 patches in this project"); + assert!( + back[3].starts_with("> HIGH list-tty-package-01"), + "{back:#?}" + ); + // One screen throughout: the page did not leave it. + assert_eq!(output.matches(ENTER_SCREEN).count(), 1, "{output:?}"); + assert!(after_leaving(&output).starts_with("Found 3 patches:\n")); +} + +/// Keys that arrive together are each acted on, in order: a held arrow, +/// a paste and a slow link all deliver several presses in one read. Two +/// arrows and Enter written at once open the third row's page; read as +/// one key they would be a sequence the browser does not know, and +/// nothing would happen. Esc by itself is still the Esc key: it comes +/// back from the page, and then leaves the table. +#[test] +fn list_acts_on_every_key_that_arrives_at_once() { + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 3); + let mut term = Terminal::list(tmp.path(), &["--offline"], 100, 16); + term.wait_for("1/3", 1); + term.press(b"\x1b[B\x1b[B\r"); + term.wait_for("Package: pkg:npm/list-tty-package-02@1.0.2", 1); + term.press(b"\x1b"); + term.wait_for("> HIGH list-tty-package-02", 1); + term.press(b"\x1b"); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + + let frames = frames(&output); + assert!( + frames + .iter() + .any(|frame| frame[0] == "pkg:npm/list-tty-package-02@1.0.2"), + "no page: {frames:#?}" + ); + // The table came back on the row the keys reached. + let back = frames.last().unwrap(); + assert_eq!(back[0], "3 patches in this project"); + assert!( + back[4].starts_with("> HIGH list-tty-package-02"), + "{back:#?}" + ); + assert!(back[15].ends_with("3/3"), "{back:#?}"); + assert!(after_leaving(&output).starts_with("Found 3 patches:\n")); +} + +/// The table goes up with what the project records, and the patch +/// service's account of each patch fills its row in as it arrives: what +/// was measured about it, the size and cost of the change, and when it +/// was published. The listing left on the terminal has them too. +#[test] +fn list_fills_its_rows_in_from_the_patch_service() { + // The pty runs a sync child while wiremock needs a live async runtime, + // so the runtime is built manually and kept alive across the pty run. + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + let mock = rt.block_on(async { + let mock = MockServer::start().await; + Mock::given(method("GET")) + .and(path_regex(format!( + r"^/v0/orgs/{ORG_SLUG}/patches/view/[0-9a-f-]+$" + ))) + .respond_with(|request: &wiremock::Request| { + let uuid = request.url.path().rsplit('/').next().unwrap().to_string(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": uuid, + "purl": "pkg:npm/list-tty-package-00@1.0.0", + "publishedAt": "Sat, 14 Nov 2026 07:13:44 GMT", + "files": {}, + "vulnerabilities": {}, + "description": "A patch", + "license": "MIT", + "tier": "free", + "statistics": { + "diff": { "linesAdded": 26, "linesRemoved": 22, "filesChanged": 2 }, + "tests": { "after": { "count": 34, "total": 35 } }, + "pocs": { "blockedAfter": { "count": 2, "total": 2 } }, + "performance": { "hotWallChange": 0.008 }, + }, + })) + }) + .mount(&mock) + .await; + mock + }); + let uri = mock.uri(); + + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 2); + let mut term = Terminal::list( + tmp.path(), + &[ + "--api-url", + &uri, + "--api-token", + "fake-token", + "--org", + ORG_SLUG, + ], + 140, + 10, + ); + // Both rows filled in. + term.wait_for("34/35", 2); + term.press(b"q"); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + + let frames = frames(&output); + // The table was up before the patch service had answered. + let first = &frames[0]; + assert_eq!( + first[0].split(" ").next(), + Some("2 patches in this project") + ); + assert_eq!( + first[2], "> CRITICAL list-tty-package-00@1.0.0 CVE-2026-01000 agent", + "{first:#?}" + ); + let filled = frames.last().unwrap(); + assert_eq!( + filled[..4], + [ + "2 patches in this project", + " SEVERITY PACKAGE FIXES EXPLOITS TESTS CHANGE PERF \ + PUBLISHED MODE", + "> CRITICAL list-tty-package-00@1.0.0 CVE-2026-01000 2/2 34/35 +26 -22 +0.8% \ + 14 Nov 2026 agent", + " HIGH list-tty-package-01@1.0.1 CVE-2026-01001 2/2 34/35 +26 -22 +0.8% \ + 14 Nov 2026 agent", + ], + "{filled:#?}" + ); + let after = after_leaving(&output); + assert!( + after.contains( + " HIGH list-tty-package-01@1.0.1 CVE-2026-01001 2/2 34/35 +26 -22 \ + +0.8% 14 Nov 2026 agent\n" + ), + "{after:?}" + ); + // One request per patch, for the view without its file contents. + let requests = rt.block_on(mock.received_requests()).unwrap_or_default(); + assert_eq!(requests.len(), 2, "{requests:#?}"); + assert!( + requests + .iter() + .all(|r| r.url.query() == Some("include_blobs=false")), + "{requests:#?}" + ); +} + +/// A row of `list` and `show` open one and the same page: the patch is +/// read the same way and shown on the same screen, so Enter on a row and +/// `show ` draw the same lines, down to the key line. There is +/// no second way to read a patch on a terminal. +#[test] +fn a_list_row_opens_the_page_show_opens() { + use base64::Engine as _; + let b64 = |text: &str| base64::engine::general_purpose::STANDARD.encode(text); + let (before, after, added) = ( + b64("one\ntwo\nthree\n"), + b64("one\nTWO\nthree\n"), + b64("new\n"), + ); + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + let mock = rt.block_on(async { + let mock = MockServer::start().await; + Mock::given(method("GET")) + .and(path_regex(format!( + r"^/v0/orgs/{ORG_SLUG}/patches/view/[0-9a-f-]+$" + ))) + .respond_with(move |request: &wiremock::Request| { + let uuid = request.url.path().rsplit('/').next().unwrap().to_string(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": uuid, + "purl": "pkg:npm/list-tty-package-00@1.0.0", + "publishedAt": "Sat, 14 Nov 2026 07:13:44 GMT", + "description": "A patch", + "license": "MIT", + "tier": "free", + "files": { + "package/index.js": { + "beforeHash": "b".repeat(64), + "afterHash": "a".repeat(64), + "beforeBlobContent": before, + "blobContent": after, + }, + "package/new.js": { "afterHash": "c".repeat(64), "blobContent": added }, + }, + "vulnerabilities": { "GHSA-aaaa-bbbb-0000": { + "cves": ["CVE-2026-01000"], + "summary": "A summary", + "severity": "critical", + "description": "A description", + }}, + "statistics": { + "diff": { "linesAdded": 2, "linesRemoved": 1, "filesChanged": 2 }, + "tests": { "after": { "count": 34, "total": 35 } }, + "pocs": { "blockedAfter": { "count": 2, "total": 2 } }, + "performance": { "hotWallChange": 0.008 }, + }, + })) + }) + .mount(&mock) + .await; + mock + }); + let uri = mock.uri(); + let service = [ + "--api-url", + uri.as_str(), + "--api-token", + "fake-token", + "--org", + ORG_SLUG, + ]; + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 1); + const LAST_DIFF: &str = "+++ b/package/new.js"; + + // From the table: Enter on the row, then back and out. + let mut term = Terminal::list(tmp.path(), &service, 100, 40); + term.wait_for("1/1", 1); + term.press(b"\r"); + term.wait_for(LAST_DIFF, 1); + term.press(b"qq"); + let (code, from_list) = term.finish(); + assert_eq!(code, 0, "{from_list}"); + + // By its uuid: `show`. + let patch = uuid(0); + let mut args = vec![patch.as_str()]; + args.extend(service); + let mut term = Terminal::run("show", tmp.path(), &args, 100, 40); + term.wait_for(LAST_DIFF, 1); + term.press(b"q"); + let (code, from_show) = term.finish(); + assert_eq!(code, 0, "{from_show}"); + + let page = |output: &str| { + frames(output) + .into_iter() + .rev() + .find(|frame| frame.iter().any(|line| line == LAST_DIFF)) + .unwrap_or_else(|| panic!("no page: {output:?}")) + }; + let (opened, shown) = (page(&from_list), page(&from_show)); + assert_eq!(opened, shown); + // And it is the patch: its title, what it fixes, what was measured, + // each file's diff, the keys. + assert_eq!(shown.len(), 40, "{shown:#?}"); + assert_eq!( + shown[0], + "pkg:npm/list-tty-package-00@1.0.0 CRITICAL [FREE]" + ); + for line in [ + "Fixes:", + " CRITICAL CVE-2026-01000 A summary", + "Measured by Socket:", + "2 files changed: +2 -1", + "--- a/package/index.js", + "-two", + "+TWO", + "--- /dev/null", + "+new", + ] { + assert!(shown.iter().any(|l| l == line), "{line:?} in {shown:#?}"); + } + assert!( + shown[39].starts_with("Up/Down scroll PgUp/PgDn page n/p file q back"), + "{shown:#?}" + ); + // `show` leaves the summary on the terminal; `list` its rows. + assert!(after_leaving(&from_show).contains("Measured by Socket:")); + assert!(after_leaving(&from_list).starts_with("Found 1 patch:\n")); +} + +/// `show --yes` on a terminal opens nothing: the summary and every diff +/// print at once, as a pipe gets them, and the run ends by itself. There +/// is no menu of files and no pager to wait on. +#[test] +fn show_yes_prints_the_patch_at_once_and_opens_nothing() { + use base64::Engine as _; + let content = base64::engine::general_purpose::STANDARD.encode("new\n"); + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + let mock = rt.block_on(async { + let mock = MockServer::start().await; + Mock::given(method("GET")) + .and(path_regex(format!( + r"^/v0/orgs/{ORG_SLUG}/patches/view/[0-9a-f-]+$" + ))) + .respond_with(move |request: &wiremock::Request| { + let uuid = request.url.path().rsplit('/').next().unwrap().to_string(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": uuid, + "purl": "pkg:npm/list-tty-package-00@1.0.0", + "publishedAt": "Sat, 14 Nov 2026 07:13:44 GMT", + "description": "A patch", + "license": "MIT", + "tier": "free", + "files": { + "package/a.js": { "afterHash": "a".repeat(64), "blobContent": content }, + "package/b.js": { "afterHash": "c".repeat(64), "blobContent": content }, + }, + "vulnerabilities": {}, + })) + }) + .mount(&mock) + .await; + mock + }); + let uri = mock.uri(); + let patch = uuid(0); + let tmp = tempfile::tempdir().unwrap(); + let term = Terminal::run( + "show", + tmp.path(), + &[ + patch.as_str(), + "--yes", + "--api-url", + uri.as_str(), + "--api-token", + "fake-token", + "--org", + ORG_SLUG, + ], + 100, + 20, + ); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + assert!(!output.contains(ENTER_SCREEN), "{output:?}"); + for line in [ + "pkg:npm/list-tty-package-00@1.0.0 [FREE]", + "2 files changed: +2 -0", + "+++ b/package/a.js", + "+++ b/package/b.js", + ] { + assert!(output.contains(line), "{line:?} in {output:?}"); + } + assert!(!output.contains("Open a file"), "{output:?}"); +} + +/// An AI coding agent that runs `list` on a pseudo-terminal gets what a +/// pipe gets: the full entries, printed, and a run that ends by itself. +/// The full-screen table would wait for keys nobody presses, and every +/// redraw of it would land in the agent's context. The agent is known by +/// a variable it sets for the commands it runs. Someone working in a +/// terminal an agent started says so with `SOCKET_PLAIN=0` and gets the +/// table. +#[test] +fn list_on_an_agents_terminal_prints_and_opens_nothing() { + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 3); + for agent in [ + ("AI_AGENT", "some-agent_1-2-3_agent"), + ("CLAUDECODE", "1"), + ("CURSOR_AGENT", "1"), + ("CODEX_SANDBOX", "seatbelt"), + ("SOCKET_PLAIN", "1"), + ] { + let term = Terminal::run_with("list", tmp.path(), &["--offline"], &[agent], 100, 16); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{agent:?}: {output}"); + assert!(!output.contains('\x1b'), "{agent:?}: {output:?}"); + assert!( + output.contains("Found 3 patches:\r\n"), + "{agent:?}: {output:?}" + ); + assert!( + output.contains("Package: pkg:npm/list-tty-package-00@1.0.0\r\n"), + "{agent:?}: {output:?}" + ); + // One line says why there is no table, for a person who finds + // themselves here, and names the variable; asking for plain + // output oneself needs no explaining. + let note = format!( + "Note: {} is set, so this terminal gets the plain output of an AI coding agent's. \ + A person at it can set SOCKET_PLAIN=0 for the interactive output.\r\n", + agent.0 + ); + let expected = usize::from(agent.0 != "SOCKET_PLAIN"); + assert_eq!(output.matches("Note: ").count(), expected, "{output:?}"); + assert_eq!(output.matches(¬e).count(), expected, "{output:?}"); + } + + let mut term = Terminal::run_with( + "list", + tmp.path(), + &["--offline"], + &[ + ("AI_AGENT", "some-agent_1-2-3_agent"), + ("SOCKET_PLAIN", "0"), + ], + 100, + 16, + ); + term.wait_for("1/3", 1); + term.press(b"q"); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + assert!(output.contains(ENTER_SCREEN), "{output:?}"); +} + +/// What a project records as a patch's uuid comes from its own files, +/// which anyone can write. Only one that is a UUID goes into a request +/// to the patch service: a record whose "uuid" is a path is never sent +/// (with the user's token) to wherever it points, its row keeps what the +/// project records, and opening it shows that record under the reason. +#[test] +fn list_asks_the_patch_service_about_uuids_only() { + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + let mock = rt.block_on(async { + let mock = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(|request: &wiremock::Request| { + let uuid = request.url.path().rsplit('/').next().unwrap().to_string(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": uuid, + "purl": "pkg:npm/list-tty-package-00@1.0.0", + "publishedAt": "Sat, 14 Nov 2026 07:13:44 GMT", + "files": {}, + "vulnerabilities": {}, + "description": "A patch", + "license": "MIT", + "tier": "free", + "statistics": { "tests": { "after": { "count": 34, "total": 35 } } }, + })) + }) + .mount(&mock) + .await; + mock + }); + let uri = mock.uri(); + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 2); + // The second record's uuid points somewhere else on the API host. + let manifest = tmp.path().join(".socket/manifest.json"); + let hostile = "../../../../v0/hostile?x=1#y"; + let text = std::fs::read_to_string(&manifest).unwrap(); + assert!(text.contains(&uuid(1))); + std::fs::write(&manifest, text.replace(&uuid(1), hostile)).unwrap(); + + let mut term = Terminal::list( + tmp.path(), + &[ + "--api-url", + &uri, + "--api-token", + "fake-token", + "--org", + ORG_SLUG, + ], + 140, + 12, + ); + // The one real patch fills in; then the other row is opened. + term.wait_for("34/35", 1); + term.press(b"\x1b[B\r"); + term.wait_for("The patch could not be read", 1); + term.press(b"qq"); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + + let frames = frames(&output); + let page = frames + .iter() + .find(|frame| { + frame + .iter() + .any(|l| l.starts_with("The patch could not be read")) + }) + .unwrap_or_else(|| panic!("no page: {frames:#?}")); + assert_eq!( + page[1], + "The patch could not be read: the project records no valid patch UUID for it." + ); + let requests = rt.block_on(mock.received_requests()).unwrap_or_default(); + assert!(!requests.is_empty()); + for request in &requests { + assert_eq!( + request.url.path(), + format!("/v0/orgs/{ORG_SLUG}/patches/view/{}", uuid(0)), + "{requests:#?}" + ); + } +} + +/// Under `SOCKET_DEBUG` the browser stays down, as the status line does: +/// the debug lines go straight to stderr, where they would land in the +/// middle of a frame and be gone with the screen. The entries print. +#[test] +fn list_under_debug_logging_prints_and_opens_nothing() { + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 2); + let term = Terminal::run_with( + "list", + tmp.path(), + &["--offline"], + &[("SOCKET_DEBUG", "1")], + 100, + 16, + ); + let (code, output) = term.finish(); + assert_eq!(code, 0, "{output}"); + assert!(!output.contains(ENTER_SCREEN), "{output:?}"); + assert!(output.contains("Found 2 patches:"), "{output:?}"); +} + +/// `--yes`, like a pipe, keeps the full entries and opens no browser: the +/// run ends by itself, and asks the patch service nothing. +#[test] +fn list_yes_prints_the_full_entries_and_opens_nothing() { + let tmp = tempfile::tempdir().unwrap(); + write_manifest(tmp.path(), 3); + let pair = portable_pty::native_pty_system() + .openpty(size(100, 30)) + .expect("openpty"); + let mut cmd = common::hermetic::pty_binary_command(); + cmd.arg("list"); + cmd.arg("--yes"); + cmd.cwd(tmp.path()); + cmd.env("TERM", "xterm-256color"); + let mut child = pair.slave.spawn_command(cmd).expect("spawn in PTY"); + drop(pair.slave); + let output = PtyOutput::spawn(pair.master.try_clone_reader().expect("clone reader")); + let status = child.wait().expect("wait"); + drop(pair.master); + let output = String::from_utf8_lossy(&output.finish()).into_owned(); + assert_eq!(status.exit_code(), 0, "{output}"); + assert!(output.contains("Found 3 patches:"), "{output}"); + assert!( + output.contains("Package: pkg:npm/list-tty-package-00@1.0.0"), + "{output}" + ); + assert!(!output.contains(ENTER_SCREEN), "{output:?}"); +} diff --git a/crates/socket-patch-cli/tests/cli/main.rs b/crates/socket-patch-cli/tests/cli/main.rs index 022f82bc1..4a31a2fdc 100644 --- a/crates/socket-patch-cli/tests/cli/main.rs +++ b/crates/socket-patch-cli/tests/cli/main.rs @@ -17,6 +17,7 @@ mod cli_dry_run_paths_e2e; mod envelope_helper_copies; mod interactive_prompts_e2e; mod list_render; +mod list_tty; mod output_modes_e2e; mod prompts_tty; mod shared_helper_copies; diff --git a/crates/socket-patch-cli/tests/cli/output_modes_e2e.rs b/crates/socket-patch-cli/tests/cli/output_modes_e2e.rs index d606a5234..ea857a22d 100644 --- a/crates/socket-patch-cli/tests/cli/output_modes_e2e.rs +++ b/crates/socket-patch-cli/tests/cli/output_modes_e2e.rs @@ -444,8 +444,9 @@ fn rollback_non_json_prints_summary() { let (code, stdout, _stderr) = common::run_with_env(tmp.path(), &["rollback", "--offline"], &[]); assert_eq!(code, 0); assert!( - stdout.contains("Rolled back packages:") && stdout.contains("pkg:npm/rb-non-json@1.0.0"), - "non-JSON rollback should print summary naming the PURL; got: {stdout}" + stdout.contains("Rolled back 1 package:\n pkg:npm/rb-non-json@1.0.0\n") + && stdout.contains("\nRemoved 1 patch from manifest.\n"), + "non-JSON rollback should print summary naming the PURL once; got: {stdout}" ); // The summary must reflect reality: the file should be restored to the // pre-patch ("before") content. The old test's `|| "original"` even diff --git a/crates/socket-patch-cli/tests/cli/prompts_tty.rs b/crates/socket-patch-cli/tests/cli/prompts_tty.rs index 8c0dcbac3..391f833e7 100644 --- a/crates/socket-patch-cli/tests/cli/prompts_tty.rs +++ b/crates/socket-patch-cli/tests/cli/prompts_tty.rs @@ -69,6 +69,45 @@ fn write_remove_manifest(root: &Path) { std::fs::write(socket.join("manifest.json"), REMOVE_MANIFEST).unwrap(); } +/// A typed yes/no question is a safeguard, not decoration: on an AI +/// coding agent's terminal it is still asked, and `n` still declines. +/// Only presentation follows the agent's variables; nothing in the +/// environment answers a confirmation (`--yes` does). +#[test] +fn remove_still_asks_on_an_agents_terminal() { + let tmp = tempfile::tempdir().unwrap(); + write_remove_manifest(tmp.path()); + + let run = pty_io::run_command( + common::hermetic::pty_binary_command(), + &[ + "remove", + "pkg:npm/__prompts_tty_remove__@1.0.0", + "--skip-rollback", + ], + tmp.path(), + &[("AI_AGENT", "some-agent_1-2-3_agent")], + &[b"n\n"], + Duration::from_secs(15), + ); + let output = run.output; + assert!( + output.contains("Remove 1 patch from the manifest without rolling back its files?"), + "the confirmation must still be asked; got: {output}" + ); + assert!(output.contains("[Y/n]"), "{output}"); + assert!( + !output.contains("Non-interactive mode detected"), + "nothing may answer for the user; got: {output}" + ); + // Declined: the manifest still records the patch. + let manifest = std::fs::read_to_string(tmp.path().join(".socket/manifest.json")).unwrap(); + assert!( + manifest.contains("__prompts_tty_remove__"), + "a declined removal must change nothing; manifest: {manifest}" + ); +} + #[test] fn remove_interactive_bare_enter_proceeds_with_default_yes() { // `ui::confirm`'s empty-answer arm returns `default_yes`, and every @@ -135,15 +174,36 @@ fn remove_interactive_bare_enter_proceeds_with_default_yes() { /// Collect the paths of every request the mock actually received. Used to /// prove which code path the binary really took (vs. fabricating the right /// output without touching the network it claims to touch). +/// +/// On a terminal `get` also asks what Socket measured about each patch it +/// lists: a view request that carries no file content +/// (`?include_blobs=false`). Those are not downloads of a patch, and are +/// left out. async fn received_paths(mock: &MockServer) -> Vec { mock.received_requests() .await .expect("wiremock must record received requests") .iter() + .filter(|r| r.url.query() != Some("include_blobs=false")) .map(|r| r.url.path().to_string()) .collect() } +/// The patches whose measurements the listing asked for +/// (`view/?include_blobs=false`), by uuid. +async fn measured_uuids(mock: &MockServer) -> Vec { + let mut uuids: Vec = mock + .received_requests() + .await + .expect("wiremock must record received requests") + .iter() + .filter(|r| r.url.query() == Some("include_blobs=false")) + .filter_map(|r| r.url.path().rsplit('/').next().map(str::to_string)) + .collect(); + uuids.sort(); + uuids +} + /// A single-file patch-view `files` map that survives the "patch has /// no applicable files" guardrail: one net-new file with an all-zero /// `beforeHash`, a real git-blob `afterHash`, and matching base64 @@ -276,7 +336,7 @@ fn get_interactive_dialoguer_enter_accepts_first_ranked_option() { ); // Enter accepted the first-ranked option and get proceeded to save it. assert!( - output.contains("Added: 1"), + output.contains("Saved 1 patch to "), "get must have saved the selected patch; got: {output}" ); let body = std::fs::read_to_string(tmp.path().join(".socket/manifest.json")) @@ -302,6 +362,12 @@ fn get_interactive_dialoguer_enter_accepts_first_ranked_option() { .any(|p| p.ends_with(&format!("/patches/view/{UUID_B}"))), "the non-selected patch must not be fetched; recorded paths={paths:?}" ); + // The listing asked what was measured about both candidates, without + // their file content. + assert_eq!( + rt.block_on(measured_uuids(&mock)), + [UUID_A.to_string(), UUID_B.to_string()] + ); } #[test] @@ -419,7 +485,7 @@ fn get_interactive_dialoguer_quit_cancels_with_exit_zero() { ); // Cancelled means NOTHING was downloaded or recorded. assert!( - !output.contains("Patches saved"), + !output.contains("Saved "), "cancelled selection must not save anything; got: {output}" ); assert!( diff --git a/crates/socket-patch-cli/tests/cli_global_args.rs b/crates/socket-patch-cli/tests/cli_global_args.rs index 353d5b833..50a371b0b 100644 --- a/crates/socket-patch-cli/tests/cli_global_args.rs +++ b/crates/socket-patch-cli/tests/cli_global_args.rs @@ -53,7 +53,7 @@ const SUBCOMMANDS_NO_POSITIONAL: &[&str] = &[ ]; /// Subcommands that require a positional identifier. -const SUBCOMMANDS_WITH_IDENTIFIER: &[&str] = &["get", "remove"]; +const SUBCOMMANDS_WITH_IDENTIFIER: &[&str] = &["get", "remove", "show"]; const DUMMY_IDENTIFIER: &str = "80630680-4da6-45f9-bba8-b888e0ffd58c"; @@ -152,6 +152,7 @@ fn common_of(cli: &Cli) -> &GlobalArgs { Apply(a) => &a.common, Rollback(a) => &a.common, Get(a) => &a.common, + Show(a) => &a.common, Scan(a) => &a.common, List(a) => &a.common, Remove(a) => &a.common, diff --git a/crates/socket-patch-cli/tests/cli_parse_main.rs b/crates/socket-patch-cli/tests/cli_parse_main.rs index 3109d214a..3df31a880 100644 --- a/crates/socket-patch-cli/tests/cli_parse_main.rs +++ b/crates/socket-patch-cli/tests/cli_parse_main.rs @@ -81,7 +81,7 @@ fn help_flag_triggers_display_help() { // listed in the rendered help. let help = err.to_string(); for name in [ - "scan", "apply", "vex", "vendor", "rollback", "get", "list", "remove", "repair", + "scan", "apply", "vex", "vendor", "rollback", "get", "show", "list", "remove", "repair", ] { assert!( help.contains(name), diff --git a/crates/socket-patch-cli/tests/cli_parse_show.rs b/crates/socket-patch-cli/tests/cli_parse_show.rs new file mode 100644 index 000000000..438b3fdc1 --- /dev/null +++ b/crates/socket-patch-cli/tests/cli_parse_show.rs @@ -0,0 +1,135 @@ +//! CLI contract tests for the `show` subcommand. +//! +//! These tests pin the public clap parser surface for `ShowArgs`: the +//! required positional identifier and the three local flags. +//! +//! See `crates/socket-patch-cli/CLI_CONTRACT.md` ("`show`: inspect a patch"). +//! +//! clap reads the flag-bound environment during every parse, so every test +//! that parses is `#[serial]`. + +use socket_patch_cli::commands::show::ShowArgs; +use socket_patch_cli::Commands; + +#[path = "common/clap_parse.rs"] +mod clap_parse; +#[path = "common/hermetic.rs"] +mod hermetic; + +use clap_parse::Globals; +use hermetic::try_parse; + +const UUID: &str = "8be53d06-7bd4-40cc-ab8f-36dc6248985a"; + +fn parse_show(extra: &[&str]) -> ShowArgs { + let mut argv = vec!["socket-patch", "show"]; + argv.extend_from_slice(extra); + let cli = try_parse(&argv).expect("parse"); + match cli.command { + Commands::Show(a) => a, + _ => panic!("expected Show"), + } +} + +/// Every parsed field of `ShowArgs`. The tests compare the whole snapshot, +/// so a flag wired to a second field fails too. +#[derive(Debug, Clone, PartialEq)] +struct Snap { + identifier: String, + common: Globals, + files: Vec, + stat: bool, + no_pager: bool, +} + +fn snapshot(a: &ShowArgs) -> Snap { + Snap { + identifier: a.identifier.clone(), + common: Globals(a.common.clone()), + files: a.files.clone(), + stat: a.stat, + no_pager: a.no_pager, + } +} + +/// The snapshot of `show `, written by hand. +fn expected_defaults() -> Snap { + Snap { + identifier: UUID.to_string(), + common: clap_parse::global_defaults(), + files: Vec::new(), + stat: false, + no_pager: false, + } +} + +#[test] +#[serial_test::serial] +fn show_defaults_match_contract() { + assert_eq!(snapshot(&parse_show(&[UUID])), expected_defaults()); +} + +#[test] +#[serial_test::serial] +fn show_requires_an_identifier() { + let err = match try_parse(&["socket-patch", "show"]) { + Ok(_) => panic!("`show` without an identifier must not parse"), + Err(e) => e, + }; + assert_eq!( + err.kind(), + clap::error::ErrorKind::MissingRequiredArgument, + "{err}" + ); +} + +#[test] +#[serial_test::serial] +fn show_takes_any_target_token_verbatim() { + for token in [ + "pkg:npm/lodash@4.17.20", + "lodash", + "CVE-2021-23337", + "GHSA-35jh-r3h4-6jhm", + ] { + let mut expected = expected_defaults(); + expected.identifier = token.to_string(); + assert_eq!(snapshot(&parse_show(&[token])), expected, "{token}"); + } +} + +#[test] +#[serial_test::serial] +fn show_file_flag_repeats() { + let args = parse_show(&[UUID, "--file", "lib/a.js", "--file", "b.js"]); + let mut expected = expected_defaults(); + expected.files = vec!["lib/a.js".to_string(), "b.js".to_string()]; + assert_eq!(snapshot(&args), expected); +} + +#[test] +#[serial_test::serial] +fn show_stat_flag() { + let args = parse_show(&[UUID, "--stat"]); + let mut expected = expected_defaults(); + expected.stat = true; + assert_eq!(snapshot(&args), expected); +} + +#[test] +#[serial_test::serial] +fn show_no_pager_flag() { + let args = parse_show(&[UUID, "--no-pager"]); + let mut expected = expected_defaults(); + expected.no_pager = true; + assert_eq!(snapshot(&args), expected); +} + +#[test] +#[serial_test::serial] +fn show_json_flag_is_the_global_one() { + let args = parse_show(&[UUID, "--json"]); + let mut expected = expected_defaults(); + expected.common.json = true; + assert_eq!(snapshot(&args), expected); +} diff --git a/crates/socket-patch-cli/tests/cli_scan_silent.rs b/crates/socket-patch-cli/tests/cli_scan_silent.rs index 2b9e0b31e..f0cc91009 100644 --- a/crates/socket-patch-cli/tests/cli_scan_silent.rs +++ b/crates/socket-patch-cli/tests/cli_scan_silent.rs @@ -1,10 +1,10 @@ //! `scan --silent` contract tests. //! //! CLI_CONTRACT.md defines `--silent` as "Errors only": the "No packages -//! found" hint, the "Found N packages" / "Found N patches" stderr chatter, -//! the results table, the summary, the "Patches to apply" listing, the -//! post-apply GC line, and the nested apply step's progress must all be -//! muted under `--silent` (not just gated on `!json`). +//! found" hint, the "Found N packages" stderr line, the result line, the +//! per-package rows, the closing totals, the post-apply GC line, and the +//! nested apply step's progress must all be muted under `--silent` (not +//! just gated on `!json`). //! //! The apply-flow test runs against a wiremock API (same fixture shape //! as `scan_sync_e2e.rs`) so the full human-mode scan→select→download→ @@ -188,10 +188,10 @@ fn scan_silent_no_packages_produces_no_output() { } /// The full human-mode apply flow under `--silent --yes` must stay -/// quiet end to end: no "Found N packages" / "Found N patches" stderr -/// chatter, no results table, no "Patches to apply" listing, and no -/// download/apply progress from the nested `download_and_apply_patches` -/// call (which `scan` configured with a hardcoded `silent: false`). +/// quiet end to end: no "Found N packages" stderr line, no result line, no +/// rows, no closing totals, and no download/apply progress from the nested +/// `download_and_apply_patches` call (which `scan` configured with a +/// hardcoded `silent: false`). /// The mutation itself must still happen. #[tokio::test] async fn scan_silent_apply_flow_produces_no_output_but_still_applies() { @@ -275,12 +275,15 @@ async fn scan_silent_apply_flow_produces_no_output_but_still_applies() { "control run must succeed; stderr={loud_stderr:?}" ); assert!( - loud_stdout.contains("PACKAGE"), - "non-silent scan must print the results table; got {loud_stdout:?}" + loud_stdout.starts_with("Applied 1 patch.\n HIGH silent-target@1.0.0\n"), + "non-silent scan must print its result line and the package's row; got {loud_stdout:?}" ); assert!( - loud_stdout.contains("Patches to apply:"), - "non-silent scan must print the pre-apply listing; got {loud_stdout:?}" + loud_stdout.ends_with( + "\nPatched 1 package.\nSaved about 2 hours of engineering time (1 package upgrade \ + at ~2 hours).\nNothing left to patch.\n" + ), + "non-silent scan must close with its totals; got {loud_stdout:?}" ); assert!( loud_stderr.contains("Found 1 package ("), diff --git a/crates/socket-patch-cli/tests/command_module_layering.rs b/crates/socket-patch-cli/tests/command_module_layering.rs index 0d50563f5..63a591a7c 100644 --- a/crates/socket-patch-cli/tests/command_module_layering.rs +++ b/crates/socket-patch-cli/tests/command_module_layering.rs @@ -28,6 +28,7 @@ const COMMAND_MODULES: &[&str] = &[ "repair", "rollback", "scan", + "show", "update", "vendor", "vex", @@ -83,6 +84,11 @@ const ALLOWED_COMMAND_IMPORTS: &[(&str, &str, &str)] = &[ "vendored staging reuses apply's variant matching", ), ("rollback", "vendor", "rollback's vendored leg"), + ( + "list", + "show", + "the interactive listing opens a patch with show", + ), ( "remove", "rollback", @@ -232,6 +238,45 @@ fn module_edges() -> BTreeSet<(String, String)> { edges } +/// Whether a stream is a terminal is asked in one place, `ui::attended`, +/// which also knows an AI coding agent's terminal from a person's. A +/// check written with `std::io::IsTerminal` anywhere else would draw for +/// a person where an agent reads, so outside `src/ui/` there is none. +/// Inside it, only `mod.rs` (`attended` itself and the color gate) and +/// `prompt.rs` (the typed yes/no question, which is deliberately asked on +/// any terminal, and the cursor guard of a menu already open) ask. +#[test] +fn terminal_checks_go_through_ui_attended() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files = Vec::new(); + rust_files(&src, &mut files); + assert!(files.len() > 20, "the scan found the sources: {files:?}"); + let allowed = [ + src.join("ui").join("mod.rs"), + src.join("ui").join("prompt.rs"), + ]; + let offenders: Vec = files + .iter() + .filter(|file| !allowed.contains(file)) + .filter_map(|file| { + let code = std::fs::read_to_string(file).ok()?; + let lines: Vec = code + .lines() + .enumerate() + .filter(|(_, line)| !line.trim_start().starts_with("//")) + .filter(|(_, line)| line.contains("is_terminal") || line.contains("IsTerminal")) + .map(|(n, line)| format!("{}:{}: {}", file.display(), n + 1, line.trim())) + .collect(); + (!lines.is_empty()).then(|| lines.join("\n")) + }) + .collect(); + assert!( + offenders.is_empty(), + "ask `ui::attended(Stream::..)` instead of `is_terminal()`:\n{}", + offenders.join("\n") + ); +} + #[test] fn edge_scanner_sees_every_import_form() { let names = |code: &str, depth: usize| -> Vec { diff --git a/crates/socket-patch-cli/tests/common/hermetic.rs b/crates/socket-patch-cli/tests/common/hermetic.rs index 6ce85ef9a..314e3bbaa 100644 --- a/crates/socket-patch-cli/tests/common/hermetic.rs +++ b/crates/socket-patch-cli/tests/common/hermetic.rs @@ -71,6 +71,14 @@ pub fn command(bin: &Path) -> Command { for k in COLOR_ENV { cmd.env_remove(k); } + // The variables an AI coding agent sets for the commands it runs. An + // agent running this suite has them in its environment, and they + // would turn the terminal output the PTY suites test into the plain + // output an agent gets. (`SOCKET_PLAIN` goes with the other + // `SOCKET_*` below.) + for k in socket_patch_cli::ui::AGENT_ENV_VARS { + cmd.env_remove(k); + } // The flag-bound vars are removed by name, not only when the sweep below // finds them: in-process tests in the same binary set some of them // (`apply_env_toggles`, env save/restore helpers), and one set between diff --git a/crates/socket-patch-cli/tests/get/get_render.rs b/crates/socket-patch-cli/tests/get/get_render.rs index 4ab6f761b..5c307409b 100644 --- a/crates/socket-patch-cli/tests/get/get_render.rs +++ b/crates/socket-patch-cli/tests/get/get_render.rs @@ -192,8 +192,10 @@ async fn human_vendored_uuid_prints_fetch_and_vendor_error_without_manifest_note ); assert_eq!(code, 1, "stdout={stdout}\nstderr={stderr}"); assert!( - stderr.contains(&format!("[fetch] {PURL}")), - "the detached download phase reports the fetched record; stderr={stderr}" + stderr.contains(&format!( + "Found patch for {PURL} [FREE]\nError: Cannot vendor {PURL}: " + )), + "the patch is named once, then the vendor error; stderr={stderr}" ); assert!( !stdout.contains("Patch record saved to") && !stdout.contains("Added: 1"), @@ -752,11 +754,11 @@ async fn silent_apply_failure_still_prints_an_error() { ); } -/// The nested apply's `Patched packages:` block puts its leading blank -/// line on stderr: stdout gets no blank line of its own before it, and -/// never two in a row. +/// `get ` says what its apply did in one line: the patch was named +/// by the save line (stderr), so stdout starts with the result and holds +/// no list of patched packages and no blank line. #[tokio::test] -async fn nested_apply_block_starts_stdout_without_a_blank_line() { +async fn nested_apply_says_its_result_in_one_line() { let server = MockServer::start().await; mount_view_files( &server, @@ -776,10 +778,17 @@ async fn nested_apply_block_starts_stdout_without_a_blank_line() { let (code, stdout, stderr) = run_get_bin(tmp.path(), &server.uri(), &[UUID]); assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); assert!( - stdout.starts_with(&format!("Patched packages:\n {PURL}")), + stdout.starts_with("Applied 1 patch.\nNext steps:\n"), "stdout={stdout:?}" ); - assert!(!stdout.contains("\n\n\n"), "stdout={stdout:?}"); + assert!( + !stdout.contains("Patched packages:") && !stdout.contains("\n\n"), + "stdout={stdout:?}" + ); + assert!( + stderr.contains("Patch saved to ") && !stderr.contains("Applying patches"), + "stderr={stderr:?}" + ); } /// The two steps agent mode needs, as `get` prints them after a run that diff --git a/crates/socket-patch-cli/tests/get/get_update_summary_e2e.rs b/crates/socket-patch-cli/tests/get/get_update_summary_e2e.rs index bf2bbddd0..b7f742870 100644 --- a/crates/socket-patch-cli/tests/get/get_update_summary_e2e.rs +++ b/crates/socket-patch-cli/tests/get/get_update_summary_e2e.rs @@ -1,14 +1,14 @@ //! The human-readable `get` summary must not report one patch twice. //! -//! `download_and_apply_patches_with` prints an `Added: / Skipped: / Failed: / -//! Updated:` block after writing the manifest. Regression guard: the "added" -//! tally was bumped for EVERY record it wrote — including the ones classified -//! `Updated` — so replacing an existing manifest entry printed both -//! `Added: 1` and `Updated: 1` for the single patch it had just swapped. +//! `download_and_apply_patches_with` says what a `--save-only` run wrote in +//! one line (`Saved 1 patch to (1 updated).`). Regression guard: +//! the "added" tally was once bumped for EVERY record it wrote — including +//! the ones classified `Updated` — so replacing an existing manifest entry +//! was reported as both an add and an update for the single patch it had +//! just swapped. //! //! The JSON `downloaded` count deliberately covers adds + updates (pinned by -//! `in_process_get_update_count.rs`); only the human `Added:` line is the -//! true-adds count. +//! `in_process_get_update_count.rs`), as does the line's "Saved N". //! //! Runs `--save-only` so the apply step never fires: this is purely about the //! download bookkeeping. @@ -120,13 +120,12 @@ async fn replacing_a_manifest_entry_is_reported_as_updated_only() { assert_eq!(code, 0, "save-only update must succeed; stderr={stderr}"); assert!( - stderr.contains("Updated: 1"), - "the replacement must be reported as an update; stderr={stderr}" - ); - assert!( - !stderr.contains("Added: 1"), - "a replaced entry must NOT also be counted as an add — one patch, one \ - line; stdout={stdout}\nstderr={stderr}" + stderr.ends_with(&format!( + " [update] {PURL} (replacing 00000000)\n\ + Saved 1 patch to ./.socket/manifest.json (1 updated).\n" + )), + "the replacement must be reported as one saved patch, an update, never also an add; \ + stdout={stdout}\nstderr={stderr}" ); // The manifest really was swapped (so the assertions above aren't @@ -149,11 +148,11 @@ async fn a_brand_new_entry_is_still_reported_as_added() { assert_eq!(code, 0, "save-only add must succeed; stderr={stderr}"); assert!( - stderr.contains("Added: 1"), - "a new entry must be reported as an add; stdout={stdout}\nstderr={stderr}" + stderr.ends_with("Saved 1 patch to ./.socket/manifest.json.\n"), + "a new entry must be reported as one saved patch; stdout={stdout}\nstderr={stderr}" ); assert!( - !stderr.contains("Updated:"), + !stderr.contains("updated") && !stderr.contains("[update]"), "a new entry must not report an update; stderr={stderr}" ); diff --git a/crates/socket-patch-cli/tests/help_text_hygiene.rs b/crates/socket-patch-cli/tests/help_text_hygiene.rs index 4816c6487..04ce9764b 100644 --- a/crates/socket-patch-cli/tests/help_text_hygiene.rs +++ b/crates/socket-patch-cli/tests/help_text_hygiene.rs @@ -203,14 +203,15 @@ fn root_command_list_leads_with_the_v5_workflow() { .filter_map(|l| l.split_whitespace().next()) .filter(|w| { [ - "scan", "vex", "vendor", "list", "get", "apply", "rollback", "remove", "repair", + "scan", "vex", "vendor", "list", "get", "show", "apply", "rollback", "remove", + "repair", ] .contains(w) }) .collect(); assert_eq!( - &order[..9], - ["scan", "get", "list", "remove", "rollback", "vex", "vendor", "apply", "repair"], + &order[..10], + ["scan", "get", "show", "list", "remove", "rollback", "vex", "vendor", "apply", "repair"], "{text}" ); assert!( diff --git a/crates/socket-patch-cli/tests/in_process_vendor.rs b/crates/socket-patch-cli/tests/in_process_vendor.rs index 8d5070b77..543555bb3 100644 --- a/crates/socket-patch-cli/tests/in_process_vendor.rs +++ b/crates/socket-patch-cli/tests/in_process_vendor.rs @@ -3917,7 +3917,9 @@ async fn scan_vendor_gem_skips_a_version_the_lock_does_not_resolve() { async fn scan_vendor_gem_unlocked_version_skip_reads_as_a_skip() { let (_, gemfile, lock) = gem_unlocked_projects().remove(0); for (extra, headline) in [ - (&[][..], "Downloading 1 patch"), + // The wet run ends on the empty-run line: with the one patch + // skipped, there was nothing to vendor. + (&[][..], "No vendorable patches in scope."), ( &["--dry-run"][..], "Would download and vendor 0 of 1 patch (1 would be skipped)", diff --git a/crates/socket-patch-cli/tests/rollback/rollback_render.rs b/crates/socket-patch-cli/tests/rollback/rollback_render.rs index ff181326c..f1e9fb923 100644 --- a/crates/socket-patch-cli/tests/rollback/rollback_render.rs +++ b/crates/socket-patch-cli/tests/rollback/rollback_render.rs @@ -107,7 +107,7 @@ fn human_wet_reports_already_original_and_not_installed() { "already-original + not-installed exits 0; stdout=\n{stdout}\nstderr=\n{stderr}" ); assert!( - stdout.contains("Rolled back packages:") + stdout.contains("Rolled back 1 package:") && stdout.contains(&format!(" {purl} (already original)")), "the no-op must print its '(already original)' line; stdout=\n{stdout}" ); diff --git a/crates/socket-patch-cli/tests/scan/hosted_fixture.rs b/crates/socket-patch-cli/tests/scan/hosted_fixture.rs index 341fe7784..f73f8648c 100644 --- a/crates/socket-patch-cli/tests/scan/hosted_fixture.rs +++ b/crates/socket-patch-cli/tests/scan/hosted_fixture.rs @@ -533,33 +533,21 @@ pub(crate) fn scan_hosted_json_or_release_fifo( } } -/// Stdout below the discovery report: human hosted `scan` prints the -/// results table and its `Summary:` block (plus any indented continuation -/// lines) before the engine's own output. +/// The project's own output of a human hosted `scan`: stdout without the +/// invocation's closing totals (the lines under its last blank line, which +/// `scan_render.rs` and the report's unit tests pin). pub(crate) fn engine_stdout(stdout: &str) -> String { - let mut lines = stdout.lines().peekable(); - let mut seen_summary = false; - let mut out = Vec::new(); - while let Some(line) = lines.next() { - if !seen_summary { - if line.starts_with("Summary: ") { - seen_summary = true; - while lines.peek().is_some_and(|l| l.starts_with(' ')) { - lines.next(); - } - } - continue; + match stdout.rfind("\n\n") { + Some(end) + if ["Patched ", "Would patch "] + .iter() + .any(|opening| stdout[end + 2..].starts_with(opening)) + || stdout[end + 2..].contains(" left to patch") => + { + stdout[..=end].to_string() } - out.push(line); - } - if !seen_summary { - return stdout.to_string(); - } - let mut joined = out.join("\n"); - if !out.is_empty() { - joined.push('\n'); + _ => stdout.to_string(), } - joined } /// Yarn classic project: package.json (with `package_manager` when given) + diff --git a/crates/socket-patch-cli/tests/scan/hosted_render.rs b/crates/socket-patch-cli/tests/scan/hosted_render.rs index 13bd7ddb9..a2404e35a 100644 --- a/crates/socket-patch-cli/tests/scan/hosted_render.rs +++ b/crates/socket-patch-cli/tests/scan/hosted_render.rs @@ -177,10 +177,10 @@ async fn hosted_human_empty_discovery_ignores_a_malformed_pre_v5_ledger() { } /// A free-tier org whose every discovered hosted offer is paid-tier: the -/// human hosted arm stops with the same `No downloadable patches (paid -/// subscription required).` line the agent/vendored arms print (after the -/// table's paid nudge), exits 0, and never enters the engine — no reference -/// grant is requested and no `Redirected 0 package(s)` line is printed. +/// human hosted arm stops with the same `No downloadable patches` line the +/// agent/vendored arms print, exits 0, and never enters the engine — no +/// reference grant is requested and no `Switched 0 packages` line is +/// printed. The run closes with the paid-plan line. #[tokio::test] async fn hosted_human_paid_only_discovery_stops_with_the_paid_hint() { let server = MockServer::start().await; @@ -226,9 +226,11 @@ async fn hosted_human_paid_only_discovery_stops_with_the_paid_hint() { stdout.contains("No downloadable patches: every patch found requires a paid Socket plan."), "stdout=\n{stdout}" ); - assert!( - stdout.contains("1 additional patch is available with a paid Socket plan"), - "the table's paid nudge still prints; stdout=\n{stdout}" + assert_eq!( + stdout, + "No downloadable patches: every patch found requires a paid Socket plan.\n\ + Upgrade to a paid Socket plan to access all patches: https://socket.dev/pricing\n", + "the paid nudge still prints" ); assert!( !stdout.contains("Switched"), @@ -507,43 +509,53 @@ async fn human_rerun_says_already_redirected_and_first_run_prints_next_steps() { assert_eq!(code, 0, "stderr=\n{stderr}"); assert_eq!( engine_stdout(&stdout), - "Switched 1 package to hosted patches; rewrote 2 files.\n\ + "Switched 1 package to hosted patches; rewrote 2 files.\n \ + HIGH covgap-hosted@1.0.0\n\ Next steps:\n \ 1. Commit .npmrc and package-lock.json to keep the hosted patches.\n \ - 2. Reinstall from the updated lockfile (e.g. `npm ci`) so the installed packages pick \ - up the patched artifacts, then run `socket-patch vex` to verify the installed \ - patches.\n", + 2. Reinstall from the updated lockfile (e.g. `npm ci`), then run `socket-patch vex` \ + to verify the installed patches.\n", "stderr=\n{stderr}" ); + assert!( + stdout.ends_with( + "\nPatched 1 package.\nSaved about 2 hours of engineering time (1 package upgrade \ + at ~2 hours).\nNothing left to patch.\n" + ), + "the run closes with its totals; stdout=\n{stdout}" + ); let (code, stdout, stderr) = scan_hosted(tmp.path(), &server.uri(), &[], &[]); assert_eq!(code, 0, "stderr=\n{stderr}"); assert_eq!( engine_stdout(&stdout), - "1 package is already on hosted patches; nothing to rewrite.\n", + "1 package is already on hosted patches; nothing to rewrite.\n \ + HIGH covgap-hosted@1.0.0\n", "stderr=\n{stderr}" ); let (code, stdout, _) = scan_hosted(tmp.path(), &server.uri(), &["--dry-run"], &[]); assert_eq!(code, 0); assert_eq!( engine_stdout(&stdout), - "1 package is already on hosted patches; nothing to rewrite.\n" + "1 package is already on hosted patches; nothing to rewrite.\n \ + HIGH covgap-hosted@1.0.0\n" ); } -/// A package with three patches gets one of them. The run names the -/// advisory that patch fixes and the two it leaves unpatched (a CVE, and an -/// advisory that has only a GHSA id), in the future tense on a dry run and +/// A package with three patches gets one of them. The package's row names +/// the advisory that patch fixes and counts the two it leaves unpatched (a +/// CVE, and an advisory that has only a GHSA id), which `--verbose` names; +/// the closing lines total them, in the future tense on a dry run, and /// again on a re-run that rewrites nothing. `--json` carries the same facts /// on the package's `packages[]` entry. #[tokio::test] async fn human_names_the_fixed_advisory_and_the_ones_left_unpatched() { const UUID_B: &str = "33333333-3333-4333-8333-333333333333"; const UUID_C: &str = "44444444-4444-4444-8444-444444444444"; - const LINE: &str = " pkg:npm/covgap-hosted@1.0.0: fixes CVE-2026-0001; still unpatched: \ - CVE-2026-0002, GHSA-cccc-cccc-cccc\n"; - const NOTE: &str = "Only one patch is applied per package version. Upgrade the package to \ - fix the advisories still unpatched.\n"; + const LINE: &str = " CRITICAL covgap-hosted@1.0.0 CVE-2026-0001 2 unpatched\n"; + const NOTE: &str = "\nPatched 1 package, fixing 1 vulnerability (1 critical).\n\ + Saved about 2 hours of engineering time (1 package upgrade at ~2 hours).\n\ + 2 vulnerabilities left to patch (67%): 2 need a package upgrade.\n"; let server = MockServer::start().await; mock_discovery_patches( @@ -565,14 +577,25 @@ async fn human_names_the_fixed_advisory_and_the_ones_left_unpatched() { let (code, stdout, stderr) = scan_hosted(tmp.path(), &server.uri(), &["--dry-run"], &[]); assert_eq!(code, 0, "stderr=\n{stderr}"); assert_eq!( - engine_stdout(&stdout), + stdout, format!( "Would switch 1 package to hosted patches and rewrite 2 files (--dry-run: nothing \ - was changed).\n pkg:npm/covgap-hosted@1.0.0: would fix CVE-2026-0001; would stay \ - unpatched: CVE-2026-0002, GHSA-cccc-cccc-cccc\n{NOTE}" + was changed).\n{LINE}\n\ + Would patch 1 package, fixing 1 vulnerability (1 critical).\n\ + Would save about 2 hours of engineering time (1 package upgrade at ~2 hours).\n\ + 2 vulnerabilities would be left to patch (67%): 2 need a package upgrade.\n" ), "stderr=\n{stderr}" ); + let (code, verbose, stderr) = + scan_hosted(tmp.path(), &server.uri(), &["--dry-run", "--verbose"], &[]); + assert_eq!(code, 0, "stderr=\n{stderr}"); + assert!( + verbose.contains(&format!( + "{LINE} still unpatched: CVE-2026-0002, GHSA-cccc-cccc-cccc\n" + )), + "stdout=\n{verbose}" + ); let (code, doc) = scan_hosted_json(tmp.path(), &server.uri(), &["--dry-run"], &[]); assert_eq!(code, 0, "{doc:#}"); @@ -600,18 +623,17 @@ async fn human_names_the_fixed_advisory_and_the_ones_left_unpatched() { let (code, stdout, stderr) = scan_hosted(tmp.path(), &server.uri(), &[], &[]); assert_eq!(code, 0, "stderr=\n{stderr}"); - let engine = engine_stdout(&stdout); assert!( - engine.starts_with(&format!( - "Switched 1 package to hosted patches; rewrote 2 files.\n{LINE}{NOTE}Next steps:\n" - )), + stdout.starts_with(&format!( + "Switched 1 package to hosted patches; rewrote 2 files.\n{LINE}Next steps:\n" + )) && stdout.ends_with(NOTE), "stdout=\n{stdout}\nstderr=\n{stderr}" ); let (code, stdout, stderr) = scan_hosted(tmp.path(), &server.uri(), &[], &[]); assert_eq!(code, 0, "stderr=\n{stderr}"); assert_eq!( - engine_stdout(&stdout), + stdout, format!("1 package is already on hosted patches; nothing to rewrite.\n{LINE}{NOTE}"), "stderr=\n{stderr}" ); @@ -750,7 +772,9 @@ async fn human_summary_counts_only_the_packages_this_run_switched() { assert_eq!( engine_stdout(&stdout), "Would switch 1 package to hosted patches and rewrite 1 file (--dry-run: nothing was \ - changed). 1 package is already on hosted patches.\n", + changed). 1 package is already on hosted patches.\n \ + HIGH covgap-hosted@1.0.0\n \ + HIGH covgap-second@1.0.0\n", "stderr=\n{stderr}" ); @@ -759,7 +783,10 @@ async fn human_summary_counts_only_the_packages_this_run_switched() { assert!( engine_stdout(&stdout).starts_with( "Switched 1 package to hosted patches; rewrote 1 file. 1 package was already on \ - hosted patches.\nNext steps:\n" + hosted patches.\n \ + HIGH covgap-hosted@1.0.0\n \ + HIGH covgap-second@1.0.0\n\ + Next steps:\n" ), "stdout=\n{stdout}\nstderr=\n{stderr}" ); @@ -768,7 +795,9 @@ async fn human_summary_counts_only_the_packages_this_run_switched() { assert_eq!(code, 0, "stderr=\n{stderr}"); assert_eq!( engine_stdout(&stdout), - "2 packages are already on hosted patches; nothing to rewrite.\n", + "2 packages are already on hosted patches; nothing to rewrite.\n \ + HIGH covgap-hosted@1.0.0\n \ + HIGH covgap-second@1.0.0\n", "stderr=\n{stderr}" ); } @@ -854,7 +883,8 @@ async fn human_pnpm_rerun_prints_only_the_reminder_and_heal_restores_guidance() assert_eq!(code, 0, "stdout=\n{stdout}\nstderr=\n{stderr}"); assert_eq!( engine_stdout(&stdout), - "1 package is already on hosted patches; nothing to rewrite.\n" + "1 package is already on hosted patches; nothing to rewrite.\n \ + HIGH covgap-hosted@1.0.0\n" ); assert_eq!( pnpm_part(&stderr), diff --git a/crates/socket-patch-cli/tests/scan/scan_project_discovery_e2e.rs b/crates/socket-patch-cli/tests/scan/scan_project_discovery_e2e.rs index c72749490..064c6fa10 100644 --- a/crates/socket-patch-cli/tests/scan/scan_project_discovery_e2e.rs +++ b/crates/socket-patch-cli/tests/scan/scan_project_discovery_e2e.rs @@ -391,6 +391,34 @@ async fn agent_scan_of_a_root_project_names_the_projects_below_it_left() { assert!(not_scanned_detail(&stdout).is_some(), "{stdout}"); } +/// A lookup that fails ends the run, and the projects below are still +/// named first: that this run would not have covered them is what the +/// user needs before running it again. +#[tokio::test] +async fn a_failed_lookup_still_names_the_projects_below() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(500).set_body_string("upstream down")) + .mount(&server) + .await; + let tmp = tempfile::tempdir().unwrap(); + write_gem_monorepo(tmp.path()); + write_gem_project(tmp.path(), "root-gem"); + + let (code, stdout, stderr) = run_agent_scan(tmp.path(), &server.uri(), &[]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stderr.contains("2 project directories below this one were not scanned (api, web)"), + "{stderr}" + ); + assert_eq!( + stderr.matches("not scanned").count(), + 1, + "said once: {stderr}" + ); +} + /// An agent-mode scan warns only of a project it did not reach. Its npm /// crawl walks the `node_modules` below `--cwd`, so a nested npm project /// is scanned from the root and is not named. Nor is a project with no diff --git a/crates/socket-patch-cli/tests/scan/scan_proxy_fallback_e2e.rs b/crates/socket-patch-cli/tests/scan/scan_proxy_fallback_e2e.rs index efc3282d8..1b0d38733 100644 --- a/crates/socket-patch-cli/tests/scan/scan_proxy_fallback_e2e.rs +++ b/crates/socket-patch-cli/tests/scan/scan_proxy_fallback_e2e.rs @@ -331,7 +331,12 @@ async fn one_unanswered_package_is_a_partial_failure_that_names_it() { let (code, stdout, stderr) = run_scan(tmp.path(), &server.uri(), &["--dry-run"]); assert_eq!(code, 1, "{stdout}\n{stderr}"); assert!(stderr.contains(&format!("Warning: {detail}")), "{stderr}"); - assert!(stdout.contains(NAMES[0]), "{stdout}"); + // The answered package's patch is acted on (here: named as one the + // fixture's server has no hosted artifact for), never dropped. + assert!( + format!("{stdout}{stderr}").contains(NAMES[0]), + "{stdout}\n{stderr}" + ); assert!(!stdout.contains("No patches available"), "{stdout}"); } diff --git a/crates/socket-patch-cli/tests/scan/scan_render.rs b/crates/socket-patch-cli/tests/scan/scan_render.rs index e3e455cca..39a904b63 100644 --- a/crates/socket-patch-cli/tests/scan/scan_render.rs +++ b/crates/socket-patch-cli/tests/scan/scan_render.rs @@ -5,13 +5,13 @@ //! //! 1. terminals reachable without a network: `--offline`, hosted //! `--prune`, an empty `--global-prefix`, `--ecosystems`, usage errors; -//! 2. the paid-tier table column, summaries and nudge; -//! 3. the results table: `[UPDATE]`, `(+N)`, full purls, the preview's +//! 2. the paid-tier terminal and nudge; +//! 3. the rows: `(+N)`, full names, newer patches, the `--verbose` preview's //! vulnerability lines, and the detail-fetch warning and error; //! 4. `[skip]`, `[re-apply]` and `[would-refuse]` lines; //! 5. report-only runs and their hints, agent-mode applies, the GC line //! and the retained-wiring warning; -//! 6. hosted mode's table, per-directory runs and corrupt `bun.lockb`. +//! 6. hosted mode's update detection, per-directory runs and corrupt `bun.lockb`. use wiremock::MockServer; @@ -155,9 +155,9 @@ fn scan_mode_conflict_error_is_capitalized_and_names_no_hidden_flag() { // Paid tier: no other fixture sends tier: "paid" // --------------------------------------------------------------------------- -/// Paid patch, NO paid access: the `free+paid` table column, the free-only -/// summary, the paid-plan nudge with the pricing URL, and the "No -/// downloadable patches" terminal (exit 0, no detail fetch attempted). +/// Paid patch, NO paid access: the "No downloadable patches" terminal +/// (exit 0, no detail fetch attempted), then the closing lines saying what +/// a paid plan would fix, with the pricing URL. #[tokio::test] async fn scan_paid_patch_without_access_nudges_and_downloads_nothing() { let mock = MockServer::start().await; @@ -166,25 +166,12 @@ async fn scan_paid_patch_without_access_nudges_and_downloads_nothing() { let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &[]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); - assert!( - stdout.contains("0+1"), - "the table column must render free+paid counts; got {stdout:?}" - ); - assert!( - stdout.contains("Summary: 1 package with 0 free patches"), - "the no-access summary counts FREE patches only; got {stdout:?}" - ); - assert!( - stdout.contains("+ 1 additional patch is available with a paid Socket plan"), - "the paid nudge must print; got {stdout:?}" - ); - assert!( - stdout.contains("https://socket.dev/pricing"), - "the pricing URL must print; got {stdout:?}" - ); - assert!( - stdout.contains("No downloadable patches: every patch found requires a paid Socket plan."), - "the gated-catalog terminal must print; got {stdout:?}" + assert_eq!( + stdout, + "No downloadable patches: every patch found requires a paid Socket plan.\n\ + Upgrade to a paid Socket plan to access all patches: https://socket.dev/pricing\n\n\ + 1 vulnerability left to patch: 1 needs a paid Socket plan.\n", + "the gated catalog says what a paid plan would fix; stderr={stderr:?}" ); assert_eq!( by_package_gets(&recorded(&mock).await), @@ -193,9 +180,9 @@ async fn scan_paid_patch_without_access_nudges_and_downloads_nothing() { ); } -/// Paid patch WITH paid access: the summary counts ALL patches (the -/// can-access arm) and no nudge prints. The deliberately failing detail -/// fetch then fails the run (its error line is pinned below). +/// Paid patch WITH paid access: no nudge prints. The deliberately failing +/// detail fetch fails the run before any result line (its error is on +/// stderr). #[tokio::test] async fn scan_paid_patch_with_access_counts_all_patches() { let mock = MockServer::start().await; @@ -208,29 +195,25 @@ async fn scan_paid_patch_with_access_counts_all_patches() { code, 1, "a failed detail fetch fails the scan; stdout={stdout}; stderr={stderr}" ); - assert!( - stdout.contains("Summary: 1 package with 1 available patch"), - "the can-access summary counts all patches; got {stdout:?}" - ); - assert!( - stdout.contains("0+1"), - "the free+paid column renders for paid-access users too; got {stdout:?}" + assert_eq!( + stdout, "", + "a failed detail fetch has no result to print, and a subscriber gets no nudge" ); assert!( - !stdout.contains("paid Socket plan"), - "no nudge for a subscriber; got {stdout:?}" + stderr.contains("could not fetch patch details"), + "the failure is on stderr; got {stderr:?}" ); } // --------------------------------------------------------------------------- -// The results table and the per-patch preview +// The rows and the per-patch preview // --------------------------------------------------------------------------- -/// The `[UPDATE]` marker and newer-patches summary (the manifest's OLD uuid -/// against the batch's NEW uuid), the `(+N)` vuln overflow, and the -/// dry-run terminal before any confirm. +/// The newer-patches line (the manifest's OLD uuid against the batch's NEW +/// uuid), the row's `(+N)` advisory overflow, and the dry-run terminal +/// before any confirm. #[tokio::test] -async fn scan_human_table_renders_update_marker_and_vuln_overflow() { +async fn scan_human_row_counts_extra_advisories_and_names_newer_patches() { let mock = MockServer::start().await; mount_batch_one( &mock, @@ -249,30 +232,35 @@ async fn scan_human_table_renders_update_marker_and_vuln_overflow() { // apply never run), so no view/blob mocks are needed. let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--dry-run", "--yes"]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); - assert!( - stdout.contains("[UPDATE]"), - "the human update marker must render; got {stdout:?}" - ); - assert!( - stdout.contains("1 package has a newer patch available."), - "the newer-patches summary must print; got {stdout:?}" + // The ids are sorted, so the first two show and the third folds into + // (+1). The row sits under the dry-run line, the totals close the run. + assert_eq!( + stdout, + "1 package has a newer patch available.\n\ + [dry-run] Would download and apply 1 patch. No changes made.\n \ + HIGH minimist@1.2.2 CVE-2024-0001, CVE-2024-0002 (+1)\n\n\ + Would patch 1 package, fixing 3 vulnerabilities.\n\ + Would save about 2 hours of engineering time (1 package upgrade at ~2 hours).\n\ + Nothing left to patch.\n", + "stderr={stderr:?}" ); - // collect_vuln_ids sorts CVEs, so the first two sorted ids show and the - // third folds into (+1). - assert!( - stdout.contains("CVE-2024-0001, CVE-2024-0002 (+1)"), - "3+ vuln ids must truncate to two plus (+N); got {stdout:?}" + // `--verbose` names every id. + let (code, stdout, stderr) = run_scan_agent( + tmp.path(), + &mock.uri(), + &["--dry-run", "--yes", "--verbose"], ); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); assert!( - stdout.contains("[dry-run] Would download and apply 1 patch. No changes made."), - "dry-run must stop before the confirm; got {stdout:?}" + stdout.contains(" HIGH minimist@1.2.2 CVE-2024-0001, CVE-2024-0002, CVE-2024-0003\n"), + "got {stdout:?}" ); } -/// The table's PACKAGE column grows to fit the PURL (a fixed-width cut -/// would drop the version), and the rule matches the table. +/// A row names the package in full, scope and version included (a +/// fixed-width cut would drop the version). #[tokio::test] -async fn scan_human_table_shows_full_purl_with_version() { +async fn scan_human_row_names_the_package_in_full_with_its_version() { let mock = MockServer::start().await; let purl = "pkg:npm/@typescript-eslint/typescript-estree@6.0.0"; mount_batch_one(&mock, purl, UUID, "free", &["CVE-2024-1"], false).await; @@ -289,29 +277,25 @@ async fn scan_human_table_shows_full_purl_with_version() { r#"{ "name": "@typescript-eslint/typescript-estree", "version": "6.0.0" }"#, ) .unwrap(); - let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &["--dry-run"]); + let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--dry-run"]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); - let row = stdout - .lines() - .find(|l| l.contains("CVE-2024-1") && l.starts_with("pkg:npm/")) - .unwrap_or_else(|| panic!("no table row in {stdout:?}")); - assert!(row.starts_with(&format!("{purl} ")), "{row:?}"); - let header = stdout.lines().find(|l| l.starts_with("PACKAGE")).unwrap(); - // The right-aligned count ends where the PATCHES header ends. - assert_eq!( - header.find("PATCHES").map(|i| i + "PATCHES".len()), - row.find(" 1 ").map(|i| i + 2), - "PATCHES header sits over the count: {stdout}" + assert!( + stdout + .lines() + .any(|l| l == " HIGH @typescript-eslint/typescript-estree@6.0.0 CVE-2024-1"), + "no row for the package in {stdout:?}" + ); + // No table: nothing is ruled off or headed by column. + assert!( + !stdout.contains("===") && !stdout.contains("PACKAGE"), + "{stdout:?}" ); - // The rule is exactly as wide as the widest table line. - let rule = stdout.lines().find(|l| l.starts_with("===")).unwrap(); - assert_eq!(rule.len(), header.len().max(row.len()), "{stdout}"); } -/// Per-patch vulnerability rendering in the "Patches to apply" preview. -/// Every other human-path fixture ships `vulnerabilities: {}`, so the -/// CVE/GHSA fold, the "Fixes:" line, and the per-vuln summary lines had -/// never executed. +/// Per-patch vulnerability rendering in the `--verbose` "Patches to apply" +/// preview. Every other human-path fixture ships `vulnerabilities: {}`, so +/// the CVE/GHSA fold, the "Fixes:" line, and the per-vuln summary lines had +/// never executed. Without `--verbose` the row names the same ids. #[tokio::test] async fn scan_human_preview_renders_vulnerability_details() { let mock = MockServer::start().await; @@ -340,6 +324,22 @@ async fn scan_human_preview_renders_vulnerability_details() { let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--dry-run", "--yes"]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert!( + stdout.contains(" HIGH minimist@1.2.2 CVE-2024-9999, GHSA-dddd-eeee-ffff\n"), + "the row names a CVE, and an advisory with none by its own id; got {stdout:?}" + ); + assert!( + !stdout.contains("Patches to apply:") && !stdout.contains("Fixes: "), + "the per-patch preview is for --verbose; got {stdout:?}" + ); + + let (code, stdout, stderr) = run_scan_agent( + tmp.path(), + &mock.uri(), + &["--dry-run", "--yes", "--verbose"], + ); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert!(stdout.contains("\nPatches to apply:\n"), "{stdout:?}"); let fixes = stdout .lines() .find(|l| l.trim_start().starts_with("Fixes: ")) @@ -374,21 +374,16 @@ async fn scan_human_invalid_package_json_says_to_fix_the_file() { assert_eq!( stdout, "1 package was not scanned: this project's own patches could not be checked (see the \ - warnings). Fix the file they name and run again.\n" + warning). Fix the file it names and run again.\n" ); - let warning = stderr - .lines() - .find(|l| l.starts_with("Warning: pkg:npm/minimist@1.2.2: ")) - .unwrap_or_else(|| panic!("the package's warning must print; stderr={stderr}")); + // One warning for the file, naming it relative to the project, however + // many packages it holds back. assert!( - warning.starts_with( - "Warning: pkg:npm/minimist@1.2.2: not patched, because this project's own patches \ - for it could not be checked: " - ) && warning.ends_with( - "package.json (not valid JSON: EOF while parsing a value at line 1 column 10). Fix \ - that file and run again." - ), - "{warning}" + stderr.lines().any(|l| l + == "Warning: 1 package not patched, because this project's own patches could not \ + be checked: package.json (not valid JSON: EOF while parsing a value at line 1 \ + column 10). Fix that file and run again."), + "the file's warning must print; stderr={stderr}" ); for output in [&stdout, &stderr] { assert!(!output.contains("--allow-patch-conflicts"), "{output}"); @@ -406,13 +401,19 @@ async fn scan_human_invalid_package_json_says_to_fix_the_file() { assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); assert_eq!( stdout, - "1 package is protected by this project's own patches and was not scanned (see the \ - warnings). Pass --allow-patch-conflicts to scan it anyway.\n" + "1 package is protected by this project's own patches and was not scanned. Pass \ + --allow-patch-conflicts to scan it anyway.\n" ); + // The packages the project patches itself are one note: the file, the + // packages, and the flag. assert!( - stderr.contains("protected by project patch/replacement metadata in "), + stderr.contains( + "Note: skipped 1 package covered by this project's own patches (package.json): \ + minimist@1.2.2.\n --allow-patch-conflicts patches it too.\n" + ), "{stderr}" ); + assert!(!stderr.contains("Warning: pkg:npm/"), "{stderr}"); } /// A `package-lock.json` that is not JSON, with nothing installed: the @@ -592,10 +593,9 @@ async fn scan_human_reapplies_an_already_recorded_patch_after_reinstall() { b"after\n", "flags={flags:?}: the recorded patch must be re-applied; stdout={stdout}; stderr={stderr}" ); + // The re-applied package has its row under the result line. assert!( - stdout.contains(&format!( - "[re-apply] {MINIMIST} (already recorded: 11111111)" - )), + stdout.starts_with("Applied 1 patch.\n HIGH minimist@1.2.2\n"), "flags={flags:?}: {stdout:?}" ); assert!( @@ -645,7 +645,14 @@ async fn scan_human_reapplies_recorded_patch_alongside_a_new_one() { b"after\n", "recorded patch re-applied; stdout={stdout}; stderr={stderr}" ); - assert!(stdout.contains("Patches to apply:"), "{stdout:?}"); + assert!( + stdout.starts_with("Applied 2 patches.\n HIGH left-pad@1.3.0\n HIGH minimist@1.2.2\n"), + "both packages have a row; got {stdout:?}" + ); + // `--verbose` also says which selection was already recorded. + std::fs::write(&index_a, before).unwrap(); + let (code, stdout, stderr) = run_scan_agent(tmp.path(), &second.uri(), &["--verbose"]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); assert!( stdout.contains(&format!( "[re-apply] {MINIMIST} (already recorded: 11111111)" @@ -668,15 +675,15 @@ async fn scan_human_dry_run_previews_reapply_of_a_recorded_patch() { let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--dry-run"]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); - assert!( - stdout.contains(&format!("[skip] {MINIMIST} (already recorded: 11111111)")), - "{stdout:?}" - ); - assert!( - stdout.contains("a run without --dry-run re-applies them"), - "{stdout:?}" + assert_eq!( + stdout, + "All selected patches are already recorded in the manifest; a run without --dry-run \ + re-applies them.\n HIGH minimist@1.2.2\n\n\ + Would patch 1 package.\n\ + Would save about 2 hours of engineering time (1 package upgrade at ~2 hours).\n\ + Nothing left to patch.\n", + "stderr={stderr:?}" ); - assert!(!stdout.contains("Patches to apply:"), "{stdout:?}"); assert_eq!( view_gets(&recorded(&mock).await), 0, @@ -828,7 +835,7 @@ async fn scan_human_empty_batch_reports_no_patches_once() { let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &[]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); - assert_eq!(stdout, "\nNo patches available for installed packages.\n"); + assert_eq!(stdout, "No patches available for installed packages.\n"); assert!(!stderr.contains("No patches"), "stderr={stderr:?}"); assert!( stderr.lines().any(|l| l == "Found 1 package (1 npm)"), @@ -867,7 +874,7 @@ async fn scan_human_empty_discovery_stops_in_every_mode() { assert_eq!(reference_posts(&recorded(&mock).await), 0); } -/// `--prune` with no mode: the discovery, table and per-patch preview +/// `--prune` with no mode: the discovery and one row per available patch /// print (the report IS the value), then the run stops with the /// agent-mode hint, writing nothing and downloading nothing. #[tokio::test] @@ -882,8 +889,8 @@ async fn scan_prune_without_a_mode_is_report_only() { "report-only is a success; stdout={stdout}; stderr={stderr}" ); assert!( - stdout.contains("Patches available:") && stdout.contains(MINIMIST), - "the per-patch preview still prints; got {stdout:?}" + stdout.starts_with("Patches available:\n HIGH minimist@1.2.2\n\n"), + "the available patch has its row; got {stdout:?}" ); assert!( !stdout.contains("Patches to apply:"), @@ -958,7 +965,7 @@ async fn scan_global_report_only_hint_keeps_the_global_scope() { "report-only is a success; stdout={stdout}; stderr={stderr}" ); assert!( - stdout.contains("Patches available:") && stdout.contains(MINIMIST), + stdout.starts_with("Patches available:\n HIGH minimist@1.2.2\n\n"), "the global scan must find the patch; got {stdout:?}" ); // Its preview is the same report, never "Would download and apply". @@ -1064,23 +1071,23 @@ async fn mount_two_patches(mock: &MockServer, purl: &str, before: &[u8]) { mount_view(mock, purl, UUID, before).await; } -const UNPATCHED_NOTE: &str = "Only one patch is applied per package version. Upgrade the \ - package to fix the advisories still unpatched."; +/// The row of the package whose patch fixes one of its two advisories. +const ROW: &str = " CRITICAL minimist@1.2.2 CVE-2021-0001 1 unpatched\n"; /// Agent mode applies one of a package's two patches. Under the apply -/// summary the run names the advisory it fixed and the one it left -/// unpatched; a re-run that finds the package already patched says the same. +/// summary the package's row names the advisory it fixed and counts the one +/// it left unpatched, and the closing lines total both; a re-run that finds +/// the package already patched says the same. #[tokio::test] async fn scan_human_agent_names_unpatched_advisories() { let mock = MockServer::start().await; let before = b"before\n"; mount_two_patches(&mock, MINIMIST, before).await; let tmp = minimist_project(before); - let expected = format!( - "Summary: 1 of 1 targeted patch applied, 0 already patched, 0 not found on disk\n \ - {MINIMIST}: fixes CVE-2021-0001; still unpatched: CVE-2021-0002\n\ - {UNPATCHED_NOTE}\n" - ); + let expected = format!("Applied 1 patch.\n{ROW}"); + let closing = "\nPatched 1 package, fixing 1 vulnerability (1 critical).\n\ + Saved about 2 hours of engineering time (1 package upgrade at ~2 hours).\n\ + 1 vulnerability left to patch (50%): 1 needs a package upgrade.\n"; let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &[]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); @@ -1089,17 +1096,33 @@ async fn scan_human_agent_names_unpatched_advisories() { b"after\n" ); assert!( - stdout.contains(&expected), + stdout.starts_with(&expected) && stdout.ends_with(closing), "stdout={stdout}; stderr={stderr}" ); + // Each package is named once: no table, no per-patch block, no list of + // patched packages. + assert_eq!(stdout.matches("minimist").count(), 1, "stdout={stdout}"); + assert!( + !stderr.contains("[add]") && !stderr.contains("Downloading"), + "stderr={stderr}" + ); let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &[]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert_eq!( + stdout, + format!("Applied 0 of 1 patch: 1 already patched.\n{ROW}{closing}"), + "stderr={stderr}" + ); + // The re-run names the package once, in its row: no `[skip]` line for + // a patch the manifest already records. + assert!(!stderr.contains("[skip]"), "stderr={stderr}"); + + // `--verbose` names the unpatched advisory under the row. + let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--verbose"]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); assert!( - stdout.ends_with(&format!( - " {MINIMIST}: fixes CVE-2021-0001; still unpatched: CVE-2021-0002\n\ - {UNPATCHED_NOTE}\n" - )), + stdout.contains(&format!("{ROW} still unpatched: CVE-2021-0002\n")), "stdout={stdout}; stderr={stderr}" ); } @@ -1118,12 +1141,13 @@ async fn scan_human_agent_ends_with_commit_and_reapply_next_steps() { let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &[]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); assert!( - stdout.ends_with(&format!( - "{UNPATCHED_NOTE}\n\ + stdout.contains(&format!( + "{ROW}\ Next steps:\n \ 1. Commit .socket/ to keep the patches.\n \ 2. Run `socket-patch apply` after every `npm install`, locally and in CI. A \ - fresh install removes the patches.\n" + fresh install removes the patches.\n\n\ + Patched 1 package" )), "stdout={stdout}; stderr={stderr}" ); @@ -1143,13 +1167,14 @@ async fn scan_human_agent_dry_run_names_unpatched_advisories_in_the_future_tense let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--dry-run"]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); - assert!( - stdout.ends_with(&format!( - "[dry-run] Would download and apply 1 patch. No changes made.\n \ - {MINIMIST}: would fix CVE-2021-0001; would stay unpatched: CVE-2021-0002\n\ - {UNPATCHED_NOTE}\n" - )), - "stdout={stdout}; stderr={stderr}" + let closing = "\nWould patch 1 package, fixing 1 vulnerability (1 critical).\n\ + Would save about 2 hours of engineering time (1 package upgrade at ~2 \ + hours).\n\ + 1 vulnerability would be left to patch (50%): 1 needs a package upgrade.\n"; + assert_eq!( + stdout, + format!("[dry-run] Would download and apply 1 patch. No changes made.\n{ROW}{closing}"), + "stderr={stderr}" ); assert!(!tmp.path().join(".socket").exists()); @@ -1162,9 +1187,7 @@ async fn scan_human_agent_dry_run_names_unpatched_advisories_in_the_future_tense assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); assert!( stdout.ends_with(&format!( - "[dry-run] Would download and vendor 1 patch. No changes made.\n \ - {MINIMIST}: would fix CVE-2021-0001; would stay unpatched: CVE-2021-0002\n\ - {UNPATCHED_NOTE}\n" + "[dry-run] Would download and vendor 1 patch. No changes made.\n{ROW}{closing}" )), "stdout={stdout}; stderr={stderr}" ); @@ -1431,11 +1454,11 @@ fn scan_human_vex_success_prints_wrote_line() { // Hosted mode, layout refusals and corrupt lockfiles // --------------------------------------------------------------------------- -/// The hosted human arm shares the table/update block with the -/// agent/vendored arms, then runs the engine without prompting (scan never -/// prompts), dry run or not. +/// The hosted human arm shares update detection with the agent/vendored +/// arms, then runs the engine without prompting (scan never prompts), dry +/// run or not. A patch the engine could not switch to counts as left. #[tokio::test] -async fn scan_hosted_human_prints_table_updates_and_redirects() { +async fn scan_hosted_human_names_newer_patches_and_redirects() { let mock = MockServer::start().await; mount_batch_one(&mock, MINIMIST, UUID, "free", &["CVE-2024-0001"], false).await; mount_by_package(&mock, MINIMIST, UUID, serde_json::json!({})).await; @@ -1448,17 +1471,12 @@ async fn scan_hosted_human_prints_table_updates_and_redirects() { // v5: a bare scan is hosted. let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &[]); assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); - assert!( - stdout.contains("VULNERABILITIES") && stdout.contains("CVE-2024-0001"), - "the results table must print in hosted mode; got {stdout:?}" - ); - assert!( - stdout.contains("Summary: 1 package with 1 free patch"), - "the summary must print in hosted mode; got {stdout:?}" - ); - assert!( - stdout.contains("[UPDATE]"), - "update detection must run in hosted mode; got {stdout:?}" + assert_eq!( + stdout, + "1 package has a newer patch available.\n\ + Switched 0 packages to hosted patches; rewrote 0 files.\n\n\ + 1 vulnerability left to patch: 1 is in packages this run did not patch.\n", + "update detection runs in hosted mode, and the refused patch is left; stderr={stderr:?}" ); assert!( !stderr.contains("Non-interactive mode detected"), @@ -1498,7 +1516,9 @@ async fn scan_hosted_human_prints_table_updates_and_redirects() { } /// Hosted PATHs name project directories: each runs as its own scan (its -/// own discovery and redirect), under a `== ==` header. +/// own redirect), under a `== ==` header. The directories are +/// crawled and looked up together before their scans, and the run asks +/// the patch service about a package once however many of them hold it. #[tokio::test] async fn scan_hosted_paths_run_once_per_project_directory() { let mock = MockServer::start().await; @@ -1531,8 +1551,67 @@ async fn scan_hosted_paths_run_once_per_project_directory() { "{stdout}" ); let reqs = recorded(&mock).await; - assert_eq!(batch_bodies(&reqs).len(), 2, "one discovery per directory"); + // Both directories hold the same package: one lookup answers both. + assert_eq!( + batch_bodies(&reqs).len(), + 1, + "the run asks about a package once" + ); + assert_eq!( + reqs.iter() + .filter(|r| r.url.path().contains("/by-package/")) + .count(), + 1, + "and reads its patches once" + ); assert_eq!(reference_posts(&reqs), 2, "one redirect per directory"); + // Each directory's scan still reports the package it found. + assert_eq!( + stderr.matches("Found 1 package (1 npm)").count(), + 2, + "{stderr}" + ); +} + +/// The read made ahead of a multi-directory scan asks the patch service +/// only what each directory's own scan would ask: a package the project +/// patches itself is protected before any question, there as in the +/// scan, and so is one a selection filter leaves out. +#[tokio::test] +async fn scan_of_several_directories_asks_about_no_package_a_scan_leaves_out() { + // Without and with the projects' own patch of `left-pad`: the first + // shows the package is asked about when nothing protects it. + for patched in [false, true] { + let mock = MockServer::start().await; + mount_batch_one(&mock, MINIMIST, UUID, "free", &[], false).await; + mount_by_package(&mock, MINIMIST, UUID, serde_json::json!({})).await; + mount_forbidden_reference(&mock, MINIMIST).await; + + let tmp = tempfile::tempdir().unwrap(); + for app in ["apps/a", "apps/b"] { + let dir = tmp.path().join(app); + std::fs::create_dir_all(&dir).unwrap(); + write_root_package_json(&dir); + write_npm_package(&dir, "minimist", "1.2.2", b"x\n"); + write_npm_package(&dir, "left-pad", "1.3.0", b"x\n"); + if patched { + std::fs::create_dir_all(dir.join("patches")).unwrap(); + std::fs::write(dir.join("patches/left-pad+1.3.0.patch"), "diff\n").unwrap(); + } + } + + let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &["apps/*"]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + let bodies = batch_bodies(&recorded(&mock).await); + assert_eq!(bodies.len(), 1, "one lookup for the run: {bodies:#?}"); + assert!(bodies[0].contains("minimist"), "{bodies:#?}"); + assert_eq!( + bodies[0].contains("left-pad"), + !patched, + "patched={patched}: a package the project patches itself is not asked about: \ + {bodies:#?}" + ); + } } /// The PnP layout refusal rides a NON-empty human scan (polyglot repo): diff --git a/crates/socket-patch-cli/tests/scan/scan_tty.rs b/crates/socket-patch-cli/tests/scan/scan_tty.rs index 7aad29b34..4808efd70 100644 --- a/crates/socket-patch-cli/tests/scan/scan_tty.rs +++ b/crates/socket-patch-cli/tests/scan/scan_tty.rs @@ -5,7 +5,8 @@ use std::time::Duration; -use wiremock::MockServer; +use wiremock::matchers::{method, path, query_param}; +use wiremock::{Mock, MockServer, ResponseTemplate}; use crate::common; use crate::pty_io; @@ -123,8 +124,8 @@ async fn scan_json_on_a_tty_never_opens_the_select_menu() { /// The live status line on a real terminal: every progress message is /// replaced (never overwritten in place), so what the user sees is the -/// result lines only — no "Found 1 patch for 1 packagesatch 1/1)" -/// residue from the longer "Querying API ... (batch 1/1)" line. +/// result lines only — no residue of a longer status ("Checking 1 package +/// for patches...") on the end of a shorter line. #[tokio::test(flavor = "multi_thread")] async fn scan_progress_on_a_tty_renders_without_stale_tail() { let mock = MockServer::start().await; @@ -149,10 +150,18 @@ async fn scan_progress_on_a_tty_renders_without_stale_tail() { assert_eq!(code, 0, "output:\n{output}"); // The raw stream really used the live line (so this test would - // catch a regression to bare `\r` rewrites)... + // catch a regression to bare `\r` rewrites): the status, behind its + // activity mark, is drawn after a clear and cleared again... + let status = " Checking 1 package for patches\r\x1b[2K"; + let drawn = output + .find(status) + .unwrap_or_else(|| panic!("expected a live status update; raw={output:?}")); + let line_start = output[..drawn] + .rfind('\r') + .expect("the line starts with a return"); assert!( - output.contains("\r\x1b[2KQuerying API for patches... (batch 1/1)"), - "expected a live status update; raw={output:?}" + output[line_start..drawn].starts_with("\r\x1b[2K"), + "the status is drawn over a cleared line; raw={output:?}" ); // ...and the screen shows only clean result lines. let screen = pty_io::render(output.as_bytes()); @@ -162,14 +171,17 @@ async fn scan_progress_on_a_tty_renders_without_stale_tail() { screen.join("\n") ); assert!( - screen.iter().any(|l| l == "Found 1 patch for 1 package"), + screen + .iter() + .any(|l| l == "Switched 0 packages to hosted patches; rewrote 0 files."), "screen:\n{}", screen.join("\n") ); for transient in [ "Scanning packages", - "Querying API", - "Fetching patch details", + "Checking 1 package", + "Reading patches", + "Resolving hosted", ] { assert!( !screen.iter().any(|l| l.contains(transient)), @@ -179,6 +191,53 @@ async fn scan_progress_on_a_tty_renders_without_stale_tail() { } } +/// A scan an AI coding agent runs on a pseudo-terminal draws nothing for +/// a person: no status line (every redraw of it would be read back into +/// the agent's context), no color, no glyphs. What reaches the agent is +/// the result lines a pipe gets, and not one escape sequence or carriage +/// return besides the terminal's own line endings. +#[tokio::test(flavor = "multi_thread")] +async fn scan_on_an_agents_terminal_draws_no_status_line() { + let mock = MockServer::start().await; + let purl = MINIMIST; + mount_batch_one(&mock, purl, UUID, "free", &[], false).await; + mount_by_package(&mock, purl, UUID, serde_json::json!({})).await; + + let tmp = minimist_project(b"x\n"); + + let uri = mock.uri(); + let cwd = tmp.path().to_path_buf(); + let run = tokio::task::spawn_blocking(move || { + pty_io::run_command( + common::hermetic::pty_binary_command(), + &[&["scan"][..], &api_args(&uri)].concat(), + &cwd, + &[("AI_AGENT", "some-agent_1-2-3_agent")], + &[], + Duration::from_secs(60), + ) + }) + .await + .expect("spawn_blocking join"); + let output = run.output; + assert_eq!(run.code, 0, "output:\n{output}"); + + assert!(!output.contains('\x1b'), "raw={output:?}"); + assert!( + !output.replace("\r\n", "\n").contains('\r'), + "raw={output:?}" + ); + for transient in ["Scanning packages", "Checking 1 package", "Reading patches"] { + assert!(!output.contains(transient), "{transient:?} in {output:?}"); + } + for line in [ + "Found 1 package (1 npm)\r\n", + "Switched 0 packages to hosted patches; rewrote 0 files.\r\n", + ] { + assert!(output.contains(line), "{line:?} in {output:?}"); + } +} + /// Under `SOCKET_DEBUG` core prints `[socket-patch debug] ...` lines /// straight to stderr. The live status line is off then, so those /// lines never land glued onto the end of a progress message. @@ -225,12 +284,111 @@ async fn scan_debug_mode_on_a_tty_keeps_debug_lines_off_the_status() { ); } assert!( - !output.contains("Querying API for patches..."), + !output.contains("Checking 1 package for patches"), "no transient status is drawn in debug mode; raw={output:?}" ); assert!( - screen.iter().any(|l| l == "Found 1 patch for 1 package"), + screen.iter().any(|l| l == "Found 1 package (1 npm)"), "the result lines still print; screen:\n{}", screen.join("\n") ); } + +/// On a terminal a scan asks what Socket measured about the patches it +/// selected (their view, without file content) and shows it: in each +/// package's row and in the closing lines. Where the locale is UTF-8 the +/// lines of what was done open with a check mark; with `LANG=C` the same +/// lines print in ASCII at the same columns. +#[tokio::test(flavor = "multi_thread")] +async fn scan_on_a_terminal_shows_what_was_measured() { + for (locale, glyphs) in [("en_US.UTF-8", true), ("C", false)] { + let mock = MockServer::start().await; + let before = b"before\n"; + mount_one_patch_api(&mock, MINIMIST, before).await; + // The measurement request: the view asked for without its blobs. + // It outranks the download's view mock, which has no statistics. + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}"))) + .and(query_param("include_blobs", "false")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": UUID, + "statistics": { + "diff": {"linesAdded": 5, "linesRemoved": 0, "filesChanged": 1}, + "functionsChanged": null, + "tests": {"before": {"count": 25, "total": 25}, + "after": {"count": 25, "total": 25}}, + "pocs": {"reproducedBefore": {"count": 1, "total": 1}, + "blockedAfter": {"count": 1, "total": 1}}, + "performance": null + } + }))) + .with_priority(1) + .expect(1) + .mount(&mock) + .await; + let tmp = minimist_project(before); + + let uri = mock.uri(); + let cwd = tmp.path().to_path_buf(); + let (code, output) = tokio::task::spawn_blocking(move || { + let run = pty_io::run_command( + common::hermetic::pty_binary_command(), + &[&["scan", "--mode", "agent"][..], &api_args(&uri)].concat(), + &cwd, + &[("LANG", locale)], + &[b""], + Duration::from_secs(60), + ); + (run.code, run.output) + }) + .await + .expect("spawn_blocking join"); + assert_eq!(code, 0, "{locale}: output:\n{output}"); + assert_eq!( + std::fs::read(tmp.path().join("node_modules/minimist/index.js")).unwrap(), + b"after\n", + "{locale}" + ); + + let screen = pty_io::render(output.as_bytes()); + let shown = screen.join("\n"); + let (mark, gutter) = if glyphs { + ("\u{2714}", " ") + } else { + (" ", "") + }; + assert!( + screen + .iter() + .any(|l| *l == format!("{mark} HIGH minimist@1.2.2 exploit blocked, 25/25 tests")), + "{locale}: the row shows the measurements; screen:\n{shown}" + ); + let done = if glyphs { "\u{2714} " } else { "" }; + assert!( + screen.iter().any( + |l| l.starts_with(&format!("{done}Patched 1 package in ")) && l.ends_with("s.") + ), + "{locale}: the totals say how long the run took; screen:\n{shown}" + ); + assert!( + screen.iter().any(|l| *l + == format!( + "{done}Verified: 1 of 1 exploit blocked, 25 of 25 package tests passing." + )), + "{locale}: the totals say what was measured; screen:\n{shown}" + ); + assert!( + screen + .iter() + .any(|l| *l == format!("{gutter}Nothing left to patch.")), + "{locale}: screen:\n{shown}" + ); + assert_eq!( + output.contains('\u{2714}'), + glyphs, + "{locale}: a check mark only where the terminal is known to show one" + ); + // Each package is named once. + assert_eq!(shown.matches("minimist").count(), 1, "{locale}:\n{shown}"); + } +} diff --git a/crates/socket-patch-cli/tests/scan_vendor_e2e.rs b/crates/socket-patch-cli/tests/scan_vendor_e2e.rs index 1be9f3f15..a0f158e01 100644 --- a/crates/socket-patch-cli/tests/scan_vendor_e2e.rs +++ b/crates/socket-patch-cli/tests/scan_vendor_e2e.rs @@ -764,13 +764,13 @@ async fn scan_vendor_fetch_failure_reports_error() { "the failed fetch must be reported on stderr, not swallowed; \ stdout={stdout}; stderr={stderr}" ); - // With --yes no prompt was answered, so the header gets no blank line - // of its own (the listing's trailing blank line separates the sections). + // The failure line follows the crawl line directly: a scan prints no + // download header and no per-patch progress lines. assert!( - stderr.contains("Downloading 1 patch...") - && !stderr.starts_with('\n') - && !stderr.contains("\n\nDownloading"), - "no extra blank line before the header under --yes; stderr={stderr}" + stderr.contains("Found 1 package (1 npm)\n [fail] pkg:npm/left-pad@1.3.0 ") + && !stderr.contains("Downloading") + && !stderr.contains("[fetch]"), + "stderr={stderr}" ); assert!( stdout.contains("Nothing was vendored: 1 patch failed (see above)."), @@ -1947,10 +1947,14 @@ async fn scan_discovers_lockfile_only_packages_with_warning() { assert_eq!(v["lockfileOnlyPackages"], 1, "{v}"); assert_eq!(v["packages"][0]["notInstalled"], true, "{v}"); - // Human output: the table marker + the note. + // Human output of an agent-mode scan, which patches installed copies: + // the note, and the package's `[skip]` line. (A hosted or vendored scan + // patches from the lockfile, so "not installed" is not news to it.) let out = hermetic_command(&binary()) .args([ "scan", + "--mode", + "agent", "--api-url", &mock.uri(), "--api-token", @@ -1966,13 +1970,32 @@ async fn scan_discovers_lockfile_only_packages_with_warning() { let stdout = String::from_utf8_lossy(&out.stdout); let stderr = String::from_utf8_lossy(&out.stderr); assert!( - stdout.contains("[NOT INSTALLED]"), + stdout.contains(" [skip] pkg:npm/left-pad@1.3.0 (not installed; "), "stdout={stdout}; stderr={stderr}" ); assert!( stderr.contains("not yet installed (lockfile-only)"), "stderr={stderr}" ); + let hosted = hermetic_command(&binary()) + .args([ + "scan", + "--api-url", + &mock.uri(), + "--api-token", + "fake-token", + "--org", + ORG_SLUG, + "--dry-run", + ]) + .current_dir(tmp.path()) + .output() + .expect("run"); + assert!( + !String::from_utf8_lossy(&hosted.stderr).contains("not yet installed"), + "a hosted scan does not note it: {}", + String::from_utf8_lossy(&hosted.stderr) + ); } /// The not-installed flag must survive the API's purl spelling: the @@ -2084,11 +2107,13 @@ async fn scan_flags_scoped_lockfile_only_package_despite_api_purl_encoding() { "notInstalled must bridge the API's percent-encoded purl: {v}" ); - // Human table: the [NOT INSTALLED] marker must match through the - // encoding difference too. + // Human output: an agent-mode scan's not-installed `[skip]` line must + // match through the encoding difference too. let out = hermetic_command(&binary()) .args([ "scan", + "--mode", + "agent", "--api-url", &mock.uri(), "--api-token", @@ -2104,7 +2129,7 @@ async fn scan_flags_scoped_lockfile_only_package_despite_api_purl_encoding() { let stdout = String::from_utf8_lossy(&out.stdout); let stderr = String::from_utf8_lossy(&out.stderr); assert!( - stdout.contains("[NOT INSTALLED]"), + stdout.contains(" [skip] pkg:npm/@scope/left-pad@1.3.0 (not installed; "), "stdout={stdout}; stderr={stderr}" ); } diff --git a/crates/socket-patch-cli/tests/show_e2e.rs b/crates/socket-patch-cli/tests/show_e2e.rs new file mode 100644 index 000000000..3d8c46f90 --- /dev/null +++ b/crates/socket-patch-cli/tests/show_e2e.rs @@ -0,0 +1,431 @@ +//! `socket-patch show` end to end, against a mock patch service. +//! +//! The run is piped (not a terminal), so nothing is paged and no menu +//! opens: the summary and every selected diff print at once, in ASCII and +//! without color. Covers the view carrying both sides of each file, the +//! blob endpoint filling in a side the view lacks, `--stat`, `--file`, +//! `--json`, `--silent`, a search that finds several patches, and the +//! failures. + +#[path = "common/mod.rs"] +mod common; +use common::{binary, hermetic_command}; + +use base64::Engine as _; +use std::path::Path; +use wiremock::matchers::{method, path, query_param}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +const ORG: &str = "test-org"; +const UUID: &str = "8be53d06-7bd4-40cc-ab8f-36dc6248985a"; +const OTHER: &str = "1d90158a-fffb-47ee-a84f-b210a3f7ae65"; +const PURL: &str = "pkg:npm/undici@8.10.0"; + +const BEFORE_A: &str = "one\ntwo\nthree\n"; +const AFTER_A: &str = "one\nTWO\nthree\nfour\n"; +const AFTER_NEW: &str = "added\n"; + +fn b64(text: &str) -> String { + base64::engine::general_purpose::STANDARD.encode(text) +} + +/// A 64-hex blob hash that is `c` repeated. +fn hash(c: char) -> String { + c.to_string().repeat(64) +} + +fn run_show(cwd: &Path, mock: &MockServer, args: &[&str]) -> (i32, String, String) { + let mut cmd = hermetic_command(&binary()); + cmd.arg("show") + .args(args) + .args([ + "--api-url", + &mock.uri(), + "--api-token", + "fake-token", + "--org", + ORG, + ]) + .current_dir(cwd); + let out = cmd.output().expect("run socket-patch show"); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).to_string(), + String::from_utf8_lossy(&out.stderr).to_string(), + ) +} + +/// The patch view: `lib/a.js` changed (its content before the patch inline +/// when `inline_before`), `lib/new.js` added. +fn view(inline_before: bool) -> serde_json::Value { + let mut a = serde_json::json!({ + "beforeHash": hash('b'), + "afterHash": hash('a'), + "blobContent": b64(AFTER_A), + }); + if inline_before { + a["beforeBlobContent"] = serde_json::json!(b64(BEFORE_A)); + } + serde_json::json!({ + "uuid": UUID, + "purl": PURL, + "publishedAt": "Mon, 03 Aug 2026 19:12:42 GMT", + "description": "", + "license": "MIT", + "tier": "free", + "files": { + "lib/a.js": a, + "lib/new.js": {"afterHash": hash('c'), "blobContent": b64(AFTER_NEW)}, + }, + "vulnerabilities": { + "GHSA-aaaa-bbbb-cccc": { + "cves": ["CVE-2026-84961"], + "summary": "TLS validation bypass", + "severity": "HIGH", + "description": "d" + } + }, + "statistics": { + "diff": {"linesAdded": 3, "linesRemoved": 1, "filesChanged": 2}, + "functionsChanged": 1, + "tests": {"before": {"count": 35, "total": 35}, "after": {"count": 35, "total": 35}}, + "pocs": {"reproducedBefore": {"count": 1, "total": 1}, + "blockedAfter": {"count": 1, "total": 1}}, + "performance": {"generalWallChange": null, "hotWallChange": 0.0356, + "peakMemChange": null} + } + }) +} + +async fn mount_view(mock: &MockServer, body: serde_json::Value) { + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .and(query_param("include_before_blobs", "true")) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(mock) + .await; +} + +const SUMMARY: &str = "\ +pkg:npm/undici@8.10.0 HIGH [FREE] +Patch 8be53d06-7bd4-40cc-ab8f-36dc6248985a, published 03 Aug 2026, MIT + +Fixes: + HIGH CVE-2026-84961 TLS validation bypass + +Measured by Socket: + Verified: 1 of 1 exploit blocked (1 of 1 worked before the patch), 35 of 35 tests passing \ +(35 of 35 before the patch) + Change: +3 -1 lines in 2 files, 1 function + Performance: patched code +3.6% + +2 files changed: +3 -1 + lib/a.js +2 -1 + lib/new.js +1 -0 +"; + +const DIFF_A: &str = "\ +--- a/lib/a.js ++++ b/lib/a.js +@@ -1,3 +1,4 @@ + one +-two ++TWO + three ++four +"; + +const DIFF_NEW: &str = "\ +--- /dev/null ++++ b/lib/new.js +@@ -0,0 +1,1 @@ ++added +"; + +#[tokio::test(flavor = "multi_thread")] +async fn show_prints_the_summary_and_every_diff_when_piped() { + let mock = MockServer::start().await; + mount_view(&mock, view(true)).await; + let tmp = tempfile::tempdir().unwrap(); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[UUID]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert_eq!(stdout, format!("{SUMMARY}\n{DIFF_A}{DIFF_NEW}")); + assert!( + !stdout.contains('\x1b') && stdout.is_ascii(), + "a pipe gets neither color nor glyphs: {stdout:?}" + ); + // The project is untouched. + assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); +} + +/// A view without the content before the patch (the public proxy's): that +/// side is read from the blob endpoint by its hash. +#[tokio::test(flavor = "multi_thread")] +async fn show_reads_a_missing_side_from_the_blob_endpoint() { + let mock = MockServer::start().await; + mount_view(&mock, view(false)).await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/blob/{}", hash('b')))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(BEFORE_A.as_bytes())) + .expect(1) + .mount(&mock) + .await; + let tmp = tempfile::tempdir().unwrap(); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[UUID, "--no-pager"]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert_eq!(stdout, format!("{SUMMARY}\n{DIFF_A}{DIFF_NEW}")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn show_stat_and_file_narrow_what_is_printed() { + let mock = MockServer::start().await; + mount_view(&mock, view(true)).await; + let tmp = tempfile::tempdir().unwrap(); + + let (code, stdout, _) = run_show(tmp.path(), &mock, &[UUID, "--stat"]); + assert_eq!(code, 0); + assert_eq!(stdout, SUMMARY); + + // The end of a path selects the file; the summary still lists both. + let (code, stdout, _) = run_show(tmp.path(), &mock, &[UUID, "--file", "new.js"]); + assert_eq!(code, 0); + assert_eq!(stdout, format!("{SUMMARY}\n{DIFF_NEW}")); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[UUID, "--file", "nope.js"]); + assert_eq!(code, 1, "stdout={stdout}"); + assert_eq!( + stderr.lines().last().unwrap_or_default(), + "Error: `nope.js` is not a file of this patch; it changes: lib/a.js, lib/new.js" + ); + assert!(stdout.is_empty(), "{stdout:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn show_json_is_one_document_without_file_content() { + let mock = MockServer::start().await; + mount_view(&mock, view(true)).await; + let tmp = tempfile::tempdir().unwrap(); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[UUID, "--json"]); + assert_eq!(code, 0, "stderr={stderr}"); + let doc: serde_json::Value = serde_json::from_str(&stdout).expect("one JSON document"); + assert_eq!(doc["command"], "show"); + assert_eq!(doc["status"], "success"); + let patch = &doc["patch"]; + assert_eq!(patch["uuid"], UUID); + assert_eq!(patch["purl"], PURL); + assert_eq!(patch["tier"], "free"); + assert_eq!(patch["statistics"]["pocs"]["blockedAfter"]["count"], 1); + assert_eq!( + patch["files"], + serde_json::json!([ + {"path": "lib/a.js", "beforeHash": hash('b'), "afterHash": hash('a'), + "added": 2, "removed": 1, "binary": false}, + {"path": "lib/new.js", "beforeHash": "", "afterHash": hash('c'), + "added": 1, "removed": 0, "binary": false}, + ]) + ); + assert!(!stdout.contains(&b64(AFTER_A)), "no file content: {stdout}"); + + // `--silent`: nothing on success. + let (code, stdout, _) = run_show(tmp.path(), &mock, &[UUID, "--silent"]); + assert_eq!((code, stdout.as_str()), (0, "")); +} + +/// A purl with several patches: piped, the best ranked is shown and the +/// others are named on stderr. +#[tokio::test(flavor = "multi_thread")] +async fn show_resolves_a_purl_to_its_best_ranked_patch() { + let mock = MockServer::start().await; + mount_view(&mock, view(true)).await; + let found = |uuid: &str, severity: &str, cve: &str| { + serde_json::json!({ + "uuid": uuid, "purl": PURL, "publishedAt": "2026-08-03T00:00:00Z", + "description": "", "license": "MIT", "tier": "free", + "vulnerabilities": { + format!("GHSA-{cve}"): {"cves": [cve], "summary": "s", "severity": severity, + "description": "d"} + } + }) + }; + Mock::given(method("GET")) + .and(path(format!( + "/v0/orgs/{ORG}/patches/by-package/{}", + PURL.replace(':', "%3A") + .replace('/', "%2F") + .replace('@', "%40") + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [ + found(OTHER, "MODERATE", "CVE-2026-85014"), + found(UUID, "HIGH", "CVE-2026-84961"), + ], + "canAccessPaidPatches": true + }))) + .mount(&mock) + .await; + let tmp = tempfile::tempdir().unwrap(); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[PURL, "--stat"]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert_eq!(stdout, SUMMARY); + assert!( + stderr.contains(&format!( + "2 patches match {PURL}; showing the best ranked. The others:\n 1d90158a {PURL} \ + MODERATE CVE-2026-85014" + )), + "{stderr}" + ); +} + +/// A token the patch service refuses is not the end of it: the public +/// service, which has the free patches, is asked for the patch. When it +/// has none either, the refusal is what is reported: it is the cause, and +/// the public service's "no such patch" would hide it. +#[tokio::test(flavor = "multi_thread")] +async fn show_reads_from_the_public_service_when_the_token_is_refused() { + let mock = MockServer::start().await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(401)) + .mount(&mock) + .await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{OTHER}"))) + .respond_with(ResponseTemplate::new(401)) + .mount(&mock) + .await; + Mock::given(method("GET")) + .and(path(format!("/patch/view/{UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(view(true))) + .mount(&mock) + .await; + Mock::given(method("GET")) + .and(path(format!("/patch/view/{OTHER}"))) + .respond_with(ResponseTemplate::new(404)) + .mount(&mock) + .await; + let tmp = tempfile::tempdir().unwrap(); + let public = mock.uri(); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[UUID, "--proxy-url", &public]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert_eq!(stdout, format!("{SUMMARY}\n{DIFF_A}{DIFF_NEW}")); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[OTHER, "--proxy-url", &public]); + assert_eq!(code, 1, "stdout={stdout}; stderr={stderr}"); + assert!(stdout.is_empty(), "{stdout:?}"); + assert!( + stderr.contains("Error: Unauthorized: Invalid API token"), + "{stderr}" + ); + assert!(!stderr.contains("no patch found"), "{stderr}"); +} + +/// A lookup the patch service fails for any reason other than refusing +/// the token is that failure: the public service is not asked, so its +/// "nothing for this package" (it has the free patches only) never +/// stands in for an outage. A `--file` the patch does not change is an +/// error in every output form. What the service says is shown as text: +/// a control sequence in an advisory's summary is not passed on. +#[tokio::test(flavor = "multi_thread")] +async fn show_reports_failures_as_what_they_are() { + let by_package = format!( + "/v0/orgs/{ORG}/patches/by-package/{}", + PURL.replace(':', "%3A") + .replace('/', "%2F") + .replace('@', "%40") + ); + let mock = MockServer::start().await; + Mock::given(method("GET")) + .and(path(by_package)) + .respond_with(ResponseTemplate::new(500).set_body_string("upstream down")) + .mount(&mock) + .await; + // The public service would answer "no patches". + Mock::given(method("GET")) + .and(wiremock::matchers::path_regex("^/patch/by-package/.*$")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [], "canAccessPaidPatches": false + }))) + .mount(&mock) + .await; + let mut hostile = view(true); + hostile["vulnerabilities"]["GHSA-aaaa-bbbb-cccc"]["summary"] = + serde_json::json!("TLS \u{1b}]0;owned\u{7}validation\u{1b}[2J bypass"); + mount_view(&mock, hostile).await; + let tmp = tempfile::tempdir().unwrap(); + let public = mock.uri(); + + let (code, stdout, stderr) = + run_show(tmp.path(), &mock, &[PURL, "--json", "--proxy-url", &public]); + assert_eq!(code, 1, "stdout={stdout}; stderr={stderr}"); + let doc: serde_json::Value = serde_json::from_str(&stdout).expect("one JSON document"); + assert_eq!(doc["error"]["code"], "patch_lookup_failed", "{doc:#}"); + let requests = mock.received_requests().await.unwrap_or_default(); + assert!( + requests + .iter() + .all(|r| !r.url.path().starts_with("/patch/")), + "the public service is asked only after a refusal: {requests:#?}" + ); + + for form in [&["--json"][..], &["--silent"], &[]] { + let args = [&[UUID, "--file", "nope.js"], form].concat(); + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &args); + assert_eq!(code, 1, "{form:?}: stdout={stdout}; stderr={stderr}"); + if form.contains(&"--json") { + let doc: serde_json::Value = serde_json::from_str(&stdout).expect("JSON"); + assert_eq!(doc["error"]["code"], "file_not_in_patch", "{doc:#}"); + } else { + assert!(stdout.is_empty(), "{form:?}: {stdout:?}"); + assert!( + stderr.contains("`nope.js` is not a file of this patch"), + "{form:?}: {stderr}" + ); + } + } + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[UUID, "--stat"]); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + assert!(!stdout.contains('\u{1b}'), "{stdout:?}"); + assert!(!stdout.contains('\u{7}'), "{stdout:?}"); + assert!( + stdout.contains(" HIGH CVE-2026-84961 TLS ]0;ownedvalidation[2J bypass\n"), + "{stdout:?}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn show_failures_are_coded_and_exit_one() { + let mock = MockServer::start().await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({ + "error": {"message": "Patch not found"} + }))) + .mount(&mock) + .await; + let tmp = tempfile::tempdir().unwrap(); + + let (code, stdout, stderr) = run_show(tmp.path(), &mock, &[UUID]); + assert_eq!(code, 1, "stdout={stdout}; stderr={stderr}"); + assert!(stdout.is_empty(), "{stdout:?}"); + assert!( + stderr.contains(&format!("Error: no patch found with UUID {UUID}")), + "{stderr}" + ); + + let (code, stdout, _) = run_show(tmp.path(), &mock, &[UUID, "--json"]); + assert_eq!(code, 1); + let doc: serde_json::Value = serde_json::from_str(&stdout).expect("one JSON document"); + assert_eq!(doc["status"], "error"); + assert_eq!(doc["error"]["code"], "patch_not_found"); + + // No network, no patch: refused before any request. + let (code, _, stderr) = run_show(tmp.path(), &mock, &[UUID, "--offline"]); + assert_eq!(code, 1); + assert!(stderr.contains("cannot run with --offline"), "{stderr}"); +} diff --git a/crates/socket-patch-cli/tests/vex/vex_render.rs b/crates/socket-patch-cli/tests/vex/vex_render.rs index ea8fb7e53..f4e7b1561 100644 --- a/crates/socket-patch-cli/tests/vex/vex_render.rs +++ b/crates/socket-patch-cli/tests/vex/vex_render.rs @@ -109,10 +109,13 @@ fn failed_run_reports_stale_document_removal() { )), "{err}" ); - // The error line is last. + // The error closes the run, with what to do about it under it. assert!( - err.trim_end() - .ends_with("Error: No applied patches with vulnerability metadata to attest."), + err.trim_end().ends_with( + "Error: No applied patches with vulnerability metadata to attest.\n\ + The patched packages are not installed here. Run your package manager's install, \ + then `socket-patch vex` again." + ), "{err}" ); } @@ -136,10 +139,24 @@ fn omissions_are_sorted_and_listed_once() { assert_eq!( lines, vec![ + // One line for the reason, its packages sorted. + "Warning: omitting 3 packages from VEX: the package is not installed \ + (package_not_found): alpha@1.0.0, mid@1.0.0, zeta@1.0.0", + "Error: No applied patches with vulnerability metadata to attest.", + "The patched packages are not installed here. Run your package manager's install, \ + then `socket-patch vex` again.", + ] + ); + // `--verbose` keeps a line per patch. + let o = vex(cwd, &["--verbose"]); + assert_eq!(o.status.code(), Some(1), "{}", stderr(&o)); + let lines: Vec = stderr(&o).lines().map(str::to_string).collect(); + assert_eq!( + lines[..3], + [ "Warning: omitting pkg:npm/alpha@1.0.0 from VEX: the package is not installed (package_not_found)", "Warning: omitting pkg:npm/mid@1.0.0 from VEX: the package is not installed (package_not_found)", "Warning: omitting pkg:npm/zeta@1.0.0 from VEX: the package is not installed (package_not_found)", - "Error: No applied patches with vulnerability metadata to attest.", ] ); diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index fc2401f1f..6d3cf9f80 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -374,6 +374,83 @@ pub struct ApiClient { /// the policy, the run-wide retry window (shared by clones, and by /// every default client in the process) and the clock hooks. api_retry: ApiRetry, + /// The lookups this client has answered, when it remembers them + /// ([`Self::remembering_lookups`]). Shared by clones. + lookups: Option>, +} + +/// What the patch service answered a client that remembers its lookups +/// ([`ApiClient::remembering_lookups`]): the batch search, per purl, and +/// the per-package search. A run over several project directories asks +/// about the same packages again and again, and asks about all of them up +/// front; the later, identical questions are answered from here. +/// +/// Only answers are kept, never failures, and an answer is reused only +/// for exactly the purl string it was given for: a question any part of +/// which is not held is sent whole, as if nothing were. +#[derive(Default)] +struct Lookups { + /// Per purl of an answered batch search: the package's patches (`None` + /// when it has none) and the response's `can_access_paid_patches`. + batch: std::sync::Mutex, bool)>>, + by_package: std::sync::Mutex>, +} + +impl Lookups { + /// The answer to a batch search of `purls`, when every one of them + /// has been answered before: their packages in the order asked. + fn batch(&self, purls: &[String]) -> Option { + let held = self.batch.lock().unwrap_or_else(|e| e.into_inner()); + let mut packages = Vec::new(); + let mut can_access_paid_patches = false; + let mut seen = HashSet::new(); + for purl in purls { + let (package, paid) = held.get(purl)?; + can_access_paid_patches |= paid; + if let Some(package) = package { + if seen.insert(purl.as_str()) { + packages.push(package.clone()); + } + } + } + Some(BatchSearchResponse { + packages, + can_access_paid_patches, + unanswered: Vec::new(), + }) + } + + /// Keep the answer to a batch search of `purls`. Nothing is kept of a + /// response that names a package by a spelling other than the one it + /// was asked with (which answer belongs to which question is then a + /// guess), and nothing for a purl the service gave no answer for. + fn remember_batch(&self, purls: &[String], response: &BatchSearchResponse) { + let asked: HashSet<&str> = purls.iter().map(String::as_str).collect(); + if response + .packages + .iter() + .any(|package| !asked.contains(package.purl.as_str())) + { + return; + } + let unanswered: HashSet<&str> = response + .unanswered + .iter() + .map(|u| u.purl.as_str()) + .collect(); + let mut held = self.batch.lock().unwrap_or_else(|e| e.into_inner()); + for purl in purls { + if unanswered.contains(purl.as_str()) { + continue; + } + let package = response + .packages + .iter() + .find(|package| package.purl == *purl) + .cloned(); + held.insert(purl.clone(), (package, response.can_access_paid_patches)); + } + } } /// A JSON request's answer after [`ApiClient::send_json_request`]'s retry @@ -555,9 +632,22 @@ impl ApiClient { service_confirmed: Arc::new(AtomicBool::new(false)), vendor_prefetch: Arc::new(std::sync::Mutex::new(None)), api_retry: ApiRetry::from_env(), + lookups: None, } } + /// This client, remembering what the patch service answers its batch + /// and per-package searches: a later search it has the whole answer + /// to makes no request (see [`Lookups`]). For a run that asks about + /// the same packages more than once, in one process, over seconds; a + /// client is otherwise forgetful, so every search is a request. The + /// memory is this client's and its clones': a client built for another + /// route (the public-proxy fallback) starts without one. + pub fn remembering_lookups(mut self) -> Self { + self.lookups.get_or_insert_with(Default::default); + self + } + /// Override the JSON calls' 429 / 503 retry policy and clock hooks /// (tests inject a recording sleep and a fixed jitter seed). The client /// and its clones get a fresh retry window of `policy.retry_window`, @@ -948,6 +1038,59 @@ impl ApiClient { self.get_json(&path, Bare404::NotFound).await } + /// [`Self::fetch_patch`] with each changed file's content before the + /// patch as well (`beforeBlobContent`), for showing what the patch + /// changes. The public proxy serves one cached view per patch whatever + /// the query, so its files come back without it: read those by + /// `beforeHash` ([`Self::fetch_blob`]). + pub async fn fetch_patch_with_sources( + &self, + uuid: &str, + ) -> Result, ApiError> { + let query = match &self.route { + ApiRoute::Org { .. } => "?include_before_blobs=true", + ApiRoute::Proxy => "", + }; + let path = self.patches_path(&format!("view/{uuid}{query}")); + self.get_json(&path, Bare404::NotFound).await + } + + /// Patch `uuid` without its file contents: what it fixes, when it was + /// published and what was measured about it, for a listing that names + /// many patches. The authenticated API leaves the contents out on + /// request; the public proxy serves one cached view per patch whatever + /// the query, so there this is the plain view. `Ok(None)` for a patch + /// that is not there. + pub async fn fetch_patch_summary(&self, uuid: &str) -> Result, ApiError> { + let query = match &self.route { + ApiRoute::Org { .. } => "?include_blobs=false", + ApiRoute::Proxy => "", + }; + let path = self.patches_path(&format!("view/{uuid}{query}")); + self.get_json(&path, Bare404::NotFound).await + } + + /// What Socket measured about patch `uuid` (see [`PatchStatistics`]): + /// its view without the file contents, which the authenticated API + /// leaves out on request. `Ok(None)` for a patch that is not there or + /// has not been measured. + /// + /// The public proxy serves one cached view per patch whatever the + /// query, so there the plain view is asked for: the same response a + /// download of the patch reads. + pub async fn fetch_patch_statistics( + &self, + uuid: &str, + ) -> Result, ApiError> { + let query = match &self.route { + ApiRoute::Org { .. } => "?include_blobs=false", + ApiRoute::Proxy => "", + }; + let path = self.patches_path(&format!("view/{uuid}{query}")); + let view: Option = self.get_json(&path, Bare404::NotFound).await?; + Ok(view.and_then(|view| view.statistics)) + } + /// Shared implementation for `search_patches_by_{cve,ghsa,package}`. /// `route` is the `by-` URL segment — the rest of the path layout /// is identical across the three endpoints. @@ -1005,8 +1148,23 @@ impl ApiClient { /// The PURL must be a valid Package URL starting with `pkg:`. /// Examples: `pkg:npm/lodash@4.17.21`, `pkg:pypi/django@3.2.0` pub async fn search_patches_by_package(&self, purl: &str) -> Result { - self.search_patches_by_route("by-package", purl, self.search_bare_404()) - .await + if let Some(lookups) = &self.lookups { + let held = lookups.by_package.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(answer) = held.get(purl) { + return Ok(answer.clone()); + } + } + let answer = self + .search_patches_by_route("by-package", purl, self.search_bare_404()) + .await?; + if let Some(lookups) = &self.lookups { + lookups + .by_package + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(purl.to_string(), answer.clone()); + } + Ok(answer) } /// Search patches for multiple packages (batch). @@ -1031,6 +1189,21 @@ impl ApiClient { pub async fn search_patches_batch( &self, purls: &[String], + ) -> Result { + if let Some(answer) = self.lookups.as_ref().and_then(|l| l.batch(purls)) { + return Ok(answer); + } + let answer = self.search_patches_batch_asking(purls).await?; + if let Some(lookups) = &self.lookups { + lookups.remember_batch(purls, &answer); + } + Ok(answer) + } + + /// [`Self::search_patches_batch`], always by asking the service. + async fn search_patches_batch_asking( + &self, + purls: &[String], ) -> Result { if let ApiRoute::Org { slug } = &self.route { let path = self.patches_path("batch"); @@ -6468,6 +6641,216 @@ mod authenticated_batch_tests { } } +#[cfg(test)] +mod lookup_memory_tests { + //! A client that remembers its lookups answers a search it has the + //! whole answer to without a request, and asks for everything else as + //! if it remembered nothing. + use super::*; + use serde_json::json; + use wiremock::matchers::{method, path, path_regex}; + use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + + fn org_client(uri: String) -> ApiClient { + ApiClient::new(ApiClientOptions { + api_url: uri, + api_token: Some("sktsec_token_placeholder_value_api".into()), + route: ApiRoute::org("acme"), + }) + } + + fn purls(names: &[&str]) -> Vec { + names + .iter() + .map(|name| format!("pkg:npm/{name}@1.0.0")) + .collect() + } + + /// A batch endpoint that reports one patch for every asked purl whose + /// name starts with `patched`, spelled as it was asked. + async fn batch_server() -> MockServer { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/batch")) + .respond_with(|request: &Request| { + let body: serde_json::Value = request.body_json().unwrap(); + let packages: Vec = body["components"] + .as_array() + .unwrap() + .iter() + .filter_map(|c| c["purl"].as_str()) + .filter(|purl| purl.contains("/patched")) + .map(|purl| { + json!({ "purl": purl, "patches": [{ + "uuid": "11111111-2222-4333-8444-555555555555", + "purl": purl, + "tier": "free", + "cveIds": ["CVE-2026-0001"], + "ghsaIds": [], + "severity": "high", + "title": "A patch", + }]}) + }) + .collect(); + ResponseTemplate::new(200) + .set_body_json(json!({ "packages": packages, "canAccessPaidPatches": true })) + }) + .mount(&server) + .await; + server + } + + async fn requests(server: &MockServer) -> usize { + server.received_requests().await.unwrap_or_default().len() + } + + #[tokio::test] + async fn a_batch_search_it_has_the_whole_answer_to_makes_no_request() { + let server = batch_server().await; + let client = org_client(server.uri()).remembering_lookups(); + let first = purls(&["plain-a", "patched-b", "plain-c", "patched-d"]); + let answer = client.search_patches_batch(&first).await.unwrap(); + assert_eq!(answer.packages.len(), 2); + assert_eq!(requests(&server).await, 1); + + // The same question, a part of it, and its purls in another order: + // answered from memory, packages in the order asked, with the + // response's paid flag. A clone shares the memory. + for asked in [ + first.clone(), + purls(&["patched-d", "plain-a"]), + purls(&["patched-d", "patched-b", "patched-d"]), + ] { + let again = client.clone().search_patches_batch(&asked).await.unwrap(); + let expected: Vec<&String> = { + let mut seen = HashSet::new(); + asked + .iter() + .filter(|purl| purl.contains("/patched") && seen.insert(purl.as_str())) + .collect() + }; + assert_eq!( + again.packages.iter().map(|p| &p.purl).collect::>(), + expected + ); + assert!(again.can_access_paid_patches); + assert!(again.unanswered.is_empty()); + } + assert_eq!(requests(&server).await, 1, "nothing was asked again"); + + // A question with a purl it has no answer for is sent whole. + let wider = purls(&["plain-a", "patched-new"]); + let answer = client.search_patches_batch(&wider).await.unwrap(); + assert_eq!(answer.packages.len(), 1); + assert_eq!(requests(&server).await, 2); + let sent = server.received_requests().await.unwrap(); + let body: serde_json::Value = sent[1].body_json().unwrap(); + assert_eq!(body["components"].as_array().unwrap().len(), 2); + // And is then remembered too. + client.search_patches_batch(&wider).await.unwrap(); + assert_eq!(requests(&server).await, 2); + } + + /// A client is forgetful unless told otherwise: every search is a + /// request, as it always was. + #[tokio::test] + async fn a_plain_client_asks_every_time() { + let server = batch_server().await; + let client = org_client(server.uri()); + let asked = purls(&["patched-a"]); + client.search_patches_batch(&asked).await.unwrap(); + client.search_patches_batch(&asked).await.unwrap(); + assert_eq!(requests(&server).await, 2); + } + + /// An answer is kept only for exactly the purl it was given for. A + /// response that names a package by another spelling than it was + /// asked with keeps nothing: which answer is which question's would be + /// a guess. + #[tokio::test] + async fn a_response_in_another_spelling_is_not_remembered() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/batch")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [{ "purl": "pkg:npm/@scope/name@1.0.0", "patches": [] }], + "canAccessPaidPatches": false + }))) + .mount(&server) + .await; + let client = org_client(server.uri()).remembering_lookups(); + let asked = vec!["pkg:npm/%40scope/name@1.0.0".to_string()]; + client.search_patches_batch(&asked).await.unwrap(); + client.search_patches_batch(&asked).await.unwrap(); + assert_eq!(requests(&server).await, 2); + } + + /// A failed search is not an answer: it is asked again. + #[tokio::test] + async fn a_failure_is_not_remembered() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/batch")) + .respond_with(ResponseTemplate::new(500).set_body_string("boom")) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/batch")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [], + "canAccessPaidPatches": false + }))) + .mount(&server) + .await; + let client = org_client(server.uri()).remembering_lookups(); + let asked = purls(&["plain-a"]); + assert!(client.search_patches_batch(&asked).await.is_err()); + assert!(client.search_patches_batch(&asked).await.is_ok()); + assert!(client.search_patches_batch(&asked).await.is_ok()); + assert_eq!(requests(&server).await, 2); + } + + #[tokio::test] + async fn a_package_search_is_asked_once() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path_regex("^/v0/orgs/acme/patches/by-package/.+")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "patches": [], + "canAccessPaidPatches": true + }))) + .mount(&server) + .await; + let client = org_client(server.uri()).remembering_lookups(); + for _ in 0..3 { + let answer = client + .search_patches_by_package("pkg:npm/a@1.0.0") + .await + .unwrap(); + assert!(answer.can_access_paid_patches); + } + assert_eq!(requests(&server).await, 1); + // Another package is another question. + client + .search_patches_by_package("pkg:npm/b@1.0.0") + .await + .unwrap(); + assert_eq!(requests(&server).await, 2); + // A plain client asks each time. + let plain = org_client(server.uri()); + plain + .search_patches_by_package("pkg:npm/a@1.0.0") + .await + .unwrap(); + plain + .search_patches_by_package("pkg:npm/a@1.0.0") + .await + .unwrap(); + assert_eq!(requests(&server).await, 4); + } +} + #[cfg(test)] mod not_found_tests { //! A 404 reads as "not there" only when the patch service says so. A diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index 3ee1cb5cc..8587704c4 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -46,6 +46,128 @@ pub struct PatchResponse { pub description: String, pub license: String, pub tier: String, + /// What Socket measured about the patch, when it has been measured. + /// Read leniently ([`lenient`]): the measurements are shown beside a + /// patch and nothing depends on them, so a `statistics` object this + /// build cannot read is one it does not show, never a patch view it + /// cannot read. Reading the view is how a patch is downloaded. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "lenient_object" + )] + pub statistics: Option, +} + +/// Deserialize an optional part of a response that nothing depends on: +/// whatever does not read as a `T` (a `null`, another shape, a number out +/// of range) is `None`, where the derived reading would fail the whole +/// response it is part of. +fn lenient<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: serde::de::DeserializeOwned, +{ + let value = Option::::deserialize(deserializer)?; + Ok(value.and_then(|value| serde_json::from_value(value).ok())) +} + +/// [`lenient`] for a part that is an object: anything else is `None` (a +/// derived struct would also read from an array, field by field). +fn lenient_object<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: serde::de::DeserializeOwned, +{ + let value = Option::::deserialize(deserializer)?; + Ok(value + .filter(serde_json::Value::is_object) + .and_then(|value| serde_json::from_value(value).ok())) +} + +/// `count` of `total`: tests that passed, exploits that reproduced or +/// were blocked. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct PatchRatio { + pub count: u64, + pub total: u64, +} + +impl PatchRatio { + /// Every one of them: all the tests passed, every exploit was blocked. + pub fn is_all(&self) -> bool { + self.total > 0 && self.count == self.total + } +} + +/// How large a patch is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PatchDiffSize { + pub lines_added: u64, + pub lines_removed: u64, + pub files_changed: u64, +} + +/// The package's own test suites, run on the unpatched release (`before`, +/// absent when a suite has no such run) and on the patched one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct PatchTestRuns { + #[serde(default)] + pub before: Option, + pub after: PatchRatio, +} + +/// The proof-of-concept exploits of the advisories a patch fixes: how many +/// reproduced on the unpatched release (absent when one has no such run), +/// and how many the patch blocks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PatchExploitRuns { + #[serde(default)] + pub reproduced_before: Option, + pub blocked_after: PatchRatio, +} + +/// What a patch costs at run time, each a relative change against the +/// unpatched release (`0.05` is 5% more): wall time of the package's +/// general workload and of the code the patch touches, and peak memory. +#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct PatchPerformance { + pub general_wall_change: Option, + pub hot_wall_change: Option, + pub peak_mem_change: Option, +} + +/// What Socket measured about one patch: the view endpoint's `statistics`. +/// Every part is optional, since a patch is measured in stages (and an +/// older patch may never have been), and each is read on its own +/// ([`lenient`]): a part that does not read (a run with no result yet) +/// is left out, and the others still show. +#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct PatchStatistics { + #[serde(deserialize_with = "lenient_object")] + pub diff: Option, + #[serde(deserialize_with = "lenient")] + pub functions_changed: Option, + #[serde(deserialize_with = "lenient_object")] + pub tests: Option, + #[serde(deserialize_with = "lenient_object")] + pub pocs: Option, + #[serde(deserialize_with = "lenient_object")] + pub performance: Option, +} + +/// The one field [`ApiClient::fetch_patch_statistics`] reads of a patch +/// view. +/// +/// [`ApiClient::fetch_patch_statistics`]: crate::api::client::ApiClient::fetch_patch_statistics +#[derive(Debug, Clone, Deserialize)] +pub(crate) struct PatchStatisticsView { + #[serde(default, deserialize_with = "lenient_object")] + pub statistics: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -227,6 +349,83 @@ where mod tests { use super::*; + fn view(statistics: serde_json::Value) -> serde_json::Value { + serde_json::json!({ + "uuid": "11111111-1111-4111-8111-111111111111", + "purl": "pkg:npm/a@1.0.0", + "publishedAt": "2026-01-01T00:00:00Z", + "files": {}, + "vulnerabilities": {}, + "description": "", + "license": "MIT", + "tier": "free", + "statistics": statistics, + }) + } + + /// The measurements ride the patch view a download reads. Whatever + /// shape they come in, the view still reads: a part this build cannot + /// read is left out and the others are kept, and a `statistics` that + /// is not an object at all is no measurements. + #[test] + fn statistics_this_build_cannot_read_never_fail_the_patch_view() { + use serde_json::json; + let whole = json!({ + "diff": { "linesAdded": 9, "linesRemoved": 2, "filesChanged": 2 }, + "functionsChanged": 3, + "tests": { "before": { "count": 24, "total": 25 }, "after": { "count": 25, "total": 25 } }, + "pocs": { "reproducedBefore": { "count": 1, "total": 1 }, "blockedAfter": { "count": 1, "total": 1 } }, + "performance": { "hotWallChange": 0.036 }, + }); + let patch: PatchResponse = serde_json::from_value(view(whole)).unwrap(); + let stats = patch.statistics.expect("measured"); + assert_eq!(stats.diff.map(|d| d.lines_added), Some(9)); + assert_eq!(stats.functions_changed, Some(3)); + assert!(stats.tests.is_some_and(|t| t.after.is_all())); + assert!(stats.pocs.is_some_and(|p| p.blocked_after.is_all())); + + // A patch measured in stages: runs with no result yet, a size + // missing a field, a count that is not a count. + let partial = json!({ + "diff": { "linesAdded": 9, "linesRemoved": 2 }, + "functionsChanged": -1, + "tests": { "before": { "count": 24, "total": 25 }, "after": null }, + "pocs": { "reproducedBefore": { "count": 1, "total": 1 }, "blockedAfter": { "count": 1.5, "total": 1 } }, + "performance": { "hotWallChange": 0.036 }, + "somethingNew": [1, 2, 3], + }); + let patch: PatchResponse = serde_json::from_value(view(partial)).unwrap(); + let stats = patch.statistics.expect("the parts that read are kept"); + assert_eq!(stats.diff, None); + assert_eq!(stats.functions_changed, None); + assert_eq!(stats.tests, None); + assert_eq!(stats.pocs, None); + assert_eq!( + stats.performance.and_then(|p| p.hot_wall_change), + Some(0.036) + ); + + for odd in [ + json!(null), + json!("soon"), + json!([1, 2]), + json!(7), + json!({}), + ] { + let patch: PatchResponse = serde_json::from_value(view(odd.clone())).unwrap(); + let expected = (odd == json!({})).then(PatchStatistics::default); + assert_eq!(patch.statistics, expected, "{odd}"); + let only: PatchStatisticsView = + serde_json::from_value(json!({ "statistics": odd })).unwrap(); + assert_eq!(only.statistics, expected); + } + // No `statistics` at all, as before this field existed. + let mut bare = view(json!(null)); + bare.as_object_mut().unwrap().remove("statistics"); + let patch: PatchResponse = serde_json::from_value(bare).unwrap(); + assert_eq!(patch.statistics, None); + } + // The structs are serde DTOs: these pin the JSON field-name contract by // deserializing payloads in the exact shape the live endpoints emit. diff --git a/crates/socket-patch-core/src/crawlers/walk_pool.rs b/crates/socket-patch-core/src/crawlers/walk_pool.rs index 1c3955595..103d86235 100644 --- a/crates/socket-patch-core/src/crawlers/walk_pool.rs +++ b/crates/socket-patch-core/src/crawlers/walk_pool.rs @@ -123,6 +123,13 @@ fn read_soft_nofile_limit() -> Option { None } +/// How many threads a directory walk outside the pool should use: the +/// pool's own count, which the measurements above settled (one under a +/// tight descriptor limit). +pub(crate) fn threads() -> usize { + walk_pool().map_or(1, rayon::ThreadPool::current_num_threads) +} + /// Whether the descriptor limit is too tight for concurrent crawling (see /// the module docs). The ecosystem dispatch then runs the crawlers one at /// a time, and the walk pool has a single thread. diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index bac1359c4..a73175e7e 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -199,6 +199,33 @@ pub(crate) fn strip_pnpm_peer_suffix(key: &str) -> &str { key.find('(').map_or(key, |p| key[..p].trim_end()) } +/// Whether a pnpm packages or snapshots key records a patch of the package +/// it names. pnpm 8+ writes that as a group of the key's own: +/// `a@1.0.0(patch_hash=…)`. A dependent repeats a patched peer's whole key +/// inside its peer group (`b@2.0.0(a@1.0.0(patch_hash=…))`), which says +/// nothing about `b`: only a group at the first level counts. A pnpm 7 key +/// has no groups and carries the hash on its version (`/a/1.0.0_…`). +pub(crate) fn pnpm_key_has_own_patch(key: &str) -> bool { + const HASH: &str = "patch_hash="; + if !key.contains('(') { + return key.contains(HASH); + } + let mut depth = 0usize; + for (at, c) in key.char_indices() { + match c { + '(' => { + if depth == 0 && key[at + 1..].starts_with(HASH) { + return true; + } + depth += 1; + } + ')' => depth = depth.saturating_sub(1), + _ => {} + } + } + false +} + /// `(name, version)` of a REGISTRY-form pnpm packages key, in every lock /// generation's grammar — v9 `name@version`, v6 (pnpm 8) the same behind a /// leading `/`, v5.4 (pnpm 7) and shrinkwrap `/name/version`; names may be diff --git a/crates/socket-patch-core/src/hosted/memory/roots.rs b/crates/socket-patch-core/src/hosted/memory/roots.rs index 36bcc9d42..f21d0bcec 100644 --- a/crates/socket-patch-core/src/hosted/memory/roots.rs +++ b/crates/socket-patch-core/src/hosted/memory/roots.rs @@ -218,8 +218,11 @@ const MAX_WALKED_ENTRIES: usize = 500_000; /// read. A marker that is itself a symlink still counts, as it does for /// the root the user names. fn marker_paths_below(dir: &std::path::Path) -> (Vec, bool) { - let walk = ignore::WalkBuilder::new(dir) - .hidden(false) + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::Mutex; + + let mut walk = ignore::WalkBuilder::new(dir); + walk.hidden(false) .ignore(false) .follow_links(false) .filter_entry(|entry| { @@ -233,33 +236,56 @@ fn marker_paths_below(dir: &std::path::Path) -> (Vec, bool) { let other_repository = entry.depth() > 0 && entry.path().join(".git").symlink_metadata().is_ok(); !excluded && !other_repository + }); + // The walk is a hosted or vendored scan's first wait in a large + // checkout (it looks for its project directories before anything + // else), and it is all directory reads: they run on as many threads as + // the crawl's walk does (one where file descriptors are scarce). + walk.threads(crate::crawlers::walk_pool::threads()); + let seen = AtomicUsize::new(0); + let truncated = AtomicBool::new(false); + let markers: Mutex> = Mutex::new(Vec::new()); + walk.build_parallel().run(|| { + Box::new(|entry| { + let Ok(entry) = entry else { + return ignore::WalkState::Continue; + }; + if seen.fetch_add(1, Ordering::Relaxed) >= MAX_WALKED_ENTRIES { + truncated.store(true, Ordering::Relaxed); + return ignore::WalkState::Quit; + } + if entry.file_type().is_none_or(|t| t.is_dir()) { + return ignore::WalkState::Continue; + } + let is_marker = entry + .file_name() + .to_str() + .is_some_and(|base| marker_ecosystem(base).is_some()); + if !is_marker { + return ignore::WalkState::Continue; + } + let Ok(rel) = entry.path().strip_prefix(dir) else { + return ignore::WalkState::Continue; + }; + // A path that is not UTF-8 names no root a `/`-joined list can + // hold. + let segments: Option> = rel.iter().map(|segment| segment.to_str()).collect(); + if let Some(segments) = segments { + markers + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(segments.join("/")); + } + ignore::WalkState::Continue }) - .build(); - let mut markers: Vec = Vec::new(); - for (seen, entry) in walk.flatten().enumerate() { - if seen >= MAX_WALKED_ENTRIES { - return (markers, true); - } - if entry.file_type().is_none_or(|t| t.is_dir()) { - continue; - } - let is_marker = entry - .file_name() - .to_str() - .is_some_and(|base| marker_ecosystem(base).is_some()); - if !is_marker { - continue; - } - let Ok(rel) = entry.path().strip_prefix(dir) else { - continue; - }; - // A path that is not UTF-8 names no root a `/`-joined list can hold. - let segments: Option> = rel.iter().map(|segment| segment.to_str()).collect(); - if let Some(segments) = segments { - markers.push(segments.join("/")); - } - } - (markers, false) + }); + let mut markers = markers + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + // The threads finish in no particular order; the list is the same + // whatever it was. + markers.sort(); + (markers, truncated.load(Ordering::Relaxed)) } /// The project roots at and below `dir` on disk, so a disk scan and the diff --git a/crates/socket-patch-core/src/patch/user_patches.rs b/crates/socket-patch-core/src/patch/user_patches.rs index f981d270e..2f4ab759f 100644 --- a/crates/socket-patch-core/src/patch/user_patches.rs +++ b/crates/socket-patch-core/src/patch/user_patches.rs @@ -876,14 +876,18 @@ impl UserPatchIndex { } } - /// The pnpm lock entries pnpm patches: a `(patch_hash=…)` key suffix, - /// or an older lock's `patched: true`. + /// The pnpm lock entries pnpm patches: a key with a `(patch_hash=…)` + /// group of its own, or an older lock's `patched: true`. A key that + /// only repeats a patched peer's hash names a package pnpm installs + /// unpatched. fn pnpm_lock_patches(&mut self, value: &Value, path: &Path) { // Older pnpm locks can carry patch hashes without a mirrored map. for field in ["packages", "snapshots"] { if let Some(map) = value[field].as_object() { for (key, entry) in map { - if key.contains("patch_hash=") || !entry["patched"].is_null() { + if crate::formats::pnpm::pnpm_key_has_own_patch(key) + || !entry["patched"].is_null() + { if let Some((name, version)) = crate::formats::pnpm::pnpm_registry_key(key) { self.add("npm", name, Some(version), path); @@ -1420,6 +1424,37 @@ mod tests { } } + /// REGRESSION: pnpm repeats a patched package's whole key, hash and + /// all, inside the peer group of every package that depends on it + /// (`@redis/json@1.0.7(@redis/client@1.6.0(patch_hash=…))`). Each of + /// those dependents was read as patched by the project, so a scan left + /// dozens of packages the project never touched without their fixes. + #[tokio::test] + async fn a_patched_peer_in_a_pnpm_key_does_not_protect_the_dependent() { + for text in [ + "lockfileVersion: '9.0'\nsnapshots:\n \ + '@redis/client@1.6.0(patch_hash=abc)': {}\n \ + '@redis/json@1.0.7(@redis/client@1.6.0(patch_hash=abc))': {}\n \ + 'next-intl@4.11.2(@swc/helpers@0.5.23)(next@16.4.5(patch_hash=def)(react@19.0.0))(react@19.0.0)': {}\n \ + 'both@3.0.0(patch_hash=ghi)(@redis/client@1.6.0(patch_hash=abc))': {}\n", + "lockfileVersion: '6.0'\npackages:\n \ + /@redis/client@1.6.0(patch_hash=abc): {}\n \ + /@redis/json@1.0.7(@redis/client@1.6.0(patch_hash=abc)): {}\n \ + /next-intl@4.11.2(next@16.4.5(patch_hash=def)): {}\n \ + /both@3.0.0(patch_hash=ghi)(@redis/client@1.6.0(patch_hash=abc)): {}\n", + ] { + let tmp = tempfile::tempdir().unwrap(); + write(tmp.path(), "pnpm-lock.yaml", text); + let index = UserPatchIndex::discover(tmp.path()).await; + for purl in ["pkg:npm/%40redis/client@1.6.0", "pkg:npm/both@3.0.0"] { + assert!(!index.conflicts(purl).is_empty(), "{purl}: {index:?}"); + } + for purl in ["pkg:npm/%40redis/json@1.0.7", "pkg:npm/next-intl@4.11.2"] { + assert!(index.conflicts(purl).is_empty(), "{purl}: {index:?}"); + } + } + } + #[tokio::test] async fn pnpm_all_versions_selector_protects_prereleases() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/socket-patch-core/src/policy/filter.rs b/crates/socket-patch-core/src/policy/filter.rs index 05bc8dfe6..b8293c3a7 100644 --- a/crates/socket-patch-core/src/policy/filter.rs +++ b/crates/socket-patch-core/src/policy/filter.rs @@ -537,17 +537,29 @@ impl SelectionFilter { .max() } - /// Why the advisory known by `ids` (its id and CVE aliases, canonical - /// spelling) needs no fix on `purl`; `None` when it does. - fn dropped( + /// Whether the file holds any reachability finding. + pub fn has_findings(&self) -> bool { + self.finding_count > 0 + } + + /// The state of the finding that decides the advisory known by `ids` + /// (its id and CVE aliases, any spelling) on `purl`: the most specific + /// finding, the most cautious of equally specific ones. `None` when no + /// finding covers it. `skip.advisories` is not consulted: a skipped + /// advisory keeps the state its findings give it. + pub fn reachability(&self, purl: &str, ids: &[String]) -> Option { + let ids: Vec = ids.iter().map(|id| canonical_id(id)).collect(); + self.finding_state(purl, &ids, self.package_state(purl)) + } + + /// [`Self::reachability`] over canonical `ids`, with the package-only + /// findings already matched (`package_state`). + fn finding_state( &self, purl: &str, ids: &[String], package_state: Option, - ) -> Option { - if ids.iter().any(|id| self.skip_advisories.contains(id)) { - return Some(Dropped::Skipped); - } + ) -> Option { // `Option`'s order puts `None` below every state. let mut for_package: Option = None; let mut anywhere: Option = None; @@ -564,7 +576,21 @@ impl SelectionFilter { None => anywhere = anywhere.max(Some(*state)), } } - match for_package.or(anywhere).or(package_state) { + for_package.or(anywhere).or(package_state) + } + + /// Why the advisory known by `ids` (its id and CVE aliases, canonical + /// spelling) needs no fix on `purl`; `None` when it does. + fn dropped( + &self, + purl: &str, + ids: &[String], + package_state: Option, + ) -> Option { + if ids.iter().any(|id| self.skip_advisories.contains(id)) { + return Some(Dropped::Skipped); + } + match self.finding_state(purl, ids, package_state) { Some(Reachability::Unreachable) => Some(Dropped::Unreachable), Some(Reachability::Reachable | Reachability::Unknown) => None, None => match self.unlisted { @@ -1071,6 +1097,46 @@ mod tests { assert!(needs_all(&f, &elsewhere)); } + /// The report's lookup: the deciding finding's state, by any spelling + /// of the advisory's id or a CVE alias, and `None` where no finding + /// reaches. A skipped advisory keeps its finding's state. + #[test] + fn reachability_reports_the_deciding_findings_state() { + let ids = |ids: &[&str]| ids.iter().map(|id| id.to_string()).collect::>(); + let none = filter(r#"{"version": 1, "skip": {"advisories": ["CVE-2021-23337"]}}"#); + assert!(!none.has_findings()); + assert_eq!(none.reachability(LODASH, &ids(&[A])), None); + + let f = filter(&format!( + r#"{{"version": 1, "skip": {{"advisories": ["{B}"]}}, "reachability": [ + {{"package": "pkg:npm/minimist", "state": "unreachable"}}, + {{"advisory": "{A}", "state": "unknown"}}, + {{"advisory": "CVE-2021-23337", "package": "pkg:npm/lodash", "state": "reachable"}}, + {{"advisory": "{B}", "state": "reachable"}} + ]}}"# + )); + assert!(f.has_findings()); + assert_eq!( + f.reachability(LODASH, &ids(&[A])), + Some(Reachability::Unknown) + ); + // An alias in another spelling finds the package-specific finding, + // which outranks the advisory-wide one. + assert_eq!( + f.reachability(LODASH, &ids(&[&A.to_lowercase(), "cve-2021-23337"])), + Some(Reachability::Reachable) + ); + assert_eq!( + f.reachability("pkg:npm/minimist@1.2.5", &ids(&["GHSA-cccc-cccc-cccc"])), + Some(Reachability::Unreachable) + ); + assert_eq!(f.reachability(LODASH, &ids(&["GHSA-cccc-cccc-cccc"])), None); + assert_eq!( + f.reachability(LODASH, &ids(&[B])), + Some(Reachability::Reachable) + ); + } + #[test] fn among_equally_specific_findings_the_most_cautious_wins() { let f = filter(&format!( diff --git a/docs/configuration.md b/docs/configuration.md index 293882ed9..5c25ead05 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -59,6 +59,15 @@ Empty environment values are treated as unset. and refuse offline operation. Other commands can use locally available state; missing records or artifacts can still prevent completion. - `SOCKET_NO_UPDATE_CHECK=1` disables the passive update notice. +- A command an AI coding agent runs gets plain output even on a terminal: no + animated status line, no color, no full-screen `list` or `show`, no arrow-key + menus. It is what a pipe gets, so an agent's context holds the results and + nothing else. Agents are recognized by the variables they set for the commands + they run (`AI_AGENT`, `CLAUDECODE`, `CURSOR_AGENT`, `CODEX_SANDBOX`, + `GEMINI_CLI`, `VSCODE_AGENT` and others). `SOCKET_PLAIN=1` asks for the same + output anywhere, and `SOCKET_PLAIN=0` keeps the full terminal output for a + person working in a terminal an agent started. Yes/no confirmations are not + affected: `--yes` is what answers them. For other settings, precedence is flag → environment → default, except for the repository policy scalars below. Socket Patch does not automatically load `.env` diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 997f141c6..004f71977 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -533,8 +533,8 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: them where they are installed. - **A hosted or vendored package disappears from `bun audit` and `bun outdated`.** Bun checks registry resolutions only, so it stops reporting the package at all, including - advisories the applied patch does not fix. `socket-patch scan` lists those as - `still unpatched`. + advisories the applied patch does not fix. `socket-patch scan` counts those on the + package's row (`2 unpatched`) and names them under `--verbose`. In vendored mode the patched tarballs are files in the repository, so a build that copies only `package.json` and `bun.lock` before `bun install` (a common Dockerfile diff --git a/docs/usage.md b/docs/usage.md index 2972e0dd0..95cae7ff8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -41,6 +41,10 @@ reach (their own `vendor/bundle` or `.venv`, for example), it lists them in the warning with the command to run for one of them (`socket-patch scan --mode agent --cwd `). Run it once per directory. +A scan of several project directories crawls them all at once and asks the patch +service about each package once for the whole run, then reports the directories one +by one, in order. + What that scan patched can be seen and undone from the same directory. `list` shows the patches of the current directory (headed `== . ==`, as in the scan) and of each patched project directory below it, and `rollback` with no target rolls all of them @@ -80,15 +84,47 @@ is available. See the [ranking contract](../crates/socket-patch-cli/CLI_CONTRACT for tie-breaking and upgrade rules. One patch is applied per package version. When a package has several patches for -different advisories, `scan` applies the top-ranked one and names the rest: +different advisories, `scan` applies the top-ranked one. Each patched package gets +one row (its severity, what the patch fixes, and how many advisories stay unpatched), +and the run closes with its totals: ```text Switched 1 package to hosted patches; rewrote 1 file. - pkg:pypi/urllib3@1.26.18: fixes CVE-2025-66418; still unpatched: CVE-2025-66471, CVE-2026-21441 -Only one patch is applied per package version. Upgrade the package to fix the advisories still unpatched. + HIGH urllib3@1.26.18 CVE-2025-66418 2 unpatched + +Patched 1 package, fixing 1 vulnerability (1 high). +Saved about 2 hours of engineering time (1 package upgrade at ~2 hours). +2 vulnerabilities left to patch (67%): 2 need a package upgrade. ``` -`scan --json` lists the same ids as `packages[].fixedIds` and `packages[].unfixedIds`. +`--verbose` names the unpatched advisories under the row, and `scan --json` lists the +same ids as `packages[].fixedIds` and `packages[].unfixedIds`. With several project +directories the totals count every one (`Patched 22 packages in 3 projects, ...`): a +package patched in three projects counts three times. "Left to patch" counts only +advisories Socket has a patch for; it says nothing about vulnerabilities with no patch. + +The `Saved about N hours` line is an estimate of the upgrade work the patches stood +in for: two hours for each patched package in each project directory. The two hours +are an assumption (finding a fixed release, moving to it, fixing what else changed, +review), not a measurement of your project. + +On a terminal, `scan` also shows what Socket measured about each patch (the exploits +of the fixed advisories blocked, the package's own tests passing) in its row and in a +`Verified:` closing line. `socket-patch show ` prints the full measurements and +the patch's diff. + +A package your project already patches itself (pnpm `patchedDependencies`, a Yarn +`patch:` entry, patch-package, a Cargo `[patch]`, a Go `replace`, Composer patches) is +left alone, and the scan says so in one note that names the files and the first few +packages: + +```text +Note: skipped 3 packages covered by this project's own patches (pnpm-workspace.yaml): next@16.4.5, next-auth@4.24.15, ts-node@10.9.2. + --allow-patch-conflicts patches them too. +``` + +`--verbose` lists every package of a longer note. `--allow-patch-conflicts` applies +Socket's patch on top of yours; review and test the result. ## CI and automation @@ -224,6 +260,19 @@ ledger when offline attestation is required. A reference no longer used by the project is excluded even with `--no-verify`; that flag bypasses file-hash checks, not reference validation. A patch record alone does not prove it is consumed. +A patch that cannot be attested is left out of the document, and the run says which +and why on stderr, one line per reason: + +```text +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) +Error: No applied patches with vulnerability metadata to attest. +The patched packages are not installed yet: the installed copies still hold their original files. Reinstall from the lockfile (hosted or vendored patches) or run `socket-patch apply` (agent-mode patches), then run `socket-patch vex` again. +``` + +`--verbose` prints a line per patch, and `--json` reports each one as its own +`skipped` event. Warnings of one kind are folded the same way: the first in full, +then a line naming the packages the rest are about. + `--no-verify` (or `SOCKET_VEX_NO_VERIFY` in the environment) attests without checking any file, so it also attests an agent-mode patch whose files are unpatched or missing. It never does so silently: the run warns how many statements it emitted that way, and @@ -267,13 +316,32 @@ The removed `setup` command is covered in the [migration guide](migrating-to-v5. | Command | Effect | | --- | --- | -| `list` | Show agent records, vendor records, and hosted pins; an empty project succeeds | +| `list` | Show agent records, vendor records, and hosted pins; an empty project succeeds. On a terminal: a full-screen table of the patches, with what was measured about each, to open one from (see below) | +| `show ` | Look inside one patch without applying it: the advisories it fixes, what Socket measured about it (exploits blocked, tests passing, size, run-time cost), the files it changes and their diffs | | `rollback [NAME\|PURL\|UUID\|PATH]...` | Restore selected patches, or all patches when no target is given, and remove their local state | | `remove ` | Restore and remove matching patches; a name or versionless PURL selects every recorded version | | `vendor --revert` | Undo vendoring from its recorded edits and remove the vendored artifacts | | `repair` | Restore missing or corrupt agent patch data and vendored artifacts using existing records, and clean unused data | | `scan --mode agent --prune` | Patch discovered packages and remove records for dependencies that left the project | +`show` reads the patch from the patch service and changes nothing. In a terminal it +opens the patch full-screen: the fixes, what Socket measured (exploits blocked, tests +passing before and after, size, run-time cost) and then the diff of every file. Scroll +with the arrow keys or `j`/`k`, page with PgUp/PgDn, step between files with `n` and +`p`, shift long lines with the left and right arrows, and leave with `q`. `--stat` +stops after the summary, `--file ` picks files, and `--no-pager` (or a pipe) +prints everything at once. + +In a terminal, `list` shows the project's patches as a full-screen table: severity +(colored), package, the advisories fixed, and, filled in from the patch service as it +answers, exploits blocked, tests passing, lines changed, run-time cost and the date +the patch was published. Move with the arrow keys or `j`/`k`, page with PgUp/PgDn, +press Enter to open a patch (the same page `show` opens) and `q` or Esc to leave. The +table follows the terminal's size, and leaving it prints the rows so the listing +stays on screen. `list --verbose`, `list --yes` and a piped `list` print every +patch's full entry instead and ask the patch service nothing; so does `--offline`, +which browses what the project records. + Use `--dry-run` to preview. `rollback --preserve-state` and `remove --preserve-state` restore dependencies while keeping local patch records and artifacts for later reuse. Hosted pins have no local state to preserve.