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
//! Windows elevation effect layer (`cfg(windows)`): token-based detection and the
//! `ShellExecuteEx("runas")` reduced-child spawn.

use windows::Win32::Foundation::HANDLE;
use windows::Win32::Security::{
    GetSidSubAuthority, GetSidSubAuthorityCount, GetTokenInformation, TokenElevation, TokenIntegrityLevel,
    TOKEN_ELEVATION, TOKEN_MANDATORY_LABEL, TOKEN_QUERY,
};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

use super::plan::{BackendSet, Host, Os};

struct OwnedToken(HANDLE);
impl Drop for OwnedToken {
    fn drop(&mut self) {
        if !self.0.is_invalid() {
            // SAFETY: a token handle owned by this guard, closed exactly once.
            if let Err(e) = unsafe { windows::Win32::Foundation::CloseHandle(self.0) } {
                log::warn!(
                    "CloseHandle of an owned token failed: {report}",
                    report = crate::error::Report(&e)
                );
                debug_assert!(
                    false,
                    "CloseHandle of an owned token should not fail: {}",
                    crate::error::Report(&e)
                );
            }
        }
    }
}

fn open_process_token() -> Option<OwnedToken> {
    // SAFETY: standard token query; the handle is wrapped in a guard.
    unsafe {
        let mut token = HANDLE::default();
        OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).ok()?;
        Some(OwnedToken(token))
    }
}

pub(super) fn is_elevated() -> bool {
    let Some(token) = open_process_token() else {
        log::warn!("could not open the process token to query elevation; assuming not elevated");
        return false;
    };
    // SAFETY: fixed-size TOKEN_ELEVATION query on a live token.
    unsafe {
        let mut e = TOKEN_ELEVATION::default();
        let mut ret = 0u32;
        let ok = GetTokenInformation(
            token.0,
            TokenElevation,
            Some(&mut e as *mut _ as *mut core::ffi::c_void),
            std::mem::size_of::<TOKEN_ELEVATION>() as u32,
            &mut ret,
        )
        .is_ok();
        if !ok {
            log::warn!("TokenElevation query failed; assuming not elevated");
            return false;
        }
        e.TokenIsElevated != 0
    }
}

/// The current token's integrity RID (e.g. Medium/High), or `None` if unreadable.
pub(super) fn integrity_level() -> Option<u32> {
    let token = open_process_token()?;
    // SAFETY: two-call GetTokenInformation into an 8-byte-aligned buffer;
    // TOKEN_MANDATORY_LABEL's Sid pointer field requires 8-byte alignment, so a
    // Vec<u64> backing avoids the align-1 UB a Vec<u8> would cause. The Sid pointer
    // is read via addr_of! + read_unaligned — never a misaligned reference.
    unsafe {
        let mut ret = 0u32;
        _ = GetTokenInformation(token.0, TokenIntegrityLevel, None, 0, &mut ret);
        if ret == 0 {
            log::debug!("could not size the integrity-level token info; integrity unknown");
            return None;
        }
        let words = (ret as usize).div_ceil(8);
        let mut buf = vec![0u64; words];
        let cap = (words * 8) as u32;
        if let Err(e) = GetTokenInformation(
            token.0,
            TokenIntegrityLevel,
            Some(buf.as_mut_ptr() as *mut core::ffi::c_void),
            cap,
            &mut ret,
        ) {
            log::debug!(
                "TokenIntegrityLevel query failed: {report}; integrity unknown",
                report = crate::error::Report(&e)
            );
            return None;
        }
        let label_ptr = buf.as_ptr() as *const TOKEN_MANDATORY_LABEL;
        let sid = std::ptr::read_unaligned(std::ptr::addr_of!((*label_ptr).Label.Sid));
        let count_ptr = GetSidSubAuthorityCount(sid);
        if count_ptr.is_null() || *count_ptr == 0 {
            log::debug!("integrity SID has no sub-authorities; integrity unknown");
            return None;
        }
        let last = (*count_ptr as u32) - 1;
        Some(*GetSidSubAuthority(sid, last))
    }
}

