subc-os 0.1.9

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
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
use std::ffi::OsString;

use super::*;

const NONCE: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

#[cfg(not(unix))]
#[test]
fn windows_reads_only_the_environment_copy_even_when_a_descriptor_is_named() {
    let got = LaunchNonceCell::new()
        .get(|key| match key {
            LAUNCH_NONCE_FD_ENV => Some(OsString::from("3:1")),
            LAUNCH_NONCE_ENV => Some(OsString::from("env-copy")),
            _ => None,
        })
        .unwrap()
        .unwrap();
    assert_eq!(
        (got.value(), got.source()),
        ("env-copy", LaunchNonceSource::Env)
    );
}

#[test]
fn without_the_descriptor_variable_the_environment_copy_is_read() {
    let got = LaunchNonceCell::new()
        .get(|key| (key == LAUNCH_NONCE_ENV).then(|| OsString::from("env-copy")))
        .unwrap()
        .unwrap();
    assert_eq!(
        (got.value(), got.source()),
        ("env-copy", LaunchNonceSource::Env)
    );
    assert_eq!(LaunchNonceCell::new().get(|_| None), Ok(None));
    assert_eq!(
        LaunchNonceCell::new().get(|key| (key == LAUNCH_NONCE_ENV).then(OsString::new)),
        Ok(None),
        "an empty environment copy is no nonce"
    );
}

#[test]
fn debug_never_prints_the_nonce() {
    let nonce = LaunchNonce {
        value: NONCE.to_string(),
        source: LaunchNonceSource::Fd,
    };
    let printed = format!("{nonce:?}");
    assert!(!printed.contains(NONCE), "{printed}");
    assert!(printed.contains("Fd"), "{printed}");
}

