harn-hostlib 0.10.134

Opt-in code-intelligence and deterministic-tool host builtins for the Harn VM
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
//! Native owner-death containment for managed background processes.
//!
//! Unix re-executes the current embedding executable as a small reaper plus a
//! process-group-leading guardian. The executable must dispatch
//! [`run_if_requested`] before its public argument parser. The supervisor
//! retains the only write end of the guardian's stdin pipe. Kernel EOF
//! therefore remains reliable even when the supervisor is killed before Rust
//! destructors or session cleanup can run, while the out-of-group reaper makes
//! guardian PGID disappearance deterministic.

#[cfg(unix)]
use std::cell::RefCell;
#[cfg(unix)]
use std::ffi::{OsStr, OsString};
#[cfg(unix)]
use std::io::{self, Read, Write};
#[cfg(unix)]
use std::os::unix::ffi::{OsStrExt, OsStringExt};
#[cfg(unix)]
use std::os::unix::process::{CommandExt, ExitStatusExt};
#[cfg(unix)]
use std::path::PathBuf;
#[cfg(unix)]
use std::process::{Child, ChildStderr, ChildStdin, Command, ExitStatus, Stdio};

#[cfg(unix)]
use serde::{Deserialize, Serialize};

#[cfg(unix)]
use super::{ProcessError, SpawnSpec};

/// Private argv marker handled before the public CLI parser runs.
pub const GUARDIAN_ARG: &str = "__harn-process-owner-guardian";

#[cfg(unix)]
const MODE_ENV: &str = "HARN_INTERNAL_PROCESS_GUARDIAN_MODE";
#[cfg(unix)]
const PIPE_MODE: &str = "request-pipe-v1";
#[cfg(unix)]
const REAPER_ENV: &str = "HARN_INTERNAL_PROCESS_GUARDIAN_REAPER";
#[cfg(unix)]
const MAX_REQUEST_BYTES: usize = 16 * 1024 * 1024;

#[cfg(unix)]
thread_local! {
    static REEXEC_ARGS: RefCell<Option<Vec<OsString>>> = const { RefCell::new(None) };
}

/// Restores the previous thread-local guardian re-exec arguments on drop.
#[cfg(unix)]
#[doc(hidden)]
pub struct GuardianReexecArgsGuard {
    previous: Option<Vec<OsString>>,
}

#[cfg(unix)]
impl Drop for GuardianReexecArgsGuard {
    fn drop(&mut self) {
        REEXEC_ARGS.with(|slot| {
            *slot.borrow_mut() = self.previous.take();
        });
    }
}

/// Override the private guardian re-exec argv on this thread.
///
/// Integration tests use this to enter a libtest fixture because their
/// generated executable does not own `main`. Production leaves it unset.
#[cfg(unix)]
#[doc(hidden)]
pub fn install_guardian_reexec_args<I, S>(args: I) -> GuardianReexecArgsGuard
where
    I: IntoIterator<Item = S>,
    S: Into<OsString>,
{
    let args = args.into_iter().map(Into::into).collect();
    let previous = REEXEC_ARGS.with(|slot| slot.replace(Some(args)));
    GuardianReexecArgsGuard { previous }
}

/// The descriptor number the populated Landlock ruleset arrives on.
///
/// Fixed rather than negotiated because the guardian learns it before it can
/// read anything: the request that would carry a negotiated number arrives on
/// stdin, and stdin is already the liveness lease.
#[cfg(all(unix, target_os = "linux"))]
const RULESET_FD: std::os::fd::RawFd = 3;

/// The confinement the guardian must enter on the payload's behalf.
///
/// The rest of [`PreparedCommand`] is a lossy projection of a `Command`: it
/// keeps what a program, its arguments, a directory and an environment can say,
/// and drops everything else. Confinement used to be in the "everything else",
/// because this backend installs it from a `pre_exec` callback and a callback
/// cannot cross an `exec`. The payload then ran unconfined while every step
/// reported success.
///
/// This is that missing half in a form the projection can carry: a byte string
/// for the compiled seccomp program, and a flag saying a ruleset descriptor was
/// handed over on [`RULESET_FD`]. `Some` is a REQUIREMENT, not a hint — a
/// guardian that cannot enter it refuses to spawn.
#[cfg(unix)]
#[derive(Deserialize, Serialize)]
struct GuardianConfinement {
    seccomp: Vec<u8>,
    ruleset: bool,
}

