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
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
//! Integration coverage for the handful of `cow` + `sidecars`
//! defensive paths that the apply-CLI path cannot reach.
//!
//! These guards (empty patched list, unknown ecosystem, lstat
//! permission-denied, etc.) live in the public API surface of
//! `socket-patch-core` and gate the engine against caller bugs.
//! Apply's own upstream checks prevent the conditions from ever
//! firing in production, which means the apply-CLI integration
//! tests can't drive them — but `cargo llvm-cov --test` over the
//! pub APIs can.
//!
//! Treating these as integration coverage (rather than `#[cfg(test)]`
//! lib unit tests inside the source files) keeps the lift/burden
//! visible in the test binary list and lets coverage tooling see the
//! same code path one consumer would.
//!
//! No network. No toolchain. Unix-gated for the chmod-based test;
//! the rest are portable.

use std::collections::HashMap;

use socket_patch_core::patch::cow::{break_hardlink_if_needed, CowAction};
use socket_patch_core::patch::sidecars::dispatch_fixup;

// ── dispatch_fixup guards ─────────────────────────────────────────────

/// Empty `patched` list short-circuits with `Ok(None)` — guards
/// against callers that forget to check `files_patched.is_empty()`
/// (apply.rs does, but the guard belongs on the engine side too).
/// Covers `sidecars/mod.rs:110`.
#[tokio::test]
async fn dispatch_fixup_empty_patched_returns_none() {
    let tmp = tempfile::tempdir().unwrap();
    let out = dispatch_fixup(
        "pkg:cargo/anything@1.0.0",
        tmp.path(),
        &[],
        &HashMap::new(),
    )
    .await
    .unwrap();
    assert!(out.is_none(), "empty patched must short-circuit to None");
}

/// Unknown PURL ecosystem (no recognized scheme prefix) also
/// short-circuits with `Ok(None)`. Covers `sidecars/mod.rs:115`.
#[tokio::test]
async fn dispatch_fixup_unknown_ecosystem_returns_none() {
    let tmp = tempfile::tempdir().unwrap();
    let out = dispatch_fixup(
        "pkg:totally-not-an-ecosystem/x@1",
        tmp.path(),
        &["x".to_string()],
        &HashMap::new(),
    )
    .await
    .unwrap();
    assert!(out.is_none(), "unknown ecosystem must short-circuit to None");
}

/// `dispatch_fixup` cargo path with a `patched` entry that points
/// at a file that doesn't exist on disk exercises the
/// `sha256_file` error arm inside `update_entries`
/// (cargo.rs:131-133). In the apply-CLI flow this is race-only
/// (apply atomically wrote the file before dispatch_fixup is
/// called), so direct invocation is the only way to drive it
/// from outside the engine.
///
/// The setup: a valid `.cargo-checksum.json` on disk + a `patched`
/// entry naming a file that doesn't exist. cargo::fixup parses the
/// checksum, then `update_entries` walks `patched`, calls
/// `sha256_file(on_disk)`, and the open fails with NotFound. The
/// `.map_err(|source| SidecarError::Io { ... })?` wraps it; the
/// dispatcher returns `Err(SidecarError::Io)`.
#[cfg(feature = "cargo")]
#[tokio::test]
async fn dispatch_fixup_cargo_sha256_file_failure_arm() {
    use socket_patch_core::patch::sidecars::SidecarError;

    let tmp = tempfile::tempdir().unwrap();
    let pkg = tmp.path();
    // Valid checksum so cargo::fixup gets past the parse step.
    std::fs::write(
        pkg.join(".cargo-checksum.json"),
        r#"{"files":{"a.txt":"deadbeef"},"package":"00"}"#,
    )
    .unwrap();
    // Note: we DO NOT create "missing-on-disk.txt" — that's
    // exactly the condition that fires the sha256_file Err arm.

    let result = dispatch_fixup(
        "pkg:cargo/anything@1.0.0",
        pkg,
        &["package/missing-on-disk.txt".to_string()],
        &HashMap::new(),
    )
    .await;

    let err = result.expect_err("missing file in patched list must surface as Err");
    match err {
        SidecarError::Io { path, .. } => {
            assert!(
                path.contains("missing-on-disk.txt"),
                "Io error path must reference the missing file; got {path:?}"
            );
        }
        other => panic!("expected SidecarError::Io, got {other:?}"),
    }
}

