cosca 0.5.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
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
#[skuld::test]
fn detect_reports_windows_os() {
    let h = crate::elevation::plan::Host::detect(crate::elevation::Backend::Auto, &crate::elevation::Auth::Interactive);
    assert_eq!(h.os, crate::elevation::plan::Os::Windows);
}

#[skuld::test]
fn integrity_level_is_always_answerable() {
    // Every Windows process has a mandatory integrity label; a `None` here means the
    // aligned two-call token read is broken, not that the runner lacks an answer. Fail
    // loud rather than let the cross-check below go vacuous.
    assert!(
        super::integrity_level().is_some(),
        "integrity_level() must resolve on any Windows runner"
    );
}

#[skuld::test]
fn is_elevated_agrees_with_integrity_level() {
    // Privilege-independent invariant (never assume ambient privilege): a full
    // (elevated) token runs at High+ integrity; a filtered token is Medium. This
    // cross-checks TokenElevation against the independent TokenIntegrityLevel class.
    use windows::Win32::System::SystemServices::SECURITY_MANDATORY_HIGH_RID;
    let elevated = super::is_elevated();
    let rid = super::integrity_level().expect("integrity level must be readable");
    let high = rid >= SECURITY_MANDATORY_HIGH_RID as u32;
    assert_eq!(
        elevated, high,
        "TokenElevation ({elevated}) disagrees with integrity RID {rid:#x} vs High"
    );
}

use crate::command::Command;
use crate::error::Error;
use crate::stdio::Stdio;

fn is_unsupported<T>(r: Result<T, Error>) -> bool {
    matches!(r, Err(Error::Unsupported { .. }))
}

/// `Io(InvalidInput)` naming `PATHEXT`: [`crate::resolve::reject_unloadable_image`]'s refusal.
fn is_pathext_refusal<T>(r: Result<T, Error>) -> bool {
    matches!(r, Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput && e.to_string().contains("PATHEXT"))
}

/// The refusal's `detail`, for the tests that assert on the message and not only the variant.
fn unsupported_detail<T: std::fmt::Debug>(r: Result<T, Error>) -> String {
    match r {
        Err(Error::Unsupported { detail, .. }) => detail,
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

#[skuld::test]
fn piped_stdio_is_unsupported() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
    c.stdout(Stdio::pipe()).unwrap();
    assert!(is_unsupported(super::reject_unsupported_config(&c)));
}

#[skuld::test]
fn null_and_merge_stdio_are_unsupported() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
    c.stdin(Stdio::null()).unwrap();
    assert!(is_unsupported(super::reject_unsupported_config(&c)));

    let mut c2 = Command::new();
    c2.args([r"C:\Windows\System32\whoami.exe"]).elevate();
    c2.stderr(Stdio::merge(crate::stdio::Fd::STDOUT)).unwrap();
    assert!(is_unsupported(super::reject_unsupported_config(&c2)));
}

#[skuld::test]
fn high_fd_is_unsupported() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
    c.fd(3, Stdio::pipe_out()).unwrap();
    assert!(is_unsupported(super::reject_unsupported_config(&c)));
}

#[skuld::test]
fn env_and_contain_are_unsupported() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate().env("FOO", "bar");
    assert!(is_unsupported(super::reject_unsupported_config(&c)));

    let mut c2 = Command::new();
    c2.args([r"C:\Windows\System32\whoami.exe"]).elevate().contain();
    assert!(is_unsupported(super::reject_unsupported_config(&c2)));
}

#[skuld::test]
fn inherit_only_is_accepted() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
    c.stdout(Stdio::inherit()).unwrap();
    assert!(super::reject_unsupported_config(&c).is_ok());
}

/// A Windows-shaped host for the pure seam. Tests below drive [`super::plan_runas`] and never
/// `launch_runas_with_host`: on an `elevated: false` host the latter's fall-through is a real
/// `ShellExecuteExW(runas)`, so a probe that slipped past a check under test would raise a UAC
/// prompt and elevate the probe program under the test runner.
fn win_host(elevated: bool) -> crate::elevation::plan::Host {
    crate::elevation::plan::Host {
        elevated,
        has_tty: false,
        available: crate::elevation::plan::BackendSet::default(),
        os: crate::elevation::plan::Os::Windows,
        arg_max: None,
        pkexec_version: crate::elevation::pkexec::PkexecVersion::NotProbed,
        pkexec_pin: None,
    }
}

/// `prefix` + an interior NUL + `suffix` — the shape Win32 silently truncates at the NUL.
fn nul_between(prefix: &str, suffix: &str) -> std::ffi::OsString {
    use std::os::windows::ffi::OsStringExt;
    std::ffi::OsString::from_wide(
        &prefix
            .encode_utf16()
            .chain([0])
            .chain(suffix.encode_utf16())
            .collect::<Vec<u16>>(),
    )
}

