socket-patch-cli 3.3.0

CLI binary for socket-patch: apply, rollback, get, scan security patches
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! `socket-patch vex` — generate an OpenVEX 0.2.0 document.
//!
//! Reads the local manifest, optionally verifies each patch's on-disk
//! state, and emits a VEX document describing the vulnerabilities that
//! have been mitigated. Designed to be piped into vexctl, Grype, Trivy,
//! and the like.
//!
//! Output channels:
//! * Default (`--output` unset, `--json` unset): VEX JSON to stdout,
//!   human-readable status to stderr.
//! * `--output <path>` (no `--json`): VEX JSON to file, one-line
//!   summary to stdout.
//! * `--json` (requires `--output`): VEX JSON to file, envelope JSON
//!   to stdout. This is the CI integration shape.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use clap::Args;
use socket_patch_core::crawlers::CrawlerOptions;
use socket_patch_core::manifest::operations::read_manifest;
use socket_patch_core::manifest::schema::PatchManifest;
use socket_patch_core::utils::telemetry::{track_vex_failed, track_vex_generated};
use socket_patch_core::vex::{
    build_document, detect_product, BuildOptions, Document, FailedPatch, VerifyOutcome,
};

use crate::args::{apply_env_toggles, GlobalArgs};
use crate::ecosystem_dispatch::{find_packages_for_rollback, partition_purls};
use crate::json_envelope::{
    Command, Envelope, EnvelopeError, PatchAction, PatchEvent,
};

#[derive(Args)]
pub struct VexArgs {
    #[command(flatten)]
    pub common: GlobalArgs,

    /// Write the VEX document to this path instead of stdout.
    #[arg(long = "output", short = 'O', env = "SOCKET_VEX_OUTPUT")]
    pub output: Option<PathBuf>,

    /// Override the auto-detected top-level product PURL/identifier.
    /// Auto-detection probes (in order):
    /// 1. `.git/config` `[remote "origin"]` — converted to
    ///    `pkg:github/<owner>/<repo>` for github.com, similar for
    ///    gitlab.com/bitbucket.org, raw URL otherwise.
    /// 2. `package.json` → `pkg:npm/<name>@<version>`
    /// 3. `pyproject.toml` → `pkg:pypi/<name>@<version>`
    /// 4. `Cargo.toml` → `pkg:cargo/<name>@<version>`
    #[arg(long = "product", env = "SOCKET_VEX_PRODUCT")]
    pub product: Option<String>,

    /// Skip the on-disk file-hash check and trust the manifest.
    /// By default every manifest entry is verified before being
    /// emitted; this flag flips that off — useful when generating a
    /// VEX doc on a build machine that doesn't have the patched files
    /// laid out yet.
    #[arg(long = "no-verify", env = "SOCKET_VEX_NO_VERIFY", default_value_t = false)]
    pub no_verify: bool,

    /// Override the document `@id`. Default is `urn:uuid:<random v4>`,
    /// regenerated on every invocation. Pin this to get a reproducible
    /// doc identifier across runs.
    #[arg(long = "doc-id", env = "SOCKET_VEX_DOC_ID")]
    pub doc_id: Option<String>,

    /// Emit compact JSON instead of pretty-printed.
    #[arg(long = "compact", env = "SOCKET_VEX_COMPACT", default_value_t = false)]
    pub compact: bool,
}

/// VEX-generation knobs embedded into `apply` and `scan` via `--vex`.
///
/// `--vex <path>` is the trigger: when set, the host command generates an
/// OpenVEX document at that path after a successful run. The remaining
/// `--vex-*` flags mirror the standalone `vex` command's knobs but are
/// namespaced so they don't collide with the host command's own
/// vocabulary (e.g. apply's `--force`). They are inert unless `--vex` is
/// set.
#[derive(Args, Default, Clone)]
pub struct VexEmbedArgs {
    /// Generate an OpenVEX 0.2.0 document at this path after a successful
    /// run. The document is always written to the file (never stdout), so
    /// it never races the command's own `--json` output.
    #[arg(long = "vex", env = "SOCKET_VEX")]
    pub vex: Option<PathBuf>,