/// `dispatch_fixup` against a non-existent `pkg_path` exercises
/// the nuget side: `remove_file(.nupkg.metadata)` returns NotFound
/// (already covered by the success-path tests), then
/// `has_signed_marker` runs and its `read_dir(pkg_path)` ALSO
/// fails — non-existent dir hits the `Err(_) => return false`
/// fallback at nuget.rs:86. The fixup then returns `Ok(None)`.
///
/// Together with the no-metadata + signed-marker tests this nails
/// down every branch in `has_signed_marker`'s setup.
#[cfg(feature = "nuget")]
#[tokio::test]
async fn dispatch_fixup_nuget_with_nonexistent_pkg_path() {
    let tmp = tempfile::tempdir().unwrap();
    let absent = tmp.path().join("does-not-exist");

    let out = dispatch_fixup(
        "pkg:nuget/Anything@1.0.0",
        &absent,
        &["package/file.txt".to_string()],
        &HashMap::new(),
    )
    .await
    .unwrap();
    // No metadata removed (NotFound), no signed marker found
    // (read_dir failed → false), advisory absent → Ok(None).
    assert!(
        out.is_none(),
        "non-existent pkg_path must yield no sidecar record"
    );
}

// ── cow.rs guards ─────────────────────────────────────────────────────

/// `break_hardlink_if_needed` on a path that doesn't exist returns
/// `CowAction::NoFile` (the explicit-NotFound arm). Belt-and-braces
/// case to keep the integration coverage of the lstat arms
/// next to its sibling tests.
#[tokio::test]
async fn cow_missing_path_yields_no_file() {
    let tmp = tempfile::tempdir().unwrap();
    let action =
        break_hardlink_if_needed(&tmp.path().join("does-not-exist.txt"))
            .await
            .expect("lstat NotFound is the explicit early-return arm");
    assert!(matches!(action, CowAction::NoFile));
}

/// `break_hardlink_if_needed` on a path inside a `chmod 0000`
/// parent directory fails the initial `symlink_metadata` call
/// with `EACCES` (search permission denied) — not `NotFound` —
/// hitting the generic `Err(e) => return Err(e)` arm of cow.rs.
/// Covers `cow.rs:59`.
///
/// Skipped under uid 0 because the root user bypasses directory
/// search permission checks, which would silently turn this into
/// a NoFile (NotFound) result and false-pass the test.
#[cfg(unix)]
#[tokio::test]
async fn cow_lstat_permission_denied_propagates_io_error() {
    use std::os::unix::fs::PermissionsExt;
    use std::process::Command;
    if Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim() == "0")
        .unwrap_or(false)
    {
        eprintln!("SKIP: root bypasses dir-search permission checks");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let locked = tmp.path().join("locked");
    std::fs::create_dir(&locked).unwrap();
    let target = locked.join("file.txt");
    std::fs::write(&target, b"content").unwrap();

    // Drop search (x) permission so lstat on `target` fails with
    // EACCES rather than NotFound. Keep read for the directory
    // itself just to be defensive — Unix specifies that EACCES on
    // path resolution comes from missing `x` on a parent.
    let mut perms = std::fs::metadata(&locked).unwrap().permissions();
    perms.set_mode(0o000);
    std::fs::set_permissions(&locked, perms).unwrap();

    let result = break_hardlink_if_needed(&target).await;

    // Restore so tempdir cleanup can recurse.
    let mut restore = std::fs::metadata(&locked).unwrap().permissions();
    restore.set_mode(0o755);
    let _ = std::fs::set_permissions(&locked, restore);

    let err = result.expect_err("expected I/O error from locked-dir lstat");
    // Different OSes pick slightly different errno: Linux returns
    // PermissionDenied, macOS may too. The contract is "not
    // NotFound" — if it were, cow would have returned NoFile.
    assert_ne!(
        err.kind(),
        std::io::ErrorKind::NotFound,
        "expected permission-denied class error; got {err:?}"
    );
}

