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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! End-to-end tests for `scan` against a local `wiremock` server.
//!
//! These tests spawn the real `socket-patch` binary as a subprocess and
//! point it at a mock HTTP server bound to an ephemeral port. They
//! exercise the full network code path — URL construction, header
//! handling, JSON deserialization, the action-decision logic — without
//! depending on the live Socket API. The real-API end-to-end suite
//! lives in `e2e_scan.rs` (gated behind `#[ignore]`).

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";

/// Write a minimal npm fixture under `<root>/node_modules/<name>/`.
/// scan's npm crawler walks node_modules and reads each package.json
/// to derive the installed PURL.
fn write_npm_package(root: &Path, name: &str, version: &str) {
    let pkg_dir = root.join("node_modules").join(name);
    std::fs::create_dir_all(&pkg_dir).expect("create pkg dir");
    let pkg_json = format!(
        r#"{{ "name": "{name}", "version": "{version}" }}"#
    );
    std::fs::write(pkg_dir.join("package.json"), pkg_json).expect("write pkg json");
}

fn write_root_package_json(root: &Path) {
    std::fs::write(
        root.join("package.json"),
        r#"{ "name": "scan-test-root", "version": "0.0.0" }"#,
    )
    .expect("write root package.json");
}

/// Run `socket-patch scan` against the given mock server URL.
fn run_scan(cwd: &Path, api_url: &str, extra: &[&str]) -> (i32, String, String) {
    let mut args = vec![
        "scan",
        "--json",
        "--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(),
    )
}

// ---------------------------------------------------------------------------
// Discovery — no installed packages, no API calls expected
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_with_no_installed_packages_reports_zero() {
    let mock = MockServer::start().await;
    // Even with no packages, scan still hits the batch endpoint with an
    // empty body if the crawler returns anything. Register a permissive
    // mock so the test doesn't fail on an unexpected call.
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());

    let (code, stdout, stderr) = run_scan(tmp.path(), &mock.uri(), &[]);
    assert_eq!(
        code, 0,
        "scan with no packages 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_eq!(v["scannedPackages"], 0);
    assert_eq!(v["packagesWithPatches"], 0);
    assert_eq!(v["totalPatches"], 0);
}

// ---------------------------------------------------------------------------
// Discovery — installed package matches an available patch
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_reports_available_patch_for_installed_package() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [{
                "purl": purl,
                "patches": [{
                    "uuid": "11111111-1111-4111-8111-111111111111",
                    "purl": purl,
                    "tier": "free",
                    "cveIds": ["CVE-2021-44906"],
                    "ghsaIds": ["GHSA-xvch-5gv4-984h"],
                    "severity": "high",
                    "title": "Prototype Pollution"
                }]
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "minimist", "1.2.2");

    let (code, stdout, stderr) = run_scan(tmp.path(), &mock.uri(), &[]);
    assert_eq!(
        code, 0,
        "scan 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_eq!(v["packagesWithPatches"], 1);
    assert_eq!(v["totalPatches"], 1);
    assert_eq!(v["freePatches"], 1);
    assert_eq!(v["paidPatches"], 0);

    // The packages array carries per-package patch metadata.
    let packages = v["packages"].as_array().expect("packages array");
    assert_eq!(packages.len(), 1);
    assert_eq!(packages[0]["purl"], purl);
    let patches = packages[0]["patches"].as_array().unwrap();
    assert_eq!(patches.len(), 1);
    assert_eq!(patches[0]["uuid"], "11111111-1111-4111-8111-111111111111");
    assert_eq!(patches[0]["severity"], "high");
}

// ---------------------------------------------------------------------------
// Discovery — `updates[]` diff detection
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_emits_updates_entry_when_newer_uuid_available() {
    // Pre-populate the manifest with an older UUID, then have the API
    // return a NEWER UUID for the same PURL. scan must add an entry to
    // `updates` showing the diff.
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    let new_uuid = "99999999-9999-4999-8999-999999999999";
    let old_uuid = "11111111-1111-4111-8111-111111111111";
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [{
                "purl": purl,
                "patches": [{
                    "uuid": new_uuid,
                    "purl": purl,
                    "tier": "free",
                    "cveIds": [],
                    "ghsaIds": [],
                    "severity": "high",
                    "title": "Newer patch"
                }]
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "minimist", "1.2.2");
    // Manifest with the older UUID — scan should detect the diff.
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{
  "patches": {{
    "{purl}": {{
      "uuid": "{old_uuid}",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {{}},
      "vulnerabilities": {{}},
      "description": "old",
      "license": "MIT",
      "tier": "free"
    }}
  }}
}}"#
        ),
    )
    .unwrap();

    let (code, stdout, _) = run_scan(tmp.path(), &mock.uri(), &[]);
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    let updates = v["updates"].as_array().expect("updates array");
    assert_eq!(updates.len(), 1, "one PURL changed UUID");
    assert_eq!(updates[0]["purl"], purl);
    assert_eq!(updates[0]["oldUuid"], old_uuid);
    assert_eq!(updates[0]["newUuid"], new_uuid);
}