    /// Override the auto-detected top-level product PURL for the VEX
    /// document. See `socket-patch vex --product`.
    #[arg(long = "vex-product", env = "SOCKET_VEX_PRODUCT")]
    pub vex_product: Option<String>,

    /// Skip the on-disk file-hash check when building the VEX document and
    /// trust the manifest. See `socket-patch vex --no-verify`.
    #[arg(long = "vex-no-verify", env = "SOCKET_VEX_NO_VERIFY", default_value_t = false)]
    pub vex_no_verify: bool,

    /// Pin the VEX document `@id`. See `socket-patch vex --doc-id`.
    #[arg(long = "vex-doc-id", env = "SOCKET_VEX_DOC_ID")]
    pub vex_doc_id: Option<String>,

    /// Emit compact (non-pretty) JSON for the VEX document.
    #[arg(long = "vex-compact", env = "SOCKET_VEX_COMPACT", default_value_t = false)]
    pub vex_compact: bool,
}

impl VexEmbedArgs {
    /// Build the core [`VexBuildParams`] from the embedded flags. The
    /// output is always the `--vex` path (embedded VEX never writes to
    /// stdout). Caller must have checked `self.vex.is_some()`.
    pub(crate) fn to_build_params(&self) -> VexBuildParams {
        VexBuildParams {
            output: self.vex.clone(),
            product: self.vex_product.clone(),
            no_verify: self.vex_no_verify,
            doc_id: self.vex_doc_id.clone(),
            compact: self.vex_compact,
        }
    }
}

/// Plain (non-clap) inputs to [`generate_vex`] so the standalone `vex`
/// command and the embedded `apply`/`scan` paths feed one code path.
pub(crate) struct VexBuildParams {
    /// Where to write the document. `None` => stdout (standalone `vex`
    /// only); embedded callers always pass `Some(path)`.
    pub output: Option<PathBuf>,
    pub product: Option<String>,
    pub no_verify: bool,
    pub doc_id: Option<String>,
    pub compact: bool,
}

/// Successful result of [`generate_vex`].
pub(crate) struct VexWriteSummary {
    pub statements: usize,
    pub failed: Vec<FailedPatch>,
    pub wrote_to_file: bool,
    /// The built document — returned so the standalone `vex` command can
    /// emit its per-subcomponent envelope without rebuilding.
    pub doc: Document,
}

/// Failure from [`generate_vex`], carrying a stable code + message the
/// caller surfaces in its own output channel.
pub(crate) struct VexGenError {
    pub code: &'static str,
    pub message: String,
    /// Patches omitted by verification, populated only for the
    /// `no_applicable_patches` case (so callers can list them).
    pub failed: Vec<FailedPatch>,
}

pub async fn run(args: VexArgs) -> i32 {
    apply_env_toggles(&args.common);

    // --json without --output would race the envelope and the VEX doc
    // on the same stdout stream. Bail out with a clear error before
    // doing any work.
    if args.common.json && args.output.is_none() {
        emit_envelope_error_and_track(
            &args,
            "json_requires_output",
            "--json requires --output (the VEX document is itself JSON; \
             route it to a file so the envelope can use stdout)",
        )
        .await;
        return 2;
    }

    let manifest_path = args.common.resolved_manifest_path();

    let manifest = match read_manifest(&manifest_path).await {
        Ok(Some(m)) => m,
        Ok(None) => {
            emit_envelope_error_and_track(
                &args,
                "manifest_not_found",
                &format!("Manifest not found at {}", manifest_path.display()),
            )
            .await;
            return 2;
        }
        Err(e) => {
            emit_envelope_error_and_track(&args, "manifest_unreadable", &e.to_string()).await;
            return 2;
        }
    };

    if manifest.patches.is_empty() {
        emit_envelope_error_and_track(
            &args,
            "no_patches",
            "Manifest is empty — nothing to attest. Run `socket-patch get` \
             or `socket-patch scan --sync` first.",
        )
        .await;
        return 1;
    }

    let params = VexBuildParams {
        output: args.output.clone(),
        product: args.product.clone(),
        no_verify: args.no_verify,
        doc_id: args.doc_id.clone(),
        compact: args.compact,
    };

    match generate_vex(&args.common, &params, &manifest).await {
        Ok(summary) => {
            if args.common.json {
                emit_envelope_success(&summary.doc, &summary.failed);
            } else if summary.wrote_to_file {
                if !args.common.silent {
                    let path = args.output.as_ref().unwrap().display();
                    println!(
                        "Wrote OpenVEX document with {} statement(s) to {path}",
                        summary.statements
                    );
                }
            } else if !args.common.silent {
                eprintln!("Emitted {} VEX statement(s)", summary.statements);
            }
            0
        }
        // `no_applicable_patches` is a soft "nothing to attest" (exit 1)
        // and lists the omitted patches; every other error is a hard
        // failure (exit 2). `generate_vex` already fired telemetry, so
        // these emit-only sinks must not re-track.
        Err(e) if e.code == "no_applicable_patches" => {
            emit_envelope_error_with_failures(&args, e.code, &e.message, &e.failed);
            1
        }
        Err(e) => {
            emit_envelope_error(&args, e.code, &e.message);
            2
        }
    }
}