pub(super) fn detect(elevated: bool) -> Host {
    if let Some(rid) = integrity_level() {
        log::debug!("current process integrity RID = 0x{rid:04x}");
    }
    Host {
        elevated,
        has_tty: false, // Windows never prompts on a TTY — UAC is a GUI gate.
        available: BackendSet::default(),
        os: Os::Windows,
        arg_max: None,
        pkexec_version: crate::elevation::pkexec::PkexecVersion::NotProbed,
        pkexec_pin: None,
    }
}

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

/// Enforce the honest capability matrix for Windows elevation. ShellExecuteEx(runas)
/// passes NO handles and no environment, and a Job Object cannot span the integrity
/// boundary — so every non-inherit slot, every fd >= 3, any explicit env, and
/// `.contain()` is a loud `Unsupported`, never a silent lie.
pub(crate) fn reject_unsupported_config(cmd: &Command) -> Result<(), Error> {
    let unsupported = |op: &str, detail: &str| {
        Err(Error::Unsupported {
            op: op.into(),
            platform: "windows",
            detail: detail.into(),
            source: None,
        })
    };
    for (&slot, resolved) in cmd.fds() {
        if slot.raw() >= 3 {
            return unsupported(
                "fd >= 3 on an elevated Windows child",
                "runas exposes no descriptor-passing mechanism; fd >= 3 needs the (deferred) broker",
            );
        }
        if !matches!(resolved, ResolvedStdio::Inherit) {
            return unsupported(
                "captured/redirected stdio on an elevated Windows child",
                "runas exposes no stdio-handle mechanism; capture/redirect needs the (deferred) broker. \
                 Use inherit(), or elevate on POSIX.",
            );
        }
    }
    if !cmd.env_ops().is_empty() {
        return unsupported(
            "env forwarding to an elevated Windows child",
            "runas provides no environment mechanism; forwarding needs the (deferred) broker",
        );
    }
    if cmd.contain_request().mode.is_some() {
        return unsupported(
            ".contain() + elevate on Windows",
            "a Job Object cannot span the integrity boundary of a runas child (deferred)",
        );
    }
    // `ShellExecuteEx` accepts no creation flags at all, so every flag intent except window
    // suppression has no mechanism here and is refused rather than silently dropped. Stated over
    // the RECORDED state, not "a method was called": `creation_flags(0)` requests nothing.
    let flags = cmd.flags_request();
    if flags.detached {
        return unsupported(
            "detached() + elevate on Windows",
            "the runas launch takes a show-command and no creation flags, so DETACHED_PROCESS \
             cannot be expressed. Elevate without it, or spawn unelevated.",
        );
    }
    if flags.breakaway_from_job {
        return unsupported(
            "breakaway_from_job() + elevate on Windows",
            "the runas launch takes a show-command and no creation flags, so \
             CREATE_BREAKAWAY_FROM_JOB cannot be expressed — and the runas child is created by a \
             system service, not by this process's job.",
        );
    }
    if flags.raw != 0 {
        return unsupported(
            "creation_flags() + elevate on Windows",
            "the runas launch takes a show-command and no creation flags, so an arbitrary \
             dwCreationFlags word cannot be expressed. no_window() is the one flag intent that \
             survives here, lowered to the launch's show-command.",
        );
    }
    Ok(())
}

/// The show-command the consent launch uses, from the caller's flag request.
///
/// Pure, so the selection is unit-testable without a UAC prompt.
///
/// **Reached only when a consent prompt is actually used.** `runas` returns
/// `Transition::RunAsIs => RunasOutcome::AlreadyElevated` before it builds the
/// `SHELLEXECUTEINFOW`, and `spawn_elevated`'s `AlreadyElevated` arm falls through to
/// `spawn_unelevated` — so an already-elevated caller's `.elevate().no_window()` is carried by
/// `CREATE_NO_WINDOW` on the ordinary backends and never touches this function.
///
/// The two lowerings differ observably for a graphical child: the show-command is the shell's
/// initial show state for the whole launched application, where the creation flag concerns the
/// child's console only.
#[cfg(windows)]
pub(crate) fn runas_show_command(
    flags: &crate::command::flags::FlagsRequest,
) -> windows::Win32::UI::WindowsAndMessaging::SHOW_WINDOW_CMD {
    use windows::Win32::UI::WindowsAndMessaging::{SW_HIDE, SW_SHOWNORMAL};
    if flags.no_window {
        SW_HIDE
    } else {
        SW_SHOWNORMAL
    }
}

// ===== ShellExecuteEx("runas") launch =====

