cosca 0.8.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
//! Unit tests for the raw `CreateProcessW` backend's pre-spawn program gate
//! ([`super::reject_batch_program`]) and command-line builder
//! ([`super::raw_program_and_line`]), which run before resolution and decide what a malformed
//! program token or argument is BLAMED on. Driven directly rather than through `spawn_raw`, so no
//! child is created and the verdict is the checks' alone.

use super::*;
use crate::command::Command;
use crate::error::Error;
use crate::test_child::Console;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;

/// A token carrying an interior NUL — `PCWSTR` truncates at it, so `prefix` is what Win32 acts on.
fn nul_between(prefix: &str, suffix: &str) -> OsString {
    OsString::from_wide(
        &prefix
            .encode_utf16()
            .chain([0])
            .chain(suffix.encode_utf16())
            .collect::<Vec<u16>>(),
    )
}

/// The `Display` of an `Io(InvalidInput)` refusal; panics on anything else, naming what came back.
fn invalid_input_message(via: &str, r: Result<(), Error>) -> String {
    match r {
        Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => e.to_string(),
        other => panic!("{via}: expected Io(InvalidInput), got {other:?}"),
    }
}

/// Every way a caller can name a program, in one place: `reject_batch_program` reads
/// `executable()` when set and otherwise the argv[0] / command-line first token, so each arm needs
/// its own leg.
fn commands_with_token(token: &OsString) -> Vec<(&'static str, Command)> {
    let mut by_argv = crate::test_child::command(Console::Hidden);
    by_argv.args([token.clone()]);

    // argv[0] is deliberately clean and DIFFERENT from `token`: with the probe in both fields a
    // passing leg would not say which one the gate read.
    let mut by_executable = crate::test_child::command(Console::Hidden);
    by_executable.executable(token).args(["ordinary.exe"]);

    let mut by_commandline = crate::test_child::command(Console::Hidden);
    by_commandline.commandline(token.clone());

    vec![
        ("argv[0]", by_argv),
        ("executable()", by_executable),
        ("commandline()", by_commandline),
    ]
}

/// `C:\tools\setup` + NUL + `.bat`. Win32 truncates it to `C:\tools\setup`, which is no batch file
/// at all, so neither gate may blame CVE-2024-24576 — the caller would be sent to audit a vector
/// they do not carry, over a token that launches a program they did not name.
#[skuld::test]
fn a_nul_before_a_batch_extension_is_diagnosed_as_a_nul_not_a_batch_refusal() {
    let token = nul_between(r"C:\tools\setup", ".bat");
    // Premise: the shared gate refuses this as a NUL as well, never as a batch file — so an
    // `Unsupported` reaching the caller could only be the batch rule misfiring.
    invalid_input_message(
        "the shared gate",
        crate::child::spawn::reject_batch_path(std::path::Path::new(&token)),
    );
    for (via, c) in commands_with_token(&token) {
        // An `Ok`, or any downstream error kind, panics in the helper.
        let msg = invalid_input_message(via, reject_batch_program(&c));
        assert!(
            !msg.contains('\0'),
            "{via}: the refusal must not carry a raw NUL into logs: {msg:?}"
        );
    }
}

/// The batch gate must still refuse a clean `.bat`. Without this leg the ordering could be
/// "satisfied" by deleting the gate outright and every NUL test here would stay green.
#[skuld::test]
fn a_clean_batch_token_is_still_refused_as_a_batch() {
    for (via, c) in commands_with_token(&OsString::from(r"C:\tools\setup.bat")) {
        assert!(
            matches!(reject_batch_program(&c), Err(Error::Unsupported { .. })),
            "{via}: a clean .bat must still be refused by the batch gate"
        );
    }
}

/// A NUL in the PROGRAM TOKEN must be blamed on the program token. The raw backend shares one NUL
/// checker with the environment-block builder, so a message hardcoded to the environment sends the
/// caller off to audit `env()` over a defect in `args()` or `executable()` — the same class of
/// misattribution the NUL-before-batch ordering exists to prevent, one field over.
#[skuld::test]
fn a_nul_in_the_program_token_is_not_blamed_on_the_environment() {
    let token = nul_between("setup.bat", "junk");
    // Premise: the shared gate refuses this too, so the assertions below are about WHICH FIELD the
    // refusal names and not about whether one arrives.
    invalid_input_message(
        "the shared gate",
        crate::child::spawn::reject_batch_path(std::path::Path::new(&token)),
    );
    for (via, c) in commands_with_token(&token) {
        let msg = invalid_input_message(via, reject_batch_program(&c));
        assert!(
            msg.contains("program token"),
            "{via}: must name the program token, got {msg}"
        );
        assert!(
            !msg.contains("environment"),
            "{via}: a program token is not the environment, got {msg}"
        );
    }
}

