cosca 0.7.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
//! Test-only: a REAL live child process whose process-object DACL denies us rights.
//!
//! A live process we may not `OpenProcess` is needed to reproduce an access-denied identity
//! read. Depending on a system service will not do — an elevated CI runner can open those.
//! So we create one: `CreateProcessW` accepts a `SECURITY_ATTRIBUTES` for the new process
//! object, and a DACL holding a single access-allowed ACE for our own user SID denies every
//! right that ACE omits — to us and to an elevated caller with the same SID.
//!
//! One privilege defeats that: a token holding `SeDebugPrivilege` **enabled** bypasses the
//! DACL outright. An interactive session does not hold it enabled; CI runners do. So
//! [`drop_se_debug_privilege`] strips it from this process, making the DACL authoritative
//! everywhere; see it for why every fixture takes the [`Completion`] of `own_process`.
//!
//! Teardown is safe: the handle `CreateProcessW` hands the creator carries full access
//! regardless of the DACL, and the child is assigned to a kill-on-close job object so any
//! grandchild dies with it.
//!
//! Both scratch buffers below are `Vec<u64>` / `Vec<u32>`, not `Vec<u8>`: `TOKEN_USER` holds
//! a pointer (align 8) and `InitializeAcl` requires a DWORD-aligned `ACL`. A `Vec<u8>` is
//! align-1, so casting one to either type is an unaligned access and can produce a malformed
//! DACL — which would silently grant more than intended and make every downstream denial
//! test pass for the wrong reason.

use std::mem::size_of;

use crate::test_own_process::Completion;
use windows::core::PWSTR;
use windows::Win32::Foundation::LUID;
use windows::Win32::Foundation::{
    CloseHandle, SetHandleInformation, HANDLE, HANDLE_FLAG_INHERIT, STILL_ACTIVE, WAIT_OBJECT_0,
};
use windows::Win32::Security::{
    AddAccessAllowedAce, AdjustTokenPrivileges, GetTokenInformation, InitializeAcl, InitializeSecurityDescriptor,
    LookupPrivilegeValueW, SetSecurityDescriptorDacl, TokenUser, ACL, ACL_REVISION, LUID_AND_ATTRIBUTES,
    PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES, SECURITY_DESCRIPTOR, SE_DEBUG_NAME, SE_PRIVILEGE_REMOVED,
    TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER,
};
use windows::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject,
    JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
use windows::Win32::System::Threading::{
    CreateProcessW, GetCurrentProcess, GetExitCodeProcess, OpenProcessToken, QueryFullProcessImageNameW, ResumeThread,
    TerminateProcess, WaitForSingleObject, CREATE_NO_WINDOW, CREATE_SUSPENDED, INFINITE, PROCESS_INFORMATION,
    PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, STARTF_USESTDHANDLES, STARTUPINFOW,
};

/// Remove `SeDebugPrivilege` from THIS process's token.
///
/// A token holding that privilege **enabled** bypasses a process object's DACL outright, so
/// every denial this module constructs would be quietly openable and every access-denied
/// test would report green while proving nothing. An interactive session does not hold it
/// enabled, which is why the fixture works locally; GitHub's Windows runners do, which is
/// why it does not work there.
///
/// Removing it makes the DACL authoritative on every runner, so this is a real fix rather
/// than a skip: if the precondition still fails to hold, `spawn_unkillable_denies_everything`
/// and its siblings fail loudly instead of passing vacuously.
///
/// `SE_PRIVILEGE_REMOVED` is irreversible for the token and the token is shared by every thread of
/// the process, so a test running beside others would change what they observe. Calling it
/// again is harmless: the privilege is already gone.
fn drop_se_debug_privilege(_alone: &Completion) {
    let mut token = HANDLE::default();
    // SAFETY: GetCurrentProcess returns a pseudo-handle needing no close.
    unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut token) }
        .expect("OpenProcessToken(TOKEN_ADJUST_PRIVILEGES)");
    let mut luid = LUID::default();
    // SAFETY: `SE_DEBUG_NAME` is a static NUL-terminated wide string.
    unsafe { LookupPrivilegeValueW(None, SE_DEBUG_NAME, &mut luid) }.expect("LookupPrivilegeValueW(SeDebugPrivilege)");
    let privileges = TOKEN_PRIVILEGES {
        PrivilegeCount: 1,
        Privileges: [LUID_AND_ATTRIBUTES {
            Luid: luid,
            Attributes: SE_PRIVILEGE_REMOVED,
        }],
    };
    // Succeeds with ERROR_NOT_ALL_ASSIGNED when the token never held the privilege —
    // the normal local case, and exactly the state we want either way.
    // SAFETY: `privileges` describes one LUID and `PrivilegeCount` matches.
    let adjusted = unsafe { AdjustTokenPrivileges(token, false, Some(&privileges), 0, None, None) };
    // SAFETY: `token` is an owned handle we are done with.
    unsafe { CloseHandle(token) }.expect("CloseHandle(process token)");
    adjusted.expect("AdjustTokenPrivileges(SeDebugPrivilege, SE_PRIVILEGE_REMOVED)");
}