/// Symlink branch read-fails-fast (cow.rs:66): when the symlink
/// target doesn't exist, the read-through propagates NotFound
/// rather than entering the remove/rewrite dance. Covers the
/// symlink-branch `?` propagation on the read step.
#[cfg(unix)]
#[tokio::test]
async fn cow_symlink_to_missing_target_propagates_read_error() {
    let tmp = tempfile::tempdir().unwrap();
    let link = tmp.path().join("dangling");
    let absent = tmp.path().join("does-not-exist");
    std::os::unix::fs::symlink(&absent, &link).unwrap();

    let err = break_hardlink_if_needed(&link)
        .await
        .expect_err("read through dangling symlink must propagate the error");
    assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
}

/// Symlink branch rename-fails arm: when the symlink itself carries
/// the `uchg` (user-immutable) flag, `read(path)` follows the link
/// and succeeds and the stage file is created fine, but the atomic
/// `rename(stage, path)` over the immutable symlink is refused with
/// EPERM. The error propagates, the stage is cleaned up, and — the
/// key invariant — the original symlink is left intact (CoW never
/// destructively unlinks before the replacement is committed).
///
/// macOS-only: BSD `chflags -h` is the only userspace tool that
/// can set flags on a symlink without dereferencing. Linux's
/// `chattr +i` only works on regular files and needs root.
#[cfg(target_os = "macos")]
#[tokio::test]
async fn cow_symlink_unremovable_propagates_remove_error() {
    use std::process::Command;
    if Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim() == "0")
        .unwrap_or(false)
    {
        eprintln!("SKIP: root bypasses chflags uchg restrictions");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let target = tmp.path().join("real-file.txt");
    std::fs::write(&target, b"content").unwrap();
    let link = tmp.path().join("immutable-link");
    std::os::unix::fs::symlink(&target, &link).unwrap();

    // -h applies the flag to the symlink itself, not its target.
    // Without it, chflags follows the link and sets uchg on the
    // regular file — wrong test.
    let status = Command::new("chflags")
        .arg("-h")
        .arg("uchg")
        .arg(&link)
        .status()
        .expect("chflags");
    assert!(status.success());

    let result = break_hardlink_if_needed(&link).await;

    // Clear so tempdir cleanup can recurse.
    let _ = Command::new("chflags").arg("-h").arg("nouchg").arg(&link).status();

    let err = result.expect_err("rename over immutable symlink must propagate EPERM");
    assert_ne!(err.kind(), std::io::ErrorKind::NotFound);

    // Regression (atomicity): the failed break must NOT have destroyed
    // the original. The path still exists and is still the symlink.
    let meta = std::fs::symlink_metadata(&link)
        .expect("failed CoW must leave the original symlink in place");
    assert!(
        meta.file_type().is_symlink(),
        "original symlink must survive a failed break, got {meta:?}"
    );
    // And no stage litter left behind.
    let leftover: Vec<_> = std::fs::read_dir(tmp.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with(".socket-cow-"))
        .collect();
    assert!(leftover.is_empty(), "stage litter left behind: {leftover:?}");
}

/// Hardlink branch read-fails arm (cow.rs:84): a hardlinked file
/// chmod'd to 0000 fails the read step. break_hardlink_if_needed
/// gets past lstat (mode bits don't affect lstat results) and the
/// `nlink > 1` check, then `read(path)` returns EACCES.
///
/// Skipped under uid 0 — root bypasses mode-bit access checks.
#[cfg(unix)]
#[tokio::test]
async fn cow_hardlink_unreadable_propagates_read_error() {
    use std::os::unix::fs::PermissionsExt;
    use std::process::Command;
    if Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim() == "0")
        .unwrap_or(false)
    {
        eprintln!("SKIP: root bypasses chmod 0000 restrictions");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    std::fs::write(&a, b"data").unwrap();
    let b = tmp.path().join("b.txt");
    std::fs::hard_link(&a, &b).unwrap();

    // chmod 0000 on either link affects the inode (both fail).
    let mut p = std::fs::metadata(&a).unwrap().permissions();
    p.set_mode(0o000);
    std::fs::set_permissions(&a, p).unwrap();

    let result = break_hardlink_if_needed(&b).await;

    // Restore so tempdir cleanup can read+unlink.
    let mut restore = std::fs::metadata(&a).unwrap().permissions();
    restore.set_mode(0o644);
    let _ = std::fs::set_permissions(&a, restore);

    let err = result.expect_err("read of unreadable hardlinked file must propagate");
    assert_ne!(err.kind(), std::io::ErrorKind::NotFound);
}