/// A NUL in a middle argv element must name WHICH element. By the time `CreateProcessW` reads it
/// the command line is one joined string, so an unindexed label leaves the caller to bisect
/// `args([..])` by hand — and `args(["a", "b\0c", "d"])` would name no element at all.
#[skuld::test]
fn a_nul_in_an_argument_is_blamed_on_its_index() {
    let mut c = crate::test_child::command(Console::Hidden);
    c.args([OsString::from("a"), nul_between("b", "c"), OsString::from("d")]);
    let msg = invalid_input_message("argv", super::raw_program_and_line(&c).map(|_| ()));
    assert!(msg.contains("argument 1"), "must name the offending element, got {msg}");
}

// ===== command-line builder: a usable first token when executable() is unset =====

// ── `lpApplicationName` must never silently end up NULL ────────────────────────────────
//
// `CreateProcessW` performs its OWN image search when `lpApplicationName` is NULL, including
// the CALLING process's current directory — the exact binary-planting hole this module's
// resolution otherwise closes (see `program_token`'s doc). `spawn_raw` keeps `lpApplicationName`
// non-NULL by falling back to `program_token(cmd)` when `executable()` is unset, but
// `program_token`'s `CommandLine` arm calls `first_token_wide`, which is documented to return
// `None` for an empty or whitespace-only line. `raw_program_and_line`'s sibling arms (`Empty`,
// `Argv`) both already error out loudly when `executable()` is unset and they have no usable
// token; the `CommandLine` arm had no matching check, so an empty/whitespace `commandline()`
// with no `executable()` silently produced `app_name: None` (`lpApplicationName == NULL`)
// instead of erroring.

#[skuld::test]
fn raw_program_and_line_rejects_an_empty_command_line_with_no_executable_set() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.commandline("");
    let err = raw_program_and_line(&cmd).unwrap_err();
    assert!(matches!(err, Error::Io(_)), "{err:?}");
}

#[skuld::test]
fn raw_program_and_line_rejects_a_whitespace_only_command_line_with_no_executable_set() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.commandline("   ");
    let err = raw_program_and_line(&cmd).unwrap_err();
    assert!(matches!(err, Error::Io(_)), "{err:?}");
}

#[skuld::test]
fn raw_program_and_line_allows_an_empty_command_line_when_executable_is_set() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    // executable() alone still supplies lpApplicationName, so an empty command line here is not
    // the NULL-lpApplicationName hazard the check above exists to close — matches the existing
    // `Empty` arm's own "executable() alone" case.
    cmd.executable(std::path::PathBuf::from(r"C:\some\app.exe"));
    cmd.commandline("");
    assert!(raw_program_and_line(&cmd).is_ok());
}

#[skuld::test]
fn raw_program_and_line_allows_a_non_empty_command_line_with_no_executable_set() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.commandline("tool --flag");
    assert!(raw_program_and_line(&cmd).is_ok());
}

/// The containment marker is an op after the user's, so it takes the name std gives it: after a
/// user's `env_remove("__cosca_group_root")`, that spelling, as on the std path.
#[skuld::test]
fn the_containment_marker_is_named_as_std_names_it() {
    let removed = "__cosca_group_root";
    let mut std_cmd = std::process::Command::new("unused");
    std_cmd.env_remove(removed).env(crate::containment::NESTED_ENV, "1");
    let std_name: Vec<_> = std_cmd.get_envs().map(|(k, _)| k.to_os_string()).collect();
    assert_eq!(std_name, [OsString::from(removed)], "std control");

    let snapshot = env_snapshot::EnvSnapshot::from_block("A=1\0\0".encode_utf16().collect());
    let user_ops = [EnvOp::Remove(removed.into())];
    let ops = child_ops(&user_ops, true);
    let block = resolve::ChildEnv::capture(&snapshot, &ops).into_block().unwrap();
    assert_eq!(String::from_utf16(&block).unwrap(), "A=1\0__cosca_group_root=1\0\0");
}

// `target`: the Search/Exact distinction, at the one site that applies it ────────────
//
// These run on the Windows CI runner rather than the host, because `target` is inside the
// `cfg(windows)` raw backend — the `Exact` arm touches no Win32 API, but it cannot be compiled
// off Windows to be reached.