/// The image path of process `pid`, read on a handle of its own; `None` once it is gone.
pub(crate) fn image_file_name(pid: u32) -> Option<String> {
    use super::backend::{close, open_classified, Opened};
    let handle = match open_classified(pid, PROCESS_QUERY_LIMITED_INFORMATION) {
        Opened::Found(handle) => handle,
        Opened::Gone => return None,
        Opened::Denied(e) => panic!("fixture: the job member {pid} cannot be opened: {e}"),
    };
    // 32 767 UTF-16 units and a terminator: the longest path Windows has.
    let mut buffer = vec![0u16; 32_768];
    let mut len = buffer.len() as u32;
    // SAFETY: `handle` is a live handle with the query right, and `len` is `buffer`'s length in units.
    let read = unsafe { QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, PWSTR(buffer.as_mut_ptr()), &mut len) };
    let mut exit_code = 0u32;
    // SAFETY: `handle` is live and owned here.
    unsafe { GetExitCodeProcess(handle, &mut exit_code) }.expect("GetExitCodeProcess on an owned handle");
    close(handle);
    match read {
        Ok(()) => Some(String::from_utf16_lossy(&buffer[..len as usize])),
        // The query fails on a process that has exited since it was listed. The fixture's
        // processes never exit with 259 (`is_running`).
        Err(e) if exit_code == STILL_ACTIVE.0 as u32 => {
            panic!("fixture: the image of the live job member {pid} cannot be read: {e}")
        }
        Err(_) => None,
    }
}

/// Sentinel for [`spawn_with_ace`]: build the DACL with no ACE at all.
const NO_ACE: u32 = u32::MAX;

/// A live child whose process object grants us only the mask passed to [`spawn_restricted`].
/// Terminated and closed on drop.
pub(crate) struct RestrictedChild {
    handle: HANDLE,
    thread: HANDLE,
    /// Kills the whole tree when closed. `TerminateProcess` does NOT cascade, so without
    /// this `spawn_restricted_shell`'s `cmd.exe` would die while the `ping.exe` it launched
    /// ran on for an hour. `wait_for_child` reads this job's members.
    job: HANDLE,
    pid: u32,
}

impl RestrictedChild {
    pub(crate) fn pid(&self) -> u32 {
        self.pid
    }

    /// The creator's full-access handle — the only way to read this child's identity.
    pub(crate) fn handle(&self) -> HANDLE {
        self.handle
    }

    /// `STILL_ACTIVE` while running, else the recorded exit code. Read through the owned
    /// handle, so the DACL never affects it.
    pub(crate) fn exit_code(&self) -> u32 {
        let mut code = 0u32;
        // SAFETY: `self.handle` is our live, owned, full-access process handle.
        unsafe { GetExitCodeProcess(self.handle, &mut code) }.expect("GetExitCodeProcess on an owned handle");
        code
    }

    /// The fixture command is chosen so it never exits with 259, making this read
    /// unambiguous for our own child (it is not, in general, for arbitrary processes).
    pub(crate) fn is_running(&self) -> bool {
        self.exit_code() == STILL_ACTIVE.0 as u32
    }

    /// Block until the child's exit is recorded. Not a timeout: the wait is bounded by an
    /// exit someone has already requested (`terminate`, or a `kill_by_identity` under test).
    pub(crate) fn await_exit(&self) {
        // SAFETY: `self.handle` is our live, owned process handle.
        let waited = unsafe { WaitForSingleObject(self.handle, INFINITE) };
        assert_eq!(
            waited, WAIT_OBJECT_0,
            "fixture: wait on pid {} returned {waited:?}",
            self.pid
        );
    }

