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
//! End-to-end tests for `get` against a wiremock-driven mock API.
//! Exercises every identifier-type branch (UUID, PURL, CVE, GHSA,
//! package-name search) plus the save-and-apply / paid / not-found
//! error paths. Real-API integration stays in `e2e_npm.rs`.

use std::path::{Path, PathBuf};
use std::process::Command;

use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn binary() -> PathBuf {
    env!("CARGO_BIN_EXE_socket-patch").into()
}

const ORG_SLUG: &str = "test-org";
const UUID: &str = "11111111-1111-4111-8111-111111111111";

fn run_get(cwd: &Path, api_url: &str, identifier: &str, extra: &[&str]) -> (i32, String, String) {
    let mut args = vec![
        "get",
        identifier,
        "--json",
        "--save-only",
        "--yes",
        "--api-url",
        api_url,
        "--api-token",
        "fake-token-for-test",
        "--org",
        ORG_SLUG,
    ];
    args.extend_from_slice(extra);
    let out = Command::new(binary())
        .args(&args)
        .current_dir(cwd)
        .output()
        .expect("run socket-patch");
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&out.stdout).to_string(),
        String::from_utf8_lossy(&out.stderr).to_string(),
    )
}

/// PatchResponse JSON suitable as a `view/{uuid}` response. All fields
/// are camelCase as the binary expects.
fn patch_response_json(purl: &str, uuid: &str) -> serde_json::Value {
    // base64 of "patched\n" — content is arbitrary, the save path
    // doesn't verify content hash. The afterHash value is what gets
    // used as the blob filename.
    serde_json::json!({
        "uuid": uuid,
        "purl": purl,
        "publishedAt": "2024-01-01T00:00:00Z",
        "files": {
            "package/index.js": {
                "beforeHash": "0000000000000000000000000000000000000000000000000000000000000000",
                "afterHash":  "1111111111111111111111111111111111111111111111111111111111111111",
                "blobContent": "cGF0Y2hlZAo=",
            }
        },
        "vulnerabilities": {
            "GHSA-test-1234": {
                "cves": ["CVE-2024-12345"],
                "summary": "Test vulnerability",
                "severity": "high",
                "description": "Synthetic test patch",
            }
        },
        "description": "Test patch",
        "license": "MIT",
        "tier": "free",
    })
}

// ---------------------------------------------------------------------------
// UUID identifier — direct fetch via /patches/view/{uuid}
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_by_uuid_save_only_writes_manifest_and_blob() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(patch_response_json(purl, UUID)))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let (code, stdout, stderr) = run_get(tmp.path(), &mock.uri(), UUID, &[]);
    assert_eq!(
        code, 0,
        "get must succeed; stdout={stdout}; stderr={stderr}"
    );
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert_eq!(v["status"], "success");

    // Manifest written under .socket/manifest.json.
    let manifest_path = tmp.path().join(".socket/manifest.json");
    assert!(manifest_path.exists(), "manifest must be written");
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
    let patches = manifest["patches"].as_object().unwrap();
    assert!(patches.contains_key(purl), "manifest must contain PURL key");
    assert_eq!(patches[purl]["uuid"], UUID);

    // Blob written under .socket/blobs/<afterHash>.
    let after_hash = "1111111111111111111111111111111111111111111111111111111111111111";
    let blob_path = tmp.path().join(".socket/blobs").join(after_hash);
    assert!(blob_path.exists(), "blob file must be written");
    let blob_content = std::fs::read(&blob_path).unwrap();
    assert_eq!(blob_content, b"patched\n");
}

#[tokio::test]
async fn get_by_uuid_not_found_emits_envelope() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}")))
        .respond_with(ResponseTemplate::new(404))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let (_, stdout, _) = run_get(tmp.path(), &mock.uri(), UUID, &[]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert_eq!(v["status"], "not_found");
    assert_eq!(v["found"], 0);
}

