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
//! End-to-end: assert the typed JSON envelope `sidecars[]` shape
//! for every ecosystem's post-apply advisory path.
//!
//! These tests drive the `socket-patch apply` binary as a subprocess
//! against handcrafted package layouts (the same layouts the crawlers
//! find on real installs). For each ecosystem we:
//!
//!   1. Stage the package directory the crawler expects.
//!   2. Write `.socket/manifest.json` referencing a synthetic PURL.
//!   3. Drop the `after_hash` blob under `.socket/blobs/<hash>` so
//!      apply runs fully offline.
//!   4. Invoke `socket-patch apply --json` with `--global-prefix`
//!      pointed at the package root, plus any per-ecosystem env
//!      gates (e.g. `SOCKET_EXPERIMENTAL_NUGET=1`,
//!      `NUGET_PACKAGES=<path>`, `GOMODCACHE=<path>`).
//!   5. Parse the JSON envelope and assert the structured
//!      `envelope.sidecars[]` record matches the ecosystem's
//!      expected `code` / `severity` / `files[]` contract.
//!
//! These are the load-bearing tests that lock the **typed** sidecar
//! JSON contract (codes are stable snake_case enum tags, severity is
//! a stable bucket) that downstream consumers — CI bots, the Socket
//! dashboard, jq pipelines, telemetry — branch on. A future refactor
//! that renames a code, flips a severity, or moves the data
//! elsewhere fires here loudly.
//!
//! Network: no. Toolchain: none. These run on every PR.

use std::path::Path;

#[path = "common/mod.rs"]
mod common;

use common::{
    git_sha256, parse_json_envelope, run_with_env, write_blob, write_minimal_manifest,
    PatchEntry,
};

/// Helper: stage a package layout + manifest + blob, run apply, and
/// return the parsed JSON envelope.
///
/// `package_root` is the directory the crawler will be pointed at via
/// `--global-prefix`; the manifest lives in `cwd/.socket/`. The two
/// are separated because `--global-prefix` semantics expect the
/// ecosystem's root (e.g. `$GOMODCACHE`, `$NUGET_PACKAGES`, site-
/// packages) which is not the same as the `--cwd` where `.socket/`
/// lives.
///
/// `extra_env` adds env vars only to the child process (the parent's
/// env is untouched so tests stay parallel-safe).
fn apply_and_parse(
    cwd: &Path,
    package_root: &Path,
    extra_env: &[(&str, &str)],
) -> serde_json::Value {
    let (_code, stdout, stderr) = run_with_env(
        cwd,
        &[
            "apply",
            "--json",
            "--cwd",
            cwd.to_str().unwrap(),
            "--global-prefix",
            package_root.to_str().unwrap(),
        ],
        extra_env,
    );
    if stdout.trim().is_empty() {
        panic!(
            "socket-patch apply emitted no JSON.\nstderr:\n{stderr}"
        );
    }
    parse_json_envelope(&stdout)
}

/// Locate the first `envelope.sidecars[]` record matching the given
/// ecosystem tag, or panic with the full envelope on miss. Tests use
/// this to drill into the per-ecosystem record without re-implementing
/// the lookup five times.
fn find_sidecar_record<'a>(
    env: &'a serde_json::Value,
    ecosystem: &str,
) -> &'a serde_json::Value {
    let sidecars = env["sidecars"]
        .as_array()
        .unwrap_or_else(|| panic!("envelope.sidecars must be an array.\nenv: {env}"));
    sidecars
        .iter()
        .find(|s| s["ecosystem"] == ecosystem)
        .unwrap_or_else(|| {
            panic!(
                "envelope.sidecars must contain a record with ecosystem={ecosystem}.\nenv: {env}"
            )
        })
}

// ─────────────────────────────────────────────────────────────────────
// PyPI — advisory-only, code = pypi_record_stale
// ─────────────────────────────────────────────────────────────────────