    /// The pid of the `ping.exe` this fixture's shell launched, once it exists.
    ///
    /// Reads the fixture's job, not the process tree: the job lists exactly the processes
    /// created under the shell, so a pre-existing orphan whose creator pid was recycled onto
    /// this shell is not in it. The job also holds the console host (`conhost.exe`) the shell
    /// was given, listed before `ping`, so the child is the member whose image is `ping.exe`.
    /// Nothing opens the shell, which may grant us no query right (`spawn_restricted_shell`
    /// with `PROCESS_SYNCHRONIZE`); the members are opened by pid, and they are not
    /// DACL-restricted.
    ///
    /// No event announces the child (a job's completion messages are not guaranteed to be
    /// delivered), so this re-reads the live member list until `cmd /c` has created it.
    pub(crate) fn wait_for_child(&self) -> u32 {
        loop {
            assert!(self.is_running(), "the fixture shell exited before spawning its child");
            let members = crate::containment::windows::query_job_pid_list(self.job).expect("the fixture job's members");
            for pid in members.into_iter().filter(|&pid| pid != self.pid) {
                let is_ping = image_file_name(pid).is_some_and(|image| {
                    std::path::Path::new(&image)
                        .file_name()
                        .is_some_and(|name| name.eq_ignore_ascii_case("ping.exe"))
                });
                if is_ping {
                    return pid;
                }
            }
            std::thread::yield_now();
        }
    }

    /// Terminate with exit code 1 and wait for the kernel to record it. Ask forgiveness, not
    /// permission: `TerminateProcess` on an already-exited child fails with ACCESS_DENIED,
    /// which is success here — a pre-check would race the child's own exit. Panics on a
    /// genuine teardown failure, so a test never quietly leaks a live process.
    pub(crate) fn terminate(&self) {
        if let Err(what) = self.try_terminate() {
            log::error!("{what}");
            if !std::thread::panicking() {
                panic!("{what}");
            }
        }
    }

    /// The non-panicking core, so `Drop` can report a failure without unwinding out of
    /// itself and skipping the handle closes.
    fn try_terminate(&self) -> Result<(), String> {
        // SAFETY: `self.handle` is our live, owned, full-access process handle.
        if let Err(e) = unsafe { TerminateProcess(self.handle, 1) } {
            if !self.is_running() {
                return Ok(()); // it exited on its own between our read and the call — fine
            }
            // Do NOT fall through to the wait: nothing asked the child to exit, so the wait
            // would park forever.
            return Err(format!(
                "fixture teardown: TerminateProcess(pid {}) failed: {e}",
                self.pid
            ));
        }
        // SAFETY: `self.handle` is live and we just asked the child to exit, so this wait is
        // bounded by that exit.
        let waited = unsafe { WaitForSingleObject(self.handle, INFINITE) };
        if waited != WAIT_OBJECT_0 {
            return Err(format!(
                "fixture teardown: wait on pid {} returned {waited:?}",
                self.pid
            ));
        }
        Ok(())
    }
}

impl Drop for RestrictedChild {
    fn drop(&mut self) {
        // Never let a teardown failure unwind out of `drop` before the closes below: the
        // child is still ALIVE on that path (that is what makes it a failure), so leaking
        // its handles would strand a process with no owner.
        let failure = self.try_terminate().err();
        // The job goes last: closing it is what kills any grandchildren.
        for (h, what) in [(self.thread, "thread"), (self.handle, "process"), (self.job, "job")] {
            // SAFETY: all three handles are ours and still open.
            if let Err(e) = unsafe { CloseHandle(h) } {
                log::error!("fixture teardown: CloseHandle({what}) for pid {} failed: {e}", self.pid);
            }
        }
        if let Some(what) = failure {
            log::error!("{what}");
            if !std::thread::panicking() {
                panic!("{what}");
            }
        }
    }
}

/// Spawn a long-running child whose process-object DACL allows our user SID exactly
/// `granted | PROCESS_TERMINATE` and nothing else.
pub(crate) fn spawn_restricted(alone: &Completion, granted: u32) -> RestrictedChild {
    spawn_with_ace(alone, granted | PROCESS_TERMINATE.0)
}

/// Spawn a child that even `PROCESS_TERMINATE` cannot open by pid. `Drop` still tears it
/// down through the owned handle.
///
/// Uses an EMPTY DACL, not an ACE with a zero access mask: an empty DACL is Windows'
/// documented "grant nothing to anyone" form, whereas a zero-mask ACE is unspecified — it
/// might be rejected by `AddAccessAllowedAce` (panicking the fixture) or normalized away
/// (silently granting access, which would send all of its consumers down the `Opened::Found`
/// path while still reporting green).
pub(crate) fn spawn_unkillable(alone: &Completion) -> RestrictedChild {
    spawn_with_ace(alone, NO_ACE)
}