/// [`target`]'s image, against the environment a spawn of `cmd` would read.
fn image(cmd: &Command) -> Result<Option<PathBuf>, Error> {
    Ok(target(cmd, &spawn_env(cmd)?)?.image)
}

/// [`target_with`]'s image with this process's cwd read as [`EXACT_CWD`].
fn image_on(cmd: &Command) -> Result<Option<PathBuf>, Error> {
    Ok(target_with(cmd, &spawn_env(cmd)?, || Ok(PathBuf::from(EXACT_CWD)))?.image)
}

const EXACT_CWD: &str = r"C:\cosca-process-cwd";

#[skuld::test]
fn target_completes_an_exact_program_without_searching_it() {
    // The contract in one assertion: a BARE name, which `executable()` would look up on PATH and
    // append `.exe` to, is only completed against this process's cwd, as the loader would.
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.raw_executable("tool").args(["tool"]);
    let image = image_on(&cmd).expect("an exact program is never searched, so it cannot miss");
    assert_eq!(image.as_deref(), Some(Path::new(r"C:\cosca-process-cwd\tool")));
}

/// The file [`fixture_load_exact_probe`] loads by relative name: a copy of this test binary.
const PROBE: &str = "cosca_exact_cwd_probe.exe";
const FIXTURE_LOAD_EXACT_PROBE_TEST: &str = "child::spawn::windows_raw::windows_raw_tests::fixture_load_exact_probe";
/// The `current_dir()` [`fixture_load_exact_probe`] gives [`PROBE`]. Its presence also marks a
/// deliberate re-exec rather than an ordinary suite run.
const FIXTURE_LOAD_EXACT_PROBE_ENV: &str = "COSCA_FIXTURE_LOAD_EXACT_PROBE_CURRENT_DIR";
/// [`fixture_load_exact_probe`]'s exit codes.
const LOADED: i32 = 0;
const FILE_NOT_FOUND: i32 = 20;
const OTHER_FAILURE: i32 = 21;

/// Inert in an ordinary suite run. Re-executed with [`FIXTURE_LOAD_EXACT_PROBE_ENV`] set, it
/// spawns `raw_executable(PROBE)` with that `current_dir()` from whatever cwd its spawner gave it,
/// and exits with [`LOADED`], [`FILE_NOT_FOUND`] or [`OTHER_FAILURE`]. The spawner sets the cwd,
/// so no process in the test moves its own.
#[skuld::test]
fn fixture_load_exact_probe() {
    let Some(current_dir) = std::env::var_os(FIXTURE_LOAD_EXACT_PROBE_ENV) else {
        return;
    };
    let mut c = crate::test_child::command(Console::Hidden);
    // A filter that matches nothing, so the probe exits 0 without running a test.
    c.raw_executable(PROBE)
        .args([PROBE, "--exact", "__cosca_no_such_test__"])
        .current_dir(current_dir);
    crate::test_reexec::scrub_env(|var| _ = c.env_remove(var));
    c.stdout(crate::stdio::Stdio::null()).expect("stdout null");
    c.stderr(crate::stdio::Stdio::null()).expect("stderr null");
    let image = image(&c).expect("target").unwrap();
    assert!(image.is_absolute() && image.ends_with(PROBE), "{image:?}");
    let not_found = windows::Win32::Foundation::ERROR_FILE_NOT_FOUND;
    let code = match c.spawn() {
        Ok(child) if child.wait().expect("wait").success() => LOADED,
        Err(Error::Io(e)) if e.raw_os_error() == Some(not_found.0 as i32) => FILE_NOT_FOUND,
        _ => OTHER_FAILURE,
    };
    std::process::exit(code);
}

/// [`fixture_load_exact_probe`]'s exit code when run with `process_cwd` as its cwd.
fn load_exact_probe(process_cwd: &Path, current_dir: &Path) -> Option<i32> {
    let mut c = crate::test_child::command(Console::Hidden);
    c.executable(std::env::current_exe().expect("current_exe"))
        .args(crate::test_child::fixture_argv(FIXTURE_LOAD_EXACT_PROBE_TEST))
        .env(FIXTURE_LOAD_EXACT_PROBE_ENV, current_dir)
        .current_dir(process_cwd);
    crate::test_reexec::scrub_env(|var| _ = c.env_remove(var));
    // The runner (libtest-mimic, under skuld) prints its test lines and summary to fd 1, and skuld
    // its start line to fd 2.
    c.stdout(crate::stdio::Stdio::null()).expect("stdout null");
    c.stderr(crate::stdio::Stdio::null()).expect("stderr null");
    c.spawn().expect("spawn the fixture").wait().expect("wait").code()
}