/// PyPI: patching a file inside a `dist-info`-discovered package
/// emits a `pypi_record_stale` advisory at severity `warning`.
///
/// Locks in the contract: PyPI's sidecar path is advisory-only (no
/// file rewrites yet — `.dist-info/RECORD` rewriter is a follow-up),
/// `files[]` is present but empty, and the advisory carries the
/// stable `pypi_record_stale` enum tag.
#[test]
fn pypi_apply_emits_pypi_record_stale_advisory() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path();
    let site_packages = cwd.join("site-packages");

    // Stage a synthetic dist-info that the python crawler will
    // recognize (`Name:` + `Version:` headers in METADATA).
    let dist_info = site_packages.join("requests-2.28.0.dist-info");
    std::fs::create_dir_all(&dist_info).unwrap();
    std::fs::write(
        dist_info.join("METADATA"),
        "Metadata-Version: 2.1\nName: requests\nVersion: 2.28.0\n",
    )
    .unwrap();

    // The file we'll "patch". The Python crawler returns the
    // site-packages dir itself as `pkg_path`, so the manifest
    // file_name is resolved relative to site-packages.
    let target = site_packages.join("payload.py");
    let original = b"# original\n";
    std::fs::write(&target, original).unwrap();

    let patched = b"# patched\n";
    let before = git_sha256(original);
    let after = git_sha256(patched);

    let socket_dir = cwd.join(".socket");
    write_minimal_manifest(
        &socket_dir,
        "pkg:pypi/requests@2.28.0",
        "20000001-0000-4001-8001-000000000001",
        &[PatchEntry {
            file_name: "package/payload.py",
            before_hash: &before,
            after_hash: &after,
        }],
    );
    write_blob(&socket_dir, &after, patched);

    let env = apply_and_parse(cwd, &site_packages, &[]);

    // The patch landed on disk before the sidecar fired.
    assert_eq!(std::fs::read(&target).unwrap(), patched);

    let record = find_sidecar_record(&env, "pypi");
    assert_eq!(
        record["purl"], "pkg:pypi/requests@2.28.0",
        "record must denormalize the PURL.\nrecord: {record}"
    );
    // Advisory-only: files[] is present but empty.
    let files = record["files"].as_array().expect("files array");
    assert!(
        files.is_empty(),
        "pypi advisory-only path must report no files[]; got {record}"
    );
    let advisory = record
        .get("advisory")
        .unwrap_or_else(|| panic!("advisory missing.\nrecord: {record}"));
    assert_eq!(
        advisory["code"], "pypi_record_stale",
        "code contract: pypi must emit pypi_record_stale"
    );
    assert_eq!(
        advisory["severity"], "warning",
        "severity contract: pypi advisory is severity=warning"
    );
    assert!(
        advisory["message"]
            .as_str()
            .map(|s| !s.is_empty())
            .unwrap_or(false),
        "advisory.message must be non-empty"
    );
}

// ─────────────────────────────────────────────────────────────────────
// Gem — advisory-only, code = gem_bundle_install_reverts
// ─────────────────────────────────────────────────────────────────────

/// Gem: patching a file inside a `<name>-<version>` gem directory
/// emits a `gem_bundle_install_reverts` advisory at severity `warning`.
///
/// The Ruby crawler treats `<gem_path>/<name>-<version>/` with a
/// `lib/` subdirectory as a valid gem (no `.gemspec` required for
/// the lib-only case).
#[test]
fn gem_apply_emits_gem_bundle_install_reverts_advisory() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path();
    let gem_root = cwd.join("gems");
    let gem_dir = gem_root.join("rails-7.1.0");
    std::fs::create_dir_all(gem_dir.join("lib")).unwrap();

    let target = gem_dir.join("lib").join("rails.rb");
    let original = b"module Rails; end\n";
    std::fs::write(&target, original).unwrap();

    let patched = b"module Rails; VERSION = '7.1.0-patched'.freeze; end\n";
    let before = git_sha256(original);
    let after = git_sha256(patched);

    let socket_dir = cwd.join(".socket");
    write_minimal_manifest(
        &socket_dir,
        "pkg:gem/rails@7.1.0",
        "20000002-0000-4002-8002-000000000002",
        &[PatchEntry {
            file_name: "package/lib/rails.rb",
            before_hash: &before,
            after_hash: &after,
        }],
    );
    write_blob(&socket_dir, &after, patched);

    let env = apply_and_parse(cwd, &gem_root, &[]);

    assert_eq!(std::fs::read(&target).unwrap(), patched);

    let record = find_sidecar_record(&env, "gem");
    assert_eq!(record["purl"], "pkg:gem/rails@7.1.0");
    let files = record["files"].as_array().expect("files array");
    assert!(
        files.is_empty(),
        "gem advisory-only path must report no files[]; got {record}"
    );
    let advisory = record.get("advisory").expect("advisory missing");
    assert_eq!(
        advisory["code"], "gem_bundle_install_reverts",
        "code contract: gem must emit gem_bundle_install_reverts"
    );
    assert_eq!(advisory["severity"], "warning");
}