/// Grants `PROCESS_QUERY_LIMITED_INFORMATION` and nothing else — identity is readable by pid
/// but `PROCESS_TERMINATE` and `PROCESS_SYNCHRONIZE` are denied, which is the only shape that
/// opens with the query right alone (`spawn_restricted` always ORs in `PROCESS_TERMINATE`).
pub(crate) fn spawn_query_only(alone: &Completion) -> RestrictedChild {
    spawn_with_ace(alone, PROCESS_QUERY_LIMITED_INFORMATION.0)
}

/// Like [`spawn_restricted`], but the restricted process is a shell that spawns an ordinary
/// grandchild. A DACL is not inherited, so the grandchild is freely openable while its
/// parent is not — the only way to build "my parent is access-denied" from a test.
pub(crate) fn spawn_restricted_shell(alone: &Completion, granted: u32) -> RestrictedChild {
    spawn_with_ace_cmdline(
        alone,
        granted | PROCESS_TERMINATE.0,
        "C:\\Windows\\System32\\cmd.exe /c ping.exe -n 3600 127.0.0.1",
        None,
    )
}

/// Like [`spawn_restricted`], but the child is `more.com` reading a piped stdin, and the caller
/// holds the write end: dropping it lets the child exit by itself, with code 0. For a test whose
/// kill is the behaviour under test: the child it spares ends on that release, so a kill that sent
/// nothing fails an assertion on the exit code (`1` for a kill) instead of leaving a wait on a child
/// that never ends.
///
/// Until it exits, the child inherits the handles this process already holds inheritable, besides
/// its stdio; the fixture's `Drop` ends it.
pub(crate) fn spawn_restricted_releasable(alone: &Completion, granted: u32) -> (RestrictedChild, std::io::PipeWriter) {
    use std::os::windows::io::AsRawHandle as _;
    let (reader, writer) = std::io::pipe().expect("pipe");
    let null = std::fs::OpenOptions::new().write(true).open("NUL").expect("open NUL");
    let (stdin, stdout) = (HANDLE(reader.as_raw_handle()), HANDLE(null.as_raw_handle()));
    for handle in [stdin, stdout] {
        // SAFETY: `handle` is live and owned by `reader` or `null`; the call only sets its flag.
        unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT) }
            .expect("make the child's stdio inheritable");
    }
    let more = crate::test_child::windows_more();
    let child = spawn_with_ace_cmdline(
        alone,
        granted | PROCESS_TERMINATE.0,
        &format!("\"{}\"", more.display()),
        Some((stdin, stdout)),
    );
    // `reader` and `null` close here, so the write end is the pipe's only other holder.
    (child, writer)
}

fn spawn_with_ace(alone: &Completion, granted: u32) -> RestrictedChild {
    spawn_with_ace_cmdline(
        alone,
        granted,
        "C:\\Windows\\System32\\ping.exe -n 3600 127.0.0.1",
        None,
    )
}