// ---------------------------------------------------------------------------
// Discovery — no manifest, no `updates` field (nothing to diff against)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_with_no_manifest_emits_empty_updates() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [{
                "purl": purl,
                "patches": [{
                    "uuid": "22222222-2222-4222-8222-222222222222",
                    "purl": purl,
                    "tier": "free",
                    "cveIds": [],
                    "ghsaIds": [],
                    "severity": "low",
                    "title": "Some patch"
                }]
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "minimist", "1.2.2");
    // No .socket/manifest.json on disk.

    let (code, stdout, _) = run_scan(tmp.path(), &mock.uri(), &[]);
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    // Without a baseline manifest, every patch found is "new" — but
    // scan's `updates` field is the *diff against an existing manifest*,
    // so it should be empty (nothing to compare against). The patches
    // themselves are in `packages[*].patches[*]`.
    assert_eq!(
        v["updates"].as_array().map(|a| a.len()),
        Some(0),
        "updates should be empty when no manifest exists; got: {v}"
    );
    assert_eq!(v["packagesWithPatches"], 1);
}

// ---------------------------------------------------------------------------
// GC field omission contract — `gc` is OPT-IN via --prune / --sync
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_without_prune_omits_gc_field() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    let (_, stdout, _) = run_scan(tmp.path(), &mock.uri(), &[]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert!(
        v.as_object().unwrap().get("gc").is_none(),
        "scan without --prune/--sync must NOT emit `gc`; got: {v}"
    );
}

// ---------------------------------------------------------------------------
// API failure paths
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// --apply --dry-run — synthesizes per-patch actions without writing
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_apply_dry_run_with_empty_manifest_emits_added_action() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    let new_uuid = "11111111-1111-4111-8111-111111111111";

    // batch search response
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [{
                "purl": purl,
                "patches": [{
                    "uuid": new_uuid,
                    "purl": purl,
                    "tier": "free",
                    "cveIds": [],
                    "ghsaIds": [],
                    "severity": "high",
                    "title": "Prototype Pollution"
                }]
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;
    // by-package search (used by --apply mode for full PatchSearchResult)
    Mock::given(method("GET"))
        .and(path(format!(
            "/v0/orgs/{ORG_SLUG}/patches/by-package/pkg%3Anpm%2Fminimist%401.2.2"
        )))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [{
                "uuid": new_uuid,
                "purl": purl,
                "publishedAt": "2024-01-01T00:00:00Z",
                "description": "Fixes prototype pollution",
                "license": "MIT",
                "tier": "free",
                "vulnerabilities": {}
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "minimist", "1.2.2");

    let (code, stdout, stderr) = run_scan(
        tmp.path(),
        &mock.uri(),
        &["--apply", "--dry-run", "--yes"],
    );
    assert_eq!(
        code, 0,
        "scan --apply --dry-run 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");
    let apply = v["apply"]
        .as_object()
        .expect("apply object present in --apply mode");
    assert_eq!(apply["dryRun"], true);
    assert_eq!(apply["found"], 1);
    assert_eq!(apply["added"], 1);
    assert_eq!(apply["updated"], 0);
    assert_eq!(apply["skipped"], 0);
    let patches = apply["patches"].as_array().expect("patches array");
    assert_eq!(patches.len(), 1);
    assert_eq!(patches[0]["action"], "added");
    assert_eq!(patches[0]["uuid"], new_uuid);
    assert_eq!(patches[0]["purl"], purl);

    // CRITICAL: dry-run must not write the manifest.
    assert!(
        !tmp.path().join(".socket/manifest.json").exists(),
        "scan --apply --dry-run must not write .socket/manifest.json"
    );
}

#[tokio::test]
async fn scan_apply_dry_run_with_existing_uuid_emits_skipped_action() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    let same_uuid = "11111111-1111-4111-8111-111111111111";

    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [{
                "purl": purl,
                "patches": [{
                    "uuid": same_uuid,
                    "purl": purl,
                    "tier": "free",
                    "cveIds": [],
                    "ghsaIds": [],
                    "severity": "low",
                    "title": "Some patch"
                }]
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path(format!(
            "/v0/orgs/{ORG_SLUG}/patches/by-package/pkg%3Anpm%2Fminimist%401.2.2"
        )))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [{
                "uuid": same_uuid,
                "purl": purl,
                "publishedAt": "2024-01-01T00:00:00Z",
                "description": "x",
                "license": "MIT",
                "tier": "free",
                "vulnerabilities": {}
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "minimist", "1.2.2");
    // Manifest already has the SAME UUID — scan --apply must skip it.
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{
  "patches": {{
    "{purl}": {{
      "uuid": "{same_uuid}",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {{}},
      "vulnerabilities": {{}},
      "description": "existing",
      "license": "MIT",
      "tier": "free"
    }}
  }}
}}"#
        ),
    )
    .unwrap();

    let (code, stdout, _) = run_scan(
        tmp.path(),
        &mock.uri(),
        &["--apply", "--dry-run", "--yes"],
    );
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    let apply = &v["apply"];
    assert_eq!(apply["skipped"], 1);
    assert_eq!(apply["added"], 0);
    assert_eq!(apply["updated"], 0);
    let patches = apply["patches"].as_array().unwrap();
    assert_eq!(patches[0]["action"], "skipped");
}