use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};

use windows::core::PCWSTR;
use windows::Win32::Foundation::{RPC_E_CHANGED_MODE, S_FALSE, S_OK};
use windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE};
use windows::Win32::System::Threading::{GetProcessId, PROCESS_ACCESS_RIGHTS};
use windows::Win32::UI::Shell::{
    ShellExecuteExW, SEE_MASK_CLASSNAME, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,
};

use crate::child::owned::OwnedChild;
use crate::child::spawn::policy::SpawnPolicy;
use crate::child::spawn::windows_raw::resolve::ensure_no_nul_wide;
use crate::child::spawn::{Classify, SpawnFailure};
use crate::containment::Attachment;
use crate::elevation::plan::Transition;
use crate::elevation::shell_file;
use crate::elevation::{ElevatedStdio, ElevatedVia, ElevationReport, Privilege};
use crate::error::ChildFate;
use crate::error::ElevationErrorKind;
use crate::identity::ProcessId;
use crate::identity::{windows_terminate_held, Termination};
use crate::os_process::windows::WindowsProcess;

/// So `raw_os_error` finds the Win32 code; an HRESULT that is not one carries its hex in the chain.
fn hresult_cause(code: windows::core::HRESULT) -> std::sync::Arc<Error> {
    let io = crate::error::win32_io_error(windows::core::Error::from_hresult(code));
    let hr = code.0 as u32;
    Error::io_cause(if hr & 0xFFFF_0000 == 0x8007_0000 {
        io
    } else {
        crate::error::io_context(format!("HRESULT {hr:#010x}"), io)
    })
}

/// The failure of `ShellExecuteExW(runas)` with error `code` and `hInstApp` `inst_app`: see
/// [`super::runas_failure::classify`]. A launch that may have happened left no process handle, so
/// what became of it is unknown.
pub(crate) fn shell_execute_failure(code: windows::core::HRESULT, inst_app: isize) -> SpawnFailure {
    use super::runas_failure::{classify, RunasFailure};

    let failed = || Error::Elevation {
        kind: ElevationErrorKind::AuthFailed,
        detail: "ShellExecuteEx(runas) failed".into(),
        source: Some(hresult_cause(code)),
    };
    match classify(code.0, inst_app) {
        RunasFailure::Declined => SpawnFailure::NotStarted(Error::Elevation {
            kind: ElevationErrorKind::AuthDeclined,
            detail: "the UAC elevation prompt was declined".into(),
            source: None,
        }),
        RunasFailure::BeforeLaunch => SpawnFailure::NotStarted(failed()),
        RunasFailure::MayHaveLaunched => SpawnFailure::started(failed(), ChildFate::Unknown, None),
    }
}

/// A NUL-terminated wide string for a `SHELLEXECUTEINFOW` field, REFUSING an interior NUL.
///
/// `PCWSTR` stops at the first NUL, so a value containing one is silently TRUNCATED rather than
/// rejected — and every field here decides something security-relevant:
///
/// - `lpFile` truncated at the NUL would load a DIFFERENT FILE than the caller named, elevated.
/// - `lpDirectory` would run the elevated child somewhere other than `current_dir()` asked for.
/// - `lpParameters` would drop everything after the NUL, silently shortening the argument line an
///   elevated program acts on.
///
/// The raw `CreateProcessW` backend already refuses all three via its own NUL checks, so this
/// closes the interior-NUL divergence between the elevated and unelevated paths. `ShellExecuteEx`
/// RESOLVING a program `CreateProcessW` would refuse — completing an extension-less token, or
/// dispatching `.lnk`, `.vbs`, `.msc`, … through an association — is closed by the gates in
/// `plan_runas`, not here.
///
/// Fallible rather than a check at each call site, so the unchecked sink does not exist: every
/// string field of the `SHELLEXECUTEINFOW` is built here. `what` names the field for the error.
/// `lpParameters` is additionally checked per argv ELEMENT by [`ensure_no_nul_wide`] before the
/// join, because by the time it is one string the refusal can no longer say which `args([..])`
/// entry carried the NUL; the check here stays as the field's own, so removing that loop cannot
/// open an unchecked sink.
///
/// The predicate and its message come from the raw `CreateProcessW` backend rather than being
/// restated here. Two copies of one sentence is exactly how the wording drifted apart before —
/// "elevated program path" against "program path" — over a defect neither backend describes
/// differently.
fn wide_nul(what: &str, s: &OsStr) -> Result<Vec<u16>, Error> {
    ensure_no_nul_wide(what, s)?;
    Ok(s.encode_wide().chain(std::iter::once(0)).collect())
}