#[cfg(unix)]
#[derive(Deserialize, Serialize)]
struct PreparedCommand {
    program: Vec<u8>,
    args: Vec<Vec<u8>>,
    cwd: Option<Vec<u8>>,
    env_clear: bool,
    env: Vec<(Vec<u8>, Option<Vec<u8>>)>,
    cleanup_token: String,
    /// Absent means this run confines no child process at all, which is the
    /// same answer the direct spawn path acts on. It never means "confinement
    /// was wanted and could not be built": that is an error at the seam that
    /// built it, and it is returned as one.
    #[serde(default)]
    confinement: Option<GuardianConfinement>,
}

#[cfg(unix)]
#[derive(Deserialize, Serialize)]
struct StartupMessage {
    ok: bool,
    error: Option<String>,
    guardian_pid: Option<u32>,
    pid: Option<u32>,
}

/// Build the guardian re-exec command and its private pipe request.
#[cfg(unix)]
pub(crate) fn prepare_guardian(
    spec: &SpawnSpec,
    cleanup_token: String,
) -> Result<(Command, Vec<u8>), ProcessError> {
    let mut payload_spec = spec.clone();
    payload_spec.configure_process_group = false;
    payload_spec.owner_death = super::OwnerDeathPolicy::None;
    let (mut payload, _) =
        super::real::prepare_command(&payload_spec, Some(cleanup_token.clone()))?;
    payload.env(
        harn_vm::op_interrupt::PROCESS_OWNER_TOKEN_ENV,
        &cleanup_token,
    );
    // Built from the SAME ambient policy the payload command was prepared
    // under, one step earlier in this function, so the two cannot disagree.
    let confinement = build_confinement(&payload_spec.program)?;
    let request = PreparedCommand::from_command(
        &payload,
        spec.env_mode == super::EnvMode::Replace,
        cleanup_token.clone(),
        confinement.as_ref().map(TransferredConfinement::request),
    );
    let request = serde_json::to_vec(&request)
        .map_err(|error| ProcessError::Spawn(format!("encode guardian request: {error}")))?;

    let executable = std::env::current_exe()
        .map_err(|error| ProcessError::Spawn(format!("resolve guardian executable: {error}")))?;
    harn_vm::op_interrupt::initialize_process_owner_group_journal(&cleanup_token)
        .map_err(|error| ProcessError::Spawn(format!("create owner process journal: {error}")))?;
    let mut guardian = Command::new(executable);
    match REEXEC_ARGS.with(|slot| slot.borrow().clone()) {
        Some(args) => {
            guardian.args(args);
        }
        None => {
            guardian.arg(GUARDIAN_ARG);
        }
    }
    strip_sensitive_parent_env(&mut guardian, std::env::vars_os());
    guardian
        .env(MODE_ENV, PIPE_MODE)
        .env(REAPER_ENV, "1")
        .env_remove(harn_vm::op_interrupt::PROCESS_CLEANUP_TOKEN_ENV)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .process_group(0);
    if let Some(confinement) = confinement {
        confinement.hand_to(&mut guardian);
    }
    Ok((guardian, request))
}

/// The parent's side of the handover.
///
/// A confinement crosses an `exec` as a descriptor plus a byte string, and only
/// the descriptor needs help: the kernel opens a Landlock ruleset close-on-exec,
/// so it has to be placed on an agreed number with that flag cleared, and it has
/// to stay open until the guardian is spawned. Owning it here does both — the
/// value lives on the guardian `Command`, which outlives the spawn.
#[cfg(target_os = "linux")]
struct TransferredConfinement {
    inner: harn_vm::process_sandbox::TransferableConfinement,
}