/// Core VEX pipeline shared by the standalone `vex` command and the
/// embedded `apply`/`scan` `--vex` paths: resolve the product, verify the
/// manifest against disk (unless `no_verify`), build the OpenVEX document,
/// serialize, write (or print to stdout when `output` is `None`), and fire
/// telemetry. Returns a [`VexWriteSummary`] on success or a structured
/// [`VexGenError`] (with a stable code) on failure. All `track_vex_*`
/// telemetry is fired here so every caller reports consistently.
pub(crate) async fn generate_vex(
    common: &GlobalArgs,
    params: &VexBuildParams,
    manifest: &PatchManifest,
) -> Result<VexWriteSummary, VexGenError> {
    // Resolve product.
    let product_id = match resolve_product_id(common, params.product.as_deref()).await {
        Ok(id) => id,
        Err(reason) => return Err(fail(common, "product_undetected", reason).await),
    };

    // Partition manifest into applied / failed.
    let outcome = if params.no_verify {
        VerifyOutcome {
            applied: manifest.patches.keys().cloned().collect(),
            failed: Vec::new(),
        }
    } else {
        let package_paths = resolve_package_paths(common, manifest).await;
        socket_patch_core::vex::applied_patches(manifest, &package_paths).await
    };

    if !outcome.failed.is_empty() && !common.silent && !common.json {
        for f in &outcome.failed {
            eprintln!(
                "Warning: omitting patch for {} from VEX ({})",
                f.purl, f.reason
            );
        }
    }

    // Build the document.
    let opts = BuildOptions {
        product_id,
        doc_id: params
            .doc_id
            .clone()
            .unwrap_or_else(|| format!("urn:uuid:{}", uuid::Uuid::new_v4())),
        author: "Socket".to_string(),
        tooling: Some(format!("socket-patch {}", env!("CARGO_PKG_VERSION"))),
    };

    let doc = match build_document(manifest, &outcome.applied, &opts) {
        Some(doc) => doc,
        None => {
            track_vex_failed(
                "no_applicable_patches",
                common.api_token.as_deref(),
                common.org.as_deref(),
            )
            .await;
            return Err(VexGenError {
                code: "no_applicable_patches",
                message: "No applied patches with vulnerability metadata to attest.".to_string(),
                failed: outcome.failed,
            });
        }
    };

    // Serialize.
    let serialized = if params.compact {
        match serde_json::to_string(&doc) {
            Ok(s) => s,
            Err(e) => return Err(fail(common, "serialize_failed", e.to_string()).await),
        }
    } else {
        match serde_json::to_string_pretty(&doc) {
            Ok(s) => s,
            Err(e) => return Err(fail(common, "serialize_failed", e.to_string()).await),
        }
    };

    // Write.
    let wrote_to_file = match &params.output {
        Some(path) => {
            if let Err(e) = tokio::fs::write(path, &serialized).await {
                return Err(fail(common, "write_failed", e.to_string()).await);
            }
            true
        }
        None => {
            println!("{serialized}");
            false
        }
    };

    track_vex_generated(
        doc.statements.len(),
        "openvex-0.2.0",
        if wrote_to_file { "file" } else { "stdout" },
        common.api_token.as_deref(),
        common.org.as_deref(),
    )
    .await;

    Ok(VexWriteSummary {
        statements: doc.statements.len(),
        failed: outcome.failed,
        wrote_to_file,
        doc,
    })
}