#[cfg(unix)]
mod unix_tests {
    use std::{
        alloc::{GlobalAlloc, Layout, System},
        cell::Cell,
        ffi::OsString,
        fs::{self, File},
        io::Read,
        os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd},
        os::unix::process::CommandExt,
        path::{Path, PathBuf},
        process::{Command, Stdio},
        sync::Arc,
    };

    use super::super::{
        launch_nonce, LaunchNonceCell, LaunchNonceError, LaunchNonceHandoff, LaunchNonceSource,
        LAUNCH_NONCE_ENV, LAUNCH_NONCE_FD_ENV,
    };
    use super::NONCE;

    // These tests open, close and duplicate descriptors by number, and a
    // number one test frees can be reused by another at once. They take this
    // lock so no two of them run together.
    static RAW_FD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn serial() -> std::sync::MutexGuard<'static, ()> {
        RAW_FD_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn fd_is_open(fd: RawFd) -> bool {
        // SAFETY: F_GETFD only reads the descriptor table.
        #[allow(unsafe_code)]
        unsafe {
            libc::fcntl(fd, libc::F_GETFD) != -1
        }
    }

    /// Whether `fd` still names the pipe with `inode`. After the accessor
    /// closes a descriptor, other tests running in parallel in this binary can
    /// open something that reuses the number at once, so "was it closed" is
    /// asked as "does the number still name that pipe", never as "is the
    /// number free".
    fn fd_names_pipe(fd: RawFd, inode: u64) -> bool {
        // SAFETY: fstat writes only into the zeroed struct passed to it.
        #[allow(unsafe_code)]
        unsafe {
            let mut stat: libc::stat = std::mem::zeroed();
            libc::fstat(fd, &mut stat) == 0
                && (stat.st_mode & libc::S_IFMT) == libc::S_IFIFO
                && stat.st_ino as u64 == inode
        }
    }

    /// A pipe holding `bytes` with its write end closed, and its inode.
    fn sealed_pipe(bytes: &[u8]) -> (OwnedFd, u64) {
        let handoff = LaunchNonceHandoff::new(std::str::from_utf8(bytes).unwrap()).unwrap();
        let inode = handoff.inode();
        let fd = handoff.read_end_fd();
        // Take the read end out of the handoff without closing it.
        // SAFETY: dup gives this test its own descriptor for the same pipe.
        #[allow(unsafe_code)]
        let copy = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
        assert!(copy >= 0);
        drop(handoff);
        // SAFETY: `copy` is a fresh descriptor nothing else owns.
        #[allow(unsafe_code)]
        (unsafe { OwnedFd::from_raw_fd(copy) }, inode)
    }

    fn naming(value: String) -> impl FnMut(&str) -> Option<OsString> {
        move |key| match key {
            LAUNCH_NONCE_FD_ENV => Some(OsString::from(value.clone())),
            // Present so a test sees any fallback to the environment copy.
            LAUNCH_NONCE_ENV => Some(OsString::from("env-copy")),
            _ => None,
        }
    }

    #[test]
    fn two_readers_share_one_descriptor_read() {
        let _serial = serial();
        let (read_end, inode) = sealed_pipe(NONCE.as_bytes());
        let fd = read_end.into_raw_fd();
        let cell = Arc::new(LaunchNonceCell::new());

        // Many first callers at once: one reads, the others wait for it.
        let threads: Vec<_> = (0..8)
            .map(|_| {
                let cell = Arc::clone(&cell);
                std::thread::spawn(move || cell.get(naming(format!("{fd}:{inode}"))))
            })
            .collect();
        for thread in threads {
            let got = thread.join().unwrap().unwrap().unwrap();
            assert_eq!(got.value(), NONCE);
            assert_eq!(got.source(), LaunchNonceSource::Fd);
        }
        assert_eq!(cell.descriptor_reads(), 1);
        assert!(
            !fd_names_pipe(fd, inode),
            "the first read closes the descriptor"
        );

        // Put a different pipe at the same number and name it, inode and
        // all, the way a second independent reader would find it. A reader
        // that went back to the descriptor would now take the planted bytes;
        // the cached value must come back instead and leave them unread.
        // F_DUPFD returns the lowest free number at or above `fd`, so it
        // lands exactly on `fd` only while that number is free, without ever
        // replacing a descriptor another thread has just opened there.
        let (planted, planted_inode) = sealed_pipe(b"planted");
        // Being the lowest free number, the new pipe usually lands on `fd`
        // by itself.
        let (planted, mut placed) = if planted.as_raw_fd() == fd {
            (None, planted.into_raw_fd())
        } else {
            (Some(planted), -1)
        };
        for _ in 0..100 {
            let Some(planted) = &planted else { break };
            // SAFETY: duplicates a descriptor this test owns.
            #[allow(unsafe_code)]
            let copy = unsafe { libc::fcntl(planted.as_raw_fd(), libc::F_DUPFD_CLOEXEC, fd) };
            if copy == fd {
                placed = copy;
                break;
            }
            // SAFETY: closes the copy just made, which this test owns.
            #[allow(unsafe_code)]
            unsafe {
                libc::close(copy)
            };
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        assert_eq!(placed, fd, "descriptor {fd} stayed taken by someone else");
        // SAFETY: `fd` now holds this test's copy of the planted pipe.
        #[allow(unsafe_code)]
        let placed = unsafe { OwnedFd::from_raw_fd(placed) };

        let second = cell
            .get(naming(format!("{fd}:{planted_inode}")))
            .unwrap()
            .unwrap();
        assert_eq!(second.value(), NONCE);
        assert_eq!(cell.descriptor_reads(), 1);
        drop(planted);
        let mut still_there = String::new();
        File::from(placed).read_to_string(&mut still_there).unwrap();
        assert_eq!(still_there, "planted");
    }

    #[test]
    fn a_closed_descriptor_is_not_open_and_never_falls_back() {
        let _serial = serial();
        // A number far above anything this test binary opens.
        let fd: RawFd = 900;
        assert!(!fd_is_open(fd));
        let got = LaunchNonceCell::new().get(naming(format!("{fd}:1")));
        assert!(
            matches!(got, Err(LaunchNonceError::NotOpen { fd: 900, .. })),
            "{got:?}"
        );
    }

    #[test]
    fn a_descriptor_that_is_not_a_pipe_is_left_open() {
        let _serial = serial();
        // Held as a raw number until the checks pass: had the accessor closed
        // it, dropping an owner would close it twice and abort the test binary
        // instead of failing this test by name.
        let fd = File::open("/dev/null").unwrap().into_raw_fd();
        let cell = LaunchNonceCell::new();
        let got = cell.get(naming(format!("{fd}:1")));
        assert!(
            fd_is_open(fd),
            "the accessor must not close a file it does not own"
        );
        assert_eq!(got, Err(LaunchNonceError::NotAPipe { fd }));
        assert_eq!(cell.descriptor_reads(), 0);
        // SAFETY: still open, and owned by this test.
        #[allow(unsafe_code)]
        drop(unsafe { OwnedFd::from_raw_fd(fd) });
    }

    #[test]
    fn a_different_pipe_at_the_number_is_left_unread() {
        let _serial = serial();
        let (_ours, expected) = sealed_pipe(NONCE.as_bytes());
        let (theirs, found) = sealed_pipe(b"someone else's");
        assert_ne!(expected, found, "pipes need distinct inodes for this test");
        // Raw until checked, for the reason given in the non-pipe test.
        let fd = theirs.into_raw_fd();
        let cell = LaunchNonceCell::new();
        let got = cell.get(naming(format!("{fd}:{expected}")));
        assert!(fd_is_open(fd), "the accessor must not close another pipe");
        // SAFETY: still open, and owned by this test.
        #[allow(unsafe_code)]
        let theirs = unsafe { OwnedFd::from_raw_fd(fd) };
        assert_eq!(
            got,
            Err(LaunchNonceError::WrongPipe {
                fd,
                expected_inode: expected,
                found_inode: found
            })
        );
        assert_eq!(cell.descriptor_reads(), 0);
        let mut left = String::new();
        File::from(theirs).read_to_string(&mut left).unwrap();
        assert_eq!(left, "someone else's");
    }

    #[test]
    fn an_empty_pipe_is_its_own_error_and_is_left_open() {
        let _serial = serial();
        let (empty, inode) = sealed_pipe(b"");
        // Raw until checked, for the reason given in the non-pipe test.
        let fd = empty.into_raw_fd();
        let cell = LaunchNonceCell::new();
        let got = cell.get(naming(format!("{fd}:{inode}")));
        assert!(fd_is_open(fd), "an empty pipe is refused, not consumed");
        assert_eq!(got, Err(LaunchNonceError::Empty { fd }));
        assert_eq!(cell.descriptor_reads(), 0);
        // SAFETY: still open, and owned by this test.
        #[allow(unsafe_code)]
        drop(unsafe { OwnedFd::from_raw_fd(fd) });
    }

    #[test]
    fn the_named_pipe_is_read_and_closed() {
        let _serial = serial();
        let (ours, inode) = sealed_pipe(NONCE.as_bytes());
        let fd = ours.into_raw_fd();
        let got = LaunchNonceCell::new()
            .get(naming(format!("{fd}:{inode}")))
            .unwrap()
            .unwrap();
        assert_eq!((got.value(), got.source()), (NONCE, LaunchNonceSource::Fd));
        assert!(!fd_names_pipe(fd, inode), "the read closes the descriptor");
    }

    #[test]
    fn malformed_values_are_refused() {
        let _serial = serial();
        for value in ["", "3", "x:1", "-1:5", "3:", "3:x", ":5"] {
            let got = LaunchNonceCell::new().get(naming(value.to_string()));
            assert!(
                matches!(got, Err(LaunchNonceError::Malformed { .. })),
                "{value}: {got:?}"
            );
        }
    }

    // Counts allocations made on the current thread, so the pre-exec step
    // can be shown to make none while other tests allocate on their own.
    struct CountingAllocator;
    thread_local! {
        static ALLOCATIONS: Cell<usize> = const { Cell::new(0) };
    }
    #[allow(unsafe_code)]
    unsafe impl GlobalAlloc for CountingAllocator {
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            let _ = ALLOCATIONS.try_with(|count| count.set(count.get() + 1));
            // SAFETY: forwards the caller's layout to the system allocator.
            unsafe { System.alloc(layout) }
        }
        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
            // SAFETY: `ptr` came from `alloc` above with this layout.
            unsafe { System.dealloc(ptr, layout) }
        }
        unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
            let _ = ALLOCATIONS.try_with(|count| count.set(count.get() + 1));
            // SAFETY: `ptr` came from `alloc` above with `layout`, and the
            // caller guarantees `new_size` is valid for it.
            unsafe { System.realloc(ptr, layout, new_size) }
        }
    }
    #[global_allocator]
    static ALLOCATOR: CountingAllocator = CountingAllocator;

    fn allocations() -> usize {
        ALLOCATIONS.with(Cell::get)
    }

    #[test]
    fn the_pre_exec_step_does_not_allocate() {
        let _serial = serial();
        // Run the step in this process onto a free high number, then on the
        // already-in-place path and on the error path.
        let moved = LaunchNonceHandoff::new(NONCE).unwrap().with_target(250);
        let in_place = LaunchNonceHandoff::new(NONCE).unwrap();
        let in_place_number = in_place.read_end_fd();
        let in_place = in_place.with_target(in_place_number);
        let failing = LaunchNonceHandoff::new(NONCE).unwrap().with_target(-5);

        let before = allocations();
        let moved_result = moved.install_in_child();
        let in_place_result = in_place.install_in_child();
        let failing_result = failing.install_in_child();
        let after = allocations();

        assert!(moved_result.is_ok(), "{moved_result:?}");
        assert!(in_place_result.is_ok(), "{in_place_result:?}");
        assert!(failing_result.is_err());
        assert_eq!(after - before, 0, "the pre-exec step allocated");
        // SAFETY: F_GETFD reads flags of descriptors this test created.
        #[allow(unsafe_code)]
        let (moved_flags, in_place_flags) = unsafe {
            (
                libc::fcntl(250, libc::F_GETFD),
                libc::fcntl(in_place_number, libc::F_GETFD),
            )
        };
        assert_eq!(
            moved_flags & libc::FD_CLOEXEC,
            0,
            "the copy must survive exec"
        );
        assert_eq!(
            in_place_flags & libc::FD_CLOEXEC,
            0,
            "the flag must be cleared in place"
        );
        // SAFETY: closes the copy this test made at 250.
        #[allow(unsafe_code)]
        unsafe {
            libc::close(250)
        };
    }

    #[test]
    fn a_new_handoff_is_close_on_exec_in_the_parent() {
        let _serial = serial();
        let handoff = LaunchNonceHandoff::new(NONCE).unwrap();
        // SAFETY: F_GETFD reads flags.
        #[allow(unsafe_code)]
        let flags = unsafe { libc::fcntl(handoff.read_end_fd(), libc::F_GETFD) };
        assert_ne!(flags & libc::FD_CLOEXEC, 0);
        assert_eq!(handoff.fd_env_value(), format!("3:{}", handoff.inode()));
    }

    // ---- Spawned processes -------------------------------------------------
    //
    // The tests below run this test binary again as a child, selecting the
    // ignored `probe_child` test, so the child is a real process that received
    // the handoff through exec. It writes what it saw to a report file.

    const ROLE_ENV: &str = "SUBC_OS_TEST_PROBE_ROLE";
    const OUT_ENV: &str = "SUBC_OS_TEST_PROBE_OUT";

    struct Scratch(PathBuf);

    impl Scratch {
        fn new(label: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "subc-os-{label}-{}-{}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            fs::create_dir_all(&path).unwrap();
            Self(path)
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    /// A command running `probe_child` in `role`, reporting to `out`. The
    /// child's XDG directories point into the scratch directory so nothing it
    /// could start touches the user's real ones.
    fn probe_command(out: &Path, role: &str) -> Command {
        let mut command = Command::new(std::env::current_exe().unwrap());
        command
            .args([
                "launch_nonce::tests::unix_tests::probe_child",
                "--exact",
                "--ignored",
                "--nocapture",
                "--test-threads=1",
                "-q",
            ])
            .env(ROLE_ENV, role)
            .env(OUT_ENV, out)
            .stdout(Stdio::null());
        let xdg = out.parent().unwrap();
        for name in ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"] {
            command.env(name, xdg.join(name));
        }
        command
    }

    fn describe(result: &Result<Option<super::super::LaunchNonce>, LaunchNonceError>) -> String {
        match result {
            Ok(Some(nonce)) => format!("{}:{}", nonce.source().as_str(), nonce.value()),
            Ok(None) => "none".to_string(),
            Err(error) => {
                let debug = format!("{error:?}");
                let name = debug.split([' ', '{', '(']).next().unwrap_or_default();
                format!("err:{name}")
            }
        }
    }

    fn report_line<'a>(report: &'a str, key: &str) -> &'a str {
        report
            .lines()
            .find_map(|line| line.strip_prefix(&format!("{key}=")))
            .unwrap_or_else(|| panic!("no {key} in report:\n{report}"))
    }

    fn run(mut command: Command, out: &Path) -> String {
        let status = command.status().unwrap();
        assert!(status.success(), "probe child failed: {status}");
        fs::read_to_string(out).unwrap()
    }

    #[test]
    #[ignore = "run as a child process by the spawned-process tests"]
    fn probe_child() {
        let Some(role) = std::env::var(ROLE_ENV).ok() else {
            return;
        };
        let out = PathBuf::from(std::env::var_os(OUT_ENV).unwrap());
        let mut report = String::new();
        if let Some(fd) = role.strip_prefix("closed-stdio:") {
            let fd: RawFd = fd.parse().unwrap();
            // Only this isolated subprocess loses a standard descriptor. Closing
            // it before making the pipe reproduces a daemon launched that way.
            #[allow(unsafe_code)]
            unsafe {
                libc::close(fd);
            }
            let handoff = LaunchNonceHandoff::new(NONCE).unwrap();
            let module_out = out.with_extension("module");
            let mut module = probe_command(&module_out, "module");
            module
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null());
            module.env(LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
            module.env(LAUNCH_NONCE_ENV, "not-the-pipe-nonce");
            handoff.install_last(&mut module);
            let report = run(module, &module_out);
            fs::write(&out, report).unwrap();
            return;
        }
        if let Some(fd) = role.strip_prefix("cat-fd:") {
            // Read a descriptor raw, to show what the step left at a number.
            let fd: RawFd = fd.parse().unwrap();
            // SAFETY: the parent put this descriptor here for this read.
            #[allow(unsafe_code)]
            let mut file = File::from(unsafe { OwnedFd::from_raw_fd(fd) });
            let mut bytes = String::new();
            let read = file.read_to_string(&mut bytes);
            report.push_str(&format!("read={}\n", read.is_ok()));
            report.push_str(&format!("bytes={bytes}\n"));
            fs::write(&out, report).unwrap();
            return;
        }
        let before: Vec<_> = std::env::vars_os().collect();
        let first = launch_nonce();
        let second = launch_nonce();
        let after: Vec<_> = std::env::vars_os().collect();
        report.push_str(&format!("result={}\n", describe(&first)));
        report.push_str(&format!("second_equal={}\n", first == second));
        report.push_str(&format!("env_unchanged={}\n", before == after));
        if role == "module-with-grandchild" {
            // Spawned after the first read, with the environment this process
            // inherited: the descriptor variable and the environment copy.
            let grandchild_out = out.with_extension("grandchild");
            let status = probe_command(&grandchild_out, "grandchild")
                .status()
                .unwrap();
            let grandchild = fs::read_to_string(&grandchild_out).unwrap_or_default();
            report.push_str(&format!("grandchild_ok={}\n", status.success()));
            report.push_str(&format!(
                "grandchild_result={}\n",
                report_line(&grandchild, "result")
            ));
        }
        fs::write(&out, report).unwrap();
    }

    #[test]
    fn a_spawned_child_reads_the_nonce_from_descriptor_3_and_leaves_the_environment_alone() {
        let _serial = serial();
        let scratch = Scratch::new("fd-child");
        let out = scratch.0.join("report");
        let mut command = probe_command(&out, "module");
        let handoff = LaunchNonceHandoff::new(NONCE).unwrap();
        command.env(LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
        // A different environment copy, so the report shows which was read.
        command.env(LAUNCH_NONCE_ENV, "environment-copy-is-not-the-nonce");
        handoff.install_last(&mut command);
        let report = run(command, &out);
        assert_eq!(report_line(&report, "result"), format!("fd:{NONCE}"));
        assert_eq!(report_line(&report, "second_equal"), "true");
        assert_eq!(report_line(&report, "env_unchanged"), "true");
    }

    #[test]
    fn handoff_survives_each_closed_standard_descriptor() {
        let _serial = serial();
        let scratch = Scratch::new("closed-stdio");
        for fd in 0..=2 {
            let out = scratch.0.join(format!("report-{fd}"));
            let report = run(probe_command(&out, &format!("closed-stdio:{fd}")), &out);
            assert_eq!(
                report_line(&report, "result"),
                format!("fd:{NONCE}"),
                "closed fd {fd}"
            );
        }
    }

    #[test]
    fn a_spawned_child_without_a_descriptor_reads_the_environment_copy() {
        let _serial = serial();
        let scratch = Scratch::new("env-child");
        let out = scratch.0.join("report");
        let mut command = probe_command(&out, "module");
        command.env_remove(LAUNCH_NONCE_FD_ENV);
        command.env(LAUNCH_NONCE_ENV, NONCE);
        let report = run(command, &out);
        assert_eq!(report_line(&report, "result"), format!("env:{NONCE}"));
        assert_eq!(report_line(&report, "env_unchanged"), "true");
    }

    #[test]
    fn a_grandchild_spawned_after_the_first_read_gets_no_descriptor_and_refuses_by_name() {
        let _serial = serial();
        let scratch = Scratch::new("grandchild");
        let out = scratch.0.join("report");
        let mut command = probe_command(&out, "module-with-grandchild");
        let handoff = LaunchNonceHandoff::new(NONCE).unwrap();
        command.env(LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
        command.env(LAUNCH_NONCE_ENV, NONCE);
        handoff.install_last(&mut command);
        let report = run(command, &out);
        assert_eq!(report_line(&report, "result"), format!("fd:{NONCE}"));
        assert_eq!(report_line(&report, "grandchild_ok"), "true");
        let grandchild = report_line(&report, "grandchild_result");
        // The grandchild inherited both variables. It must refuse by name,
        // and must not fall back to the environment copy it can still see.
        assert!(
            ["err:NotOpen", "err:NotAPipe", "err:WrongPipe"].contains(&grandchild),
            "grandchild got {grandchild}"
        );
    }

    #[test]
    fn the_handoff_installed_after_an_earlier_step_survives_a_colliding_descriptor_3() {
        let _serial = serial();
        let scratch = Scratch::new("collision");
        let out = scratch.0.join("report");
        let marker_path = scratch.0.join("marker");
        let marker = File::create(&marker_path).unwrap();
        let marker_fd = marker.as_raw_fd();
        let mut command = probe_command(&out, "cat-fd:3");
        // Stands in for the Linux cgroup placement: an earlier step that
        // writes through a descriptor it captured, which here has number 3.
        // SAFETY: dup2 and write only, on descriptors opened before the fork.
        #[allow(unsafe_code)]
        unsafe {
            command.pre_exec(move || {
                if libc::dup2(marker_fd, 3) == -1 {
                    return Err(std::io::Error::last_os_error());
                }
                let line = b"earlier step\n";
                if libc::write(3, line.as_ptr().cast(), line.len()) == -1 {
                    return Err(std::io::Error::last_os_error());
                }
                Ok(())
            });
        }
        LaunchNonceHandoff::new(NONCE)
            .unwrap()
            .install_last(&mut command);
        let report = run(command, &out);
        drop(marker);
        assert_eq!(report_line(&report, "bytes"), NONCE);
        assert_eq!(fs::read_to_string(&marker_path).unwrap(), "earlier step\n");
    }

    #[test]
    fn a_read_end_already_at_the_target_number_still_reaches_the_child() {
        let _serial = serial();
        let scratch = Scratch::new("in-place");
        let out = scratch.0.join("report");
        let handoff = LaunchNonceHandoff::new(NONCE).unwrap();
        let number = handoff.read_end_fd();
        let handoff = handoff.with_target(number);
        let mut command = probe_command(&out, &format!("cat-fd:{number}"));
        handoff.install_last(&mut command);
        let report = run(command, &out);
        assert_eq!(report_line(&report, "read"), "true");
        assert_eq!(report_line(&report, "bytes"), NONCE);
    }

    #[test]
    fn the_accessor_leaves_this_process_environment_alone() {
        let _serial = serial();
        let before: Vec<_> = std::env::vars_os().collect();
        let (ours, inode) = sealed_pipe(NONCE.as_bytes());
        let fd = ours.into_raw_fd();
        LaunchNonceCell::new()
            .get(naming(format!("{fd}:{inode}")))
            .unwrap()
            .unwrap();
        let after: Vec<_> = std::env::vars_os().collect();
        assert_eq!(before, after);
    }
}