#[cfg(target_os = "linux")]
impl TransferredConfinement {
    fn request(&self) -> GuardianConfinement {
        GuardianConfinement {
            seccomp: self.inner.seccomp_bytes(),
            ruleset: self.inner.ruleset_fd().is_some(),
        }
    }

    fn hand_to(self, guardian: &mut Command) {
        let Some(ruleset) = self.inner.into_ruleset_fd() else {
            return;
        };
        // SAFETY: `dup2` and `fcntl` are async-signal-safe, which is what
        // `pre_exec` requires. The guard closes the descriptor if it is still
        // ours when the command is dropped, so an unspawned command leaks
        // nothing.
        let guard = RulesetDescriptor(ruleset);
        unsafe {
            guardian.pre_exec(move || {
                // `guard.raw()` and not `guard.0`. An edition-2021 closure
                // captures the FIELDS it names, so naming the descriptor alone
                // captures a `RawFd`, which is `Copy`, and leaves the guard
                // itself behind to drop at the end of this function — closing
                // the ruleset before the child that has to enter it exists. A
                // method call captures the whole guard, which is the lifetime
                // this handover depends on.
                let held = guard.raw();
                if held == RULESET_FD {
                    // Already on the agreed number: it only needs the
                    // close-on-exec flag cleared to survive the `exec`.
                    if libc::fcntl(held, libc::F_SETFD, 0) < 0 {
                        return Err(io::Error::last_os_error());
                    }
                } else if libc::dup2(held, RULESET_FD) < 0 {
                    // `dup2` clears close-on-exec on the new descriptor.
                    return Err(io::Error::last_os_error());
                }
                Ok(())
            });
        }
    }
}

/// Owns the ruleset descriptor for as long as the guardian command does.
#[cfg(target_os = "linux")]
struct RulesetDescriptor(std::os::fd::RawFd);

#[cfg(target_os = "linux")]
impl RulesetDescriptor {
    fn raw(&self) -> std::os::fd::RawFd {
        self.0
    }
}

#[cfg(target_os = "linux")]
impl Drop for RulesetDescriptor {
    fn drop(&mut self) {
        unsafe {
            libc::close(self.0);
        }
    }
}

/// Build the confinement this spawn must carry, or state that it carries none.
///
/// `Ok(None)` means the run confines no child. It never means confinement was
/// wanted and could not be built: that is an error, and it is returned as one,
/// so no caller can read a refusal as an absent request.
#[cfg(target_os = "linux")]
fn build_confinement(program: &str) -> Result<Option<TransferredConfinement>, ProcessError> {
    harn_vm::process_sandbox::transferable_confinement(program)
        .map(|inner| inner.map(|inner| TransferredConfinement { inner }))
        .map_err(|error| ProcessError::SandboxSetup(format!("{error:?}")))
}

/// Other platforms wrap the payload's argv, and the request carries argv, so
/// their confinement crosses the handover on its own.
#[cfg(all(unix, not(target_os = "linux")))]
fn build_confinement(_program: &str) -> Result<Option<TransferredConfinement>, ProcessError> {
    Ok(None)
}

/// The no-op the non-Linux paths type-check against.
#[cfg(all(unix, not(target_os = "linux")))]
struct TransferredConfinement;

#[cfg(all(unix, not(target_os = "linux")))]
impl TransferredConfinement {
    fn request(&self) -> GuardianConfinement {
        unreachable!("no platform but Linux builds a transferred confinement")
    }

    fn hand_to(self, _guardian: &mut Command) {}
}

#[cfg(unix)]
fn strip_sensitive_parent_env<I>(guardian: &mut Command, parent_env: I)
where
    I: IntoIterator<Item = (OsString, OsString)>,
{
    for (key, _) in parent_env {
        if key
            .to_str()
            .is_some_and(super::handle::is_sensitive_env_name)
        {
            guardian.env_remove(key);
        }
    }
}