/// `write_via_stage_rename` stage-write failure (cow.rs:111): the
/// hardlink branch reads the file content successfully, then
/// `tokio::fs::write(&stage, bytes)` fails because the parent
/// directory is r-x-only (write permission revoked after setup).
///
/// Goes through the nlink>1 path so we don't touch the symlink
/// branch's remove_file (which would also fail on a no-write
/// parent, taking us down a different code path).
///
/// Skipped under uid 0.
#[cfg(unix)]
#[tokio::test]
async fn cow_stage_write_failure_propagates() {
    use std::os::unix::fs::PermissionsExt;
    use std::process::Command;
    if Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim() == "0")
        .unwrap_or(false)
    {
        eprintln!("SKIP: root bypasses chmod 0500 restrictions");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("pkg");
    std::fs::create_dir(&dir).unwrap();
    let a = dir.join("orig.txt");
    std::fs::write(&a, b"content").unwrap();
    let b = dir.join("link.txt");
    std::fs::hard_link(&a, &b).unwrap();

    // Drop write permission on the parent so stage-file creation
    // (parent/.socket-cow-*) fails — keeping read+execute so
    // lstat, the nlink check, and `read(path)` all succeed first.
    let mut p = std::fs::metadata(&dir).unwrap().permissions();
    p.set_mode(0o500);
    std::fs::set_permissions(&dir, p).unwrap();

    let result = break_hardlink_if_needed(&b).await;

    // Restore so tempdir cleanup works.
    let mut restore = std::fs::metadata(&dir).unwrap().permissions();
    restore.set_mode(0o755);
    let _ = std::fs::set_permissions(&dir, restore);

    let err = result.expect_err("stage write into read-only parent must fail");
    assert_ne!(err.kind(), std::io::ErrorKind::NotFound);
}

/// Symlink-branch `write_via_stage_rename` stage-create failure arm:
/// after `read(symlink)` succeeds, `write_via_stage_rename` fails to
/// create its `.socket-cow-*` stage file because the parent directory
/// has a macOS ACL that denies `add_file` while still allowing
/// `delete_child` — a state POSIX mode bits can't express (write perm
/// on a dir is monolithic for create+delete).
///
/// This same ACL is what made the old, destructive flow dangerous:
/// the previous code did `remove_file(symlink)` (a `delete_child`,
/// which the ACL *allows*) BEFORE the stage write, so the link was
/// gone the instant the denied stage create failed — destroying the
/// package file with no rollback. The current flow stages first and
/// never pre-unlinks, so this asserts the original symlink survives.
/// macOS-only because BSD extended ACLs (`chmod +a`) are the only
/// userspace mechanism for this kind of fine-grained denial; Linux's
/// POSIX.1e ACLs can't split create-vs-delete on directories.
#[cfg(target_os = "macos")]
#[tokio::test]
async fn cow_symlink_stage_write_failure_propagates() {
    use std::process::Command;

    if Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim() == "0")
        .unwrap_or(false)
    {
        eprintln!("SKIP: root bypasses ACL deny entries");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("pkg");
    std::fs::create_dir(&dir).unwrap();
    let target = dir.join("orig.txt");
    std::fs::write(&target, b"shared bytes").unwrap();
    let link = dir.join("link");
    std::os::unix::fs::symlink(&target, &link).unwrap();

    // Get the current user name for the ACL entry.
    let user = std::env::var("USER").unwrap_or_else(|_| "$(id -un)".to_string());

    // Add a deny-add_file ACL: blocks creation of new files in `dir`
    // while leaving `delete_child` (remove_file) intact. POSIX mode
    // bits couldn't express this — `chmod 0500` would block both.
    let status = Command::new("chmod")
        .arg("+a")
        .arg(format!("{user} deny add_file"))
        .arg(&dir)
        .status()
        .expect("chmod +a");
    assert!(status.success(), "ACL set must succeed");

    let result = break_hardlink_if_needed(&link).await;

    // Strip the ACL so tempdir cleanup works.
    let _ = Command::new("chmod").arg("-a#").arg("0").arg(&dir).status();

    let err = result.expect_err(
        "with deny-add_file ACL, write_via_stage_rename's stage create must fail, \
         surfacing the stage-write `?` Err arm",
    );
    assert_ne!(err.kind(), std::io::ErrorKind::NotFound);

    // Regression (atomicity / rollback): the old code unlinked the
    // symlink before this denied stage write, leaving the package file
    // gone. The current code stages first, so the original symlink must
    // still be present after the failure.
    let meta = std::fs::symlink_metadata(&link)
        .expect("failed CoW must leave the original symlink in place");
    assert!(
        meta.file_type().is_symlink(),
        "original symlink must survive a failed stage write, got {meta:?}"
    );
    assert_eq!(
        std::fs::read(&link).unwrap(),
        b"shared bytes",
        "symlink must still resolve to its original target content"
    );
}