/// Read the manifest at `manifest_path`, then [`generate_vex`]. Manifest
/// read failures are wrapped as [`VexGenError`] so embedded callers
/// (`apply`/`scan`) get a single error channel. Used by the embedded
/// `--vex` paths, which always write to a file.
pub(crate) async fn generate_vex_from_manifest_path(
    common: &GlobalArgs,
    params: &VexBuildParams,
    manifest_path: &Path,
) -> Result<VexWriteSummary, VexGenError> {
    let manifest = match read_manifest(manifest_path).await {
        Ok(Some(m)) => m,
        Ok(None) => {
            return Err(fail(
                common,
                "manifest_not_found",
                format!("Manifest not found at {}", manifest_path.display()),
            )
            .await)
        }
        Err(e) => return Err(fail(common, "manifest_unreadable", e.to_string()).await),
    };
    if manifest.patches.is_empty() {
        return Err(fail(
            common,
            "no_patches",
            "Manifest is empty — nothing to attest.".to_string(),
        )
        .await);
    }
    generate_vex(common, params, &manifest).await
}

/// Fire `vex_failed` telemetry and build the matching [`VexGenError`].
/// Centralizes the "track then return error" pattern in [`generate_vex`].
async fn fail(common: &GlobalArgs, code: &'static str, message: String) -> VexGenError {
    track_vex_failed(code, common.api_token.as_deref(), common.org.as_deref()).await;
    VexGenError {
        code,
        message,
        failed: Vec::new(),
    }
}

/// Pick the product PURL from an explicit override or by filesystem
/// auto-detect.
async fn resolve_product_id(common: &GlobalArgs, product: Option<&str>) -> Result<String, String> {
    if let Some(p) = product {
        return Ok(p.to_string());
    }
    let detect = detect_product(&common.cwd).await;
    for w in &detect.warnings {
        if !common.silent && !common.json {
            eprintln!("Warning: {w}");
        }
    }
    detect.purl.ok_or_else(|| {
        format!(
            "Could not auto-detect a top-level product PURL in {}. \
             Provide one with --product <purl> (e.g. pkg:npm/my-app@1.0.0).",
            common.cwd.display()
        )
    })
}

/// Walk the ecosystem dispatch to build the PURL -> on-disk-path map
/// used by `vex::verify::applied_patches`.
async fn resolve_package_paths(
    common: &GlobalArgs,
    manifest: &PatchManifest,
) -> HashMap<String, PathBuf> {
    let purls: Vec<String> = manifest.patches.keys().cloned().collect();
    let partitioned = partition_purls(&purls, common.ecosystems.as_deref());
    let crawler_options = CrawlerOptions {
        cwd: common.cwd.clone(),
        global: common.global,
        global_prefix: common.global_prefix.clone(),
        batch_size: 0, // unused for find_packages_for_rollback
    };
    // Use the rollback (qualified-aware) resolver, NOT
    // `find_packages_for_purls`. Release-variant ecosystems
    // (PyPI / RubyGems / Maven) key the manifest by *qualified* PURLs
    // (`?artifact_id=`, `?platform=`, `?classifier=&ext=`), but the
    // crawler only knows the *base* PURL. `find_packages_for_purls`
    // would key the result map by the base PURL, so the qualified
    // lookups in `vex::applied_patches` would all miss and every
    // PyPI/Gem/Maven patch would be silently dropped from the VEX doc
    // as `package_not_found`. The rollback variant fans each base path
    // back out to every qualified manifest PURL — the same mapping the
    // manifest was written with (`get` uses the same resolver).
    find_packages_for_rollback(&partitioned, &crawler_options, common.silent).await
}