/// The outcome of a runas launch. `Launched` carries the owned handle, the access it was granted,
/// pid, stable identity, and the report — the async path builds its own `Child` from these.
pub(crate) enum RunasOutcome {
    AlreadyElevated,
    Launched {
        proc: OwnedHandle,
        granted: PROCESS_ACCESS_RIGHTS,
        pid: u32,
        id: ProcessId,
        report: ElevationReport,
    },
}

/// Balances a `CoInitializeEx` with `CoUninitialize` only when WE incremented the refcount.
struct ComInit {
    uninit: bool,
}
impl ComInit {
    fn init() -> Result<ComInit, Error> {
        // SAFETY: COM apartment init on the calling thread; balanced in Drop.
        let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) };
        if hr == S_OK || hr == S_FALSE {
            // S_FALSE = already initialized on this thread WITH the refcount incremented,
            // so it still requires a matching CoUninitialize.
            Ok(ComInit { uninit: true })
        } else if hr == RPC_E_CHANGED_MODE {
            // Already initialized in a different apartment model; we did NOT increment.
            Ok(ComInit { uninit: false })
        } else {
            Err(Error::Elevation {
                kind: ElevationErrorKind::AuthFailed,
                detail: "CoInitializeEx failed before ShellExecuteEx".into(),
                source: Some(hresult_cause(hr)),
            })
        }
    }
}
impl Drop for ComInit {
    fn drop(&mut self) {
        if self.uninit {
            // SAFETY: balances our CoInitializeEx that incremented the refcount.
            unsafe { CoUninitialize() };
        }
    }
}

/// The argv runas can work from at all. Split from [`elevated_params`] so the program's NUL check
/// can sit between them — see [`plan_runas`].
fn elevated_argv(cmd: &Command) -> Result<&[OsString], Error> {
    super::elevation_argv(cmd, &ARGV_REFUSALS)
}

/// The runas launch's words for [`super::elevation_argv`]'s refusals.
pub(crate) const ARGV_REFUSALS: super::ArgvRefusals = super::ArgvRefusals {
    platform: "windows",
    op_prefix: "elevation",
    commandline: "runas elevation requires an argv command (set .args([...]))",
    setter: super::SETTER_REFUSAL,
};

/// The joined `lpParameters` line, NUL-checked per element BEFORE the join: `lpParameters` is one
/// string, so a refusal built from it could only say that SOME element carried a NUL.
fn elevated_params(argv: &[OsString]) -> Result<OsString, Error> {
    let mut tail_wide: Vec<Vec<u16>> = Vec::with_capacity(argv.len() - 1);
    for (i, a) in argv.iter().enumerate().skip(1) {
        ensure_no_nul_wide(&format!("argument {i}"), a)?;
        tail_wide.push(a.encode_wide().collect());
    }
    let tail_refs: Vec<&[u16]> = tail_wide.iter().map(|v| v.as_slice()).collect();
    Ok(OsString::from_wide(&crate::quote::windows::join_wide(&tail_refs)))
}

// Both the sync (`spawn_elevated`) and async spawn arms route an elevated `Command` here.
pub(crate) fn launch_runas(cmd: &Command) -> Result<RunasOutcome, SpawnFailure> {
    let request = cmd.elevation_request();
    launch_runas_with_host(cmd, &Host::detect(request.backend, &request.auth, None, is_elevated()))
}

/// The validated `SHELLEXECUTEINFOW` payload: every string field, NUL-terminated, plus the show
/// command. Built only when a consent prompt is actually warranted.
pub(crate) struct RunasLaunch {
    file_w: Vec<u16>,
    /// `lpClass`, with `SEE_MASK_CLASSNAME`: always `exefile`, which has the `runas` verb and runs a
    /// `.com` as well (measured; `comfile` has no `runas` verb).
    class_w: Vec<u16>,
    params_w: Vec<u16>,
    dir_w: Option<Vec<u16>>,
    verb_w: Vec<u16>,
    show: windows::Win32::UI::WindowsAndMessaging::SHOW_WINDOW_CMD,
}