// ─────────────────────────────────────────────────────────────────────
// Go — advisory-only, code = go_mod_verify_fails
// ─────────────────────────────────────────────────────────────────────

/// Go: patching a file inside a `$GOMODCACHE/<encoded-module>@<ver>/`
/// directory emits a `go_mod_verify_fails` advisory at severity
/// `warning`.
///
/// The Go crawler expects the GOMODCACHE layout: an encoded module
/// path followed by `@<version>/`. We pass both `--global-prefix` and
/// `GOMODCACHE` for redundancy (the apply CLI consumes the former,
/// some downstream code paths read the latter).
#[cfg(feature = "golang")]
#[test]
fn golang_apply_emits_go_mod_verify_fails_advisory() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path();
    let cache = cwd.join("gomodcache");
    // GOMODCACHE layout: <encoded-module>@<version>/. For
    // `github.com/gin-gonic/gin` there are no uppercase letters,
    // so the encoded form equals the path verbatim.
    let module_dir = cache.join("github.com").join("gin-gonic").join("gin@v1.9.1");
    std::fs::create_dir_all(&module_dir).unwrap();

    let target = module_dir.join("gin.go");
    let original = b"package gin\n";
    std::fs::write(&target, original).unwrap();

    let patched = b"package gin\n// patched\n";
    let before = git_sha256(original);
    let after = git_sha256(patched);

    let socket_dir = cwd.join(".socket");
    write_minimal_manifest(
        &socket_dir,
        "pkg:golang/github.com/gin-gonic/gin@v1.9.1",
        "20000003-0000-4003-8003-000000000003",
        &[PatchEntry {
            file_name: "package/gin.go",
            before_hash: &before,
            after_hash: &after,
        }],
    );
    write_blob(&socket_dir, &after, patched);

    let env = apply_and_parse(
        cwd,
        &cache,
        &[("GOMODCACHE", cache.to_str().unwrap())],
    );

    assert_eq!(std::fs::read(&target).unwrap(), patched);

    let record = find_sidecar_record(&env, "golang");
    assert_eq!(
        record["purl"],
        "pkg:golang/github.com/gin-gonic/gin@v1.9.1"
    );
    let files = record["files"].as_array().expect("files array");
    assert!(
        files.is_empty(),
        "golang advisory-only path must report no files[]; got {record}"
    );
    let advisory = record.get("advisory").expect("advisory missing");
    assert_eq!(
        advisory["code"], "go_mod_verify_fails",
        "code contract: golang must emit go_mod_verify_fails"
    );
    assert_eq!(advisory["severity"], "warning");
}

// ─────────────────────────────────────────────────────────────────────
// NuGet — file deletion (no advisory), code path proves
// `.nupkg.metadata` is removed and recorded as `Deleted`
// ─────────────────────────────────────────────────────────────────────