/// `lpCurrentDirectory` takes no part in image lookup: a relative `Exact` image loads from the
/// process's cwd whatever `current_dir()` says. The Windows counterpart of the POSIX
/// `a_bare_exact_name_loads_the_file_in_the_childs_cwd_not_one_on_path` and
/// `a_relative_current_dir_is_entered_from_a_cwd_that_has_no_path`, where the child's directory
/// decides instead.
#[skuld::test]
fn an_exact_image_is_loaded_from_the_process_cwd_not_current_dir() {
    let (with, without) = (
        tempfile::tempdir().expect("tempdir"),
        tempfile::tempdir().expect("tempdir"),
    );
    std::fs::copy(std::env::current_exe().expect("current_exe"), with.path().join(PROBE)).expect("copy");
    assert_eq!(load_exact_probe(with.path(), without.path()), Some(LOADED));
    assert_eq!(
        load_exact_probe(without.path(), with.path()),
        Some(FILE_NOT_FOUND),
        "current_dir() holds the image but the process cwd does not"
    );
}

#[skuld::test]
fn target_resolves_a_search_program_to_an_absolute_path() {
    // The other half, so the test pair proves a DIFFERENCE rather than one arm in isolation:
    // the same bare name through `executable()` is resolved and absolute. `cmd` is chosen because
    // it lives in the System32 directory the bare-name search visits on any Windows host.
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.executable("cmd").args(["cmd"]);
    let image = image(&cmd).expect("cmd resolves on any Windows host").unwrap();
    assert!(
        image.is_absolute(),
        "a Search program must be absolute by the time the backend sees it, got {image:?}"
    );
    assert_ne!(image, Path::new("cmd"), "it must actually have been resolved");
}

#[skuld::test]
fn target_rejects_an_empty_exact_program() {
    // An empty `lpApplicationName` is a pointer to a lone NUL, not the NULL pointer, and whether
    // CreateProcessW treats the two alike is undocumented. Fail closed rather than find out.
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.raw_executable("").args(["tool"]);
    match image(&cmd) {
        Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
        other => panic!("an empty exact program must be Io(InvalidInput), got {other:?}"),
    }
}

/// End to end, the batch gate's token check runs first, and it refuses a name that names no file
/// with the same `InvalidInput` `raw_executable()` and `executable()` document.
#[skuld::test]
fn a_spawn_of_a_program_that_names_no_file_is_invalid_input() {
    for n in [r"C:\t\dir\", ".", "..", "C:", r"x\.."] {
        let mut exact = crate::test_child::command(Console::Hidden);
        exact.raw_executable(n).args(["tool"]);
        let mut search = crate::test_child::command(Console::Hidden);
        search.executable(n).args(["tool"]);
        for (via, mut c) in [("raw_executable", exact), ("executable", search)] {
            match c.spawn() {
                Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
                other => panic!(
                    "{via}({n:?}) names no file and must be Io(InvalidInput), got {:?}",
                    other.map(|_| "a child")
                ),
            }
        }
    }
}

#[skuld::test]
fn target_rejects_an_exact_program_that_names_no_file() {
    // The raw backend's `Exact` arm passes the path through untouched, so a directory would reach
    // `lpApplicationName` verbatim. `CreateProcessW` would refuse it anyway, but as an OS error
    // after the spawn is under way; refusing here makes it `InvalidInput`, as on the elevated
    // sink. `C:\t\...` and `C:\t\. ` (one trailing space) name no file only after Win32
    // normalisation, so they pin the post-check.
    for n in [r"C:\t\dir\", r"C:\t\.", ".", "..", "C:", r"C:\t\...", r"C:\t\. "] {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.raw_executable(n).args(["tool"]);
        match image(&cmd) {
            Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
            other => panic!("{n:?} names no file and must be Io(InvalidInput), got {other:?}"),
        }
    }
}

#[skuld::test]
fn target_completes_an_exact_program_as_the_loader_does() {
    // Completed by `GetFullPathNameW`'s rules, which the loader applies to `lpApplicationName`:
    // the trailing dot goes, as it would there.
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.raw_executable(r"t\tool.").args(["tool"]);
    assert_eq!(
        image_on(&cmd).unwrap().as_deref(),
        Some(Path::new(r"C:\cosca-process-cwd\t\tool"))
    );
}