#[tokio::test]
async fn scan_apply_dry_run_with_different_uuid_emits_updated_action() {
    let mock = MockServer::start().await;
    let purl = "pkg:npm/minimist@1.2.2";
    let new_uuid = "99999999-9999-4999-8999-999999999999";
    let old_uuid = "11111111-1111-4111-8111-111111111111";

    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [{
                "purl": purl,
                "patches": [{
                    "uuid": new_uuid,
                    "purl": purl,
                    "tier": "free",
                    "cveIds": [],
                    "ghsaIds": [],
                    "severity": "high",
                    "title": "Newer patch"
                }]
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path(format!(
            "/v0/orgs/{ORG_SLUG}/patches/by-package/pkg%3Anpm%2Fminimist%401.2.2"
        )))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "patches": [{
                "uuid": new_uuid,
                "purl": purl,
                "publishedAt": "2024-02-01T00:00:00Z",
                "description": "newer",
                "license": "MIT",
                "tier": "free",
                "vulnerabilities": {}
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "minimist", "1.2.2");
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{
  "patches": {{
    "{purl}": {{
      "uuid": "{old_uuid}",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {{}},
      "vulnerabilities": {{}},
      "description": "older",
      "license": "MIT",
      "tier": "free"
    }}
  }}
}}"#
        ),
    )
    .unwrap();

    let (code, stdout, _) = run_scan(
        tmp.path(),
        &mock.uri(),
        &["--apply", "--dry-run", "--yes"],
    );
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    let apply = &v["apply"];
    assert_eq!(apply["updated"], 1);
    assert_eq!(apply["added"], 0);
    assert_eq!(apply["skipped"], 0);
    let patches = apply["patches"].as_array().unwrap();
    assert_eq!(patches[0]["action"], "updated");
    assert_eq!(patches[0]["oldUuid"], old_uuid);
    assert_eq!(patches[0]["uuid"], new_uuid);
}

// ---------------------------------------------------------------------------
// --prune / --sync — GC field reporting
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_prune_dry_run_reports_prunable_manifest_entries() {
    // Manifest has a patch for a PURL whose package is NOT installed.
    // `--prune --dry-run` should report it as prunable without removing.
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    // Install a real package so scan's crawler has something to scan —
    // the early "no packages" return path skips the prune block entirely.
    write_npm_package(tmp.path(), "fresh-pkg", "1.0.0");
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        r#"{
  "patches": {
    "pkg:npm/uninstalled@1.0.0": {
      "uuid": "11111111-1111-4111-8111-111111111111",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {},
      "vulnerabilities": {},
      "description": "stranded entry",
      "license": "MIT",
      "tier": "free"
    }
  }
}"#,
    )
    .unwrap();

    let (code, stdout, stderr) = run_scan(
        tmp.path(),
        &mock.uri(),
        &["--prune", "--dry-run", "--yes"],
    );
    assert_eq!(code, 0, "expected exit 0; stdout={stdout}; stderr={stderr}");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    let gc = v["gc"].as_object().unwrap_or_else(|| {
        panic!("--prune must emit gc field; full envelope was: {v}")
    });
    // Dry-run uses the *prunable*/* orphan* preview field names per the
    // CLI contract.
    let prunable = gc["prunableManifestEntries"]
        .as_array()
        .expect("prunableManifestEntries present in dry-run gc");
    assert_eq!(prunable.len(), 1);
    assert_eq!(prunable[0], "pkg:npm/uninstalled@1.0.0");

    // Manifest must not have been mutated.
    let body = std::fs::read_to_string(socket.join("manifest.json")).unwrap();
    let manifest: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(manifest["patches"].as_object().unwrap().len(), 1);
}