/// What the launch will do, decided with no effect whatsoever.
pub(crate) enum RunasStep {
    AlreadyElevated,
    Launch(Box<RunasLaunch>),
}

/// PURE given `host` (the Windows gate seam): every config gate, every input check, and the
/// planner decision — and NOTHING that touches the system.
///
/// Split out from the launch so the unit tests can drive it. They probe what happens when a check
/// is removed, and a test that drove `launch_runas_with_host` instead would, on the unelevated
/// leg of that hypothetical, fall through the planner and issue a REAL `ShellExecuteExW` with
/// verb `runas` — raising a UAC prompt and elevating the probe program on the developer's own
/// machine. Returning the decision instead makes that outcome unreachable from a test.
pub(crate) fn plan_runas(cmd: &Command, host: &Host) -> Result<RunasStep, Error> {
    let req = cmd.elevation_request();
    let (backend, auth) = (req.backend, req.auth.clone());
    // Structural config gate FIRST — privilege-independent (before the short-circuit), so
    // an already-elevated caller gets the same verdict for piped/env/contain/commandline.
    reject_unsupported_config(cmd)?;
    // The program is argv[0] as written: `ShellExecuteEx` gets it unresolved, and the gates below
    // refuse anything but a fully qualified `.exe`/`.com`, so it has no search to make.
    let argv = elevated_argv(cmd)?; // refuses executable()/raw_executable()/commandline()/empty too
    let program = &argv[0];

    // Input validation stays with `reject_unsupported_config`, ABOVE the short-circuit, so every
    // verdict here is a property of the REQUEST rather than of the caller's ambient privilege.
    // Putting it below would make the same `Command` refused when unelevated and accepted when
    // already elevated — the exact "depends which path ran" divergence these checks exist to
    // remove.

    // Ahead of EVERY other field's check, including the per-element argv loop, because this is the
    // field that decides which image runs ELEVATED: `C:\tools\setup` + NUL + `.bat` launches
    // `C:\tools\setup`, a program the caller never named, and a request poisoning the program and
    // an argument together would otherwise come back naming only `argument 1`. `reject_batch_path`
    // below refuses an interior NUL too, but it runs after those fields, so this ordering is the
    // elevated path's own.
    let file_w = wide_nul("program path", program.as_os_str())?;

    // Then EVERY remaining field, and only then the batch gate: a truncating argument or working
    // directory is a defect the caller can fix, and "batch escaping is not implemented" would hide
    // it — a clean `.bat` next to a poisoned `current_dir()` would never mention that `lpDirectory`
    // truncates too. `params` is checked per element, by index, inside `elevated_params`.
    let params = elevated_params(argv)?;
    let dir = cmd
        .cwd()
        .map(|d| wide_nul("working directory", d.as_os_str()))
        .transpose()?;
    let params_w = wide_nul("argument line", params.as_os_str())?;
    let verb_w = wide_nul("verb", OsStr::new("runas"))?;

    // Refuse a `.bat`/`.cmd` spelled in the program, argv[0]. `ShellExecuteEx`'s `runas` resolves
    // the `batfile` association, which routes through `cmd.exe` and substitutes `lpParameters`
    // into `%*` UNESCAPED — and `join_wide` quotes only for
    // whitespace, never for cmd metacharacters, so `args(["setup.bat", "a&calc"])` is command
    // injection into an ELEVATED cmd.exe. That is CVE-2024-24576, which the raw and std backends
    // both refuse outright.
    //
    // The batch gate judges the name Win32 resolves the token to — trailing dots and spaces, `..`
    // collapse, drive and UNC and device roots, and data-stream pieces. The launch is `exefile`
    // (`SEE_MASK_CLASSNAME`), which runs `HKCR\exefile\shell\runas\command` (`"%1" %*`) on
    // `lpFile`. Measured only for an ELEVATED caller, which cosca never launches from: no App
    // Paths, no bare-name search, `%` literal. The consent route an unelevated caller takes is
    // unmeasured, so the rest is conservative (see `shell_file`): a fully qualified `.exe`/`.com`
    // path, which leaves no extensionless name for `PATHEXT` to complete (whether it applies to a
    // name already ending in `.exe` is unmeasured on every route), with no `"` or `%`, and a
    // `current_dir()` with no `%`. A relative or bare token is refused until the image is resolved
    // before the launch.
    let program_path = std::path::Path::new(program);
    crate::child::spawn::reject_batch_path(program_path)?;
    shell_file::reject_elevated_program(program_path)?;
    if let Some(dir) = cmd.cwd() {
        shell_file::reject_percent_in_directory(dir)?;
    }

    match host.plan(Privilege::Elevated, backend, auth) {
        Transition::RunAsIs => return Ok(RunasStep::AlreadyElevated),
        Transition::Reject { error } => return Err(error),
        Transition::ElevatePosix { .. } => unreachable!("planner never yields ElevatePosix on a windows host"),
        Transition::ElevateMacosGui { .. } => {
            unreachable!("planner never yields ElevateMacosGui on a windows host")
        }
        Transition::ElevateWindows { .. } => {}
    }

    Ok(RunasStep::Launch(Box::new(RunasLaunch {
        file_w,
        class_w: wide_nul("class", OsStr::new("exefile"))?,
        params_w,
        dir_w: dir,
        verb_w,
        show: runas_show_command(cmd.flags_request()),
    })))
}