/// Send the prepared command before retaining the same pipe as the owner's
/// liveness lease. The payload may contain credentials, so it must never be
/// placed in argv or the guardian environment.
#[cfg(unix)]
pub(crate) fn write_request(pipe: &mut ChildStdin, request: &[u8]) -> Result<(), ProcessError> {
    if request.len() > MAX_REQUEST_BYTES {
        return Err(ProcessError::Spawn(format!(
            "guardian request exceeded {MAX_REQUEST_BYTES} bytes"
        )));
    }
    pipe.write_all(request)
        .and_then(|()| pipe.write_all(b"\n"))
        .and_then(|()| pipe.flush())
        .map_err(|error| ProcessError::Spawn(format!("write guardian request: {error}")))
}

#[cfg(unix)]
impl PreparedCommand {
    fn from_command(
        command: &Command,
        env_clear: bool,
        cleanup_token: String,
        confinement: Option<GuardianConfinement>,
    ) -> Self {
        Self {
            confinement,
            program: os_bytes(command.get_program()),
            args: command.get_args().map(os_bytes).collect(),
            cwd: command
                .get_current_dir()
                .map(|path| os_bytes(path.as_os_str())),
            env_clear,
            env: command
                .get_envs()
                .map(|(key, value)| (os_bytes(key), value.map(os_bytes)))
                .collect(),
            cleanup_token,
        }
    }

    fn into_command(self) -> io::Result<(Command, String)> {
        let mut command = Command::new(OsString::from_vec(self.program));
        command.args(self.args.into_iter().map(OsString::from_vec));
        if let Some(cwd) = self.cwd {
            command.current_dir(PathBuf::from(OsString::from_vec(cwd)));
        }
        if self.env_clear {
            command.env_clear();
        }
        for (key, value) in self.env {
            let key = OsString::from_vec(key);
            match value {
                Some(value) => {
                    command.env(key, OsString::from_vec(value));
                }
                None => {
                    command.env_remove(key);
                }
            }
        }
        command
            .env_remove(MODE_ENV)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        apply_confinement(&mut command, self.confinement)?;
        Ok((command, self.cleanup_token))
    }
}

/// Attach the transferred confinement to the payload spawn, or refuse.
///
/// Built here, before the fork, because rebuilding allocates and the `pre_exec`
/// side may not. The closure is then two raw syscalls.
///
/// Fail-closed by construction: every path that cannot install what it was
/// handed returns an error, and the guardian answers the startup handshake with
/// it instead of spawning. A confinement that could not be applied must never
/// come out as a payload that merely ran.
#[cfg(target_os = "linux")]
fn apply_confinement(
    command: &mut Command,
    confinement: Option<GuardianConfinement>,
) -> io::Result<()> {
    let Some(confinement) = confinement else {
        return Ok(());
    };
    let ruleset = confinement.ruleset.then_some(RULESET_FD);
    let transferable = harn_vm::process_sandbox::TransferableConfinement::from_parts(
        ruleset,
        &confinement.seccomp,
    )?;
    // SAFETY: `enter` is two raw syscalls for Landlock and one for seccomp,
    // with no allocation, locking, or I/O, which is what `pre_exec` requires.
    unsafe {
        command.pre_exec(move || transferable.enter());
    }
    Ok(())
}

/// Every other platform puts its confinement in the spawn's argv, which the
/// request already carries, so there is nothing to reattach here. Being handed
/// one anyway means the two sides disagree about who confines, and the safe
/// reading of that is a refusal rather than an unconfined payload.
#[cfg(all(unix, not(target_os = "linux")))]
fn apply_confinement(
    _command: &mut Command,
    confinement: Option<GuardianConfinement>,
) -> io::Result<()> {
    if confinement.is_some() {
        return Err(io::Error::other(
            "guardian was handed a transferred confinement on a platform whose backend carries its own",
        ));
    }
    Ok(())
}

#[cfg(unix)]
fn os_bytes(value: &OsStr) -> Vec<u8> {
    value.as_bytes().to_vec()
}