#[tokio::test]
async fn scan_prune_removes_stale_manifest_entries() {
    // Same setup as the dry-run test, but without `--dry-run` — the
    // stale entry should be REMOVED from the manifest.
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "fresh-pkg", "1.0.0");
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        r#"{
  "patches": {
    "pkg:npm/uninstalled@1.0.0": {
      "uuid": "11111111-1111-4111-8111-111111111111",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {},
      "vulnerabilities": {},
      "description": "stranded",
      "license": "MIT",
      "tier": "free"
    }
  }
}"#,
    )
    .unwrap();

    let (code, stdout, _) = run_scan(tmp.path(), &mock.uri(), &["--prune", "--yes"]);
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    let gc = &v["gc"];
    let pruned = gc["prunedManifestEntries"]
        .as_array()
        .expect("prunedManifestEntries present in apply-mode gc");
    assert_eq!(pruned.len(), 1);

    let body = std::fs::read_to_string(socket.join("manifest.json")).unwrap();
    let manifest: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(
        manifest["patches"].as_object().unwrap().len(),
        0,
        "stale entry must be pruned from manifest"
    );
}

// ---------------------------------------------------------------------------
// API failure paths
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scan_handles_api_500_error_gracefully() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(500).set_body_string("internal server error"))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "minimist", "1.2.2");
    let (code, _stdout, _stderr) = run_scan(tmp.path(), &mock.uri(), &[]);
    // Scan tolerates batch search failure: it reports an empty result
    // rather than crashing. Exit code may be 0 or 1 depending on
    // whether the error is fatal — both are acceptable; we just want
    // to confirm the binary doesn't panic.
    assert!(
        code == 0 || code == 1,
        "scan must not crash on 500; got exit code {code}"
    );
}

// ---------------------------------------------------------------------------
// Lifecycle: withdrawn patches and patch updates
// ---------------------------------------------------------------------------

/// Defensive scoping test for `--prune`: a manifest entry whose package
/// is still installed but for which the API now returns *no* patches
/// (e.g. the upstream withdrew the only patch but the package itself is
/// still present in the project) MUST NOT be silently pruned. The
/// current prune semantics target manifest entries whose PURL is no
/// longer in the crawl results — not entries the API has fallen silent
/// on. If we ever change that, we want to do it deliberately.
#[tokio::test]
async fn scan_prune_keeps_entry_when_package_installed_but_api_silent() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    // The package is still installed locally — only its patch is gone.
    write_npm_package(tmp.path(), "still-installed", "1.0.0");
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(&socket).unwrap();
    let original_manifest = r#"{
  "patches": {
    "pkg:npm/still-installed@1.0.0": {
      "uuid": "22222222-2222-4222-8222-222222222222",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {},
      "vulnerabilities": {},
      "description": "still here, just no patch this scan",
      "license": "MIT",
      "tier": "free"
    }
  }
}"#;
    std::fs::write(socket.join("manifest.json"), original_manifest).unwrap();

    let (code, _stdout, _stderr) = run_scan(tmp.path(), &mock.uri(), &["--prune", "--yes"]);
    assert_eq!(code, 0);

    let body = std::fs::read_to_string(socket.join("manifest.json")).unwrap();
    let manifest: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(
        manifest["patches"].as_object().unwrap().len(),
        1,
        "entry for still-installed package must survive prune when API is silent"
    );
    assert!(
        manifest["patches"]["pkg:npm/still-installed@1.0.0"]
            .as_object()
            .is_some(),
        "the original PURL/UUID record must remain intact"
    );
}