/// `CreateProcessW` loads the name Win32 normalises the token to, so a batch file reached only
/// through normalisation is refused as a plainly-spelled one is — by the token gate, the raw
/// backend's one batch check, which judges that name.
#[skuld::test]
fn the_token_gate_refuses_an_exact_batch_reached_through_win32_normalisation() {
    // Trailing dot; one trailing space; a file named `.bat`, which has no extension to `Path`.
    for n in ["setup.bat.", "setup.bat ", r"C:\t\.bat"] {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.raw_executable(n).args(["tool"]);
        match reject_batch_program(&cmd) {
            Err(Error::Unsupported { platform, detail, .. }) => {
                assert_eq!(platform, "windows");
                assert!(detail.contains("CVE-2024-24576"), "{n:?}: {detail}");
            }
            other => panic!("{n:?} reaches a batch file and must be refused, got {other:?}"),
        }
    }
}

/// Negative control: a name that merely contains `.bat` loads, completed.
#[skuld::test]
fn target_completes_an_exact_program_that_is_not_a_batch_file() {
    for n in ["setup.exe", "setup.bat.exe"] {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.raw_executable(n).args(["tool"]);
        assert_eq!(image_on(&cmd).unwrap(), Some(Path::new(EXACT_CWD).join(n)));
    }
}

#[skuld::test]
fn target_falls_back_to_the_program_token_when_no_executable_is_set() {
    // The fd>=3 route: neither setter was called, so `lpApplicationName` would be NULL without
    // this fallback — and a NULL makes CreateProcessW search, including the calling process's cwd.
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["cmd", "/C", "exit 0"]);
    let image = image(&cmd).expect("argv[0] resolves").unwrap();
    assert!(image.is_absolute(), "the fallback must resolve too, got {image:?}");
}

// `program_token`: which string the gate judges when `executable()` is unset =====

/// A command with no `executable()` that routes to the raw backend anyway, through the
/// `fd >= 3` arm of `routes_to_raw_backend`. On this route `program_token` alone picks the string
/// `reject_batch_program` judges, so a wrong pick skips the gate entirely.
fn high_fd_command() -> Command {
    let mut c = crate::test_child::command(Console::Hidden);
    c.fd(3, crate::stdio::Stdio::pipe_out()).expect("fd 3");
    c
}

/// The argv arm reads `argv.first()`. Probes put the batch name FIRST with clean names after it,
/// and a clean name first with a batch name after it — a lone element cannot tell `first()` from
/// `last()` or from "any".
#[skuld::test]
fn program_token_reads_the_first_argv_element() {
    let mut refused = high_fd_command();
    refused.args(["x.bat", "ordinary.exe", "tail.exe"]);
    assert!(crate::child::spawn::routes_to_raw_backend(&refused));
    assert_eq!(program_token(&refused), Some(PathBuf::from("x.bat")));
    assert!(
        matches!(reject_batch_program(&refused), Err(Error::Unsupported { .. })),
        "argv[0] is a batch file"
    );

    let mut allowed = high_fd_command();
    allowed.args(["ordinary.exe", "x.bat", "y.cmd"]);
    assert_eq!(program_token(&allowed), Some(PathBuf::from("ordinary.exe")));
    reject_batch_program(&allowed).expect("only argv[0] is the program");
}