/// Read the guardian's spawn handshake without consuming payload stderr.
#[cfg(unix)]
pub(crate) fn await_startup(child: &mut Child) -> Result<(ChildStderr, u32, u32), ProcessError> {
    let mut stderr = child
        .stderr
        .take()
        .ok_or_else(|| ProcessError::Spawn("guardian stderr pipe missing".to_string()))?;
    let mut line = Vec::new();
    loop {
        let mut byte = [0_u8; 1];
        match stderr.read_exact(&mut byte) {
            Ok(()) if byte[0] == b'\n' => break,
            Ok(()) => {
                line.push(byte[0]);
                if line.len() > 64 * 1024 {
                    return Err(ProcessError::Spawn(
                        "guardian startup response exceeded 64 KiB".to_string(),
                    ));
                }
            }
            Err(error) => {
                let _ = child.wait();
                return Err(ProcessError::Spawn(format!(
                    "guardian exited before payload startup: {error}"
                )));
            }
        }
    }
    let message: StartupMessage = serde_json::from_slice(&line)
        .map_err(|error| ProcessError::Spawn(format!("decode guardian startup: {error}")))?;
    if message.ok {
        let guardian_pid = message.guardian_pid.ok_or_else(|| {
            ProcessError::Spawn("guardian startup response omitted guardian pid".to_string())
        })?;
        let pid = message.pid.ok_or_else(|| {
            ProcessError::Spawn("guardian startup response omitted payload pid".to_string())
        })?;
        Ok((stderr, guardian_pid, pid))
    } else {
        let _ = child.wait();
        Err(ProcessError::Spawn(message.error.unwrap_or_else(|| {
            "guardian could not launch payload".to_string()
        })))
    }
}