/// NuGet (unsigned): patching a file inside a `<lowercase-name>/<ver>/`
/// global-cache layout deletes `.nupkg.metadata` (the on-disk content
/// hash sidecar) and records the deletion under
/// `envelope.sidecars[].files[]`. No advisory is emitted for the
/// unsigned case — the deletion alone is the operator surface.
#[cfg(feature = "nuget")]
#[test]
fn nuget_apply_deletes_metadata_and_records_files() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path();
    let packages = cwd.join("nuget-packages");
    // Global cache layout: <lowercase-name>/<version>/
    let pkg_dir = packages.join("newtonsoft.json").join("13.0.3");
    std::fs::create_dir_all(pkg_dir.join("lib")).unwrap();

    // The on-disk metadata sidecar the NuGet fixup will remove.
    std::fs::write(
        pkg_dir.join(".nupkg.metadata"),
        r#"{"contentHash":"deadbeef"}"#,
    )
    .unwrap();

    let target = pkg_dir.join("payload.txt");
    let original = b"hello\n";
    std::fs::write(&target, original).unwrap();
    let patched = b"hello patched\n";
    let before = git_sha256(original);
    let after = git_sha256(patched);

    let socket_dir = cwd.join(".socket");
    write_minimal_manifest(
        &socket_dir,
        "pkg:nuget/Newtonsoft.Json@13.0.3",
        "20000004-0000-4004-8004-000000000004",
        &[PatchEntry {
            file_name: "package/payload.txt",
            before_hash: &before,
            after_hash: &after,
        }],
    );
    write_blob(&socket_dir, &after, patched);

    let env = apply_and_parse(
        cwd,
        &packages,
        &[
            ("NUGET_PACKAGES", packages.to_str().unwrap()),
            ("SOCKET_EXPERIMENTAL_NUGET", "1"),
        ],
    );

    // Patch landed.
    assert_eq!(std::fs::read(&target).unwrap(), patched);
    // Sidecar deleted the metadata file.
    assert!(
        !pkg_dir.join(".nupkg.metadata").exists(),
        "nuget fixup must delete .nupkg.metadata"
    );

    let record = find_sidecar_record(&env, "nuget");
    let files = record["files"].as_array().expect("files array");
    assert_eq!(
        files.len(),
        1,
        "expected one file entry for .nupkg.metadata deletion; got {record}"
    );
    assert_eq!(files[0]["path"], ".nupkg.metadata");
    assert_eq!(
        files[0]["action"], "deleted",
        "action contract: .nupkg.metadata is `deleted`, not `rewritten`"
    );
    // No advisory on the unsigned path — the sidecar emits files
    // only. Either `advisory` is absent from JSON or `null`.
    assert!(
        record.get("advisory").is_none() || record["advisory"].is_null(),
        "unsigned nuget path must not emit an advisory; got {record}"
    );
}