/// The detail, cause, cleanup and fate of a launched child that could not be tracked, after its
/// termination came back as `outcome`. `unread` is what could not be read: the error of
/// `GetProcessId` when the pid could not be, else the pid whose identity could not be resolved, with
/// the identity read's error. Never waits.
///
/// The detail says what was done. The failed read is the cause (the `source`), and a refused
/// termination, which is a failure of the cleanup, not of what the call was doing, is the cleanup.
fn untracked_outcome(
    unread: Result<(u32, windows::core::Error), windows::core::Error>,
    outcome: Termination,
) -> (
    String,
    Option<std::sync::Arc<Error>>,
    Option<crate::error::Failures>,
    ChildFate,
) {
    let (who, why, read_failure) = match unread {
        Ok((pid, e)) => (
            format!("the elevated child (pid {pid})"),
            "its identity could not be resolved".to_string(),
            e,
        ),
        Err(e) => (
            "the elevated child".to_string(),
            "its pid could not be read (GetProcessId)".to_string(),
            e,
        ),
    };
    let cause = |e| Error::io_cause(crate::error::win32_io_error(e));
    let source = Some(cause(read_failure));
    match outcome {
        Termination::Terminated => (
            format!("the elevated child launched but {why}; it was terminated"),
            source,
            None,
            ChildFate::Killed,
        ),
        Termination::Exited => (
            format!("the elevated child launched but {why}; it exited or is exiting, and its exit was not waited for"),
            source,
            None,
            // `Killed` is "dead or dying, exit not collected": it claims no completion. Waiting here
            // would block, and this launch runs inside the async spawn too.
            ChildFate::Killed,
        ),
        Termination::Failed(e) => (
            format!("{who} launched but {why} and could not be terminated; it may still be running"),
            source,
            crate::error::Failures::collect([Error::io_cause(crate::error::io_context(
                "terminating the elevated child",
                crate::error::win32_io_error(e),
            ))]),
            ChildFate::Running { id: None },
        ),
    }
}