/// The command-line arm reads `first_token_wide` — different extraction code from the argv arm,
/// with quoting of its own. A whole-line read would judge `x.bat --flag` (no batch suffix) and let
/// the first probe through; a last-token read would miss it the same way.
#[skuld::test]
fn program_token_reads_the_first_command_line_token() {
    for (line, token) in [
        ("x.bat --flag", "x.bat"),
        (r#""C:\dir with space\x.bat" --flag"#, r"C:\dir with space\x.bat"),
        (r"\\srv\x.bat\.. & calc", r"\\srv\x.bat\.."),
    ] {
        let mut c = high_fd_command();
        c.commandline(line);
        assert!(crate::child::spawn::routes_to_raw_backend(&c));
        assert_eq!(program_token(&c), Some(PathBuf::from(token)), "{line:?}");
        assert!(
            matches!(reject_batch_program(&c), Err(Error::Unsupported { .. })),
            "{line:?}: the first token is a batch file"
        );
    }

    let mut allowed = high_fd_command();
    allowed.commandline(r#"ordinary.exe x.bat "y.cmd""#);
    assert_eq!(program_token(&allowed), Some(PathBuf::from("ordinary.exe")));
    reject_batch_program(&allowed).expect("only the first token is the program");
}

/// End to end on the same route: `spawn()` must refuse before any child exists.
#[skuld::test]
fn a_high_fd_spawn_without_an_executable_is_gated_on_its_program_token() {
    let mut by_argv = high_fd_command();
    by_argv.args(["x.bat", "--flag"]);
    let mut by_line = high_fd_command();
    by_line.commandline("x.bat --flag");
    for (via, mut c) in [("argv", by_argv), ("commandline", by_line)] {
        let err = crate::child::spawn::failure::expect_not_started(
            c.spawn().expect_err("a batch program token must be refused"),
        );
        assert!(matches!(err, Error::Unsupported { .. }), "{via}: got {err:?}");
    }
}

/// The raw backend runs the child in the directory its image was resolved against: one read of the
/// process cwd serves both, so a `set_current_dir` in between cannot split them.
#[skuld::test]
fn target_pins_the_resolved_directory_as_the_childs() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir(dir.path().join("sub")).unwrap();
    std::fs::write(dir.path().join("sub").join("tool.exe"), b"x").unwrap();
    for (cmd_cwd, want_dir) in [(Some("sub"), dir.path().join("sub")), (None, dir.path().to_path_buf())] {
        let token = if cmd_cwd.is_some() {
            r".\tool.exe"
        } else {
            r"sub\tool.exe"
        };
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.executable(token).args([token]);
        if let Some(c) = cmd_cwd {
            cmd.current_dir(c);
        }
        let reads = std::cell::Cell::new(0);
        let got = target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
            reads.set(reads.get() + 1);
            Ok(dir.path().to_path_buf())
        })
        .unwrap();
        assert_eq!(reads.get(), 1, "{cmd_cwd:?}");
        assert_eq!(got.cwd, want_dir, "{cmd_cwd:?}");
        let image = got.image.unwrap();
        assert!(image.starts_with(&want_dir), "{cmd_cwd:?}: {image:?}");
    }
}

/// A share-less UNC `current_dir` is refused with `InvalidInput`, never a panic in the resolver.
#[skuld::test]
fn target_refuses_a_share_less_unc_current_dir() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.executable(r".\tool.exe")
        .args([r".\tool.exe"])
        .current_dir(r"\\server");
    match target(&cmd, &spawn_env(&cmd).unwrap()) {
        Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e}"),
        Err(other) => panic!("expected Io(InvalidInput), got {other:?}"),
        Ok(_) => panic!("a share-less UNC directory must be refused"),
    }
}

/// `raw_executable()` completes against this process's cwd, not `current_dir`, as `CreateProcessW`
/// does; `current_dir` is completed against the same one read and is the child's directory.
#[skuld::test]
fn target_completes_an_exact_program_and_its_current_dir_from_one_read() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.raw_executable("tool.exe").args(["tool.exe"]).current_dir("sub");
    let reads = std::cell::Cell::new(0);
    let got = target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
        reads.set(reads.get() + 1);
        Ok(PathBuf::from(EXACT_CWD))
    })
    .unwrap();
    assert_eq!(reads.get(), 1);
    assert_eq!(got.cwd, Path::new(EXACT_CWD).join("sub"));
    assert_eq!(got.image, Some(Path::new(EXACT_CWD).join("tool.exe")));
}

/// `current_dir("")` gets one verdict on both arms: it names no directory.
#[skuld::test]
fn an_empty_current_dir_is_refused_on_both_arms() {
    let mut search = crate::test_child::command(Console::Hidden);
    search.executable("tool").args(["tool"]).current_dir("");
    let mut exact = crate::test_child::command(Console::Hidden);
    exact.raw_executable(r"C:\t\tool.exe").args(["tool"]).current_dir("");
    for (arm, cmd) in [("Search", search), ("Exact", exact)] {
        match target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
            panic!("{arm}: must not read the cwd")
        }) {
            Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "{arm}: {e}"),
            Err(other) => panic!("{arm}: expected Io(NotFound), got {other:?}"),
            Ok(_) => panic!("{arm}: an empty current_dir must be refused"),
        }
    }
}