/// NuGet `has_signed_marker` non-UTF8 filename skip: dropping a
/// file with a non-UTF8 name into the package directory exercises
/// the `entry.file_name().to_str()` None arm of
/// `has_signed_marker`'s iteration (line 93). The fixup then
/// continues — the sha512 marker isn't present, no advisory; the
/// `.nupkg.metadata` deletion still fires because we stage it too.
///
/// Linux-only (`OsStr::from_bytes` is Unix-gated; macOS HFS+/APFS
/// also accept arbitrary byte sequences in filenames). Falls back
/// to a portable shape on other Unices where the filesystem
/// rejects non-UTF8 names.
#[cfg(all(unix, feature = "nuget"))]
#[test]
fn nuget_apply_with_non_utf8_filename_in_pkg_dir() {
    use std::ffi::OsStr;
    use std::os::unix::ffi::OsStrExt;

    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path();
    let packages = cwd.join("nuget-packages");
    let pkg_dir = packages.join("newtonsoft.json").join("13.0.3");
    std::fs::create_dir_all(pkg_dir.join("lib")).unwrap();
    std::fs::write(
        pkg_dir.join(".nupkg.metadata"),
        r#"{"contentHash":"deadbeef"}"#,
    )
    .unwrap();
    // Drop a file with a non-UTF8 name into the package dir. The
    // sidecar's `has_signed_marker` iteration calls
    // `entry.file_name().to_str()` on each entry; this one returns
    // None and the iteration skips past it (covering line 93 of
    // nuget.rs).
    //
    // APFS/HFS+/ext4 all accept arbitrary byte sequences in
    // filenames; some networked filesystems may reject. If the
    // filesystem rejects, skip — the iteration arm is exercised on
    // the runners where it can run.
    let bad_name = OsStr::from_bytes(&[0xff, 0xfe, b'-', b'b', b'a', b'd']);
    let bad_path = pkg_dir.join(bad_name);
    if std::fs::write(&bad_path, b"binary").is_err() {
        eprintln!("SKIP: filesystem rejects non-UTF8 filenames");
        return;
    }

    let target = pkg_dir.join("payload.txt");
    let original = b"hello\n";
    std::fs::write(&target, original).unwrap();
    let patched = b"hello patched\n";
    let before = git_sha256(original);
    let after = git_sha256(patched);

    let socket_dir = cwd.join(".socket");
    write_minimal_manifest(
        &socket_dir,
        "pkg:nuget/Newtonsoft.Json@13.0.3",
        "20000007-0000-4007-8007-000000000007",
        &[PatchEntry {
            file_name: "package/payload.txt",
            before_hash: &before,
            after_hash: &after,
        }],
    );
    write_blob(&socket_dir, &after, patched);

    let env = apply_and_parse(
        cwd,
        &packages,
        &[
            ("NUGET_PACKAGES", packages.to_str().unwrap()),
            ("SOCKET_EXPERIMENTAL_NUGET", "1"),
        ],
    );

    // Patch landed and .nupkg.metadata removal succeeded; the
    // non-UTF8 file didn't trip the sidecar (the implicit-skip arm
    // is what we're locking in).
    assert_eq!(std::fs::read(&target).unwrap(), patched);
    assert!(!pkg_dir.join(".nupkg.metadata").exists());

    let record = find_sidecar_record(&env, "nuget");
    let files = record["files"].as_array().expect("files array");
    assert_eq!(files.len(), 1, "metadata deletion expected");
    assert_eq!(files[0]["path"], ".nupkg.metadata");
    // No advisory — the non-UTF8 file is NOT a `.nupkg.sha512`
    // marker (its name isn't even valid UTF-8), so the signed-
    // package branch stays cold.
    assert!(
        record.get("advisory").is_none() || record["advisory"].is_null(),
        "non-UTF8 file must not trigger the signed-marker advisory; got {record}"
    );
}

/// NuGet sidecar I/O-error boundary: when `.nupkg.metadata` exists
/// as a *directory* (not a file), `tokio::fs::remove_file` fails
/// with a non-NotFound error and `nuget::fixup` returns
/// `SidecarError::Io`. The boundary in `apply_package_patch`
/// converts that into a `sidecar_fixup_failed` advisory.
///
/// Covers the non-NotFound arm of the remove_file match in
/// `sidecars/nuget.rs` (lines 50-54) — the path the existing
/// success and signed-package tests can't reach. As with the
/// cargo equivalent, the directory-as-file ruse beats chmod
/// because it fails uniformly across uids and platforms.
#[cfg(feature = "nuget")]
#[test]
fn nuget_apply_with_metadata_directory_reports_sidecar_fixup_failed() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path();
    let packages = cwd.join("nuget-packages");
    let pkg_dir = packages.join("newtonsoft.json").join("13.0.3");
    std::fs::create_dir_all(pkg_dir.join("lib")).unwrap();
    // `.nupkg.metadata` as a non-empty directory. remove_file
    // refuses to unlink a directory; that's an EISDIR-class I/O
    // error, not NotFound.
    std::fs::create_dir(pkg_dir.join(".nupkg.metadata")).unwrap();
    std::fs::write(
        pkg_dir.join(".nupkg.metadata").join("placeholder"),
        b"non-empty so the dir can't be remove_file-removed even on permissive platforms",
    )
    .unwrap();

    let target = pkg_dir.join("payload.txt");
    let original = b"hello\n";
    std::fs::write(&target, original).unwrap();
    let patched = b"hello patched\n";
    let before = git_sha256(original);
    let after = git_sha256(patched);

    let socket_dir = cwd.join(".socket");
    write_minimal_manifest(
        &socket_dir,
        "pkg:nuget/Newtonsoft.Json@13.0.3",
        "20000006-0000-4006-8006-000000000006",
        &[PatchEntry {
            file_name: "package/payload.txt",
            before_hash: &before,
            after_hash: &after,
        }],
    );
    write_blob(&socket_dir, &after, patched);

    let env = apply_and_parse(
        cwd,
        &packages,
        &[
            ("NUGET_PACKAGES", packages.to_str().unwrap()),
            ("SOCKET_EXPERIMENTAL_NUGET", "1"),
        ],
    );

    // Patch landed (atomic write commits before the sidecar runs).
    assert_eq!(std::fs::read(&target).unwrap(), patched);

    let record = find_sidecar_record(&env, "nuget");
    let advisory = record.get("advisory").expect("advisory");
    assert_eq!(advisory["code"], "sidecar_fixup_failed");
    assert_eq!(advisory["severity"], "error");
    let msg = advisory["message"].as_str().unwrap_or("");
    assert!(
        msg.contains(".nupkg.metadata"),
        "advisory message must reference the metadata path; got {msg:?}"
    );
    // Boundary contract: failure path emits NO files[] entries.
    let files = record["files"].as_array().expect("files array");
    assert!(
        files.is_empty(),
        "failed fixup must not report any deleted files; got {record}"
    );
}

