socket-patch-cli 3.2.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
//! Full-lifecycle tests for `remove` and `repair`.
//!
//! `remove` exercises the rollback → manifest delete → blob cleanup
//! chain. `repair` exercises blob fetching + GC across all three
//! download modes (file/diff/package). Both are run in-process so
//! coverage is captured.

use std::path::Path;

use serial_test::serial;
use sha2::{Digest, Sha256};
use socket_patch_cli::commands::remove::{run as remove_run, RemoveArgs};
use socket_patch_cli::commands::repair::{run as repair_run, RepairArgs};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

const ORG: &str = "test-org";

fn git_sha256(content: &[u8]) -> String {
    let header = format!("blob {}\0", content.len());
    let mut hasher = Sha256::new();
    hasher.update(header.as_bytes());
    hasher.update(content);
    hex::encode(hasher.finalize())
}

fn write_root(cwd: &Path) {
    std::fs::write(cwd.join("package.json"), r#"{"name":"r","version":"0.0.0"}"#).unwrap();
}

fn write_npm_pkg(cwd: &Path, name: &str, version: &str, file: &str, content: &[u8]) {
    let pkg = cwd.join("node_modules").join(name);
    std::fs::create_dir_all(&pkg).unwrap();
    std::fs::write(
        pkg.join("package.json"),
        format!(r#"{{ "name": "{name}", "version": "{version}" }}"#),
    )
    .unwrap();
    let p = pkg.join(file);
    if let Some(parent) = p.parent() {
        std::fs::create_dir_all(parent).unwrap();
    }
    std::fs::write(p, content).unwrap();
}

// ---------------------------------------------------------------------------
// remove full lifecycle: rollback first, then drop from manifest, then GC
// ---------------------------------------------------------------------------

#[tokio::test]
#[serial]
async fn remove_with_rollback_full_chain() {
    let tmp = tempfile::tempdir().unwrap();
    write_root(tmp.path());

    let original = b"original\n";
    let patched = b"patched\n";
    let before_hash = git_sha256(original);
    let after_hash = git_sha256(patched);

    // Installed package — currently in the PATCHED state, so remove
    // should roll it back to original via the beforeHash blob.
    write_npm_pkg(tmp.path(), "remove-target", "1.0.0", "index.js", patched);

    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{ "patches": {{
                "pkg:npm/remove-target@1.0.0": {{
                    "uuid": "11111111-1111-4111-8111-111111111111",
                    "exportedAt": "2024-01-01T00:00:00Z",
                    "files": {{ "package/index.js": {{
                        "beforeHash": "{before_hash}", "afterHash": "{after_hash}"
                    }}}},
                    "vulnerabilities": {{}}, "description": "x",
                    "license": "MIT", "tier": "free"
                }}
            }}}}"#
        ),
    )
    .unwrap();
    let blobs = socket.join("blobs");
    std::fs::create_dir_all(&blobs).unwrap();
    std::fs::write(blobs.join(&before_hash), original).unwrap();
    std::fs::write(blobs.join(&after_hash), patched).unwrap();

    let args = RemoveArgs {
        common: socket_patch_cli::args::GlobalArgs {
            cwd: tmp.path().to_path_buf(),
            manifest_path: ".socket/manifest.json".to_string(),
            yes: true,
            global: false,
            global_prefix: None,
            json: true,
            ..socket_patch_cli::args::GlobalArgs::default()
        },
        identifier: "pkg:npm/remove-target@1.0.0".to_string(),
        skip_rollback: false,
    };
    let code = remove_run(args).await;
    assert_eq!(code, 0, "remove with rollback must succeed");

    // 1. File restored to original.
    assert_eq!(
        std::fs::read(tmp.path().join("node_modules/remove-target/index.js")).unwrap(),
        original
    );
    // 2. Manifest no longer has the entry.
    let m: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(socket.join("manifest.json")).unwrap())
            .unwrap();
    assert_eq!(m["patches"].as_object().unwrap().len(), 0);
    // 3. Blobs no longer referenced — cleanup should have removed them.
    let blobs_remaining: Vec<_> = std::fs::read_dir(&blobs).unwrap().flatten().collect();
    assert!(
        blobs_remaining.is_empty(),
        "blob cleanup must remove orphaned blobs after remove; still present: {:?}",
        blobs_remaining
    );
}