#[skuld::test]
fn launch_runas_rejects_bad_config_before_the_short_circuit_regardless_of_privilege() {
    // Piped stdio must fail with Unsupported and never prompt — the gate runs BEFORE the
    // already-elevated short-circuit, so the verdict is identical for elevated=false/true.
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
        c.stdout(Stdio::pipe()).unwrap();
        assert!(
            is_unsupported(super::plan_runas(&c, &win_host(elevated))),
            "piped elevated config must reject with elevated={elevated}"
        );
    }
}

#[skuld::test]
fn commandline_elevated_is_unsupported_on_windows_regardless_of_privilege() {
    for elevated in [false, true] {
        let mut c = Command::new();
        c.commandline("whoami").elevate();
        assert!(is_unsupported(super::plan_runas(&c, &win_host(elevated))));
    }
}

/// An argv-less command is not a `commandline()` one. Both of these are reachable from the public
/// builder and neither calls `.commandline()`, so naming it sends the caller to audit a line of
/// their code that does not exist — and says nothing about the program they actually failed to set.
#[skuld::test]
fn an_argv_less_command_is_not_reported_as_a_commandline_command() {
    let mut by_executable = Command::new();
    by_executable.executable("x.exe").elevate();

    let mut bare = Command::new();
    bare.elevate();

    for (via, c) in [("executable() only", &by_executable), ("nothing at all", &bare)] {
        match super::plan_runas(c, &win_host(false)) {
            Err(e @ Error::Unsupported { .. }) => {
                let msg = e.to_string();
                assert!(!msg.contains("commandline"), "{via}: none was set, got {msg}");
                assert!(
                    msg.contains("empty command"),
                    "{via}: the refusal must name the missing program, got {msg}"
                );
            }
            other => panic!(
                "{via}: an argv-less elevate() must be refused, got {:?}",
                other.map(|_| "Ok")
            ),
        }
    }
}

/// The affirmative leg. Every other `plan_runas` test asserts a REFUSAL, so all of them would
/// still pass against a seam that refused everything — and "no consent prompt ever happens" is not
/// the property this file is pinning. A clean inherit-only request on an UNELEVATED host must
/// reach `Launch`, with every `SHELLEXECUTEINFOW` string built and NUL-terminated.
#[skuld::test]
fn a_clean_unelevated_request_plans_a_launch() {
    use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;

    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe", "/all"]).elevate();
    let launch = match super::plan_runas(&c, &win_host(false)) {
        Ok(super::RunasStep::Launch(launch)) => launch,
        Ok(super::RunasStep::AlreadyElevated) => panic!("an unelevated host must not short-circuit"),
        Err(e) => panic!("a clean inherit-only request must not be refused: {e:?}"),
    };
    assert_eq!(
        launch.class_w,
        "exefile\0".encode_utf16().collect::<Vec<u16>>(),
        "the launch skips shell32's lookup by class"
    );
    for (field, w) in [
        ("lpVerb", &launch.verb_w),
        ("lpFile", &launch.file_w),
        ("lpParameters", &launch.params_w),
    ] {
        assert_eq!(w.last(), Some(&0), "{field} must be NUL-terminated: {w:?}");
        assert!(w.len() > 1, "{field} must carry the value, not just its terminator");
    }
    assert_eq!(
        launch.dir_w, None,
        "no current_dir() was set, so lpDirectory stays null"
    );
    assert_eq!(launch.show, SW_SHOWNORMAL);
}

/// A `%` in `current_dir()` is refused, whatever the caller's privilege: whether the consent
/// launch expands it in `lpDirectory` is unmeasured.
#[skuld::test]
fn a_percent_in_current_dir_is_refused() {
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([r"C:\Windows\System32\whoami.exe"])
            .current_dir(r"C:\work\%TEMP%")
            .elevate();
        match super::plan_runas(&c, &win_host(elevated)) {
            Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
            other => panic!(
                "elevated={elevated}: expected Io(InvalidInput), got {:?}",
                other.map(|_| "Ok")
            ),
        }
    }
}

/// The affirmative leg with a `current_dir()`: `lpDirectory` carries it, wide and NUL-terminated.
#[skuld::test]
fn a_clean_request_with_a_current_dir_plans_a_launch_in_it() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"])
        .current_dir(r"C:\Windows\Temp")
        .elevate();
    let launch = match super::plan_runas(&c, &win_host(false)) {
        Ok(super::RunasStep::Launch(launch)) => launch,
        Ok(super::RunasStep::AlreadyElevated) => panic!("an unelevated host must not short-circuit"),
        Err(e) => panic!("a clean request with a current_dir() must not be refused: {e:?}"),
    };
    assert_eq!(
        launch.dir_w,
        Some(r"C:\Windows\Temp".encode_utf16().chain([0]).collect::<Vec<u16>>()),
        "lpDirectory is current_dir(), wide and NUL-terminated"
    );
}

#[skuld::test]
fn already_elevated_inherit_only_is_run_as_is() {
    // The RunAsIs branch: an inherit-only elevated request on an already-elevated host
    // passes the gate and short-circuits (no ShellExecuteEx).
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
    assert!(matches!(
        super::plan_runas(&c, &win_host(true)),
        Ok(super::RunasStep::AlreadyElevated)
    ));
}