/// NuGet (signed): when the package also carries a `.nupkg.sha512`
/// signature sidecar, the typed payload surfaces BOTH the metadata-
/// deleted file entry AND a `nuget_signed_package_tampered` advisory
/// at severity `warning`. The old single-variant `SidecarOutcome`
/// design lost the advisory in this case; the typed schema keeps
/// both visible.
#[cfg(feature = "nuget")]
#[test]
fn nuget_apply_signed_package_emits_files_and_advisory() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path();
    let packages = cwd.join("nuget-packages");
    let pkg_dir = packages.join("newtonsoft.json").join("13.0.3");
    std::fs::create_dir_all(pkg_dir.join("lib")).unwrap();

    // Both the content-hash sidecar AND the signed-package marker.
    std::fs::write(
        pkg_dir.join(".nupkg.metadata"),
        r#"{"contentHash":"deadbeef"}"#,
    )
    .unwrap();
    std::fs::write(
        pkg_dir.join("newtonsoft.json.13.0.3.nupkg.sha512"),
        "abc123",
    )
    .unwrap();

    let target = pkg_dir.join("payload.txt");
    let original = b"hello\n";
    std::fs::write(&target, original).unwrap();
    let patched = b"hello patched\n";
    let before = git_sha256(original);
    let after = git_sha256(patched);

    let socket_dir = cwd.join(".socket");
    write_minimal_manifest(
        &socket_dir,
        "pkg:nuget/Newtonsoft.Json@13.0.3",
        "20000005-0000-4005-8005-000000000005",
        &[PatchEntry {
            file_name: "package/payload.txt",
            before_hash: &before,
            after_hash: &after,
        }],
    );
    write_blob(&socket_dir, &after, patched);

    let env = apply_and_parse(
        cwd,
        &packages,
        &[
            ("NUGET_PACKAGES", packages.to_str().unwrap()),
            ("SOCKET_EXPERIMENTAL_NUGET", "1"),
        ],
    );

    let record = find_sidecar_record(&env, "nuget");

    // Files[] still carries the metadata deletion — even in the
    // signed-package case the new schema does NOT collapse this
    // away (old design's bug).
    let files = record["files"].as_array().expect("files array");
    assert_eq!(files.len(), 1, "metadata deletion must still be reported");
    assert_eq!(files[0]["path"], ".nupkg.metadata");
    assert_eq!(files[0]["action"], "deleted");

    // AND the signed-package advisory rides alongside.
    let advisory = record.get("advisory").unwrap_or_else(|| {
        panic!(
            "signed package must emit an advisory alongside files[].\nrecord: {record}"
        )
    });
    assert_eq!(
        advisory["code"], "nuget_signed_package_tampered",
        "code contract: signed-package case emits nuget_signed_package_tampered"
    );
    assert_eq!(advisory["severity"], "warning");
    assert!(advisory["message"]
        .as_str()
        .map(|s| !s.is_empty())
        .unwrap_or(false));
}