/// Run the guardian payload when the private request pipe is active.
///
/// This is public only so a re-executed integration-test fixture can enter the
/// same native guardian path as the shipped `harn` executable.
#[cfg(unix)]
#[doc(hidden)]
pub fn run_guardian_from_pipe() -> io::Result<()> {
    if std::env::var_os(REAPER_ENV).is_some() {
        run_guardian_reaper();
    }
    if std::env::var(MODE_ENV).as_deref() != Ok(PIPE_MODE) {
        return Err(io::Error::other("guardian request pipe is not active"));
    }
    let raw = read_request()?;
    let request: PreparedCommand = serde_json::from_slice(&raw)
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
    let (mut payload_command, cleanup_token) = match request.into_command() {
        Ok(prepared) => prepared,
        Err(error) => {
            write_startup(StartupMessage {
                ok: false,
                error: Some(format!("guardian could not confine the payload: {error}")),
                guardian_pid: None,
                pid: None,
            })?;
            return Err(error);
        }
    };
    let _journal_cleanup = OwnerJournalCleanup(cleanup_token.clone());
    configure_child_reaper()?;
    let mut payload = match payload_command.spawn() {
        Ok(payload) => payload,
        Err(error) => {
            write_startup(StartupMessage {
                ok: false,
                error: Some(error.to_string()),
                guardian_pid: None,
                pid: None,
            })?;
            return Err(error);
        }
    };
    let payload_pid = payload.id();
    write_startup(StartupMessage {
        ok: true,
        error: None,
        guardian_pid: Some(std::process::id()),
        pid: Some(payload_pid),
    })?;

    let stdout = payload.stdout.take();
    let stderr = payload.stderr.take();
    let (event_tx, event_rx) = std::sync::mpsc::channel();

    if let Some(mut stdout) = stdout {
        let event_tx = event_tx.clone();
        std::thread::spawn(move || {
            let _ = io::copy(&mut stdout, &mut io::stdout());
            let _ = event_tx.send(GuardianEvent::OutputClosed);
        });
    }
    if let Some(mut stderr) = stderr {
        let event_tx = event_tx.clone();
        std::thread::spawn(move || {
            let _ = io::copy(&mut stderr, &mut io::stderr());
            let _ = event_tx.send(GuardianEvent::OutputClosed);
        });
    }
    {
        let event_tx = event_tx.clone();
        std::thread::spawn(move || {
            let status = wait_for_payload_while_reaping_adopted(payload);
            let _ = event_tx.send(GuardianEvent::PayloadExited(status));
        });
    }
    {
        let event_tx = event_tx.clone();
        std::thread::spawn(move || {
            let mut stdin = io::stdin();
            let mut sink = [0_u8; 256];
            loop {
                match stdin.read(&mut sink) {
                    Ok(0) | Err(_) => break,
                    Ok(_) => {}
                }
            }
            let _ = event_tx.send(GuardianEvent::OwnerClosed);
        });
    }
    drop(event_tx);

    let mut payload_status = None;
    let mut open_outputs = 2_u8;
    while let Ok(event) = event_rx.recv() {
        match event {
            GuardianEvent::OwnerClosed => {
                let _ =
                    harn_vm::op_interrupt::signal_pid_tree_and_token_preserving_group_with_report(
                        payload_pid,
                        Some(&cleanup_token),
                        unsafe { libc::getpgrp() as u32 },
                        libc::SIGKILL,
                    );
                wait_for_payload_exit(&event_rx, &mut payload_status)?;
                reap_adopted_children()?;
                harn_vm::op_interrupt::remove_process_owner_group_journal(&cleanup_token);
                unsafe {
                    libc::kill(-libc::getpgrp(), libc::SIGKILL);
                }
                return Err(io::Error::other("guardian process group survived SIGKILL"));
            }
            GuardianEvent::PayloadExited(status) => {
                payload_status = Some(status?);
                let _ =
                    harn_vm::op_interrupt::signal_pid_tree_and_token_preserving_group_with_report(
                        payload_pid,
                        Some(&cleanup_token),
                        unsafe { libc::getpgrp() as u32 },
                        libc::SIGKILL,
                    );
                reap_adopted_children()?;
                let survivors = harn_vm::op_interrupt::process_owner_survivors(&cleanup_token);
                if !survivors.is_empty() {
                    let guardian_pid = std::process::id();
                    let guardian_pgid = unsafe { libc::getpgrp() };
                    let summary = survivors
                        .iter()
                        .map(|process| {
                            let process_group = unsafe { libc::getpgid(process.pid as i32) };
                            let process_group = if process_group < 0 {
                                "<unknown>".to_string()
                            } else {
                                process_group.to_string()
                            };
                            format!(
                                "pid={} parent={} pgid={} command={}",
                                process.pid,
                                process
                                    .parent_pid
                                    .map_or_else(|| "<unknown>".to_string(), |pid| pid.to_string()),
                                process_group,
                                process.command_name.as_deref().unwrap_or("<unknown>")
                            )
                        })
                        .collect::<Vec<_>>()
                        .join(", ");
                    return Err(io::Error::other(format!(
                        "owner-death guardian pid={guardian_pid} pgid={guardian_pgid} left helper \
                         processes alive after cleanup: {summary}"
                    )));
                }
            }
            GuardianEvent::OutputClosed => open_outputs = open_outputs.saturating_sub(1),
        }
        if let Some(status) = payload_status.filter(|_| open_outputs == 0) {
            harn_vm::op_interrupt::remove_process_owner_group_journal(&cleanup_token);
            propagate_exit(status);
        }
    }
    harn_vm::op_interrupt::remove_process_owner_group_journal(&cleanup_token);
    Err(io::Error::other(
        "guardian event channels closed unexpectedly",
    ))
}

/// Compatibility name for embedders that entered the hidden guardian helper
/// directly. The request now comes from stdin, not the environment.
#[cfg(unix)]
#[doc(hidden)]
#[deprecated(note = "use run_guardian_from_pipe")]
pub fn run_guardian_from_env() -> io::Result<()> {
    run_guardian_from_pipe()
}

#[cfg(unix)]
fn read_request() -> io::Result<Vec<u8>> {
    let mut stdin = io::stdin();
    let mut request = Vec::new();
    loop {
        let mut byte = [0_u8; 1];
        stdin.read_exact(&mut byte)?;
        if byte[0] == b'\n' {
            return Ok(request);
        }
        request.push(byte[0]);
        if request.len() > MAX_REQUEST_BYTES {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("guardian request exceeded {MAX_REQUEST_BYTES} bytes"),
            ));
        }
    }
}