/// Kills replacing `elevated_program`'s `Exact` arm with `let program = token;`, which hands
/// `ShellExecuteEx` a path-less `lpFile` to search (see `absolutise_exact`'s doc): the result must
/// be absolute, and for a relative input must DIFFER from the token as written.
#[skuld::test]
fn elevated_exact_program_is_completed_to_an_absolute_path() {
    let mut c = Command::new();
    c.raw_executable("tool.exe").args(["tool.exe"]).elevate();
    let argv = super::elevated_argv(&c).expect("an argv command");
    let program = super::elevated_program(&c, argv).expect("a relative Exact program completes");
    let p = std::path::Path::new(&program);
    assert!(
        p.is_absolute(),
        "an Exact program must reach lpFile absolute, got {program:?}"
    );
    assert_ne!(
        p.as_os_str(),
        std::ffi::OsStr::new("tool.exe"),
        "a relative Exact token must have been completed, not passed through"
    );
    // Completed, NOT searched: no extension invented and the file name is untouched.
    assert_eq!(p.file_name().unwrap(), std::ffi::OsStr::new("tool.exe"), "{program:?}");
}

/// The consent path's `Exact` arm applies [`crate::resolve::reject_unloadable_image`]: an absolute
/// extensionless `lpFile` may still be PATHEXT-completed by `ShellExecuteEx` (measured without a
/// class, unmeasured for the `exefile` consent launch). Relative too, since completion does not add
/// an extension.
#[skuld::test]
fn an_extensionless_exact_program_is_refused_on_the_consent_path() {
    for n in [r"C:\tools\setup", "setup", r"C:\tools\setup.bat.exe.lnk"] {
        let mut c = Command::new();
        c.raw_executable(n).args([n]).elevate();
        match super::plan_runas(&c, &win_host(false)) {
            Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {
                assert!(
                    e.to_string().contains("PATHEXT"),
                    "{n:?}: the reason must be named: {e}"
                );
            }
            other => panic!("{n:?}: expected Io(InvalidInput), got {:?}", other.map(|_| "Ok")),
        }
    }
}

/// The allowlist is part of `shell_file::reject_elevated_program`, which runs above the
/// short-circuit, so an already-elevated caller gets the same refusal though it re-spawns through
/// `CreateProcessW`, which assumes no default extension.
#[skuld::test]
fn an_extensionless_exact_program_is_refused_when_already_elevated_too() {
    let mut c = Command::new();
    c.raw_executable(r"C:\tools\setup").args([r"C:\tools\setup"]).elevate();
    assert!(is_pathext_refusal(super::plan_runas(&c, &win_host(true)).map(|_| ())));
}

/// Negative control: a loadable image name still plans a launch.
#[skuld::test]
fn an_exact_exe_or_com_program_plans_a_launch() {
    for n in [r"C:\tools\setup.exe", r"C:\tools\SETUP.COM", "setup.exe"] {
        let mut c = Command::new();
        c.raw_executable(n).args([n]).elevate();
        assert!(
            matches!(super::plan_runas(&c, &win_host(false)), Ok(super::RunasStep::Launch(_))),
            "{n:?} must plan a launch"
        );
    }
}

/// The allowlist is the consent path's, not `raw_executable()`'s: an `executable()` or argv[0]
/// token is passed to `ShellExecuteEx` as written, so an extensionless one could be
/// PATHEXT-completed. The bare `whoami` is not fully qualified either; the allowlist refuses it
/// first.
#[skuld::test]
fn an_extensionless_search_program_is_refused_on_the_consent_path() {
    for (via, c) in search_commands(&[r"C:\tools\setup", "whoami"]) {
        match super::plan_runas(&c, &win_host(false)) {
            Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {
                assert!(
                    e.to_string().contains("PATHEXT"),
                    "{via}: the reason must be named: {e}"
                );
            }
            other => panic!("{via}: expected Io(InvalidInput), got {:?}", other.map(|_| "Ok")),
        }
    }
}

/// Negative control for the `Search` and argv[0] arms. Fully qualified: a bare `whoami.exe` is
/// refused (see `launch_runas_refuses_a_program_that_is_not_fully_qualified`).
#[skuld::test]
fn a_search_exe_or_com_program_plans_a_launch() {
    for (via, c) in search_commands(&[r"C:\tools\setup.exe", r"C:\Windows\System32\WHOAMI.COM"]) {
        assert!(
            matches!(super::plan_runas(&c, &win_host(false)), Ok(super::RunasStep::Launch(_))),
            "{via} must plan a launch"
        );
    }
}