#[tokio::test]
#[serial]
async fn remove_by_uuid_finds_correct_purl() {
    let tmp = tempfile::tempdir().unwrap();
    write_root(tmp.path());
    let uuid = "abcdef01-2345-4789-8abc-def012345678";

    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{ "patches": {{
                "pkg:npm/uuid-remove@1.0.0": {{
                    "uuid": "{uuid}",
                    "exportedAt": "2024-01-01T00:00:00Z",
                    "files": {{}}, "vulnerabilities": {{}},
                    "description": "x", "license": "MIT", "tier": "free"
                }}
            }}}}"#
        ),
    )
    .unwrap();

    let args = RemoveArgs {
        common: socket_patch_cli::args::GlobalArgs {
            cwd: tmp.path().to_path_buf(),
            manifest_path: ".socket/manifest.json".to_string(),
            yes: true,
            global: false,
            global_prefix: None,
            json: true,
            ..socket_patch_cli::args::GlobalArgs::default()
        },
        identifier: uuid.to_string(),
        skip_rollback: true,
    };
    assert_eq!(remove_run(args).await, 0);
    let m: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(socket.join("manifest.json")).unwrap())
            .unwrap();
    assert_eq!(m["patches"].as_object().unwrap().len(), 0);
}

#[tokio::test]
#[serial]
async fn remove_no_matching_purl_exits_not_found() {
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(socket.join("manifest.json"), r#"{ "patches": {} }"#).unwrap();

    let args = RemoveArgs {
        common: socket_patch_cli::args::GlobalArgs {
            cwd: tmp.path().to_path_buf(),
            manifest_path: ".socket/manifest.json".to_string(),
            yes: true,
            global: false,
            global_prefix: None,
            json: true,
            ..socket_patch_cli::args::GlobalArgs::default()
        },
        identifier: "pkg:npm/does-not-exist@9.9.9".to_string(),
        skip_rollback: true,
    };
    assert_eq!(remove_run(args).await, 1);
}

#[tokio::test]
#[serial]
async fn remove_invalid_manifest_emits_error() {
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(socket.join("manifest.json"), "{ not json").unwrap();

    let args = RemoveArgs {
        common: socket_patch_cli::args::GlobalArgs {
            cwd: tmp.path().to_path_buf(),
            manifest_path: ".socket/manifest.json".to_string(),
            yes: true,
            global: false,
            global_prefix: None,
            json: true,
            ..socket_patch_cli::args::GlobalArgs::default()
        },
        identifier: "pkg:npm/anything@1.0.0".to_string(),
        skip_rollback: true,
    };
    assert_eq!(remove_run(args).await, 1);
}

#[tokio::test]
#[serial]
async fn remove_no_manifest_emits_not_found() {
    let tmp = tempfile::tempdir().unwrap();
    let args = RemoveArgs {
        common: socket_patch_cli::args::GlobalArgs {
            cwd: tmp.path().to_path_buf(),
            manifest_path: ".socket/manifest.json".to_string(),
            yes: true,
            global: false,
            global_prefix: None,
            json: true,
            ..socket_patch_cli::args::GlobalArgs::default()
        },
        identifier: "pkg:npm/anything@1.0.0".to_string(),
        skip_rollback: true,
    };
    assert_eq!(remove_run(args).await, 1);
}

// ---------------------------------------------------------------------------
// repair: download in all three modes (file/diff/package)
// ---------------------------------------------------------------------------

fn make_repair_args(cwd: &Path, mode: &str) -> RepairArgs {
    RepairArgs {
        common: socket_patch_cli::args::GlobalArgs {
            cwd: cwd.to_path_buf(),
            manifest_path: ".socket/manifest.json".to_string(),
            dry_run: false,
            offline: false,
            json: true,
            download_mode: mode.to_string(),
            ..socket_patch_cli::args::GlobalArgs::default()
        },
        download_only: false,
    }
}

#[tokio::test]
#[serial]
async fn repair_diff_mode_downloads_diff_archives() {
    let tmp = tempfile::tempdir().unwrap();
    let uuid = "12121212-1212-4121-8121-121212121212";
    let _after_hash = "abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc1";

    let server = MockServer::start().await;
    // Diff mode fetches /v0/orgs/<org>/patches/diff/<uuid> → tar.gz body.
    let fake_archive = b"fake diff archive";
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG}/patches/diff/{uuid}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(fake_archive.to_vec()))
        .mount(&server)
        .await;
    // Fallback blob endpoint should also be available.
    let real_blob = b"real blob content";
    let real_hash = git_sha256(real_blob);
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG}/patches/blob/{real_hash}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(real_blob.to_vec()))
        .mount(&server)
        .await;

    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{ "patches": {{
                "pkg:npm/diff-test@1.0.0": {{
                    "uuid": "{uuid}",
                    "exportedAt": "2024-01-01T00:00:00Z",
                    "files": {{ "package/x.js": {{
                        "beforeHash": "0000000000000000000000000000000000000000000000000000000000000000",
                        "afterHash": "{real_hash}"
                    }}}},
                    "vulnerabilities": {{}}, "description": "x",
                    "license": "MIT", "tier": "free"
                }}
            }}}}"#
        ),
    )
    .unwrap();

    std::env::set_var("SOCKET_API_URL", server.uri());
    std::env::set_var("SOCKET_API_TOKEN", "fake");
    std::env::set_var("SOCKET_ORG_SLUG", ORG);
    let code = repair_run(make_repair_args(tmp.path(), "diff")).await;
    std::env::remove_var("SOCKET_API_URL");
    std::env::remove_var("SOCKET_API_TOKEN");
    std::env::remove_var("SOCKET_ORG_SLUG");
    assert_eq!(code, 0, "repair --download-mode diff must succeed");

    // The diff archive should be on disk at .socket/diffs/<uuid>.tar.gz.
    let archive_path = socket.join(format!("diffs/{uuid}.tar.gz"));
    assert!(
        archive_path.exists(),
        "diff archive must be persisted to {}",
        archive_path.display()
    );
}