/// `break_hardlink_if_needed` failure-cleanup arm (cow.rs:116-120):
/// when `rename(stage, path)` inside `write_via_stage_rename`
/// fails, the function must `remove_file(stage)` before
/// propagating the error so we don't leak a `.socket-cow-…`
/// turd in the package directory.
///
/// macOS-only: we use BSD-style `chflags uchg <path>` to set the
/// user-immutable flag on the cow target. The kernel then refuses
/// `rename(stage, target)` with EPERM even though the user owns
/// the file — the cow code's lstat/read/remove flow upstream
/// works fine (reads succeed on immutable files, hardlink creation
/// doesn't touch them), but the final stage→target rename hits the
/// kernel's immutable-bit refusal. After the test, we clear the
/// flag so tempdir cleanup can recurse.
///
/// Linux's analogue is `chattr +i`, but that requires CAP_LINUX_IMMUTABLE
/// (root in most setups), so the Linux variant lives outside the
/// integration suite. On macOS dev/CI uid=0 also bypasses uchg, so
/// skip there too.
#[cfg(target_os = "macos")]
#[tokio::test]
async fn cow_rename_failure_runs_stage_cleanup() {
    use std::os::unix::fs::MetadataExt;
    use std::process::Command;

    if Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim() == "0")
        .unwrap_or(false)
    {
        eprintln!("SKIP: root bypasses chflags uchg restrictions");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let target = tmp.path().join("file.txt");
    std::fs::write(&target, b"original").unwrap();

    // Create a hardlink so cow takes the nlink>1 branch (which
    // calls write_via_stage_rename without first remove_file'ing
    // the target — exactly the rename-collision-into-target
    // shape we want).
    let link = tmp.path().join("hardlink.txt");
    std::fs::hard_link(&target, &link).unwrap();
    assert_eq!(
        std::fs::metadata(&target).unwrap().nlink(),
        2,
        "test setup: target must have nlink=2 to drive cow's hardlink branch"
    );

    // Make `target` immutable so the final rename(stage, target)
    // fails. `chflags` is the only way to set BSD file flags from
    // the shell — there's no portable Rust API.
    let chflags_status = Command::new("chflags")
        .arg("uchg")
        .arg(&target)
        .status()
        .expect("chflags binary must exist on macOS");
    assert!(
        chflags_status.success(),
        "chflags uchg must succeed for a file we own"
    );

    let cow_result = break_hardlink_if_needed(&target).await;

    // Restore the flag so tempdir cleanup can unlink the file.
    let _ = Command::new("chflags").arg("nouchg").arg(&target).status();

    // The cow attempt itself returned the rename error — that's the
    // contract: when stage commit fails, the caller learns of the
    // failure rather than silently succeeding on a half-state.
    let err = cow_result.expect_err("immutable target must cause rename failure");
    assert_ne!(
        err.kind(),
        std::io::ErrorKind::NotFound,
        "expected EPERM-class error, got {err:?}"
    );

    // The cleanup arm (cow.rs:117-119) ran: no `.socket-cow-…`
    // file should be left behind in the package directory.
    let leftover_stages: Vec<_> = std::fs::read_dir(tmp.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .starts_with(".socket-cow-")
        })
        .collect();
    assert!(
        leftover_stages.is_empty(),
        "stage cleanup must remove all .socket-cow-* turds; found {leftover_stages:?}"
    );
}