/// The batch gate applies to every arm, before the planner, and judges the name Win32 normalises
/// the token to — a stream piece included, on a token ending in `.exe`/`.com`.
#[skuld::test]
fn a_search_batch_reached_through_normalisation_is_refused_regardless_of_privilege() {
    let probes = [
        r"C:\t\setup.bat.",
        r"C:\t\setup.bat ",
        r"C:\t\.bat",
        r"C:\t\setup.bat:.exe",
    ];
    for elevated in [false, true] {
        for (via, c) in search_commands(&probes) {
            let detail = unsupported_detail(super::plan_runas(&c, &win_host(elevated)).map(|_| ()));
            assert!(
                detail.contains("CVE-2024-24576"),
                "elevated={elevated}, {via}: {detail}"
            );
        }
    }
}

/// Each name as an `executable()` and as a bare argv[0], the two ways a token reaches `lpFile`
/// unresolved.
fn search_commands(names: &[&str]) -> Vec<(String, Command)> {
    let mut out = Vec::new();
    for &n in names {
        let mut exe = Command::new();
        exe.executable(n).args([n]).elevate();
        out.push((format!("executable({n:?})"), exe));
        let mut argv = Command::new();
        argv.args([n]).elevate();
        out.push((format!("args([{n:?}])"), argv));
    }
    out
}

// ===== creation-flag intents on the consent-prompt path =====

/// `ShellExecuteEx` takes a show-command and no creation-flag word, so this is the only knob the
/// consent launch has for the window-suppression intent. Two inputs, two values: a constant
/// implementation fails one of the pair.
#[skuld::test]
fn runas_hides_the_window_when_no_window_is_requested() {
    use crate::command::flags::FlagsRequest;
    use windows::Win32::UI::WindowsAndMessaging::SW_HIDE;
    let flags = FlagsRequest {
        no_window: true,
        ..Default::default()
    };
    assert_eq!(super::runas_show_command(&flags), SW_HIDE);
}

#[skuld::test]
fn runas_shows_the_window_by_default() {
    use crate::command::flags::FlagsRequest;
    use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
    assert_eq!(super::runas_show_command(&FlagsRequest::default()), SW_SHOWNORMAL);
}

/// The consent launch accepts no creation flags at all, so a raw word is refused rather than
/// silently dropped. Stated over the RECORDED state, not "a method was called": `creation_flags(0)`
/// requests nothing, so there is nothing to refuse.
#[skuld::test]
fn elevation_rejects_raw_creation_flags() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"])
        .elevate()
        .creation_flags(0x0000_0040);
    let detail = unsupported_detail(super::reject_unsupported_config(&c));
    crate::error::assert_detail_is_not_hard_wrapped(&detail);
}

#[skuld::test]
fn elevation_accepts_a_zero_creation_flags_word() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate().creation_flags(0);
    assert!(super::reject_unsupported_config(&c).is_ok());
}

#[skuld::test]
fn elevation_rejects_detached() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate().detached();
    let detail = unsupported_detail(super::reject_unsupported_config(&c));
    crate::error::assert_detail_is_not_hard_wrapped(&detail);
}

#[skuld::test]
fn elevation_rejects_breakaway() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"])
        .elevate()
        .breakaway_from_job();
    let detail = unsupported_detail(super::reject_unsupported_config(&c));
    crate::error::assert_detail_is_not_hard_wrapped(&detail);
}

/// The one flag intent that survives the gate — which is the whole of the elevated half of the
/// window-suppression feature. Without this leg, a future tightening could take it away again in
/// silence, and the three rejections above would all still pass.
#[skuld::test]
fn elevation_accepts_no_window() {
    let mut c = Command::new();
    c.args([r"C:\Windows\System32\whoami.exe"]).elevate().no_window();
    assert!(super::reject_unsupported_config(&c).is_ok());
}

// ===== interior NULs must be refused, not silently truncated =====

/// `PCWSTR` stops at the first NUL, so every `SHELLEXECUTEINFOW` string field is TRUNCATED rather
/// than rejected when it contains one. Each truncation changes what an ELEVATED process does:
/// a different image loads, a different working directory applies, or the argument line is cut
/// short. The raw `CreateProcessW` backend already refuses all three via its own NUL checks, so
/// leaving them unchecked here would make THIS divergence depend on whether `.elevate()` was
/// called. A separate, still-open divergence — `ShellExecuteEx` resolving a program
/// `CreateProcessW` would refuse, whether by PATHEXT-completing an extension-less token or by
/// another registered `runas` association (`.lnk`, `.vbs`, `.msc`, …) — is not closed here.
///
/// Tested directly on the builder rather than through `ShellExecuteExW`, so it needs no UAC
/// prompt and no elevated child.
#[skuld::test]
fn wide_nul_refuses_an_interior_nul_in_any_value() {
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;

    // A value whose FIRST unit is NUL, and one where the NUL hides in the middle — the second is
    // the dangerous shape, because it looks like a perfectly ordinary path until Win32 cuts it.
    for units in [
        vec![0u16],
        "C:\\a\\b.exe\0junk".encode_utf16().collect::<Vec<u16>>(),
        "D:\\work\0junk".encode_utf16().collect::<Vec<u16>>(),
    ] {
        let value = OsString::from_wide(&units);
        let got = super::wide_nul("probe field", &value);
        assert!(
            got.is_err(),
            "an interior NUL must be refused, not truncated to {:?}",
            value.to_string_lossy().split('\0').next().unwrap()
        );
        match got.unwrap_err() {
            Error::Io(e) => {
                assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e:?}");
                assert!(
                    e.to_string().contains("probe field"),
                    "refusal must name the field: {e}"
                );
            }
            other => panic!("expected Io(InvalidInput), got {other:?}"),
        }
    }
}