#[cfg(unix)]
fn run_guardian_reaper() -> ! {
    let executable = std::env::current_exe().unwrap_or_else(|error| {
        eprintln!("resolve guardian executable: {error}");
        std::process::exit(1);
    });
    let mut guardian = Command::new(executable);
    guardian
        .args(std::env::args_os().skip(1))
        .env_remove(REAPER_ENV)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .process_group(0);
    let mut guardian = guardian.spawn().unwrap_or_else(|error| {
        eprintln!("spawn process guardian: {error}");
        std::process::exit(1);
    });
    match guardian.wait() {
        Ok(status) => propagate_exit(status),
        Err(error) => {
            eprintln!("reap process guardian: {error}");
            std::process::exit(1);
        }
    }
}

#[cfg(target_os = "linux")]
fn configure_child_reaper() -> io::Result<()> {
    if unsafe { libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) } == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

#[cfg(all(unix, not(target_os = "linux")))]
fn configure_child_reaper() -> io::Result<()> {
    Ok(())
}

#[cfg(unix)]
fn wait_for_payload_while_reaping_adopted(payload: Child) -> io::Result<ExitStatus> {
    let payload_pid = payload.id() as libc::pid_t;
    // Keep the Child handle alive while waitpid(2) owns reaping. On Linux the
    // guardian is a subreaper, so detached helpers become its direct children.
    // Reaping all children here prevents successfully terminated helpers from
    // remaining as zombies until the conformance payload itself exits.
    let _payload = payload;
    loop {
        let mut status = 0;
        let waited = unsafe { libc::waitpid(-1, &raw mut status, 0) };
        if waited == payload_pid {
            return Ok(ExitStatus::from_raw(status));
        }
        if waited > 0 {
            continue;
        }
        let error = io::Error::last_os_error();
        match error.raw_os_error() {
            Some(libc::EINTR) => continue,
            _ => return Err(error),
        }
    }
}