/// Panics on any Win32 failure: a fixture that silently degrades would make its consumers
/// pass vacuously. `stdio` is the child's stdin and its stdout and stderr, as inheritable
/// handles; given, the child is created with handle inheritance on.
fn spawn_with_ace_cmdline(
    alone: &Completion,
    granted: u32,
    cmdline: &str,
    stdio: Option<(HANDLE, HANDLE)>,
) -> RestrictedChild {
    // Before the child is created, so no denial assertion can observe a token that still
    // bypasses DACLs.
    drop_se_debug_privilege(alone);

    // Our own user SID, from our own token. `token` is a real handle — closed below.
    let mut token = HANDLE::default();
    // SAFETY: GetCurrentProcess returns a pseudo-handle needing no close.
    unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }.expect("OpenProcessToken");
    let mut needed = 0u32;
    // SAFETY: a null buffer with length 0 is the documented size query; it fails with
    // ERROR_INSUFFICIENT_BUFFER and writes the required size.
    _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, &mut needed) };
    // u64-backed so the TOKEN_USER cast below is 8-aligned.
    let mut sid_buf = vec![0u64; (needed as usize).div_ceil(8).max(1)];
    // SAFETY: `sid_buf` is at least `needed` bytes.
    let info = unsafe {
        GetTokenInformation(
            token,
            TokenUser,
            Some(sid_buf.as_mut_ptr().cast()),
            (sid_buf.len() * 8) as u32,
            &mut needed,
        )
    };
    // SAFETY: `token` is an owned handle we are done with.
    unsafe { CloseHandle(token) }.expect("CloseHandle(process token)");
    info.expect("GetTokenInformation(TokenUser)");
    // SAFETY: the kernel wrote a TOKEN_USER at the head of an 8-aligned buffer, and
    // `sid_buf` outlives every use of `sid` (dropped at the end of this function, after
    // CreateProcessW).
    let sid = unsafe { (*sid_buf.as_ptr().cast::<TOKEN_USER>()).User.Sid };

    // A DACL with ONE allow-ACE: everything it does not name is denied. u32-backed so the
    // ACL is DWORD-aligned, as InitializeAcl requires.
    let mut acl_buf = vec![0u32; 256];
    let acl = acl_buf.as_mut_ptr().cast::<ACL>();
    // SAFETY: `acl_buf` is 1024 bytes, far more than one ACE needs.
    unsafe { InitializeAcl(acl, (acl_buf.len() * 4) as u32, ACL_REVISION) }.expect("InitializeAcl");
    if granted != NO_ACE {
        // SAFETY: `acl` is initialized above; `sid` is a valid SID owned by `sid_buf`.
        unsafe { AddAccessAllowedAce(acl, ACL_REVISION, granted, sid) }.expect("AddAccessAllowedAce");
    }

    let mut sd = SECURITY_DESCRIPTOR::default();
    let psd = PSECURITY_DESCRIPTOR(&mut sd as *mut _ as *mut _);
    // SAFETY: `sd` is a stack SECURITY_DESCRIPTOR; 1 is the only defined revision.
    unsafe { InitializeSecurityDescriptor(psd, 1) }.expect("InitializeSecurityDescriptor");
    // SAFETY: `psd` is initialized; `acl_buf` stays alive until after CreateProcessW.
    unsafe { SetSecurityDescriptorDacl(psd, true, Some(acl), false) }.expect("SetSecurityDescriptorDacl");

    let sa = SECURITY_ATTRIBUTES {
        nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: psd.0,
        bInheritHandle: false.into(),
    };

    // NUL-terminated HERE, centrally: `CreateProcessW` takes a `PWSTR` and reads until the
    // terminator, so a caller that forgot one would send it reading past the end of the
    // allocation. No call site can get this wrong.
    let mut cmdline: Vec<u16> = cmdline.encode_utf16().chain(std::iter::once(0)).collect();
    let mut si = STARTUPINFOW {
        cb: size_of::<STARTUPINFOW>() as u32,
        ..Default::default()
    };
    if let Some((stdin, stdout)) = stdio {
        si.dwFlags = STARTF_USESTDHANDLES;
        si.hStdInput = stdin;
        si.hStdOutput = stdout;
        si.hStdError = stdout;
    }
    let mut pi = PROCESS_INFORMATION::default();
    // SAFETY: `cmdline` is a NUL-terminated writable UTF-16 buffer; `sa` and the DACL it
    // points at are alive for the duration of the call.
    unsafe {
        CreateProcessW(
            None,
            Some(PWSTR(cmdline.as_mut_ptr())),
            Some(&sa),
            None,
            stdio.is_some(),
            CREATE_NO_WINDOW | CREATE_SUSPENDED,
            None,
            None,
            &si,
            &mut pi,
        )
    }
    .expect("CreateProcessW for the restricted fixture child");

    // SAFETY: an unnamed job object has no preconditions; the handle is owned by the
    // RestrictedChild and closed in Drop.
    let job = unsafe { CreateJobObjectW(None, None) }.expect("CreateJobObjectW");
    let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
        BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
            LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
            ..Default::default()
        },
        ..Default::default()
    };
    // SAFETY: `limits` matches the class being set.
    unsafe {
        SetInformationJobObject(
            job,
            JobObjectExtendedLimitInformation,
            &limits as *const _ as *const core::ffi::c_void,
            size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
        )
    }
    .expect("SetInformationJobObject");
    // SAFETY: both handles are live and ours.
    unsafe { AssignProcessToJobObject(job, pi.hProcess) }.expect("AssignProcessToJobObject");

    // Only NOW may the child run. Windows enrols a process-s children in its job only from
    // the moment the parent is already a member, so a child that started running before the
    // assignment could spawn a grandchild permanently outside the job - which is exactly the
    // orphan the job exists to prevent. CREATE_SUSPENDED closes that window by construction.
    // SAFETY: `pi.hThread` is the freshly created, still-suspended main thread.
    let prev = unsafe { ResumeThread(pi.hThread) };
    assert_eq!(prev, 1, "the fixture child must resume from exactly one suspend");

    let child = RestrictedChild {
        handle: pi.hProcess,
        thread: pi.hThread,
        job,
        pid: pi.dwProcessId,
    };
    // A child that died on startup would still keep its kernel object alive through our
    // handle, so every OpenProcess verdict would look right while testing nothing.
    assert!(
        child.is_running(),
        "the fixture child exited immediately — the command line is wrong"
    );
    child
}

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