/// Withdrawn-patch lifecycle: a patch present in the manifest for a
/// package that has since been *uninstalled* (no longer in crawl
/// results) must be pruned by `--prune`. This complements
/// `scan_prune_removes_stale_manifest_entries` by additionally placing
/// a stub blob file on disk for the to-be-withdrawn patch and asserting
/// the manifest no longer references it (so `repair` can subsequently
/// GC the blob).
#[tokio::test]
async fn scan_prune_removes_withdrawn_patch_entry() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    // Only a different package is now present — the previously patched
    // package was uninstalled, simulating withdrawal.
    write_npm_package(tmp.path(), "unrelated", "1.0.0");
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(socket.join("blobs")).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        r#"{
  "patches": {
    "pkg:npm/withdrawn-pkg@1.0.0": {
      "uuid": "33333333-3333-4333-8333-333333333333",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {},
      "vulnerabilities": {},
      "description": "withdrawn from upstream",
      "license": "MIT",
      "tier": "free"
    }
  }
}"#,
    )
    .unwrap();
    // Drop a stub blob on disk so we can confirm subsequent `repair`
    // would GC it. Real blob name uses content hash; for prune's
    // purposes the file's mere presence is enough.
    std::fs::write(
        socket.join("blobs").join("stub-blob"),
        b"placeholder bytes for withdrawn patch",
    )
    .unwrap();

    let (code, _stdout, _stderr) = run_scan(tmp.path(), &mock.uri(), &["--prune", "--yes"]);
    assert_eq!(code, 0);

    let manifest: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(socket.join("manifest.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(
        manifest["patches"].as_object().unwrap().len(),
        0,
        "withdrawn entry must be removed"
    );
}

/// Update detection: when the API returns a different UUID for the
/// same PURL that's in the manifest, `scan` surfaces that in the
/// `updates` array even without `--apply`. Sibling to
/// `scan_emits_updates_entry_when_newer_uuid_available` but exercised
/// with a stub blob on disk so we pin the read-only behavior: scan
/// alone never mutates files.
#[tokio::test]
async fn scan_detects_update_without_touching_existing_blobs() {
    const OLD_UUID: &str = "44444444-4444-4444-8444-444444444444";
    const NEW_UUID: &str = "55555555-5555-4555-8555-555555555555";

    let purl = "pkg:npm/lodash@4.17.20";
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "packages": [{
                "purl": purl,
                "patches": [{
                    "uuid": NEW_UUID,
                    "purl": purl,
                    "tier": "free",
                    "cveIds": [],
                    "ghsaIds": [],
                    "severity": "high",
                    "title": "Updated lodash patch",
                }]
            }],
            "canAccessPaidPatches": false,
        })))
        .mount(&mock)
        .await;

    let tmp = tempfile::tempdir().expect("tempdir");
    write_root_package_json(tmp.path());
    write_npm_package(tmp.path(), "lodash", "4.17.20");
    let socket = tmp.path().join(".socket");
    std::fs::create_dir_all(socket.join("blobs")).unwrap();
    std::fs::write(
        socket.join("manifest.json"),
        format!(
            r#"{{
  "patches": {{
    "pkg:npm/lodash@4.17.20": {{
      "uuid": "{OLD_UUID}",
      "exportedAt": "2024-01-01T00:00:00Z",
      "files": {{}},
      "vulnerabilities": {{}},
      "description": "Original lodash patch",
      "license": "MIT",
      "tier": "free"
    }}
  }}
}}"#
        ),
    )
    .unwrap();
    // Marker blob: scan without --apply must leave it untouched.
    let marker = socket.join("blobs").join("untouched-by-scan");
    std::fs::write(&marker, b"original contents").unwrap();

    let (code, stdout, _stderr) = run_scan(tmp.path(), &mock.uri(), &[]);
    assert_eq!(code, 0);

    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    let updates = v["updates"].as_array().expect("updates array present");
    assert_eq!(updates.len(), 1, "exactly one update detected");
    assert_eq!(updates[0]["purl"], "pkg:npm/lodash@4.17.20");
    assert_eq!(updates[0]["oldUuid"], OLD_UUID);
    assert_eq!(updates[0]["newUuid"], NEW_UUID);

    // Critical: scan is read-only. The manifest still records the OLD
    // UUID and the marker blob is byte-for-byte unchanged.
    let manifest: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(socket.join("manifest.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(
        manifest["patches"]["pkg:npm/lodash@4.17.20"]["uuid"], OLD_UUID,
        "scan without --apply must not rewrite the manifest"
    );
    assert_eq!(
        std::fs::read(&marker).unwrap(),
        b"original contents",
        "scan without --apply must not touch existing blobs"
    );
}