diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 81188b146..87ee2a119 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -311,7 +311,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | `get` | positional `identifier`; `--id` / `--cve` / `--ghsa` / `--package` (`-p`); `--save-only`; `--mode ` | `SOCKET_SAVE_ONLY` | Patch lookup + consumption mode (v3.6). `--mode` reuses scan's value enum (same hidden value aliases `host`/`redirect`/`vendor`; deliberately no env binding, matching scan). Default (v5.0): the mode the project's patch state records, like scan (see **Mode resolution**), so `hosted` for a project with no state; `agent` (save + apply in place) when `--save-only` or `--global`/`--global-prefix` is given. An explicit `--mode hosted\|vendored` with `--global`/`--global-prefix` is a usage error (exit 2, scan's wording: global installs have no project lockfile). An explicit `--save-only` conflicts with `--mode hosted\|vendored` — rejected with **exit 1** via get's established self-enforced-conflict style (unlike scan's exit-2 mode conflicts; see the exit-code table) | | `remove` | positional `identifier` (target grammar: UUID, PURL with or without version, or exact package name); `--skip-rollback`; `--preserve-state` (v5.0) | `SOCKET_SKIP_ROLLBACK`, `SOCKET_PRESERVE_STATE` | Manifest entry removal. The identifier matches like a `rollback` target (a PyPI name compares by its PEP 503 canonical form). `--preserve-state` is the single-patch twin of `rollback --preserve-state`: restore the tree and unwind the identifier's vendored/hosted wiring, but keep the manifest entry, the vendored artifact + ledger entry, and skip all GC. Combining it with `--skip-rollback` is a self-enforced usage error (exit 2): one flag keeps the tree and drops the state, the other restores the tree and keeps the state — together they select the do-nothing quadrant ("the combination would be a no-op: nothing would change"). The conflict fires whether either flag is spelled on the command line or sourced from its env var | | `rollback` | optional variadic positional `targets` (PURL \| UUID \| package name \| path glob); `--preserve-state` (v5.0) | `SOCKET_PRESERVE_STATE` | Rollback scope. Multiple targets union. A token becomes a path glob ONLY when it is path-SHAPED — contains a separator (`/` or `\`) or a glob metacharacter (`*?[`), or starts with `./`, or is absolute (an npm `@scope/name` is a name, not a path; a relative slash name without glob metacharacters or `.`/`..` segments — composer `vendor/pkg`, a go module path — is a name when it selects a recorded or hosted patch); a `pkg:` prefix is a PURL and every other token keeps the target grammar (UUID, PURL or exact package name), so a mistyped identifier or truncated UUID stays a safe exit-1 "No patch found matching identifier: X" (with a hint suggesting `./X` or `X/**` for directory targeting) instead of silently becoming a path scope. An unparseable glob is a usage error (exit 2) | -| `vex` | `--output` / `-O`, `--product`, `--no-verify`, `--no-bazel`, `--doc-id`, `--compact` | `SOCKET_VEX_OUTPUT`, `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT` | OpenVEX 0.2.0 document generation; see "vex output channels" below. `--no-bazel` is **Experimental** (Bazel workspaces) | +| `vex` | `--output` / `-O`, `--product`, `--no-verify`, `--no-bazel`, `--doc-id`, `--compact`, `--grype-config []` | `SOCKET_VEX_OUTPUT`, `SOCKET_VEX_PRODUCT`, `SOCKET_VEX_NO_VERIFY`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_VEX_DOC_ID`, `SOCKET_VEX_COMPACT`, `SOCKET_VEX_GRYPE_CONFIG` | OpenVEX 0.2.0 document generation; see "vex output channels" below. `--grype-config` lists the document in a Grype config (see "Grype config" below). `--no-bazel` is **Experimental** (Bazel workspaces) | | `repair` | `--download-only` | `SOCKET_DOWNLOAD_ONLY` | Repair-specific cleanup mode (mutually exclusive with `--offline`; combining them is a usage error, exit 2) | **pnpm hosted-mode contract**: `scan --mode hosted` handles block and flow resolutions in legacy `shrinkwrap.yaml` and lockfileVersion 5.x, 6.0, and 9.0. The [pinned compatibility matrix](../../docs/testing/pnpm-compatibility.md) samples pnpm majors 1–12. Early shrinkwrapVersion 3 without a positive minor version is refused with `redirect_pnpm_legacy_lockfile_unsupported`: pnpm 1.0.0 discards hosted URLs even on frozen installs. Upgrade to a tested release (1.43.1 or newer) and regenerate the lock, or use agent mode. @@ -2782,6 +2782,7 @@ outcome for a selected record, rather than inferring a write from exit 0. | `invalid_env` | scan | Usage error (exit 2): a malformed `SOCKET_MIN_SEVERITY` or `SOCKET_MAX_NEW_PATCHES`. | | `filter_invalid` | scan | Usage error (exit 2): the `--selection-filter` file cannot be read or honored (internal interface, see "Selection filter"). | | `json_requires_output` | vex | Usage error (exit 2): `--json` without `--output`. | +| `grype_config_requires_output` | vex | Usage error (exit 2): `--grype-config` without `--output` (Grype reads the document from a file). | | `no_patches` | vex | The manifest file exists but is empty AND no vendor-ledger record or lockfile reference names a patch (exit 1). | | `vendor_ledger_corrupt` | vex (every form) | `.socket/vendor/state.json` exists but is malformed or unreadable. The vendor ledger is an attestation input (records and liveness), so attesting from a partial view is refused (exit 2 standalone; the host command fails). A missing ledger is simply empty. | | `redirect_ledger_corrupt` | vex, list (`warnings[]`) | v5.0: a WARNING, no longer an error — a pre-v5 `.socket/vendor/redirect-state.json` exists but is malformed or unreadable. v5 hosted mode keeps no ledger (hosted references come from the lockfiles, their records from the API), so the file is only an optional migration record source: its records are not consulted and the run continues. Delete the file or restore it from version control. | @@ -3202,6 +3203,16 @@ The VEX document is JSON-LD, which collides with the standard `--json` envelope When verification is enabled (the default) and a patch is omitted, the failed PURLs are surfaced on stderr in plain mode or as `skipped` events on the envelope in JSON mode (one per patch, sorted by PURL; `errorCode` is the tag). Plain mode prints one line per reason, largest first: `Warning: omitting 82 packages from VEX: the patched files still hold the original content (not_applied): @sigstore/core@1.1.0, @sigstore/core@2.0.0, @simple-git/argv-parser@1.1.1 and 79 more (--verbose lists them all)`; a reason with a single patch keeps the per-patch line `Warning: omitting from VEX: ()`, and `--verbose` prints that line for every patch. The run's advisories print before them, folded the same way: the first of each kind in full, then ` ... and 9 more like these: glob@10.4.5, glob@11.0.3, minimatch@3.1.2 and 6 more (--verbose lists them all)` (the packages are named where each advisory opens with one). When nothing could be attested, the `Error: No applied patches with vulnerability metadata to attest.` line is followed by the remedy for the patches that only need installing (`The patched packages are not installed yet: ... Reinstall from the lockfile (hosted or vendored patches) or run \`socket-patch apply\` (agent-mode patches), then run \`socket-patch vex\` again.`, or `N of the patched packages ...` when other reasons are among them). A hosted gem among them is not told to reinstall, since Bundler keeps a gem it has already installed and `bundle pristine` on Bundler 2.6+ removes the gems and then fails on the lock's checksum; its remedy is the scan that replaces the installed copy: `The patched packages are hosted gems whose installed copies are still the upstream builds. ... Run \`socket-patch scan\` to replace the installed copies (for a gem home outside the project, run \`bundle config set --local path vendor/bundle && bundle install\` instead, or add \`--gem-refresh-shared\` to the scan), then run \`socket-patch vex\` again.` (see "Gem stale-install guard"). Where a scan with no `--mode` is not a hosted one (the project also holds agent-mode or vendored patches), that sentence names the files to remove instead: `Remove each gem's \`specifications/-.gemspec\` and \`cache/-.gem\` from its gem home (and its archive in \`vendor/cache\`, if the project keeps one) and run \`bundle install\`. Other projects may load a gem home outside the project, so for one run \`bundle config set --local path vendor/bundle && bundle install\` instead, then run \`socket-patch vex\` again.` A gem the manifest records under the same patch as the hosted pin keeps the general remedy, since `apply` patches it in place; a record of another patch, which the pin superseded, does not. `--json` is unchanged: every advisory is its own `warnings[]` entry and every omission its own `skipped` event. Status becomes `partialFailure` when at least one patch was omitted but at least one was emitted. It is `partialFailure` too, with exit `0`, when a statement of the document says `affected`, also when every one does: `summary.verified` counts the packages attested as patched and no other. +### Grype config (`vex --grype-config`) + +`--grype-config []` (`SOCKET_VEX_GRYPE_CONFIG`; `.grype.yaml` when the flag has no value, or when the value is a switch value — `1`, `true`, `yes` — while `0`, `false`, `no` turn it off; resolved like `--output` against the current directory) keeps the config's top-level `vex-documents` list naming the `--output` document, so `grype` run in the config's directory reads it without `--vex`. It needs `--output` (`grype_config_requires_output`, exit 2, otherwise). + +* **Entry.** The document's path relative to the config's directory, `/`-separated, quoted only when YAML would read it differently. Grype resolves a listed path against the directory it runs in. A document outside the config's directory, or a config or document path that contains `..`, is not listed. An item that names the same path in another spelling (`./socket.vex.json`, `out/../socket.vex.json`, `\` separators) counts as the entry, when adding and when removing. +* **Edit.** A missing config is created as `vex-documents:` with the one item. An existing one gains the item: under its `vex-documents` block list, with the indentation of the last item, or as a new key appended to the document when it has none, or in place of an inline `[]`. Every other byte stays: each line keeps its own ending (a file mixing CRLF and LF is read line by line), new lines take the file's most common ending, and a missing final newline stays missing. A listed entry leaves the file unchanged. +* **Refused shapes.** A config the editor cannot read with certainty is left unchanged: `vex-documents` with any other inline value (a flow list, a scalar), spelled in another case or named twice (Grype refuses both), items other than plain paths, uneven or tab indentation, nested content, a flow-style root, an indented root, or more than one YAML document. So is a config that is not a regular file or cannot be read or written. The run then warns `grype_config_not_updated` with the line to add, and the document and exit status stay the run's own. +* **Removal.** Grype fails the whole scan when a listed document is missing. A failed run that leaves no document at `--output` (it removed the previous one, `vex_stale_doc_removed`, or there was none) takes every spelling of the entry out of the list, leaving the key. A config it cannot read or check with certainty is warned about (`grype_config_not_updated`, saying to remove the entry if it is there). +* **Output.** The human summary adds one line when the config changes (`Created .grype.yaml, listing socket.vex.json in vex-documents`, `Listed … in vex-documents of …`, `Removed … from vex-documents of …, since the document is gone`). The success envelope carries `grypeConfig: { path, entry, change }`, with `change` one of `created`, `added`, `listed`, `not_updated`, or under `--dry-run` (which writes nothing) `would_create` / `would_add`. The error envelope of a failed run that touched the config carries it too, with `change` `removed`, `not_updated` or, under `--dry-run`, `would_remove`. + ## Semver policy Versioning lives in **`Cargo.toml`** at the workspace root (`version = "..."`) and is propagated to the Cargo and npm packages by **`scripts/version-sync.sh `** (the full list of stamped files is below). diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 2184c23ef..a97fe667c 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -850,6 +850,7 @@ pub const LOCAL_ARG_ENV_VARS: &[&str] = &[ "SOCKET_VEX_NO_BAZEL", "SOCKET_VEX_DOC_ID", "SOCKET_VEX_COMPACT", + "SOCKET_VEX_GRYPE_CONFIG", ]; /// Remove exported-but-empty flag-bound env vars before clap parses, so diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index 790194e60..d09cd25d2 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -26,6 +26,7 @@ pub(crate) mod vendor_orphans; pub(crate) mod vendored_backend; pub mod vex; pub(crate) mod vex_consumed; +pub(crate) mod vex_grype; pub(crate) mod vex_sources; pub(crate) mod vlt_heal; diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 8e8f5adff..d4526e012 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -31,6 +31,7 @@ use socket_patch_core::vex::{ }; use crate::args::{apply_env_toggles, parse_bool_flag, GlobalArgs}; +use crate::commands::vex_grype; use crate::commands::vex_sources::{ self, Plan, RunApiClient, Sources, GO_WORKSPACE_OVERRIDE, RECORD_MISMATCH, RECORD_UNAVAILABLE, REDIRECT_UNWIRED, VENDOR_UNWIRED, WIRING_CONFLICT, @@ -117,6 +118,22 @@ pub struct VexArgs { value_parser = parse_bool_flag, )] pub compact: bool, + + /// List the document in this Grype config's `vex-documents`, so a plain + /// `grype dir:.` reads it (`.grype.yaml` when given without a path). + /// Needs `--output`. The config names the document relative to its own + /// directory; run Grype there. A run that leaves no document at + /// `--output` takes the entry out again, since Grype fails a scan whose + /// listed document is missing. A config it cannot edit with certainty is + /// left alone, with a warning. + #[arg( + long = "grype-config", + env = "SOCKET_VEX_GRYPE_CONFIG", + value_name = "PATH", + num_args = 0..=1, + default_missing_value = vex_grype::DEFAULT_CONFIG + )] + pub grype_config: Option, } /// VEX-generation knobs embedded into `apply`, `vendor` and `scan` via `--vex`. @@ -405,6 +422,18 @@ pub async fn run(args: VexArgs) -> i32 { ); } + let grype_config = vex_grype::config_path(args.grype_config.as_deref()); + // Grype reads the document from a file, never from stdout. + if grype_config.is_some() && output.is_none() { + return crate::json_envelope::usage_error( + Command::Vex, + args.common.json, + args.common.dry_run, + "grype_config_requires_output", + "--grype-config requires --output (Grype reads the VEX document from a file)", + ); + } + // `-o` is `--org`, `-O` is `--output`: a file-shaped org slug is almost // certainly a mistyped `-O` (the document then silently went to stdout). let mut run_warnings: Vec = Vec::new(); @@ -448,9 +477,19 @@ pub async fn run(args: VexArgs) -> i32 { match generate_vex_from_manifest_path(&common, ¶ms, &manifest_path).await { Ok(mut summary) => { run_warnings.append(&mut summary.warnings); + let grype = match (&grype_config, &output) { + (Some(config), Some(path)) => { + Some(vex_grype::list_document(config, path, params.dry_run).await) + } + _ => None, + }; + let grype_warning = grype.as_ref().and_then(|g| g.warning.clone()); + if let Some(warning) = &grype_warning { + run_warnings.push(warning.clone()); + } summary.warnings = run_warnings; if args.common.json { - emit_envelope_success(&summary, params.dry_run); + emit_envelope_success(&summary, params.dry_run, grype.as_ref()); } else if !args.common.silent { let count = summary.statements; match &output { @@ -462,6 +501,13 @@ pub async fn run(args: VexArgs) -> i32 { } None => eprintln!("{}", format_vex_emitted(count, summary.affected)), } + if let Some(line) = grype.as_ref().and_then(|g| g.human_line()) { + println!("{line}"); + } + // After the summary, so it reads as about the config. + if let Some(warning) = &grype_warning { + print_warnings(&args.common, std::slice::from_ref(warning)); + } } 0 } @@ -471,6 +517,28 @@ pub async fn run(args: VexArgs) -> i32 { // telemetry, so these emit-only sinks must not re-track. Err(mut e) => { run_warnings.append(&mut e.warnings); + // No document is left at `--output`: an entry naming it would + // fail every Grype scan. + let grype = match (&grype_config, &output) { + (Some(config), Some(path)) => { + // A dry run leaves a stale document in place, so it asks + // whether the real run would have removed it. + let stale_doc_kept = params.dry_run && is_openvex_doc(path).await; + vex_grype::unlist_missing_document(config, path, params.dry_run, stale_doc_kept) + .await + } + _ => None, + }; + if let Some(grype) = &grype { + if let Some(warning) = grype.warning.clone() { + print_warnings(&args.common, std::slice::from_ref(&warning)); + run_warnings.push(warning); + } else if !args.common.json && !args.common.silent { + if let Some(line) = grype.human_line() { + eprintln!("{line}"); + } + } + } // Nothing to attest at `--cwd`: when scan patched the project // directories below it instead, name them and their run. let below = match e.code { @@ -519,7 +587,15 @@ pub async fn run(args: VexArgs) -> i32 { _ => (e.message, 2), }; let gems = StaleHostedGems::among(&common, &manifest_path, &e.failed, &e.hosted).await; - emit_envelope_error(&args, e.code, &message, &e.failed, &gems, &run_warnings); + emit_envelope_error( + &args, + e.code, + &message, + &e.failed, + &gems, + &run_warnings, + grype.as_ref(), + ); if !args.common.json { below.print(); } @@ -2285,20 +2361,26 @@ async fn generate_vex_with_cleanup( /// Removal errors are swallowed: the non-zero exit is the contract, the /// deletion is hygiene. Returns whether a document was actually removed. async fn remove_stale_vex_doc(path: &Path) -> bool { + is_openvex_doc(path).await && tokio::fs::remove_file(path).await.is_ok() +} + +/// Whether `path` is a regular file holding an OpenVEX document (JSON whose +/// `@context` names openvex.dev): the file a failed run removes. A dry run +/// asks this to say what the real run would do. +async fn is_openvex_doc(path: &Path) -> bool { // FIFO-safe read: `--vex` can name any path, and a plain read of a FIFO // there would block this failure path forever. let Ok(bytes) = socket_patch_core::utils::fs::read_regular_to_bytes(path).await else { return false; }; - let is_openvex = serde_json::from_slice::(&bytes) + serde_json::from_slice::(&bytes) .ok() .and_then(|v| { v.get("@context") .and_then(|c| c.as_str()) .map(|c| c.contains("openvex.dev")) }) - .unwrap_or(false); - is_openvex && tokio::fs::remove_file(path).await.is_ok() + .unwrap_or(false) } /// [`generate_vex_from_manifest_path`] without the failure-cleanup wrapper. @@ -2648,9 +2730,13 @@ fn emit_envelope_error( failures: &[FailedPatch], gems: &StaleHostedGems, warnings: &[RunWarning], + grype: Option<&vex_grype::GrypeConfigOutcome>, ) { if args.common.json { let mut env = Envelope::new(Command::Vex); + if let Some(grype) = grype { + env.set_extra("grypeConfig", grype.to_json()); + } env.dry_run = args.common.dry_run; for f in failures { env.record( @@ -2973,7 +3059,11 @@ fn omission_reason_message(reason: &str) -> String { format!("patch omitted from VEX: {}", omission_phrase(reason)) } -fn emit_envelope_success(summary: &VexWriteSummary, dry_run: bool) { +fn emit_envelope_success( + summary: &VexWriteSummary, + dry_run: bool, + grype: Option<&vex_grype::GrypeConfigOutcome>, +) { let mut env = Envelope::new(Command::Vex); env.dry_run = dry_run; for st in &summary.doc.statements { @@ -3005,6 +3095,9 @@ fn emit_envelope_success(summary: &VexWriteSummary, dry_run: bool) { env.mark_partial_failure(); } env.warnings = summary.warnings.clone(); + if let Some(grype) = grype { + env.set_extra("grypeConfig", grype.to_json()); + } println!("{}", env.to_pretty_json()); } diff --git a/crates/socket-patch-cli/src/commands/vex_grype.rs b/crates/socket-patch-cli/src/commands/vex_grype.rs new file mode 100644 index 000000000..39a68a6ee --- /dev/null +++ b/crates/socket-patch-cli/src/commands/vex_grype.rs @@ -0,0 +1,317 @@ +//! `vex --grype-config`: keep a Grype config's `vex-documents` list naming +//! the document `vex` writes, so a plain `grype dir:.` reads it. +//! +//! Grype fails the whole scan when a listed document is missing, so a run +//! that leaves no document at `--output` (it could attest nothing and +//! removed the previous one) takes the entry out again. A config whose +//! shape the editor cannot read with certainty is left as it is, and the +//! run warns with the line to add by hand. Either way the VEX document and +//! the exit status are the run's own. + +use std::path::{Component, Path, PathBuf}; + +use serde_json::json; +use socket_patch_core::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_string}; +use socket_patch_core::vex::grype_config::{ + add_vex_document, remove_vex_document, GrypeConfigEdit, VEX_DOCUMENTS_KEY, +}; + +use crate::json_envelope::RunWarning; + +/// The run warning for a config the run could not update. +pub(crate) const GRYPE_CONFIG_NOT_UPDATED: &str = "grype_config_not_updated"; + +/// The config `--grype-config` / `SOCKET_VEX_GRYPE_CONFIG` names. The other +/// `SOCKET_VEX_*` variables are switches, so a switch value is read as one: +/// `1` / `true` / `yes` names `.grype.yaml`, `0` / `false` / `no` none. +pub(crate) fn config_path(value: Option<&Path>) -> Option { + let value = value?; + match value.to_str().map(str::to_ascii_lowercase).as_deref() { + Some("1" | "true" | "yes") => Some(PathBuf::from(DEFAULT_CONFIG)), + Some("0" | "false" | "no") => None, + _ => Some(value.to_path_buf()), + } +} + +/// The config a bare `--grype-config` names. +pub(crate) const DEFAULT_CONFIG: &str = ".grype.yaml"; + +/// What a run did to the Grype config. +pub(crate) struct GrypeConfigOutcome { + pub path: PathBuf, + /// The path the config lists, relative to its directory. + pub entry: Option, + /// `created`, `added`, `listed` (already there), `removed`, `absent` + /// (nothing to remove), `not_updated`, or `would_create` / + /// `would_add` / `would_remove` under `--dry-run`. + pub change: &'static str, + pub warning: Option, +} + +impl GrypeConfigOutcome { + /// The envelope's `grypeConfig` object. + pub(crate) fn to_json(&self) -> serde_json::Value { + json!({ + "path": self.path.display().to_string(), + "entry": self.entry, + "change": self.change, + }) + } + + /// The line a human run prints, when the config changed. + pub(crate) fn human_line(&self) -> Option { + let entry = self.entry.as_deref()?; + let path = self.path.display(); + let line = match self.change { + "created" => format!("Created {path}, listing {entry} in {VEX_DOCUMENTS_KEY}"), + "added" => format!("Listed {entry} in {VEX_DOCUMENTS_KEY} of {path}"), + "removed" => format!( + "Removed {entry} from {VEX_DOCUMENTS_KEY} of {path}, since the document is gone" + ), + "would_create" => { + format!("Would create {path}, listing {entry} in {VEX_DOCUMENTS_KEY}") + } + "would_add" => format!("Would list {entry} in {VEX_DOCUMENTS_KEY} of {path}"), + "would_remove" => { + format!("Would remove {entry} from {VEX_DOCUMENTS_KEY} of {path}") + } + _ => return None, + }; + Some(line) + } +} + +/// List `output` in the config at `config` after the document was written. +pub(crate) async fn list_document( + config: &Path, + output: &Path, + dry_run: bool, +) -> GrypeConfigOutcome { + let entry = match entry_for(config, output) { + Ok(entry) => entry, + Err(why) => return not_updated(config, None, output, &why), + }; + let text = match read_config(config).await { + Ok(text) => text, + Err(why) => return not_updated(config, Some(entry), output, &why), + }; + let existed = text.is_some(); + match add_vex_document(text.as_deref(), &entry) { + Ok(GrypeConfigEdit::Unchanged) => outcome(config, entry, "listed"), + Ok(GrypeConfigEdit::Write(new)) => { + let change = match (existed, dry_run) { + (false, false) => "created", + (true, false) => "added", + (false, true) => "would_create", + (true, true) => "would_add", + }; + if !dry_run { + if let Err(e) = atomic_write_bytes_preserving_mode(config, new.as_bytes()).await { + let why = format!("could not be written ({e})"); + return not_updated(config, Some(entry), output, &why); + } + } + outcome(config, entry, change) + } + Err(why) => not_updated(config, Some(entry), output, &why), + } +} + +/// Take `output` out of the config at `config` when no document is left +/// there. `None` when the document is still there, or nothing is to be done. +/// +/// `stale_doc_kept` says a dry run left in place a stale document that the +/// real run would remove: the config step then previews that removal +/// although a file is still at `output`. +pub(crate) async fn unlist_missing_document( + config: &Path, + output: &Path, + dry_run: bool, + stale_doc_kept: bool, +) -> Option { + if !stale_doc_kept && tokio::fs::symlink_metadata(output).await.is_ok() { + return None; + } + // A document this run could not have listed is not looked for. + let entry = entry_for(config, output).ok()?; + let text = match read_config(config).await { + Ok(Some(text)) => text, + Ok(None) => return None, + Err(why) => return Some(unchecked(config, entry, &why)), + }; + match remove_vex_document(&text, &entry) { + Ok(GrypeConfigEdit::Unchanged) => None, + Ok(GrypeConfigEdit::Write(_)) if dry_run => Some(outcome(config, entry, "would_remove")), + Ok(GrypeConfigEdit::Write(new)) => { + match atomic_write_bytes_preserving_mode(config, new.as_bytes()).await { + Ok(()) => Some(outcome(config, entry, "removed")), + Err(e) => Some(stale_entry( + config, + entry, + &format!("could not be written ({e})"), + )), + } + } + Err(why) => Some(unchecked(config, entry, &why)), + } +} + +fn outcome(config: &Path, entry: String, change: &'static str) -> GrypeConfigOutcome { + GrypeConfigOutcome { + path: config.to_path_buf(), + entry: Some(entry), + change, + warning: None, + } +} + +fn not_updated( + config: &Path, + entry: Option, + output: &Path, + why: &str, +) -> GrypeConfigOutcome { + let listed = entry + .clone() + .unwrap_or_else(|| output.display().to_string()); + GrypeConfigOutcome { + path: config.to_path_buf(), + entry, + change: "not_updated", + warning: Some(RunWarning { + code: GRYPE_CONFIG_NOT_UPDATED.to_string(), + detail: format!( + "{} not updated: it {why}. List `{listed}` in `{VEX_DOCUMENTS_KEY}` yourself, \ + or run grype with `--vex {}`.", + config.display(), + output.display() + ), + }), + } +} + +fn stale_entry(config: &Path, entry: String, why: &str) -> GrypeConfigOutcome { + GrypeConfigOutcome { + path: config.to_path_buf(), + warning: Some(RunWarning { + code: GRYPE_CONFIG_NOT_UPDATED.to_string(), + detail: format!( + "{} still lists `{entry}` in `{VEX_DOCUMENTS_KEY}`, and Grype fails a scan \ + whose listed document is missing: it {why}. Remove the entry by hand.", + config.display() + ), + }), + entry: Some(entry), + change: "not_updated", + } +} + +/// A config the run could not check for `entry` after the document went. +fn unchecked(config: &Path, entry: String, why: &str) -> GrypeConfigOutcome { + GrypeConfigOutcome { + path: config.to_path_buf(), + warning: Some(RunWarning { + code: GRYPE_CONFIG_NOT_UPDATED.to_string(), + detail: format!( + "{} was not checked for `{entry}`: it {why}. Grype fails a scan whose listed \ + document is missing, so remove `{entry}` from `{VEX_DOCUMENTS_KEY}` if it is \ + there.", + config.display() + ), + }), + entry: Some(entry), + change: "not_updated", + } +} + +/// The config's text; `None` when there is no file. +async fn read_config(config: &Path) -> Result, String> { + match tokio::fs::symlink_metadata(config).await { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("could not be read ({e})")), + Ok(meta) if !meta.is_file() => return Err("is not a regular file".to_string()), + Ok(_) => {} + } + read_regular_to_string(config) + .await + .map(Some) + .map_err(|e| format!("could not be read ({e})")) +} + +/// `output` as the config lists it: relative to the config's directory, +/// with `/` separators. Grype resolves the list against the directory it +/// runs in, so it is run from the config's directory. +fn entry_for(config: &Path, output: &Path) -> Result { + // `..` after a symlinked directory is resolved by the OS, not by the + // lexical fold below, so such a path could name another file. + for path in [config, output] { + if path.components().any(|c| c == Component::ParentDir) { + return Err(format!( + "is named with `..` (in {}), which this run does not resolve", + path.display() + )); + } + } + let cwd = std::env::current_dir().map_err(|e| format!("has no base directory ({e})"))?; + let dir = lexical(&cwd.join(config)); + let dir = dir.parent().map(Path::to_path_buf).unwrap_or(dir); + let document = lexical(&cwd.join(output)); + let relative = document.strip_prefix(&dir).map_err(|_| { + format!( + "is not above the VEX document {}, and Grype reads a listed path from the \ + directory it runs in", + output.display() + ) + })?; + let parts: Vec = relative + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + if parts.is_empty() { + return Err("names the VEX document's own path".to_string()); + } + Ok(parts.join("/")) +} + +/// `path` with `.` dropped and `..` folded into its parent, without +/// touching the file system (the document may not exist yet). +fn lexical(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + other => out.push(other.as_os_str()), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_entry_is_relative_to_the_config() { + assert_eq!( + entry_for(Path::new(".grype.yaml"), Path::new("socket.vex.json")).unwrap(), + "socket.vex.json" + ); + assert_eq!( + entry_for( + Path::new("./.grype.yaml"), + Path::new("out/./socket.vex.json") + ) + .unwrap(), + "out/socket.vex.json" + ); + assert!(entry_for(Path::new("sub/.grype.yaml"), Path::new("socket.vex.json")).is_err()); + assert!(entry_for( + Path::new(".grype.yaml"), + Path::new("build/../socket.vex.json") + ) + .is_err()); + } +} diff --git a/crates/socket-patch-cli/tests/cli_parse_vex.rs b/crates/socket-patch-cli/tests/cli_parse_vex.rs index 4012fb9c3..4877962ff 100644 --- a/crates/socket-patch-cli/tests/cli_parse_vex.rs +++ b/crates/socket-patch-cli/tests/cli_parse_vex.rs @@ -50,6 +50,7 @@ struct Snap { no_bazel: bool, doc_id: Option, compact: bool, + grype_config: Option, } fn snapshot(a: &VexArgs) -> Snap { @@ -61,6 +62,7 @@ fn snapshot(a: &VexArgs) -> Snap { no_bazel: a.no_bazel, doc_id: a.doc_id.clone(), compact: a.compact, + grype_config: a.grype_config.clone(), } } @@ -74,6 +76,7 @@ fn expected_defaults() -> Snap { no_bazel: false, doc_id: None, compact: false, + grype_config: None, } } @@ -228,3 +231,32 @@ fn no_vlt_install_cleanup_env_is_accepted_silently_by_vex() { want.common.no_vlt_install_cleanup = true; assert_eq!(snapshot(&a), want); } + +/// `--grype-config` without a value names `.grype.yaml`; with one, that path; +/// `SOCKET_VEX_GRYPE_CONFIG` sets it like the flag. +#[test] +#[serial_test::serial] +fn grype_config_takes_an_optional_path() { + for (args, env, want) in [ + ( + &["socket-patch", "vex", "--grype-config"][..], + None, + ".grype.yaml", + ), + ( + &["socket-patch", "vex", "--grype-config", "ci/grype.yaml"][..], + None, + "ci/grype.yaml", + ), + ( + &["socket-patch", "vex"][..], + Some(("SOCKET_VEX_GRYPE_CONFIG", "env.yaml")), + "env.yaml", + ), + ] { + let a = parse_vex(try_parse_with_env(env.as_slice(), args)); + let mut expected = expected_defaults(); + expected.grype_config = Some(PathBuf::from(want)); + assert_eq!(snapshot(&a), expected, "{args:?}"); + } +} diff --git a/crates/socket-patch-cli/tests/e2e_vex_grype_config.rs b/crates/socket-patch-cli/tests/e2e_vex_grype_config.rs new file mode 100644 index 000000000..1dac9a6c2 --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_vex_grype_config.rs @@ -0,0 +1,235 @@ +//! `vex --grype-config`: the document is listed in the Grype config's +//! `vex-documents`, and taken out again when a run leaves no document. + +#[path = "common/mod.rs"] +mod common; + +use std::collections::HashMap; +use std::path::Path; +use std::process::Output; + +use serde_json::Value; +use socket_patch_core::manifest::schema::{ + PatchFileInfo, PatchManifest, PatchRecord, VulnerabilityInfo, +}; + +const CONFIG: &str = ".grype.yaml"; +const DOCUMENT: &str = "socket.vex.json"; + +fn write_manifest(cwd: &Path, purls: &[&str]) { + let mut manifest = PatchManifest::new(); + for purl in purls { + let mut files = HashMap::new(); + files.insert( + "package/index.js".to_string(), + PatchFileInfo { + before_hash: "a".repeat(64), + after_hash: "b".repeat(64), + }, + ); + let mut vulnerabilities = HashMap::new(); + vulnerabilities.insert( + "GHSA-aaaa-bbbb-cccc".to_string(), + VulnerabilityInfo { + cves: vec!["CVE-2024-1111".to_string()], + summary: "test summary".to_string(), + severity: "high".to_string(), + description: "test description".to_string(), + }, + ); + manifest.patches.insert( + purl.to_string(), + PatchRecord { + uuid: "11111111-1111-4111-8111-111111111111".to_string(), + exported_at: "2024-01-01T00:00:00Z".to_string(), + files, + vulnerabilities, + description: "test".to_string(), + license: "MIT".to_string(), + tier: "free".to_string(), + }, + ); + } + let dir = cwd.join(".socket"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("manifest.json"), + serde_json::to_string_pretty(&manifest).unwrap(), + ) + .unwrap(); +} + +/// `vex --output socket.vex.json --json` in `cwd`, plus `extra`. +fn vex(cwd: &Path, extra: &[&str]) -> (Output, Value) { + let out = common::hermetic::binary_command() + .current_dir(cwd) + .args([ + "vex", + "--cwd", + ".", + "--no-verify", + "--product", + "pkg:npm/test-app@1.0.0", + "--output", + DOCUMENT, + "--json", + ]) + .args(extra) + .output() + .expect("invoke vex"); + let envelope = serde_json::from_slice(&out.stdout).unwrap_or_else(|e| { + panic!( + "envelope: {e}\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }); + (out, envelope) +} + +fn config(cwd: &Path) -> String { + std::fs::read_to_string(cwd.join(CONFIG)).unwrap() +} + +#[test] +fn a_missing_config_is_created_and_a_second_run_leaves_it() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + write_manifest(cwd, &["pkg:npm/lodash@4.17.20"]); + + let (out, envelope) = vex(cwd, &["--grype-config"]); + assert!(out.status.success(), "{envelope}"); + assert_eq!(envelope["grypeConfig"]["change"], "created", "{envelope}"); + assert_eq!(envelope["grypeConfig"]["entry"], DOCUMENT); + assert_eq!(config(cwd), "vex-documents:\n - socket.vex.json\n"); + + let (out, envelope) = vex(cwd, &["--grype-config"]); + assert!(out.status.success(), "{envelope}"); + assert_eq!(envelope["grypeConfig"]["change"], "listed", "{envelope}"); + assert_eq!(config(cwd), "vex-documents:\n - socket.vex.json\n"); +} + +#[test] +fn an_existing_config_keeps_its_lines() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + write_manifest(cwd, &["pkg:npm/lodash@4.17.20"]); + let before = "# team settings\nfail-on-severity: high\nvex-documents:\n - other.vex.json\n"; + std::fs::write(cwd.join(CONFIG), before).unwrap(); + + let (out, envelope) = vex(cwd, &["--grype-config", CONFIG]); + assert!(out.status.success(), "{envelope}"); + assert_eq!(envelope["grypeConfig"]["change"], "added", "{envelope}"); + assert_eq!(config(cwd), format!("{before} - socket.vex.json\n")); +} + +#[test] +fn a_run_that_leaves_no_document_takes_the_entry_out() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + write_manifest(cwd, &["pkg:npm/lodash@4.17.20"]); + let (out, envelope) = vex(cwd, &["--grype-config"]); + assert!(out.status.success(), "{envelope}"); + assert!(cwd.join(DOCUMENT).exists()); + + // Nothing left to attest: the run removes the previous document, and + // with it the entry Grype would fail on. + write_manifest(cwd, &[]); + // A dry run keeps the document but says the entry would go with it. + let (out, envelope) = vex(cwd, &["--grype-config", "--dry-run"]); + assert!(!out.status.success(), "{envelope}"); + assert!(cwd.join(DOCUMENT).exists()); + assert_eq!(config(cwd), "vex-documents:\n - socket.vex.json\n"); + assert_eq!( + envelope["grypeConfig"]["change"], "would_remove", + "{envelope}" + ); + + let (out, envelope) = vex(cwd, &["--grype-config"]); + assert!(!out.status.success(), "{envelope}"); + assert!(!cwd.join(DOCUMENT).exists()); + assert_eq!(config(cwd), "vex-documents:\n"); + assert_eq!(envelope["grypeConfig"]["change"], "removed", "{envelope}"); +} + +#[test] +fn a_switch_value_in_the_env_names_the_default_config() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + write_manifest(cwd, &["pkg:npm/lodash@4.17.20"]); + let out = common::hermetic::binary_command() + .current_dir(cwd) + .env("SOCKET_VEX_GRYPE_CONFIG", "true") + .args([ + "vex", + "--no-verify", + "--product", + "pkg:npm/test-app@1.0.0", + "--output", + DOCUMENT, + ]) + .output() + .expect("invoke vex"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(!cwd.join("true").exists()); + assert_eq!(config(cwd), "vex-documents:\n - socket.vex.json\n"); +} + +#[test] +fn a_config_it_cannot_edit_is_left_alone_with_a_warning() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + write_manifest(cwd, &["pkg:npm/lodash@4.17.20"]); + let before = "vex-documents: [other.vex.json]\n"; + std::fs::write(cwd.join(CONFIG), before).unwrap(); + + let (out, envelope) = vex(cwd, &["--grype-config"]); + assert!(out.status.success(), "the document is written: {envelope}"); + assert_eq!(envelope["grypeConfig"]["change"], "not_updated"); + let warnings = envelope["warnings"].as_array().unwrap(); + assert!( + warnings + .iter() + .any(|w| w["code"] == "grype_config_not_updated"), + "{envelope}" + ); + assert_eq!(config(cwd), before); + assert!(cwd.join(DOCUMENT).exists()); +} + +#[test] +fn dry_run_says_what_it_would_do() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + write_manifest(cwd, &["pkg:npm/lodash@4.17.20"]); + + let (out, envelope) = vex(cwd, &["--grype-config", "--dry-run"]); + assert!(out.status.success(), "{envelope}"); + assert_eq!(envelope["grypeConfig"]["change"], "would_create"); + assert!(!cwd.join(CONFIG).exists()); +} + +#[test] +fn grype_config_needs_an_output_file() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + write_manifest(cwd, &["pkg:npm/lodash@4.17.20"]); + let out = common::hermetic::binary_command() + .current_dir(cwd) + .args([ + "vex", + "--no-verify", + "--product", + "pkg:npm/test-app@1.0.0", + "--grype-config", + ]) + .output() + .expect("invoke vex"); + assert_eq!(out.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&out.stderr).contains("--grype-config requires --output")); + assert!(!cwd.join(CONFIG).exists()); +} diff --git a/crates/socket-patch-cli/tests/in_process_alternate_installers.rs b/crates/socket-patch-cli/tests/in_process_alternate_installers.rs index 2d16db2ef..cc32e5a05 100644 --- a/crates/socket-patch-cli/tests/in_process_alternate_installers.rs +++ b/crates/socket-patch-cli/tests/in_process_alternate_installers.rs @@ -1253,6 +1253,7 @@ async fn apply_check_and_vex_see_unpatched_member_named_like_a_build_dir() { no_bazel: false, doc_id: None, compact: false, + grype_config: None, }) .await; (code, std::fs::read_to_string(&vex_path).unwrap_or_default()) @@ -1325,6 +1326,7 @@ async fn apply_check_and_vex_see_unpatched_member_in_a_hidden_dir() { no_bazel: false, doc_id: None, compact: false, + grype_config: None, }) .await; (code, std::fs::read_to_string(&vex_path).unwrap_or_default()) diff --git a/crates/socket-patch-core/src/utils/process.rs b/crates/socket-patch-core/src/utils/process.rs index 86a4c3009..2a3b29814 100644 --- a/crates/socket-patch-core/src/utils/process.rs +++ b/crates/socket-patch-core/src/utils/process.rs @@ -129,6 +129,7 @@ pub const CHILD_ENV_SCRUB: &[&str] = &[ "SOCKET_VEX_NO_BAZEL", "SOCKET_VEX_DOC_ID", "SOCKET_VEX_COMPACT", + "SOCKET_VEX_GRYPE_CONFIG", // Socket-specific service URLs read from the environment alone. "SOCKET_NPM_REGISTRY", "SOCKET_PYPI_JSON_API", diff --git a/crates/socket-patch-core/src/vex/grype_config.rs b/crates/socket-patch-core/src/vex/grype_config.rs new file mode 100644 index 000000000..d2406e567 --- /dev/null +++ b/crates/socket-patch-core/src/vex/grype_config.rs @@ -0,0 +1,515 @@ +//! Keep a Grype config's `vex-documents` list naming a VEX document. +//! +//! Grype reads every document that list names on each scan, so a VEX +//! document listed there suppresses its findings without `--vex`. Grype +//! fails the whole scan when a listed document is missing, and refuses a +//! config that names the key twice, so the editor only changes a file whose +//! shape it can read with certainty and leaves every other byte as it was, +//! each line's own ending and a missing final newline included. Anything +//! else is refused with the reason, for the caller to print the line to add +//! by hand. +//! +//! Pure text in, text out; the caller owns the reads and writes. + +use crate::formats::pnpm::workspace::{block_insert_point, top_level_key, yaml_scalar}; + +/// The key Grype reads VEX documents from. +pub const VEX_DOCUMENTS_KEY: &str = "vex-documents"; + +/// What an edit does to the config. +#[derive(Debug, PartialEq, Eq)] +pub enum GrypeConfigEdit { + /// The list already says what was asked; the file stays as it is. + Unchanged, + /// The new text of the file. + Write(String), +} + +/// Add `entry` to the `vex-documents` list of the config `text` (`None`: +/// the file does not exist). An item naming the same path in another +/// spelling (`./socket.vex.json`) counts as listed. `Err` says why the file +/// is left alone. +pub fn add_vex_document(text: Option<&str>, entry: &str) -> Result { + let item = format!(" - {}", yaml_item(entry)); + let Some(text) = text else { + return Ok(GrypeConfigEdit::Write(format!( + "{VEX_DOCUMENTS_KEY}:\n{item}\n" + ))); + }; + let mut doc = Lines::parse(text); + // One block-mapping document, whatever the edit: the check refuses + // flow and indented roots and a second document. + let end = block_insert_point(&doc.lines)?; + match find_key(&doc.lines)? { + None => { + doc.insert(end, format!("{VEX_DOCUMENTS_KEY}:")); + doc.insert(end + 1, item); + } + Some(key) => { + let list = read_list(&doc.lines, key)?; + if list.items.iter().any(|(_, value)| same_path(value, entry)) { + return Ok(GrypeConfigEdit::Unchanged); + } + if list.empty_flow { + let line = &doc.lines[key]; + doc.lines[key] = line.replacen("[]", "", 1).trim_end().to_string(); + } + match list.items.last() { + // A new item takes the indentation of the last one. + Some((last, _)) => { + let indent: String = + doc.lines[*last].chars().take_while(|c| *c == ' ').collect(); + doc.insert(*last + 1, format!("{indent}- {}", yaml_item(entry))); + } + None => doc.insert(key + 1, item), + } + } + } + Ok(GrypeConfigEdit::Write(doc.join())) +} + +/// Remove every item naming `entry` (in any spelling) from the +/// `vex-documents` list of the config `text`. A config without the key, or +/// without the entry, is unchanged. `Err` says why the file could not be +/// read with certainty. +pub fn remove_vex_document(text: &str, entry: &str) -> Result { + let mut doc = Lines::parse(text); + block_insert_point(&doc.lines)?; + let Some(key) = find_key(&doc.lines)? else { + return Ok(GrypeConfigEdit::Unchanged); + }; + let list = read_list(&doc.lines, key)?; + let named: Vec = list + .items + .iter() + .filter(|(_, value)| same_path(value, entry)) + .map(|(line, _)| *line) + .collect(); + if named.is_empty() { + return Ok(GrypeConfigEdit::Unchanged); + } + for line in named.into_iter().rev() { + doc.remove(line); + } + Ok(GrypeConfigEdit::Write(doc.join())) +} + +/// The line of the top-level `vex-documents` key. Grype's config loader +/// matches keys without regard to case and refuses a key named twice, so +/// any other spelling, or a second one, leaves the file alone. +fn find_key(lines: &[String]) -> Result, String> { + let mut found = None; + for (i, line) in lines.iter().enumerate() { + let Some((key, _)) = top_level_key(line) else { + continue; + }; + if !key.eq_ignore_ascii_case(VEX_DOCUMENTS_KEY) { + continue; + } + if key != VEX_DOCUMENTS_KEY { + return Err(format!("spells the key `{key}`")); + } + if found.is_some() { + return Err(format!("names `{VEX_DOCUMENTS_KEY}` more than once")); + } + found = Some(i); + } + Ok(found) +} + +/// The items of the list under the key on line `key`. +struct List { + /// (line, decoded value) of each item, in order. + items: Vec<(usize, String)>, + /// The key's value is an inline `[]`. + empty_flow: bool, +} + +fn read_list(lines: &[String], key: usize) -> Result { + let (_, inline) = top_level_key(&lines[key]).expect("a key line"); + let inline = inline.trim(); + if inline == "[]" { + return Ok(List { + items: Vec::new(), + empty_flow: true, + }); + } + if !inline.is_empty() { + return Err(format!("has `{VEX_DOCUMENTS_KEY}: {inline}` on one line")); + } + let mut items = Vec::new(); + let mut indent = None; + for (i, line) in lines.iter().enumerate().skip(key + 1) { + let trimmed = line.trim_start(); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + if line.starts_with('\t') { + return Err(format!("indents `{VEX_DOCUMENTS_KEY}` with a tab")); + } + let depth = line.len() - trimmed.len(); + let is_item = trimmed == "-" || trimmed.starts_with("- "); + if !is_item { + if depth == 0 { + break; // the next top-level key + } + return Err(format!( + "holds something other than a list of paths under `{VEX_DOCUMENTS_KEY}`" + )); + } + match indent { + None => indent = Some(depth), + Some(d) if d == depth => {} + Some(_) => { + return Err(format!( + "indents the items of `{VEX_DOCUMENTS_KEY}` unevenly" + )) + } + } + let value = strip_comment(trimmed[1..].trim()); + if value.is_empty() || value.starts_with(['[', '{', '|', '>', '&', '*', '!']) { + return Err(format!( + "holds an item of `{VEX_DOCUMENTS_KEY}` that is not a plain path" + )); + } + items.push((i, yaml_scalar(value))); + } + Ok(List { + items, + empty_flow: false, + }) +} + +/// `value` without a trailing comment. A quote counts only where it opens +/// the value, as in YAML: `team's.json # ci` is the plain `team's.json`. +fn strip_comment(value: &str) -> &str { + let bytes = value.as_bytes(); + let mut start = 0; + if let Some("e) = bytes.first().filter(|b| matches!(b, b'\'' | b'"')) { + let mut i = 1; + while i < bytes.len() { + if bytes[i] == quote { + // `''` is an escaped quote inside single quotes. + if quote == b'\'' && bytes.get(i + 1) == Some(&b'\'') { + i += 2; + continue; + } + if quote == b'"' && bytes[i - 1] == b'\\' { + i += 1; + continue; + } + break; + } + i += 1; + } + start = (i + 1).min(bytes.len()); + } + for i in start..bytes.len() { + if bytes[i] == b'#' && i > 0 && matches!(bytes[i - 1], b' ' | b'\t') { + return value[..i].trim_end(); + } + } + value +} + +/// Whether two listed paths name the same file: `./a`, `a` and `b/../a` +/// alike, with `\` read as `/`. A leading `..` of a relative path stays, +/// so `../a` is not `a`. +fn same_path(a: &str, b: &str) -> bool { + fn normal(path: &str) -> String { + let path = path.replace('\\', "/"); + let absolute = path.starts_with('/'); + let mut parts: Vec<&str> = Vec::new(); + for segment in path.split('/') { + match segment { + "" | "." => {} + ".." => { + if parts.last().is_some_and(|last| *last != "..") { + parts.pop(); + } else if !absolute { + // Nothing to climb out of: the path leaves its base. + parts.push(".."); + } + } + other => parts.push(other), + } + } + let joined = parts.join("/"); + if path.starts_with('/') { + format!("/{joined}") + } else { + joined + } + } + normal(a) == normal(b) +} + +/// `entry` as a list item: plain when YAML reads it back unchanged, +/// single-quoted otherwise. +fn yaml_item(entry: &str) -> String { + let plain = !entry.is_empty() + && entry + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '-' | '_')) + && !entry.starts_with('-'); + if plain { + entry.to_string() + } else { + format!("'{}'", entry.replace('\'', "''")) + } +} + +/// A file's lines without their terminators, each with its own, so a +/// mixed-ending file splits at every line and joins back byte for byte. +/// A last line with no terminator keeps having none. +struct Lines { + lines: Vec, + ends: Vec<&'static str>, + /// The terminator new lines get: the file's most common one. + eol: &'static str, +} + +impl Lines { + fn parse(text: &str) -> Self { + let mut lines = Vec::new(); + let mut ends = Vec::new(); + for chunk in text.split_inclusive('\n') { + if let Some(line) = chunk.strip_suffix("\r\n") { + lines.push(line.to_string()); + ends.push("\r\n"); + } else if let Some(line) = chunk.strip_suffix('\n') { + lines.push(line.to_string()); + ends.push("\n"); + } else { + lines.push(chunk.to_string()); + ends.push(""); + } + } + let crlf = ends.iter().filter(|end| **end == "\r\n").count(); + let lf = ends.iter().filter(|end| **end == "\n").count(); + let eol = if crlf > lf { "\r\n" } else { "\n" }; + Lines { lines, ends, eol } + } + + /// Insert `line` before line `at`. After an unterminated last line, the + /// new line becomes the unterminated one. + fn insert(&mut self, at: usize, line: String) { + let end = if at > 0 && at == self.lines.len() && self.ends[at - 1].is_empty() { + self.ends[at - 1] = self.eol; + "" + } else { + self.eol + }; + self.lines.insert(at, line); + self.ends.insert(at, end); + } + + /// Remove line `at`. A removed unterminated last line leaves the line + /// before it unterminated. + fn remove(&mut self, at: usize) { + if self.ends[at].is_empty() && at > 0 { + self.ends[at - 1] = ""; + } + self.lines.remove(at); + self.ends.remove(at); + } + + fn join(&self) -> String { + self.lines + .iter() + .zip(&self.ends) + .map(|(line, end)| format!("{line}{end}")) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn added(text: Option<&str>) -> String { + match add_vex_document(text, "socket.vex.json").unwrap() { + GrypeConfigEdit::Write(text) => text, + GrypeConfigEdit::Unchanged => panic!("expected a write"), + } + } + + #[test] + fn a_missing_config_is_created() { + assert_eq!(added(None), "vex-documents:\n - socket.vex.json\n"); + } + + #[test] + fn the_key_is_appended_to_a_config_without_it() { + let text = "# grype settings\nfail-on-severity: high\n"; + assert_eq!( + added(Some(text)), + "# grype settings\nfail-on-severity: high\nvex-documents:\n - socket.vex.json\n" + ); + } + + #[test] + fn the_entry_joins_an_existing_list_with_its_indentation() { + let text = "vex-documents:\n - other.json # ours\noutput: table\n"; + assert_eq!( + added(Some(text)), + "vex-documents:\n - other.json # ours\n - socket.vex.json\noutput: table\n" + ); + } + + #[test] + fn a_listed_entry_leaves_the_file_alone() { + for text in [ + "vex-documents:\n - socket.vex.json\n", + "vex-documents:\n- 'socket.vex.json' # pinned\n", + "vex-documents:\n - \"socket.vex.json\"\n", + "vex-documents:\n - ./socket.vex.json\n", + "vex-documents:\n - out/../socket.vex.json\n", + ] { + assert_eq!( + add_vex_document(Some(text), "socket.vex.json"), + Ok(GrypeConfigEdit::Unchanged), + "{text}" + ); + } + } + + #[test] + fn an_empty_flow_list_becomes_a_block_list() { + assert_eq!( + added(Some("vex-documents: []\n")), + "vex-documents:\n - socket.vex.json\n" + ); + } + + #[test] + fn line_endings_and_a_missing_final_newline_are_kept() { + assert_eq!( + added(Some("output: table\r\n")), + "output: table\r\nvex-documents:\r\n - socket.vex.json\r\n" + ); + assert_eq!( + added(Some("output: table")), + "output: table\nvex-documents:\n - socket.vex.json" + ); + } + + #[test] + fn a_mixed_ending_file_is_read_line_by_line() { + // The key sits on an LF line of a CRLF file: it is found, not + // appended a second time. + let text = "output: table\r\nvex-documents:\n - other.json\n"; + assert_eq!( + added(Some(text)), + "output: table\r\nvex-documents:\n - other.json\n - socket.vex.json\n" + ); + } + + #[test] + fn shapes_it_cannot_read_are_refused() { + for text in [ + "vex-documents: [a.json]\n", + "vex-documents: a.json\n", + "Vex-Documents:\n - a.json\n", + "vex-documents:\n - a.json\nvex-documents:\n - b.json\n", + "vex-documents:\n - a.json\n - b.json\n", + "vex-documents:\n key: value\n", + "{vex-documents: [a.json]}\n", + "output: table\n---\nfail-on-severity: high\n", + "vex-documents:\n - a.json\n---\nfail-on-severity: high\n", + ] { + assert!( + add_vex_document(Some(text), "socket.vex.json").is_err(), + "{text}" + ); + assert!( + remove_vex_document(text, "socket.vex.json").is_err(), + "{text}" + ); + } + } + + #[test] + fn a_quote_inside_a_plain_path_is_part_of_it() { + let text = "vex-documents:\n - o'brien/socket.vex.json # ci\n"; + assert_eq!( + add_vex_document(Some(text), "o'brien/socket.vex.json"), + Ok(GrypeConfigEdit::Unchanged) + ); + } + + #[test] + fn an_entry_that_needs_quotes_is_quoted() { + assert_eq!( + add_vex_document(None, "vex docs/socket.vex.json"), + Ok(GrypeConfigEdit::Write( + "vex-documents:\n - 'vex docs/socket.vex.json'\n".to_string() + )) + ); + } + + #[test] + fn a_parent_path_is_not_the_local_document() { + // `..` with nothing to climb out of leaves the base: the parent's + // document is another file. + let text = "vex-documents:\n - ../socket.vex.json\n"; + assert_eq!( + add_vex_document(Some(text), "socket.vex.json"), + Ok(GrypeConfigEdit::Write( + "vex-documents:\n - ../socket.vex.json\n - socket.vex.json\n".to_string() + )) + ); + assert_eq!( + remove_vex_document(text, "socket.vex.json"), + Ok(GrypeConfigEdit::Unchanged) + ); + assert!(same_path("a/../../b", "../b")); + assert!(!same_path("../../b", "../b")); + assert!(same_path("/../b", "/b")); + } + + #[test] + fn remove_drops_every_spelling_of_the_entry() { + let text = "vex-documents:\n - other.json\n - socket.vex.json\n - ./socket.vex.json\noutput: table\n"; + assert_eq!( + remove_vex_document(text, "socket.vex.json"), + Ok(GrypeConfigEdit::Write( + "vex-documents:\n - other.json\noutput: table\n".to_string() + )) + ); + assert_eq!( + remove_vex_document("output: table\n", "socket.vex.json"), + Ok(GrypeConfigEdit::Unchanged) + ); + assert_eq!( + remove_vex_document("vex-documents:\n - other.json\n", "socket.vex.json"), + Ok(GrypeConfigEdit::Unchanged) + ); + } + + #[test] + fn removing_an_unterminated_last_item_keeps_the_file_unterminated() { + assert_eq!( + remove_vex_document( + "vex-documents:\n - a\n - socket.vex.json", + "socket.vex.json" + ), + Ok(GrypeConfigEdit::Write("vex-documents:\n - a".to_string())) + ); + } + + #[test] + fn add_then_remove_restores_the_file() { + let text = "# settings\nfail-on-severity: high\n"; + let GrypeConfigEdit::Write(with) = add_vex_document(Some(text), "socket.vex.json").unwrap() + else { + panic!() + }; + let GrypeConfigEdit::Write(without) = + remove_vex_document(&with, "socket.vex.json").unwrap() + else { + panic!() + }; + assert_eq!(without, format!("{text}vex-documents:\n")); + } +} diff --git a/crates/socket-patch-core/src/vex/mod.rs b/crates/socket-patch-core/src/vex/mod.rs index 615676ba9..bac74b753 100644 --- a/crates/socket-patch-core/src/vex/mod.rs +++ b/crates/socket-patch-core/src/vex/mod.rs @@ -19,6 +19,7 @@ pub mod build; pub mod discover; +pub mod grype_config; pub mod product; pub mod schema; pub mod time; diff --git a/docs/usage.md b/docs/usage.md index 91eaf4cfe..5480da62f 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -279,6 +279,19 @@ copy the document leaves out, is left out, so the scanner keeps reporting that c Scanners match a package wherever they find it, so use the document only on the project it was made for. +For Grype, `--grype-config` lists the document in the project's Grype config, so a +plain `grype dir:.` reads it: + +```sh +socket-patch vex --output socket.vex.json --grype-config +``` + +It creates `.grype.yaml` or adds `socket.vex.json` to its `vex-documents` list, +leaving the rest of the file as it was. Run Grype from that directory. Grype fails a +scan whose listed document is missing, so generate the document in CI before Grype +runs, or commit it and regenerate it whenever the patches change; a run that ends +with no document takes the entry out again. + | Patch mode | Evidence used by VEX | | --- | --- | | Agent | Installed patched files, checked against the manifest's hashes |