// ---------------------------------------------------------------------------
// CVE identifier — fetch via /patches/by-cve/{cve}
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_by_cve_returns_matching_patches() {
    let mock = MockServer::start().await;
    let cve = "CVE-2021-44906";
    let purl = "pkg:npm/minimist@1.2.2";

    // by-cve returns SearchResponse shape (lightweight patch metadata).
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/by-cve/{cve}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [{
                "uuid": UUID,
                "purl": purl,
                "publishedAt": "2024-01-01T00:00:00Z",
                "description": "Fixes CVE",
                "license": "MIT",
                "tier": "free",
                "vulnerabilities": {}
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;
    // After selecting a search result, get fetches the full patch.
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(patch_response_json(purl, UUID)))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let (code, stdout, stderr) = run_get(tmp.path(), &mock.uri(), cve, &[]);
    assert_eq!(
        code, 0,
        "get by CVE must succeed; stdout={stdout}; stderr={stderr}"
    );
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert_eq!(v["status"], "success");
    assert!(
        tmp.path().join(".socket/manifest.json").exists(),
        "CVE-based get must write the manifest"
    );
}

#[tokio::test]
async fn get_by_cve_no_match_emits_not_found() {
    let mock = MockServer::start().await;
    let cve = "CVE-2099-99999";
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/by-cve/{cve}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let (_, stdout, _) = run_get(tmp.path(), &mock.uri(), cve, &[]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert_eq!(v["status"], "not_found");
}

// ---------------------------------------------------------------------------
// GHSA identifier — fetch via /patches/by-ghsa/{ghsa}
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_by_ghsa_returns_matching_patches() {
    let mock = MockServer::start().await;
    let ghsa = "GHSA-xvch-5gv4-984h";
    let purl = "pkg:npm/minimist@1.2.2";

    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/by-ghsa/{ghsa}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [{
                "uuid": UUID,
                "purl": purl,
                "publishedAt": "2024-01-01T00:00:00Z",
                "description": "Fixes GHSA",
                "license": "MIT",
                "tier": "free",
                "vulnerabilities": {}
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(patch_response_json(purl, UUID)))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let (code, stdout, _) = run_get(tmp.path(), &mock.uri(), ghsa, &[]);
    assert_eq!(code, 0, "get by GHSA must succeed; stdout={stdout}");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert_eq!(v["status"], "success");
}

// ---------------------------------------------------------------------------
// PURL identifier — fetch via /patches/by-package/{purl}
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_by_purl_returns_matching_patches() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    // URL-encoded form of the PURL (`:` → `%3A`, `/` → `%2F`, `@` → `%40`).
    let encoded = "pkg%3Anpm%2Fminimist%401.2.2";

    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/by-package/{encoded}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [{
                "uuid": UUID,
                "purl": purl,
                "publishedAt": "2024-01-01T00:00:00Z",
                "description": "Patch for purl",
                "license": "MIT",
                "tier": "free",
                "vulnerabilities": {}
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(patch_response_json(purl, UUID)))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let (code, stdout, _) = run_get(tmp.path(), &mock.uri(), purl, &[]);
    assert_eq!(code, 0, "get by PURL must succeed; stdout={stdout}");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert_eq!(v["status"], "success");
}

// ---------------------------------------------------------------------------
// Multiple patches available — JSON mode returns selection_required
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_multiple_patches_in_json_mode_returns_selection_required() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/foo@1.0.0";
    let encoded = "pkg%3Anpm%2Ffoo%401.0.0";
    let uuid_a = "11111111-1111-4111-8111-111111111111";
    let uuid_b = "22222222-2222-4222-8222-222222222222";

    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/by-package/{encoded}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [
                {
                    "uuid": uuid_a,
                    "purl": purl,
                    "publishedAt": "2024-01-01T00:00:00Z",
                    "description": "First patch",
                    "license": "MIT",
                    "tier": "free",
                    "vulnerabilities": {}
                },
                {
                    "uuid": uuid_b,
                    "purl": purl,
                    "publishedAt": "2024-02-01T00:00:00Z",
                    "description": "Second patch",
                    "license": "MIT",
                    "tier": "free",
                    "vulnerabilities": {}
                }
            ],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let (code, stdout, _) = run_get(tmp.path(), &mock.uri(), purl, &[]);
    // With multiple free patches and --json, get must NOT prompt
    // interactively — it must emit a selection_required envelope so
    // the caller can pick one via --id.
    assert!(
        code == 0 || code == 1,
        "should exit with a stable code; got {code}"
    );
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    let status = v["status"].as_str().expect("status string");
    assert!(
        status == "selection_required" || status == "success",
        "expected selection_required or success in JSON multi-patch path; got {status}: {v}"
    );
}

// ---------------------------------------------------------------------------
// Paid patch path
// ---------------------------------------------------------------------------

/// UUID-by-UUID fetch via public proxy when the patch is paid:
/// the binary recognises the identifier as a UUID, hits the
/// `/patch/view/<uuid>` endpoint on the proxy, sees `tier: "paid"`
/// in the response, and emits a `paid_required` JSON envelope.
/// Covers the UUID-specific branch of the paid path in
/// `commands::get::run`.
#[tokio::test]
async fn get_uuid_paid_patch_via_public_proxy_emits_paid_required_envelope() {
    let mock = MockServer::start().await;

    // Public-proxy view-by-UUID endpoint.
    Mock::given(method("GET"))
        .and(path(format!("/patch/view/{UUID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "uuid": UUID,
            "purl": "pkg:npm/paid-by-uuid@1.0.0",
            "publishedAt": "2024-01-01T00:00:00Z",
            "files": {},
            "vulnerabilities": {},
            "description": "Paid patch fetched by UUID",
            "license": "MIT",
            "tier": "paid",
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let out = Command::new(binary())
        .args([
            "get",
            UUID,
            "--json",
            "--save-only",
            "--yes",
            "--api-url",
            &mock.uri(),
        ])
        .current_dir(tmp.path())
        .env("SOCKET_PATCH_PROXY_URL", mock.uri())
        .env_remove("SOCKET_API_TOKEN")
        .output()
        .expect("run socket-patch");

    let stdout = String::from_utf8_lossy(&out.stdout);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
        panic!("invalid JSON envelope: {e}\nstdout:\n{stdout}\nstderr:\n{}",
            String::from_utf8_lossy(&out.stderr))
    });
    assert_eq!(
        v["status"], "paid_required",
        "UUID-fetched paid patch via public proxy must emit paid_required; got {v}"
    );
    assert_eq!(v["found"], 1);
    assert_eq!(v["downloaded"], 0);
    assert_eq!(v["applied"], 0);
    let patches = v["patches"].as_array().expect("patches array");
    assert_eq!(patches.len(), 1);
    assert_eq!(patches[0]["uuid"], UUID);
    assert_eq!(patches[0]["tier"], "paid");
}

#[tokio::test]
async fn get_paid_patch_via_public_proxy_returns_paid_required() {
    // When using the public proxy (no api-token + no org), a paid patch
    // returns a `paid_required` status. To simulate this we DON'T pass
    // --api-token / --org so the binary falls back to the public proxy.
    // We also have to point SOCKET_PATCH_PROXY_URL at the mock.
    let mock = MockServer::start().await;
    let purl = "pkg:npm/paidpkg@1.0.0";
    let encoded = "pkg%3Anpm%2Fpaidpkg%401.0.0";

    // Public-proxy by-package path: /patch/by-package/...
    Mock::given(method("GET"))
        .and(path(format!("/patch/by-package/{encoded}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [{
                "uuid": UUID,
                "purl": purl,
                "publishedAt": "2024-01-01T00:00:00Z",
                "description": "Paid patch",
                "license": "MIT",
                "tier": "paid",
                "vulnerabilities": {}
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let out = Command::new(binary())
        .args([
            "get",
            purl,
            "--json",
            "--save-only",
            "--yes",
            "--api-url",
            &mock.uri(),
        ])
        .current_dir(tmp.path())
        .env("SOCKET_PATCH_PROXY_URL", mock.uri())
        .env_remove("SOCKET_API_TOKEN")
        .output()
        .expect("run socket-patch");

    let stdout = String::from_utf8_lossy(&out.stdout);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    // The exact status varies by code path (paid_required vs error),
    // but it must NOT be `success` because no paid token was provided.
    let status = v["status"].as_str().expect("status string");
    assert_ne!(
        status, "success",
        "paid patch without token must not succeed; got: {v}"
    );
}