fn emit_envelope_error(args: &VexArgs, code: &str, message: &str) {
    if args.common.json {
        let mut env = Envelope::new(Command::Vex);
        env.mark_error(EnvelopeError::new(code, message.to_string()));
        println!("{}", env.to_pretty_json());
    } else {
        eprintln!("Error: {message}");
    }
}

/// Async error sink that mirrors `emit_envelope_error` and also fires
/// the `vex_failed` telemetry event. Centralizes both side effects so
/// each `return` site in `run` only needs one call.
async fn emit_envelope_error_and_track(args: &VexArgs, code: &str, message: &str) {
    track_vex_failed(
        code,
        args.common.api_token.as_deref(),
        args.common.org.as_deref(),
    )
    .await;
    emit_envelope_error(args, code, message);
}

fn emit_envelope_error_with_failures(
    args: &VexArgs,
    code: &str,
    message: &str,
    failures: &[FailedPatch],
) {
    if args.common.json {
        let mut env = Envelope::new(Command::Vex);
        for f in failures {
            env.record(
                PatchEvent::new(PatchAction::Skipped, f.purl.clone())
                    .with_reason(f.reason.clone(), "patch omitted from VEX"),
            );
        }
        env.mark_error(EnvelopeError::new(code, message.to_string()));
        println!("{}", env.to_pretty_json());
    } else {
        eprintln!("Error: {message}");
        for f in failures {
            eprintln!("  omitted: {} ({})", f.purl, f.reason);
        }
    }
}

fn emit_envelope_success(doc: &Document, failures: &[FailedPatch]) {
    let mut env = Envelope::new(Command::Vex);
    for st in &doc.statements {
        for prod in &st.products {
            for sub in &prod.subcomponents {
                env.record(
                    PatchEvent::new(PatchAction::Verified, sub.id.clone())
                        .with_details(serde_json::json!({
                            "vulnerability": st.vulnerability.name,
                            "aliases": st.vulnerability.aliases,
                            "status": "not_affected",
                        })),
                );
            }
        }
    }
    for f in failures {
        env.record(
            PatchEvent::new(PatchAction::Skipped, f.purl.clone())
                .with_reason(f.reason.clone(), "patch omitted from VEX"),
        );
    }
    if !failures.is_empty() {
        env.mark_partial_failure();
    }
    println!("{}", env.to_pretty_json());
}

#[cfg(test)]
mod tests {
    //! Lightweight tests at the args/wiring layer. End-to-end behavior
    //! lives in `tests/e2e_vex*.rs`.
    use super::*;
    use clap::Parser;

    #[derive(Parser)]
    struct Wrap {
        #[command(subcommand)]
        cmd: Sub,
    }

    #[derive(clap::Subcommand)]
    enum Sub {
        Vex(VexArgs),
    }

    #[test]
    fn parses_with_defaults() {
        let w = Wrap::parse_from(["test", "vex"]);
        match w.cmd {
            Sub::Vex(args) => {
                assert!(args.output.is_none());
                assert!(args.product.is_none());
                assert!(!args.no_verify);
                assert!(args.doc_id.is_none());
                assert!(!args.compact);
            }
        }
    }

    #[test]
    fn parses_all_flags() {
        let w = Wrap::parse_from([
            "test",
            "vex",
            "--output",
            "out.vex.json",
            "--product",
            "pkg:npm/app@1.0.0",
            "--no-verify",
            "--doc-id",
            "urn:uuid:fixed",
            "--compact",
        ]);
        match w.cmd {
            Sub::Vex(args) => {
                assert_eq!(args.output.unwrap().to_str(), Some("out.vex.json"));
                assert_eq!(args.product.as_deref(), Some("pkg:npm/app@1.0.0"));
                assert!(args.no_verify);
                assert_eq!(args.doc_id.as_deref(), Some("urn:uuid:fixed"));
                assert!(args.compact);
            }
        }
    }
}