#[cfg(unix)]
fn wait_for_payload_exit(
    events: &std::sync::mpsc::Receiver<GuardianEvent>,
    payload_status: &mut Option<ExitStatus>,
) -> io::Result<()> {
    while payload_status.is_none() {
        match events.recv() {
            Ok(GuardianEvent::PayloadExited(status)) => *payload_status = Some(status?),
            Ok(GuardianEvent::OutputClosed | GuardianEvent::OwnerClosed) => {}
            Err(_) => {
                return Err(io::Error::other(
                    "guardian events closed before payload exit",
                ));
            }
        }
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn reap_adopted_children() -> io::Result<()> {
    loop {
        let result = unsafe { libc::waitpid(-1, std::ptr::null_mut(), 0) };
        if result > 0 {
            continue;
        }
        let error = io::Error::last_os_error();
        match error.raw_os_error() {
            Some(libc::EINTR) => continue,
            Some(libc::ECHILD) => return Ok(()),
            _ => return Err(error),
        }
    }
}

#[cfg(all(unix, not(target_os = "linux")))]
fn reap_adopted_children() -> io::Result<()> {
    Ok(())
}

/// Whether this process carries a private guardian request pipe marker.
#[cfg(unix)]
#[doc(hidden)]
pub fn guardian_requested() -> bool {
    std::env::var(MODE_ENV).as_deref() == Ok(PIPE_MODE)
}

#[cfg(unix)]
struct OwnerJournalCleanup(String);

#[cfg(unix)]
impl Drop for OwnerJournalCleanup {
    fn drop(&mut self) {
        harn_vm::op_interrupt::remove_process_owner_group_journal(&self.0);
    }
}

#[cfg(unix)]
enum GuardianEvent {
    OwnerClosed,
    PayloadExited(io::Result<ExitStatus>),
    OutputClosed,
}

#[cfg(unix)]
fn write_startup(message: StartupMessage) -> io::Result<()> {
    let mut stderr = io::stderr();
    serde_json::to_writer(&mut stderr, &message)?;
    stderr.write_all(b"\n")?;
    stderr.flush()
}

#[cfg(unix)]
fn propagate_exit(status: ExitStatus) -> ! {
    if let Some(code) = status.code() {
        std::process::exit(code);
    }
    if let Some(signal) = status.signal() {
        unsafe {
            libc::signal(signal, libc::SIG_DFL);
            libc::raise(signal);
        }
        std::process::exit(128 + signal);
    }
    std::process::exit(1);
}

/// Enter the private guardian mode before public CLI parsing.
///
/// Executables embedding `harn-hostlib` process tools must call this at the
/// beginning of `main`, before inspecting or rejecting command-line arguments.
/// Unix owner-death containment re-executes the embedding executable with a
/// private argument; omitting this dispatch makes contained process startup
/// fail. The function returns `false` for normal invocations and on platforms
/// that do not use the re-exec guardian. Guardian invocations do not return.
#[cfg(unix)]
pub fn run_if_requested() -> bool {
    if std::env::args_os().nth(1).as_deref() != Some(OsStr::new(GUARDIAN_ARG)) {
        return false;
    }
    if let Err(error) = run_guardian_from_pipe() {
        eprintln!("harn process guardian failed: {error}");
        std::process::exit(1);
    }
    unreachable!("guardian execution always exits")
}

#[cfg(all(test, unix))]
mod tests {
    use std::collections::BTreeMap;

    use super::*;
    use crate::process::{EnvMode, OutputCapture, OwnerDeathPolicy};

    #[test]
    fn guardian_request_keeps_explicit_credentials_out_of_argv_and_env() {
        let canary = "guardian-request-pipe-canary";
        let spec = SpawnSpec {
            builtin: "guardian_request_test",
            program: "/usr/bin/env".to_string(),
            args: Vec::new(),
            cwd: None,
            env: BTreeMap::from([("EXAMPLE_API_KEY".to_string(), canary.to_string())]),
            env_remove: Vec::new(),
            env_mode: EnvMode::Patch,
            use_stdin: false,
            configure_process_group: true,
            owner_death: OwnerDeathPolicy::KillContainment,
            output_capture: OutputCapture::Pipe,
        };

        let cleanup_token = harn_vm::op_interrupt::new_process_cleanup_token();
        let (guardian, request) =
            prepare_guardian(&spec, cleanup_token.clone()).expect("prepare guardian");
        harn_vm::op_interrupt::remove_process_owner_group_journal(&cleanup_token);
        let decoded: PreparedCommand =
            serde_json::from_slice(&request).expect("decode private guardian request");
        assert!(
            decoded.env.iter().any(|(key, value)| {
                key.as_slice() == b"EXAMPLE_API_KEY" && value.as_deref() == Some(canary.as_bytes())
            }),
            "the private request must still carry the explicit child credential"
        );
        assert!(
            guardian
                .get_args()
                .all(|arg| !arg.to_string_lossy().contains(canary)),
            "the guardian argv must not carry child credentials"
        );
        assert!(
            guardian.get_envs().all(|(key, value)| {
                !key.to_string_lossy().contains(canary)
                    && !value.is_some_and(|value| value.to_string_lossy().contains(canary))
            }),
            "the guardian environment must not carry child credentials"
        );
    }

    #[test]
    fn guardian_scrubs_sensitive_values_inherited_from_its_parent() {
        let mut guardian = Command::new("/usr/bin/true");
        strip_sensitive_parent_env(
            &mut guardian,
            [
                (
                    OsString::from("EXAMPLE_API_KEY"),
                    OsString::from("secret-canary"),
                ),
                (OsString::from("PATH"), OsString::from("/usr/bin")),
            ],
        );

        let env = guardian.get_envs().collect::<Vec<_>>();
        assert!(
            env.iter()
                .any(|(key, value)| { *key == OsStr::new("EXAMPLE_API_KEY") && value.is_none() }),
            "the guardian must remove inherited credentials before re-exec"
        );
        assert!(
            env.iter().all(|(key, _)| *key != OsStr::new("PATH")),
            "the guardian must preserve ordinary inherited environment"
        );
    }
}

/// Unix alone uses the re-exec guardian; Windows uses a Job Object.
#[cfg(not(unix))]
pub fn run_if_requested() -> bool {
    false
}