/// With no `current_dir`, the child runs in the one read of this process's cwd, whatever the
/// program: `lpCurrentDirectory` is never left for `CreateProcessW` to read again.
#[skuld::test]
fn target_pins_the_process_cwd_for_every_program() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.executable("cmd").args(["cmd"]);
    let reads = std::cell::Cell::new(0);
    let got = target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
        reads.set(reads.get() + 1);
        Ok(PathBuf::from(EXACT_CWD))
    })
    .unwrap();
    assert_eq!(reads.get(), 1);
    assert_eq!(got.cwd, PathBuf::from(EXACT_CWD));
}

// The post-spawn identity read and attach =====

/// A raw-backend blocker only a kill ends: `more.com` on a pipe whose writer the teardown's kill
/// releases (see [`fault::teardown_blocker_stdin`]), so a teardown that sent no kill reaps a child
/// that exited 0, which `assert_killed` rejects, instead of waiting on it for ever. `executable()`
/// routes it to the raw backend.
fn raw_blocker() -> (Command, crate::child::spawn::fault::TeardownBlocker) {
    let crate::child::spawn::fault::TeardownBlockerParts {
        argv,
        stdin,
        stdout,
        guard,
    } = crate::child::spawn::fault::teardown_blocker_parts();
    let mut c = crate::test_child::command(Console::Hidden);
    c.executable(&argv[0]).args(argv);
    c.stdin(stdin).expect("stdin");
    c.stdout(stdout.expect("a Windows blocker nulls its stdout"))
        .expect("stdout");
    (c, guard)
}

/// A raw spawn reads and checks the child's identity before it attaches the containment: with the
/// attach and the identity read both forced to fail, the identity's error is the one answered.
///
/// Mutant: the raw spawn attaches first, so the attach's `Containment` is answered; or the teardown
/// sends no kill (the child then exits 0 on its released stdin).
#[skuld::test]
fn a_raw_spawn_reads_the_identity_before_it_attaches() {
    use crate::child::spawn::fault;
    let (mut c, teardown) = raw_blocker();
    fault::set_force_identity_vanished(true);
    fault::set_force_attach_failure(true);
    let result = c.spawn();
    fault::set_force_attach_failure(false);
    fault::set_force_identity_vanished(false);
    let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
        result.expect_err("a forced failure fails the spawn"),
    );
    assert!(
        matches!(&err, Error::Io(e) if e.to_string().contains("reaped by another party")),
        "the identity check comes first: {err:?}"
    );
    assert_eq!(
        fate,
        crate::error::ChildFate::Reaped,
        "the raw teardown kills and reaps the child"
    );
    teardown.assert_killed();
    fault::assert_child_reaped(fault::take_captured().expect("the seam captured the child"));
}

/// A raw spawn whose attach fails kills and reaps its child, and answers the attach's error.
///
/// Mutant: the raw teardown is skipped, leaving the child running; or it sends no kill (the child
/// then exits 0 on its released stdin).
#[skuld::test]
fn a_raw_spawn_whose_attach_fails_tears_its_child_down() {
    use crate::child::spawn::fault;
    let (mut c, teardown) = raw_blocker();
    fault::set_force_attach_failure(true);
    let result = c.spawn();
    fault::set_force_attach_failure(false);
    let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
        result.expect_err("the forced attach failure fails the spawn"),
    );
    assert!(matches!(err, Error::Containment { .. }), "{err:?}");
    assert_eq!(fate, crate::error::ChildFate::Reaped, "terminated and waited for");
    teardown.assert_killed();
    fault::assert_child_reaped(fault::take_captured().expect("the seam captured the child"));
}

/// A raw spawn whose `CreateProcessW` fails, here on an image that is not a program (Windows
/// answers `ERROR_BAD_EXE_FORMAT` or `ERROR_EXE_MACHINE_TYPE_MISMATCH`), did not start one.
///
/// Mutant: the raw backend's `CreateProcessW` failure answers that the program may have started.
#[skuld::test]
fn a_raw_spawn_whose_create_process_fails_did_not_start() {
    let dir = tempfile::tempdir().expect("tempdir");
    let image = dir.path().join("not-a-program.exe");
    std::fs::write(&image, b"not a PE image").expect("write the image");
    let mut c = crate::test_child::command(Console::Hidden);
    c.executable(&image).args(["not-a-program"]);
    let err = crate::child::spawn::failure::expect_not_started(c.spawn().expect_err("a non-PE image fails"));
    assert!(matches!(err, Error::Io(ref e) if e.raw_os_error().is_some()), "{err:?}");
}

// The refusals before `CreateProcessW` =====