/// The ordinary case still works, so the guard above is gating NULs rather than rejecting
/// everything — and the result really is NUL-TERMINATED, which is what `PCWSTR` requires.
#[skuld::test]
fn wide_nul_accepts_an_ordinary_value_and_terminates_it() {
    let w = super::wide_nul("program path", std::ffi::OsStr::new("C:\\tools\\app.exe")).unwrap();
    assert_eq!(w.last(), Some(&0), "the buffer must be NUL-terminated: {w:?}");
    assert!(!w[..w.len() - 1].contains(&0), "no interior NUL in a clean value");
}

/// THE WIRING of the fallible call sites, not the helper. `wide_nul` being correct is worthless
/// if a field is built by an inline `encode_wide().chain(once(0))` instead — reverting any single
/// call site to that leaves the helper's own tests green, so this drives `plan_runas` and pins
/// that the truncating value is actually refused, AND blamed on the right field, where it is used.
///
/// A call site that ESCAPED the check comes back `Ok(Launch)`, which the fall-through arm below
/// panics on. That is the whole reason this drives the pure seam: on `launch_runas_with_host` the
/// same escape would hand the probe to `ShellExecuteExW` and raise a UAC prompt under the test
/// runner.
///
/// One leg per field a caller can poison — `lpFile`, `lpParameters`, `lpDirectory`. A single-argv,
/// no-cwd probe only reaches `lpFile`: with an empty joined parameter line and `cmd.cwd() == None`,
/// dropping either of the other two checks leaves every test green, which is exactly the gap this
/// test exists to close. Each leg also asserts the detail names ITS field, not just `InvalidInput`
/// — a swap that trips the right error kind but blames the wrong field would otherwise still pass.
///
/// The `lpParameters` leg lands on the per-ELEMENT check, which is what can name `argument 1`;
/// `plan_runas` has two further `wide_nul(...)?` sites with no failing input reachable from the
/// public builder (`verb_w` is the literal `"runas"`, and `params_w` is the join of elements this
/// leg already checked), so neither is tested here.
///
/// Run for both privilege levels because the check now sits above the short-circuit: an
/// already-elevated caller must get the same refusal, not a silent `AlreadyElevated`.
#[skuld::test]
fn launch_runas_refuses_a_truncating_nul_regardless_of_privilege() {
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;

    let nul_path = OsString::from_wide(
        &r"Z:\cosca-nonexistent\x.exe"
            .encode_utf16()
            .chain([0])
            .chain("junk".encode_utf16())
            .collect::<Vec<u16>>(),
    );

    let clean = OsString::from(r"Z:\cosca-nonexistent\x.exe");
    for elevated in [false, true] {
        // lpFile, lpParameters, lpDirectory — one probe each, every other field clean so the
        // refusal can only have come from the field under test.
        let mut by_program = Command::new();
        by_program.args([nul_path.clone()]).elevate();

        let mut by_argument = Command::new();
        by_argument.args([clean.clone(), nul_path.clone()]).elevate();

        let mut by_cwd = Command::new();
        by_cwd.args([clean.clone()]).current_dir(&nul_path).elevate();

        for (field, needle, c) in [
            ("lpFile", "program path", &by_program),
            ("lpParameters", "argument 1", &by_argument),
            ("lpDirectory", "working directory", &by_cwd),
        ] {
            match super::plan_runas(c, &win_host(elevated)) {
                Err(Error::Io(e)) => {
                    assert_eq!(
                        e.kind(),
                        std::io::ErrorKind::InvalidInput,
                        "elevated={elevated} {field}: expected the NUL refusal, got {e:?}"
                    );
                    assert!(
                        e.to_string().contains(needle),
                        "elevated={elevated} {field}: refusal must name the field ({needle:?}), got {e}"
                    );
                }
                other => panic!(
                    "elevated={elevated} {field}: a truncating NUL must be refused at the call \
                     site, got {:?}",
                    other.map(|_| "Ok")
                ),
            }
        }
    }
}

/// One predicate, one sentence. The elevated path and the raw `CreateProcessW` backend refuse an
/// interior NUL for the same reason on the same field, and restating it per path is what let
/// "elevated program path" drift away from "program path" — a wording difference a caller reads as
/// two different defects.
#[skuld::test]
fn the_elevated_and_raw_paths_word_the_nul_refusal_identically() {
    let token = nul_between(r"C:\tools\x.exe", "junk");

    let mut c = Command::new();
    c.args([token.clone()]).elevate();
    let elevated = match super::plan_runas(&c, &win_host(false)) {
        Err(Error::Io(e)) => e.to_string(),
        other => panic!(
            "a truncating program path must be refused, got {:?}",
            other.map(|_| "Ok")
        ),
    };

    let raw = crate::child::spawn::windows_raw::resolve::ensure_no_nul_wide("program path", &token)
        .expect_err("the raw backend refuses the same token")
        .to_string();

    assert_eq!(elevated, raw, "one defect, described two ways");
}