/// The effect: `ShellExecuteEx(runas)` on an already-validated payload, plus the identity read of
/// the child it launched. Everything that could refuse the request happened in [`plan_runas`].
///
/// A failure once `ShellExecuteEx` succeeded may come after the program started.
pub(crate) fn launch_runas_with_host(cmd: &Command, host: &Host) -> Result<RunasOutcome, SpawnFailure> {
    let launch = match plan_runas(cmd, host).not_started()? {
        RunasStep::AlreadyElevated => return Ok(RunasOutcome::AlreadyElevated),
        RunasStep::Launch(launch) => launch,
    };
    let RunasLaunch {
        file_w,
        class_w,
        params_w,
        dir_w,
        verb_w,
        show,
    } = *launch;

    let com = ComInit::init().not_started()?;
    // SAFETY: `info` is fully initialized with the correct cbSize; the wide buffers
    // outlive the call; SEE_MASK_NOCLOSEPROCESS yields an owned hProcess.
    let proc: OwnedHandle = unsafe {
        let mut info = SHELLEXECUTEINFOW {
            cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
            fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC | SEE_MASK_CLASSNAME,
            lpVerb: PCWSTR(verb_w.as_ptr()),
            lpFile: PCWSTR(file_w.as_ptr()),
            lpParameters: PCWSTR(params_w.as_ptr()),
            lpDirectory: dir_w.as_ref().map_or(PCWSTR::null(), |d| PCWSTR(d.as_ptr())),
            nShow: show.0,
            lpClass: PCWSTR(class_w.as_ptr()),
            ..Default::default()
        };
        if let Err(e) = ShellExecuteExW(&mut info) {
            return Err(shell_execute_failure(e.code(), info.hInstApp.0 as isize));
        }
        // `ShellExecuteEx` succeeded, and a handle that names no process does not show none started.
        if info.hProcess.is_invalid() {
            return Err(SpawnFailure::started(
                Error::Elevation {
                    kind: ElevationErrorKind::AuthFailed,
                    detail: "ShellExecuteEx(runas) returned no process handle".into(),
                    source: None,
                },
                ChildFate::Unknown,
                None,
            ));
        }
        OwnedHandle::from_raw_handle(info.hProcess.0 as std::os::windows::io::RawHandle)
    };
    drop(com);

    // Identity from the OWNED handle — no second OpenProcess.
    let handle = HANDLE(proc.as_raw_handle());
    // The one read of what the handle was granted: the kill below and the child it becomes take it.
    let granted = crate::os_process::windows::uac_access(handle);
    // SAFETY: `handle` is our live, owned process handle.
    let pid = match unsafe { GetProcessId(handle) } {
        0 => Err(windows::core::Error::from_thread()),
        pid => Ok(pid),
    };
    // What could not be read: the pid's error, or the pid with the identity read's.
    let tracked = match pid {
        Ok(pid) => crate::identity::windows_identity_from_handle_result(handle, pid)
            .map(|id| (pid, id))
            .map_err(|e| Ok((pid, e))),
        Err(e) => Err(Err(e)),
    };
    let (pid, id) = match tracked {
        Ok(tracked) => tracked,
        Err(unread) => {
            // Auth SUCCEEDED but we cannot track the child. Terminate it, and report the
            // ACTUAL outcome (terminated vs still-running) in the detail — the kind stays neutral.
            let (detail, source, cleanup, fate) = untracked_outcome(unread, windows_terminate_held(handle, granted));
            return Err(SpawnFailure::started(
                Error::Elevation {
                    kind: ElevationErrorKind::Untracked,
                    detail,
                    source,
                },
                fate,
                None,
            )
            .with_cleanup(cleanup));
        }
    };

    let report = ElevationReport {
        via: ElevatedVia::WindowsUac,
        stripped_env: Vec::new(),
        stdio: ElevatedStdio::OwnConsole,
    };
    Ok(RunasOutcome::Launched {
        proc,
        granted,
        pid,
        id,
        report,
    })
}

pub(crate) fn spawn_elevated(
    cmd: &mut Command,
    kill_on_drop: bool,
    policy: SpawnPolicy,
) -> Result<crate::child::Child, SpawnFailure> {
    match launch_runas(&*cmd)? {
        RunasOutcome::AlreadyElevated => spawn_already_elevated(cmd, kill_on_drop, policy),
        RunasOutcome::Launched {
            proc,
            granted,
            pid,
            id,
            report,
        } => Ok(crate::child::Child::from_parts(
            OwnedChild::new(Box::new(WindowsProcess::for_uac(proc, pid, granted))),
            Some(id),
            BTreeMap::new(),
            kill_on_drop,
            Attachment::uac_elevated(),
            Some(report),
            policy,
        )),
    }
}

/// Spawn `cmd` as an ordinary child that reports itself already elevated, as the POSIX rewrite
/// does: from a derived command, so `cmd` keeps no report.
fn spawn_already_elevated(
    cmd: &mut Command,
    kill_on_drop: bool,
    policy: SpawnPolicy,
) -> Result<crate::child::Child, SpawnFailure> {
    let (input, env_ops) = (cmd.input().clone(), cmd.env_ops().to_vec());
    let mut derived = cmd.derive_for_elevation(
        input,
        env_ops,
        crate::elevation::already_elevated_report(ElevatedStdio::Passthrough),
    );
    crate::child::spawn::spawn_unelevated(&mut derived, kill_on_drop, policy)
}

#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;