#[tokio::test]
#[serial]
async fn repair_package_mode_downloads_package_archives() {
    let tmp = tempfile::tempdir().unwrap();
    let uuid = "13131313-1313-4131-8131-131313131313";
    let _after_hash = "def456def456def456def456def456def456def456def456def456def456def4";

    let server = MockServer::start().await;
    let archive_bytes = b"fake package archive bytes";
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG}/patches/package/{uuid}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(archive_bytes.to_vec()))
        .mount(&server)
        .await;
    let real_blob = b"real blob";
    let real_hash = git_sha256(real_blob);
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG}/patches/blob/{real_hash}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(real_blob.to_vec()))
        .mount(&server)
        .await;

    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{ "patches": {{
                "pkg:npm/pkg-test@1.0.0": {{
                    "uuid": "{uuid}",
                    "exportedAt": "2024-01-01T00:00:00Z",
                    "files": {{ "package/x.js": {{
                        "beforeHash": "0000000000000000000000000000000000000000000000000000000000000000",
                        "afterHash": "{real_hash}"
                    }}}},
                    "vulnerabilities": {{}}, "description": "x",
                    "license": "MIT", "tier": "free"
                }}
            }}}}"#
        ),
    )
    .unwrap();

    std::env::set_var("SOCKET_API_URL", server.uri());
    std::env::set_var("SOCKET_API_TOKEN", "fake");
    std::env::set_var("SOCKET_ORG_SLUG", ORG);
    let code = repair_run(make_repair_args(tmp.path(), "package")).await;
    std::env::remove_var("SOCKET_API_URL");
    std::env::remove_var("SOCKET_API_TOKEN");
    std::env::remove_var("SOCKET_ORG_SLUG");
    assert_eq!(code, 0);
    assert!(socket.join(format!("packages/{uuid}.tar.gz")).exists());
}

#[tokio::test]
#[serial]
async fn repair_file_mode_downloads_individual_blobs() {
    let tmp = tempfile::tempdir().unwrap();
    let blob_content = b"some patched content\n";
    let after_hash = git_sha256(blob_content);

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path(format!("/v0/orgs/{ORG}/patches/blob/{after_hash}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(blob_content.to_vec()))
        .mount(&server)
        .await;

    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{ "patches": {{
                "pkg:npm/file-test@1.0.0": {{
                    "uuid": "14141414-1414-4141-8141-141414141414",
                    "exportedAt": "2024-01-01T00:00:00Z",
                    "files": {{ "package/x.js": {{
                        "beforeHash": "0000000000000000000000000000000000000000000000000000000000000000",
                        "afterHash": "{after_hash}"
                    }}}},
                    "vulnerabilities": {{}}, "description": "x",
                    "license": "MIT", "tier": "free"
                }}
            }}}}"#
        ),
    )
    .unwrap();

    std::env::set_var("SOCKET_API_URL", server.uri());
    std::env::set_var("SOCKET_API_TOKEN", "fake");
    std::env::set_var("SOCKET_ORG_SLUG", ORG);
    let code = repair_run(make_repair_args(tmp.path(), "file")).await;
    std::env::remove_var("SOCKET_API_URL");
    std::env::remove_var("SOCKET_API_TOKEN");
    std::env::remove_var("SOCKET_ORG_SLUG");
    assert_eq!(code, 0);
    assert!(socket.join("blobs").join(&after_hash).exists());
}