/// A `.bat`/`.cmd` SPELLED IN THE TOKEN must be refused here as on every other backend.
/// `ShellExecuteEx`'s `runas` resolves the `batfile` association through `cmd.exe` and substitutes
/// `lpParameters` into `%*` unescaped, while `join_wide` quotes only for whitespace — so an
/// argument like `a&calc` is command injection into an ELEVATED shell (CVE-2024-24576).
///
/// Scope, so this test is not read as proving more than it does: the gate keys on the caller's
/// string, and `ShellExecuteEx` resolves the file. An extension-less `args(["setup", "a&calc"])`
/// passes it; `shell_file::reject_elevated_program` refuses that one, which is neither an
/// `.exe`/`.com` nor fully qualified.
///
/// Privilege-independent for the same reason as the config gate: the already-elevated caller
/// falls through to a backend that refuses this, so refusing it here keeps the verdict a property
/// of the request rather than of the host.
#[skuld::test]
fn launch_runas_refuses_a_batch_program_regardless_of_privilege() {
    for elevated in [false, true] {
        for probe in ["setup.bat", "setup.cmd", "SETUP.BAT"] {
            let mut c = Command::new();
            c.args([probe, "a&calc"]).elevate();
            assert!(
                is_unsupported(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
                "elevated={elevated}: {probe:?} must be refused before ShellExecuteEx hands it to cmd.exe"
            );
        }
    }
}

/// An `Exact` batch file reached only through Win32 normalisation is refused as the batch file it
/// is, before the planner, so the verdict does not depend on privilege.
#[skuld::test]
fn launch_runas_refuses_an_exact_batch_reached_through_normalisation_regardless_of_privilege() {
    for elevated in [false, true] {
        // Trailing dot; one trailing space; a file named `.bat`.
        for probe in [r"C:\t\setup.bat.", r"C:\t\setup.bat ", r"C:\t\.bat"] {
            let mut c = Command::new();
            c.raw_executable(probe).args([probe, "a&calc"]).elevate();
            let detail = unsupported_detail(super::plan_runas(&c, &win_host(elevated)).map(|_| ()));
            assert!(
                detail.contains("CVE-2024-24576"),
                "elevated={elevated}, {probe:?}: {detail}"
            );
        }
    }
}

/// A token ShellExecuteEx would complete by lookup is refused: an extension-less one can become
/// `setup.bat` (`PathResolveW` with `PRF_TRYPROGRAMEXTENSIONS`), and any other extension runs
/// through its association.
#[skuld::test]
fn launch_runas_refuses_a_program_not_ending_in_exe_or_com() {
    for elevated in [false, true] {
        for probe in [
            r"C:\tools\setup",
            "setup",
            "setup.lnk",
            "setup.msc",
            r"C:\tools\setup.exe.",
        ] {
            let mut c = Command::new();
            c.args([probe, "a&calc"]).elevate();
            assert!(
                is_pathext_refusal(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
                "elevated={elevated}: {probe:?} may be completed or dispatched by ShellExecuteEx"
            );
        }
    }
}

/// An elevated program that is not fully qualified is refused: a relative or bare token leaves
/// ShellExecuteEx a lookup to make, App Paths included, which is unmeasured for the consent launch.
#[skuld::test]
fn launch_runas_refuses_a_program_that_is_not_fully_qualified() {
    for elevated in [false, true] {
        for probe in ["whoami.exe", r"tools\setup.exe", r"\tools\setup.exe", "C:setup.exe"] {
            let mut c = Command::new();
            c.args([probe]).elevate();
            assert!(
                is_unsupported(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
                "elevated={elevated}: {probe:?} is not fully qualified"
            );
        }
    }
}

/// A token ShellExecuteEx rewrites before it opens it is refused, whatever it rewrites to: a
/// quoted batch path and a percent-encoded `file:` URL both open `setup.bat`. The quote is refused
/// as a quote; the rest end in no `.exe`/`.com`.
#[skuld::test]
fn launch_runas_refuses_a_token_shell_execute_rewrites() {
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([r#""C:\tools\setup.bat""#, "a&calc"]).elevate();
        assert!(
            is_unsupported(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
            "elevated={elevated}: a quote is refused"
        );
        for probe in ["file:///C:/tools/setup%2Ebat", "shell:startup", r"C:\tools\%X%"] {
            let mut c = Command::new();
            c.args([probe, "a&calc"]).elevate();
            assert!(
                is_pathext_refusal(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
                "elevated={elevated}: {probe:?} is not a fully qualified image path without a quote"
            );
        }
    }
}

/// A NUL-truncated path that only LOOKS like a batch file (`C:\tools\setup` + NUL + `.bat`): Win32
/// launches `C:\tools\setup`, a different program than the caller named and no batch file at all.
/// Whichever gate refuses it must therefore say NUL and not CVE-2024-24576, or the caller is sent
/// to audit a vector they do not carry while the wrong image still runs elevated.
#[skuld::test]
fn nul_bearing_batch_looking_path_is_diagnosed_as_a_nul_not_a_batch_refusal() {
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;

    let nul_bat = OsString::from_wide(
        &r"C:\tools\setup"
            .encode_utf16()
            .chain([0])
            .chain(".bat".encode_utf16())
            .collect::<Vec<u16>>(),
    );
    // `\0` is not a path separator, so `extension()` reads `bat` straight through it — the reason
    // the gate refuses the NUL ahead of its batch rule. Derived in `reject_batch_path_on`'s doc.
    assert_eq!(
        std::path::Path::new(&nul_bat).extension().map(|e| e.to_string_lossy()),
        Some("bat".into()),
        "premise: the token's extension is misleading"
    );
    assert!(
        matches!(
            crate::child::spawn::reject_batch_path(std::path::Path::new(&nul_bat)),
            Err(Error::Io(ref e)) if e.kind() == std::io::ErrorKind::InvalidInput
        ),
        "premise: the shared gate refuses this as a NUL too, never as a batch file"
    );
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([nul_bat.clone()]).elevate();
        match super::plan_runas(&c, &win_host(elevated)) {
            Err(Error::Io(e)) => {
                assert_eq!(
                    e.kind(),
                    std::io::ErrorKind::InvalidInput,
                    "elevated={elevated}: expected the NUL refusal, got {e:?}"
                );
                // The kind alone lets "right kind, blamed the wrong field" pass — which is the
                // misattribution this test exists to catch, one level down.
                assert!(
                    e.to_string().contains("program path"),
                    "elevated={elevated}: the refusal must blame the program path, got {e}"
                );
            }
            other => panic!(
                "elevated={elevated}: a NUL-bearing batch-looking path must be diagnosed as a NUL, \
                 got {:?}",
                other.map(|_| "Ok")
            ),
        }
    }
}

/// The mirror shape: `setup.bat` + NUL + `junk`, which Win32 truncates back to the real batch file
/// `setup.bat`. Its extension is the one the batch rule could plausibly claim, so this pins that
/// the caller is still told about the NUL — their actual defect — and not about batch escaping.
#[skuld::test]
fn a_nul_after_a_batch_extension_is_blamed_on_the_nul_not_the_batch_gate() {
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;

    let bat_nul = OsString::from_wide(
        &r"C:\tools\setup.bat"
            .encode_utf16()
            .chain([0])
            .chain("junk".encode_utf16())
            .collect::<Vec<u16>>(),
    );
    // Premise: the shared gate refuses this token too, as a NUL — so an `Unsupported` arriving
    // below could only be the batch rule jumping the NUL it is ordered behind.
    assert!(
        matches!(
            crate::child::spawn::reject_batch_path(std::path::Path::new(&bat_nul)),
            Err(Error::Io(ref e)) if e.kind() == std::io::ErrorKind::InvalidInput
        ),
        "premise: the shared gate refuses this as a NUL"
    );
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([bat_nul.clone(), OsString::from("a&calc")]).elevate();
        match super::plan_runas(&c, &win_host(elevated)) {
            Err(Error::Io(e)) => {
                assert_eq!(
                    e.kind(),
                    std::io::ErrorKind::InvalidInput,
                    "elevated={elevated}: expected the NUL refusal, got {e:?}"
                );
                assert!(
                    e.to_string().contains("program path"),
                    "elevated={elevated}: the refusal must blame the program path, got {e}"
                );
            }
            other => panic!(
                "elevated={elevated}: a NUL that truncates back to a real batch file must be \
                 blamed on the NUL, got {:?}",
                other.map(|_| "Ok")
            ),
        }
    }
}

/// WHICH field a MULTI-poisoned request names. Every leg above poisons exactly one, so none of
/// them pins the order: with the per-element argv loop running ahead of the program's own check,
/// `args(["setup.bat\0junk", "x\0y"])` came back "argument 1" and never mentioned that the program
/// path — the field deciding which image runs ELEVATED — is truncating too. NUL on the program
/// path first, for attribution, as on the raw backend.
#[skuld::test]
fn a_poisoned_program_path_is_named_before_a_poisoned_argument_or_cwd() {
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([nul_between(r"C:\tools\setup.bat", "junk"), nul_between("x", "y")])
            .current_dir(nul_between(r"C:\work", "junk"))
            .elevate();
        match super::plan_runas(&c, &win_host(elevated)) {
            Err(Error::Io(e)) => {
                assert_eq!(
                    e.kind(),
                    std::io::ErrorKind::InvalidInput,
                    "elevated={elevated}: expected the NUL refusal, got {e:?}"
                );
                assert!(
                    e.to_string().contains("program path"),
                    "elevated={elevated}: the program path outranks the other poisoned fields, got {e}"
                );
            }
            other => panic!(
                "elevated={elevated}: a truncating NUL must be refused, got {:?}",
                other.map(|_| "Ok")
            ),
        }
    }
}

/// The cwd leg of that same rule, which no test above reaches: each multi-field probe poisons the
/// program too, so the program's own check short-circuits before `lpDirectory` is ever built. A
/// clean `.bat` with a truncating `current_dir()` is a NUL the caller can fix, and "batch escaping
/// is not implemented" would never mention that `lpDirectory` truncates as well.
#[skuld::test]
fn a_poisoned_working_directory_is_named_before_the_batch_gate() {
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([std::ffi::OsString::from(r"C:\tools\setup.bat")])
            .current_dir(nul_between(r"C:\work", "junk"))
            .elevate();
        match super::plan_runas(&c, &win_host(elevated)) {
            Err(Error::Io(e)) => {
                assert_eq!(
                    e.kind(),
                    std::io::ErrorKind::InvalidInput,
                    "elevated={elevated}: expected the NUL refusal, got {e:?}"
                );
                assert!(
                    e.to_string().contains("working directory"),
                    "elevated={elevated}: the refusal must name the working directory, got {e}"
                );
            }
            other => panic!(
                "elevated={elevated}: the cwd's NUL must be refused before the batch gate, got {:?}",
                other.map(|_| "Ok")
            ),
        }
    }
}

/// The other side of that ordering: the batch gate must not jump ahead of a poisoned ARGUMENT
/// either. A clean `.bat` with a truncating argument is a NUL the caller can fix, and
/// "batch escaping is not implemented" would hide it.
#[skuld::test]
fn a_poisoned_argument_is_named_before_the_batch_gate() {
    for elevated in [false, true] {
        let mut c = Command::new();
        c.args([std::ffi::OsString::from(r"C:\tools\setup.bat"), nul_between("x", "y")])
            .elevate();
        match super::plan_runas(&c, &win_host(elevated)) {
            Err(Error::Io(e)) => assert!(
                e.to_string().contains("argument 1"),
                "elevated={elevated}: the refusal must name the poisoned argument, got {e}"
            ),
            other => panic!(
                "elevated={elevated}: the argument's NUL must be refused before the batch gate, got {:?}",
                other.map(|_| "Ok")
            ),
        }
    }
}

/// A failed `CloseHandle` of an owned token is logged and asserted, as `identity::windows::close`
/// does for a process handle. `0x3` is a handle that cannot be one: the kernel ignores a handle's
/// low two bits, so this closes handle 0, which fails `ERROR_INVALID_HANDLE` without touching any
/// real handle — and `is_invalid()` screens only 0 and -1.
#[skuld::test]
fn a_failed_token_close_is_logged() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let outcome = std::panic::catch_unwind(|| drop(super::OwnedToken(windows::Win32::Foundation::HANDLE(0x3 as _))));
    assert_eq!(
        outcome.is_err(),
        cfg!(debug_assertions),
        "the debug_assert fires in exactly the builds that keep it"
    );
    assert!(
        crate::log_capture::contains_since(mark, "CloseHandle of an owned token failed"),
        "a failed token close must be logged"
    );
}

/// The launch maps each classification of a failed `ShellExecuteEx(runas)` (see
/// `runas_failure_tests`) to its answer: a declined prompt and an error before the launch did not
/// start the program, and anything else may have, with no handle to say what became of it.
///
/// Mutant: the launch drops the classification's answer.
#[skuld::test]
fn a_shell_execute_failure_takes_its_answer_from_the_classification() {
    use windows::core::HRESULT;
    use windows::Win32::Foundation::{ERROR_CANCELLED, ERROR_DDE_FAIL, ERROR_FILE_NOT_FOUND};

    use crate::child::spawn::SpawnFailure;
    use crate::error::{ChildFate, ElevationErrorKind, Error};

    assert!(matches!(
        super::shell_execute_failure(HRESULT::from_win32(ERROR_CANCELLED.0), 0),
        SpawnFailure::NotStarted(Error::Elevation {
            kind: ElevationErrorKind::AuthDeclined,
            ..
        })
    ));
    assert!(matches!(
        super::shell_execute_failure(HRESULT::from_win32(ERROR_FILE_NOT_FOUND.0), 2),
        SpawnFailure::NotStarted(Error::Elevation {
            kind: ElevationErrorKind::AuthFailed,
            ..
        })
    ));
    assert!(matches!(
        super::shell_execute_failure(HRESULT::from_win32(ERROR_DDE_FAIL.0), 0),
        SpawnFailure::MayHaveStarted {
            cause: Error::Elevation {
                kind: ElevationErrorKind::AuthFailed,
                ..
            },
            fate: ChildFate::Unknown,
            wrapper_elevated: false,
        }
    ));
}