/// Every refusal the raw backend makes before `CreateProcessW` says the program did not start, and
/// is the refusal's own error: a batch program, a NUL in the working directory or the command line,
/// an fd table over its limit, and `inherit` on fd 3.
///
/// Mutant: any one of those arms answers that the program may have started, or another error.
#[skuld::test]
fn raw_refusals_before_create_process_did_not_start() {
    use crate::child::spawn::failure::{invalid_input, unsupported};
    use crate::stdio::Stdio;
    let dir = tempfile::tempdir().expect("tempdir");
    let bat = dir.path().join("x.bat");
    std::fs::write(&bat, b"@echo off\n").expect("write the batch file");
    let mut batch = crate::test_child::command(Console::Hidden);
    batch.executable(&bat).args(["x.bat"]);
    let mut cwd_nul = crate::test_child::command(Console::Hidden);
    cwd_nul
        .executable("findstr")
        .args(["findstr", "x"])
        .current_dir(std::path::PathBuf::from("a\u{0}b"));
    let mut line_nul = crate::test_child::command(Console::Hidden);
    line_nul.executable("findstr").args(["findstr", "a\u{0}b"]);
    let mut oversized = crate::test_child::command(Console::Hidden);
    oversized.executable("findstr").args(["findstr", "x"]);
    oversized.fd(70_000, Stdio::null()).expect("fd 70000");
    let mut inherit_fd3 = crate::test_child::command(Console::Hidden);
    inherit_fd3.executable("findstr").args(["findstr", "x"]);
    inherit_fd3.fd(3, Stdio::inherit()).expect("fd 3");
    for (what, mut cmd, variant) in [
        ("batch", batch, unsupported as fn(&Error) -> bool),
        ("cwd NUL", cwd_nul, invalid_input),
        ("command-line NUL", line_nul, invalid_input),
        ("oversized fd table", oversized, unsupported),
        ("inherit on fd 3", inherit_fd3, unsupported),
    ] {
        let err = crate::child::spawn::failure::expect_not_started(cmd.spawn().expect_err(what));
        assert!(variant(&err), "{what}: not the refusal's own error: {err:?}");
    }
}

/// A failed `SetHandleInformation` reports the plain Win32 code. A null handle is a real
/// `ERROR_INVALID_HANDLE`.
///
/// Mutant: `set_inherit` converts with the `windows` crate's own `io::Error` conversion, which
/// keeps the HRESULT (`0x80070006`).
#[skuld::test]
fn a_failed_set_inherit_is_reported_as_its_win32_code() {
    let err = set_inherit(HANDLE::default()).expect_err("a null handle cannot be marked inheritable");
    let Error::Io(err) = err else {
        panic!("expected Error::Io, got {err:?}");
    };
    assert_eq!(
        err.raw_os_error(),
        Some(windows::Win32::Foundation::ERROR_INVALID_HANDLE.0 as i32),
        "{err:?}"
    );
}

// Win32 codes of attribute-list failures =====

fn io_code(r: Result<impl std::fmt::Debug, Error>) -> Option<i32> {
    match r {
        Err(Error::Io(e)) => e.raw_os_error(),
        other => panic!("expected Io, got {other:?}"),
    }
}

/// A buffer smaller than the sizing call reported fails to initialize with
/// `ERROR_INSUFFICIENT_BUFFER` (122), not its HRESULT.
///
/// Mutant: `initialize_attribute_list` converts with `.into()`, so the code is `0x8007007A`.
#[skuld::test]
fn initialize_attribute_list_failure_carries_the_win32_code() {
    let code = io_code(initialize_attribute_list(&mut []).map(|_| ()));
    assert_eq!(code, Some(122), "ERROR_INSUFFICIENT_BUFFER expected");
}

/// An empty handle list is not a valid HANDLE_LIST attribute, so `UpdateProcThreadAttribute`
/// fails with `ERROR_BAD_LENGTH`; the error carries the plain Win32 code.
///
/// Mutant: `add_handle_list_or_delete` converts with `.into()`, so the code is `0x80070018`.
#[skuld::test]
fn add_handle_list_failure_carries_the_win32_code() {
    let mut size = 0usize;
    // SAFETY: the null-list form is the documented way to query the buffer size.
    _ = unsafe { InitializeProcThreadAttributeList(None, 1, None, &mut size) };
    let mut buf = vec![0u8; size];
    let list = initialize_attribute_list(&mut buf).expect("a right-sized buffer initializes");
    let code = io_code(add_handle_list_or_delete(list, &[]));
    assert_eq!(code, Some(24), "ERROR_BAD_LENGTH (24) expected");
}