#[tokio::test]
#[serial]
async fn repair_dry_run_does_not_download() {
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        r#"{ "patches": {
            "pkg:npm/dryrun@1.0.0": {
                "uuid": "15151515-1515-4151-8151-151515151515",
                "exportedAt": "2024-01-01T00:00:00Z",
                "files": { "package/x.js": {
                    "beforeHash": "0000000000000000000000000000000000000000000000000000000000000000",
                    "afterHash":  "1111111111111111111111111111111111111111111111111111111111111111"
                }},
                "vulnerabilities": {}, "description": "x",
                "license": "MIT", "tier": "free"
            }
        }}"#,
    )
    .unwrap();

    let mut args = make_repair_args(tmp.path(), "file");
    args.common.dry_run = true;
    args.common.offline = true;
    assert_eq!(repair_run(args).await, 0);
    // Nothing should be downloaded.
    assert!(
        !socket.join("blobs").exists() || socket.join("blobs").read_dir().unwrap().count() == 0,
        "dry-run must not download blobs"
    );
}

#[tokio::test]
#[serial]
async fn repair_with_no_manifest_emits_error() {
    let tmp = tempfile::tempdir().unwrap();
    assert_eq!(repair_run(make_repair_args(tmp.path(), "file")).await, 1);
}

/// Regression: a repair where a missing artifact fails to download must
/// exit non-zero. The blob the manifest references is absent from disk AND
/// the mock server has no route for it (→ 404 / not found), so the fetch
/// fails. Before the fix `run()` reported success (exit 0) even though it
/// had marked the run a partial failure and emitted a `Failed` event —
/// hiding the failure from any CI guarding on the exit code.
#[tokio::test]
#[serial]
async fn repair_download_failure_exits_nonzero() {
    let tmp = tempfile::tempdir().unwrap();
    // A valid-format (64 hex) afterHash the server will never serve.
    let after_hash = git_sha256(b"never served by the mock\n");

    // Mock server with NO blob route → every fetch 404s.
    let server = MockServer::start().await;

    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{ "patches": {{
                "pkg:npm/fetch-fail@1.0.0": {{
                    "uuid": "17171717-1717-4171-8171-171717171717",
                    "exportedAt": "2024-01-01T00:00:00Z",
                    "files": {{ "package/x.js": {{
                        "beforeHash": "0000000000000000000000000000000000000000000000000000000000000000",
                        "afterHash": "{after_hash}"
                    }}}},
                    "vulnerabilities": {{}}, "description": "x",
                    "license": "MIT", "tier": "free"
                }}
            }}}}"#
        ),
    )
    .unwrap();

    std::env::set_var("SOCKET_API_URL", server.uri());
    std::env::set_var("SOCKET_API_TOKEN", "fake");
    std::env::set_var("SOCKET_ORG_SLUG", ORG);
    let code = repair_run(make_repair_args(tmp.path(), "file")).await;
    std::env::remove_var("SOCKET_API_URL");
    std::env::remove_var("SOCKET_API_TOKEN");
    std::env::remove_var("SOCKET_ORG_SLUG");

    assert_eq!(
        code, 1,
        "a failed artifact download must surface as a non-zero exit"
    );
    // The blob must not have been written.
    assert!(!socket.join("blobs").join(&after_hash).exists());
}

#[tokio::test]
#[serial]
async fn repair_offline_with_present_blobs_succeeds() {
    let tmp = tempfile::tempdir().unwrap();
    let blob = b"already present\n";
    let hash = git_sha256(blob);

    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{ "patches": {{
                "pkg:npm/present@1.0.0": {{
                    "uuid": "16161616-1616-4161-8161-161616161616",
                    "exportedAt": "2024-01-01T00:00:00Z",
                    "files": {{ "package/x.js": {{
                        "beforeHash": "0000000000000000000000000000000000000000000000000000000000000000",
                        "afterHash": "{hash}"
                    }}}},
                    "vulnerabilities": {{}}, "description": "x",
                    "license": "MIT", "tier": "free"
                }}
            }}}}"#
        ),
    )
    .unwrap();
    let blobs = socket.join("blobs");
    std::fs::create_dir_all(&blobs).unwrap();
    std::fs::write(blobs.join(&hash), blob).unwrap();

    let mut args = make_repair_args(tmp.path(), "file");
    args.common.offline = true;
    assert_eq!(repair_run(args).await, 0);
}