Skip to main content

workpen/wrap/
mod.rs

1//! Process-jail wrap. Feature `nono`.
2//!
3//! Unix uses pinned nono (Landlock / Seatbelt). Windows uses a
4//! write-restricted token. Never grant filesystem root (`/` or a
5//! Windows drive root) or the current user's home directory. Inspect
6//! [`KernelPolicy::grants`]; do not parse nono internals. Do not call
7//! [`KernelPolicy::apply`] from unit tests (`Sandbox::apply_auto` is
8//! irreversible). [`KernelPolicy::apply_pre_exec`] only installs a Unix
9//! child hook. Hosts that need a jail on every OS call
10//! [`KernelPolicy::run_child`], which errors instead of spawning when
11//! the kernel cannot apply. The default crate (`default = []`) does not
12//! compile this module. nono is pinned with `default-features = false`.
13//! That build does not depend on `reqwest`. nono still depends on
14//! `sigstore-verify` 0.15.1, which does not link `aws-lc-sys`. There is
15//! no nono feature that drops `sigstore-verify`. Do not enable nono's
16//! default features, and do not fork nono.
17
18use std::ffi::{OsStr, OsString};
19#[cfg(unix)]
20use std::os::fd::AsRawFd;
21use std::path::{Path, PathBuf};
22use std::process::{Command, ExitStatus};
23#[cfg(unix)]
24use std::sync::Arc;
25#[cfg(unix)]
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::time::Duration;
28#[cfg(unix)]
29use std::time::Instant;
30
31use crate::deny::{
32    CheckDestError, DenyPolicy, DestDeny, DestDenyKind, dest_deny_at, dest_deny_at_root,
33    dest_deny_glob_only,
34};
35
36#[cfg(target_os = "linux")]
37mod linux;
38#[cfg(unix)]
39mod pty;
40#[cfg(unix)]
41mod reaper;
42#[cfg(windows)]
43mod windows;
44
45/// Access granted for one path. Hosts branch on this; do not parse messages.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum KernelAccess {
48    Read,
49    ReadWrite,
50}
51
52/// One grant we will hand to the kernel backend.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct KernelGrant {
55    pub path: PathBuf,
56    pub access: KernelAccess,
57}
58
59/// Process-jail policy. Workspace RW, extra roots RW, existing system dirs Read.
60///
61/// Dest-deny names are a second list, not a grant of `/`. Linux Landlock
62/// cannot dest-deny a file inside an allowed tree
63/// ([nono #1592](https://github.com/nolabs-ai/nono/discussions/1592)).
64/// macOS `run_child` applies Seatbelt `(deny file-read* / file-write* /
65/// network-outbound)` literals (and `subpath` for directories) via nono
66/// `add_platform_rule`. `network-outbound` covers `connect(2)` to a Unix
67/// socket, which Seatbelt does not treat as a file operation.
68/// Linux `run_child` bind-overs dest-deny paths in a private mount ns
69/// when unprivileged user namespaces are available. If `unshare` is
70/// denied, remount is skipped and Landlock still applies (in-tree
71/// dest-deny stays a hole). Windows `run_child` adds a DENY ACE on
72/// dest-deny paths for the Restricted SID.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct KernelPolicy {
75    grants: Vec<KernelGrant>,
76    dest_denies: Vec<DestDeny>,
77    deny_policy: DenyPolicy,
78    network_blocked: bool,
79    /// Read by [`Self::require_spawn`] on Unix. Windows has no remount.
80    #[cfg_attr(not(unix), allow(dead_code))]
81    require_dest_hide: bool,
82}
83
84/// Result of applying the jail. Hosts match the variant, not English.
85///
86/// New variants are breaking for exhaustive hosts even in 0.x. See
87/// [`crate::threat_model`].
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum KernelApply {
90    /// Kernel jail is active in this process, or hooked/spawned for the child.
91    /// Linux remount ran when dest-deny paths existed. Windows WFP ran
92    /// when [`KernelPolicy::network_blocked`] and the token could add
93    /// filters.
94    Applied,
95    /// Landlock/Seatbelt applied. Dest-deny remount was skipped
96    /// (unshare / maps / `MS_PRIVATE` denied). In-tree dest-deny is
97    /// userspace argv only. Extra-root dests still fail-closed.
98    RemountSkipped,
99    /// Write-restricted token and AppContainer applied. WFP filters
100    /// were skipped (`ERROR_ACCESS_DENIED`, win32 5). AppContainer
101    /// network deny is still on.
102    WfpSkipped,
103    /// Platform has no kernel backend. Userspace dest-deny + PathGuard only.
104    UserspaceOnly,
105}
106
107/// Hosts match the variant, not English. New variants are breaking
108/// for exhaustive hosts even in 0.x.
109#[derive(Debug, thiserror::Error)]
110pub enum KernelError {
111    #[error("kernel wrap root is not usable: {0}")]
112    Root(String),
113    #[error("kernel wrap refused filesystem root {0}; use a subdirectory, not `/`")]
114    FsRoot(PathBuf),
115    #[error("kernel wrap refused home directory {0}; use a project subdirectory, not $HOME")]
116    Home(PathBuf),
117    #[error("kernel wrap apply failed: {0}")]
118    Apply(String),
119    /// Argv dest-deny before spawn. Hosts match [`CheckDestError`] /
120    /// [`crate::DestDenyError`], not English.
121    #[error("kernel wrap dest-deny: {0}")]
122    DestDeny(#[from] CheckDestError),
123    /// The child was killed after the deadline.
124    #[error("kernel wrap child was killed after the deadline")]
125    Timeout,
126    /// Child finished; DACL restore failed. Hosts match this, not English.
127    #[error("kernel wrap restore failed: {0}")]
128    Restore(String),
129    /// A descendant pid did not fit in the recorded set, or macOS left
130    /// a recorded pid running. macOS also returns this when a live
131    /// session leader with the command's name is outside that set.
132    /// That session leader called `setsid`.
133    /// [`KernelPolicy::run_child`] returns this instead of the child
134    /// status. Hosts that spawn after [`KernelPolicy::apply_pre_exec`]
135    /// get it from [`KernelPolicy::finish_pre_exec`] on that same thread.
136    /// Hosts that wait on another thread, including after `.await`, get
137    /// it from [`PreExecReport::finish`]. The CLI exits 4.
138    #[error("kernel wrap did not track every descendant")]
139    Descendants,
140}
141
142/// Owns the reaper report for one [`KernelPolicy::apply_pre_exec_report`].
143///
144/// `Send`, so the host can move it across an `.await` or onto another
145/// thread with the child wait. [`Self::finish`] reads the pipe.
146/// [`Self::discard`] and `Drop` close it, so a cancelled task does not
147/// leave the descriptor open. This value is not the thread-local report
148/// used by [`KernelPolicy::finish_pre_exec`].
149#[must_use = "finish the report or drop it to close the reaper pipe"]
150pub struct PreExecReport {
151    #[cfg(unix)]
152    pipe: reaper::ReportPipe,
153    #[cfg(not(unix))]
154    _private: (),
155}
156
157impl PreExecReport {
158    #[cfg(unix)]
159    fn from_pipe(pipe: reaper::ReportPipe) -> Self {
160        Self { pipe }
161    }
162
163    fn unarmed() -> Self {
164        #[cfg(unix)]
165        {
166            Self {
167                pipe: reaper::unarmed_report(),
168            }
169        }
170        #[cfg(not(unix))]
171        {
172            Self { _private: () }
173        }
174    }
175
176    /// Keep an armed pipe for [`KernelPolicy::finish_pre_exec`].
177    /// An unarmed pipe is not a report, so it is not stored.
178    fn stash(self) {
179        #[cfg(unix)]
180        {
181            let pipe = self.pipe;
182            if pipe.armed {
183                reaper::stash_report(pipe);
184            }
185        }
186        #[cfg(not(unix))]
187        {
188            let _ = self;
189        }
190    }
191
192    /// Read the descendant report.
193    ///
194    /// `Ok(status)` means every descendant was tracked, or no reaper was
195    /// installed. [`KernelError::Descendants`] means the reaper reported
196    /// a miss, the pipe was missing, or it wrote nothing. Pass
197    /// `timed_out: true` when the host deadline already fired. The
198    /// deadline wins and this returns `Ok(status)`.
199    pub fn finish(self, status: ExitStatus, timed_out: bool) -> Result<ExitStatus, KernelError> {
200        #[cfg(unix)]
201        {
202            if self.pipe.tracked(timed_out) {
203                Ok(status)
204            } else {
205                Err(KernelError::Descendants)
206            }
207        }
208        #[cfg(not(unix))]
209        {
210            let _ = (self, timed_out);
211            Ok(status)
212        }
213    }
214
215    /// Close the reaper pipe without reading it.
216    ///
217    /// Same as dropping the report. Use this when spawn failed.
218    pub fn discard(self) {
219        drop(self);
220    }
221}
222
223/// Merge spawn and DACL-restore results. Timeout stays Timeout.
224/// A successful child plus restore failure is Restore that names the exit.
225#[cfg(any(windows, test))]
226pub(crate) fn combine_spawn_restore(
227    result: Result<(KernelApply, ExitStatus), KernelError>,
228    restore: Result<(), KernelError>,
229) -> Result<(KernelApply, ExitStatus), KernelError> {
230    match (result, restore) {
231        (ok, Ok(())) => ok,
232        (Err(KernelError::Timeout), Err(_)) => Err(KernelError::Timeout),
233        (Err(spawn), Err(restore_err)) => Err(KernelError::Apply(format!(
234            "{}; {}",
235            apply_detail(&spawn),
236            apply_detail(&restore_err)
237        ))),
238        (Ok((_, status)), Err(restore_err)) => {
239            let code = status
240                .code()
241                .map(|c| c.to_string())
242                .unwrap_or_else(|| "signal".into());
243            Err(KernelError::Restore(format!(
244                "child exited {code}; {}",
245                apply_detail(&restore_err)
246            )))
247        }
248    }
249}
250
251#[cfg(any(windows, test))]
252fn apply_detail(err: &KernelError) -> String {
253    match err {
254        KernelError::Apply(msg) | KernelError::Restore(msg) => msg.clone(),
255        KernelError::DestDeny(err) => err.to_string(),
256        other => other.to_string(),
257    }
258}
259
260/// Drain stdout/stderr on helper threads while waiting so a chatty child
261/// cannot fill the pipe (~64KiB) and block until the deadline.
262///
263/// The bool is `timed_out`. Deadline still returns the drained bytes so
264/// callers can write them before GNU timeout 124. [`KernelError::Timeout`]
265/// stays a unit variant on [`KernelPolicy::run_child_timeout`].
266/// The child is an unreaped zombie (`WNOWAIT`), so its pid cannot be
267/// recycled. Signal its process group before the reap when this pid
268/// leads that group. A `setsid` grandchild is stopped by the pre_exec
269/// reaper, not by this `killpg`.
270#[cfg(unix)]
271fn kill_group_if_zombie(pid: libc::pid_t) -> bool {
272    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
273    let rc = unsafe {
274        libc::waitid(
275            libc::P_PID,
276            pid as libc::id_t,
277            &mut info,
278            libc::WEXITED | libc::WNOWAIT | libc::WNOHANG,
279        )
280    };
281    if rc != 0 || info.si_signo != libc::SIGCHLD {
282        return false;
283    }
284    if reaper::is_group_leader(pid) {
285        unsafe {
286            libc::killpg(pid, libc::SIGKILL);
287        }
288    }
289    true
290}
291
292/// Wait until the direct child exits or `timeout` elapses, then signal
293/// its process group. `true` means the deadline fired.
294#[cfg(unix)]
295fn reap_process_group(
296    child: &mut std::process::Child,
297    timeout: Option<Duration>,
298) -> Result<(ExitStatus, bool), KernelError> {
299    use std::time::Instant;
300
301    let pid = child.id() as libc::pid_t;
302    let deadline = match timeout {
303        None => None,
304        Some(limit) => match timeout_deadline(limit) {
305            Ok(end) => Some(end),
306            Err(err) => {
307                unsafe {
308                    libc::kill(pid, libc::SIGKILL);
309                }
310                if reaper::is_group_leader(pid) {
311                    unsafe {
312                        libc::killpg(pid, libc::SIGKILL);
313                    }
314                }
315                let _ = wait_reaped(child);
316                reaper::discard_report();
317                return Err(err);
318            }
319        },
320    };
321    loop {
322        if kill_group_if_zombie(pid) {
323            let status = wait_reaped(child)?;
324            return finish_reap(status, false);
325        }
326        if deadline.is_some_and(|end| Instant::now() >= end) {
327            // Ask the reaper to kill the command and any `setsid`
328            // descendant, then exit. SIGKILL would skip that cleanup.
329            unsafe {
330                libc::kill(pid, libc::SIGTERM);
331            }
332            let grace = Instant::now() + Duration::from_millis(300);
333            loop {
334                if kill_group_if_zombie(pid) {
335                    let status = wait_reaped(child)?;
336                    return finish_reap(status, true);
337                }
338                if Instant::now() >= grace {
339                    unsafe {
340                        libc::kill(pid, libc::SIGKILL);
341                    }
342                    if reaper::is_group_leader(pid) {
343                        unsafe {
344                            libc::killpg(pid, libc::SIGKILL);
345                        }
346                    }
347                    let status = wait_reaped(child)?;
348                    return finish_reap(status, true);
349                }
350                std::thread::sleep(Duration::from_millis(10));
351            }
352        }
353        std::thread::sleep(Duration::from_millis(10));
354    }
355}
356
357/// `Instant + duration` panics when the sum does not fit.
358#[cfg(unix)]
359fn timeout_deadline(limit: Duration) -> Result<std::time::Instant, KernelError> {
360    std::time::Instant::now()
361        .checked_add(limit)
362        .ok_or_else(|| KernelError::Apply("timeout does not fit on the clock".into()))
363}
364
365#[cfg(unix)]
366fn wait_reaped(child: &mut std::process::Child) -> Result<ExitStatus, KernelError> {
367    child.wait().map_err(|err| {
368        reaper::discard_report();
369        KernelError::Apply(err.to_string())
370    })
371}
372
373#[cfg(unix)]
374fn finish_reap(status: ExitStatus, timed_out: bool) -> Result<(ExitStatus, bool), KernelError> {
375    let outcome = reaper::take_report(timed_out);
376    if outcome == reaper::ReportOutcome::Miss {
377        return Err(KernelError::Descendants);
378    }
379    let timed_out = timed_out || outcome == reaper::ReportOutcome::PreexecDeadline;
380    Ok((status, timed_out))
381}
382
383#[cfg(unix)]
384fn spawn_jailed(cmd: &mut Command) -> Result<std::process::Child, KernelError> {
385    spawn_jailed_deadline(cmd, None)
386}
387
388/// `timeout` is copied into the forked reaper so a pre-exec stall
389/// cannot outlive it. The guard drops on this thread after spawn.
390#[cfg(unix)]
391fn spawn_jailed_deadline(
392    cmd: &mut Command,
393    timeout: Option<Duration>,
394) -> Result<std::process::Child, KernelError> {
395    let _guard = timeout.map(reaper::arm_spawn_deadline);
396    match cmd.spawn() {
397        Ok(child) => {
398            reaper::close_parent_report_write();
399            Ok(child)
400        }
401        Err(err) => {
402            reaper::discard_report();
403            Err(KernelError::Apply(err.to_string()))
404        }
405    }
406}
407
408#[cfg(unix)]
409fn wait_until_deadline(
410    child: &mut std::process::Child,
411    timeout: Duration,
412) -> Result<(ExitStatus, bool), KernelError> {
413    reap_process_group(child, Some(timeout))
414}
415
416#[cfg(unix)]
417fn wait_child_timeout_output(
418    mut child: std::process::Child,
419    timeout: Duration,
420) -> Result<(std::process::Output, bool), KernelError> {
421    let stdout = child.stdout.take().map(drain_pipe);
422    let stderr = child.stderr.take().map(drain_pipe);
423    let (status, timed_out) = wait_until_deadline(&mut child, timeout)?;
424    Ok((
425        std::process::Output {
426            status,
427            stdout: join_drain(stdout),
428            stderr: join_drain(stderr),
429        },
430        timed_out,
431    ))
432}
433
434/// Copy child pipes to this process as bytes arrive. No unbounded `Vec`.
435#[cfg(unix)]
436fn wait_child_timeout_forward(
437    mut child: std::process::Child,
438    timeout: Duration,
439) -> Result<(std::process::ExitStatus, bool), KernelError> {
440    let started = Instant::now();
441    let stop = forward_stop();
442    let stdout = child
443        .stdout
444        .take()
445        .map(|p| copy_pipe(p, std::io::stdout(), Arc::clone(&stop)));
446    let stderr = child
447        .stderr
448        .take()
449        .map(|p| copy_pipe(p, std::io::stderr(), Arc::clone(&stop)));
450    let (status, mut timed_out) = wait_until_deadline(&mut child, timeout)?;
451    // The child can exit while the last chunk is still stuck on a
452    // reader that stopped. Joining that write would ignore the deadline.
453    if finish_copies(&stop, stdout, stderr, started + timeout) {
454        timed_out = true;
455    }
456    Ok((status, timed_out))
457}
458
459#[cfg(unix)]
460fn drain_pipe(mut pipe: impl std::io::Read + Send + 'static) -> std::thread::JoinHandle<Vec<u8>> {
461    std::thread::spawn(move || {
462        let mut buf = Vec::new();
463        let _ = std::io::Read::read_to_end(&mut pipe, &mut buf);
464        buf
465    })
466}
467
468#[cfg(unix)]
469fn forward_stop() -> Arc<AtomicBool> {
470    Arc::new(AtomicBool::new(false))
471}
472
473/// Stdout's buffer flushes 8KiB. Linux also reports `POLLOUT` when a
474/// single byte is free, so a blocking `PIPE_BUF` write can still wait.
475#[cfg(unix)]
476fn forward_chunk(fd: std::os::fd::RawFd) -> usize {
477    let mut stat = unsafe { std::mem::zeroed::<libc::stat>() };
478    // SAFETY: stat is a live object. A regular file never blocks a
479    // short write, so the copy can keep the previous 16KiB chunk.
480    let rc = unsafe { libc::fstat(fd, &mut stat) };
481    if rc == 0 && stat.st_mode & libc::S_IFMT == libc::S_IFREG {
482        16 * 1024
483    } else {
484        512
485    }
486}
487
488#[cfg(unix)]
489enum PollOut {
490    Ready,
491    Later,
492    Stop,
493}
494
495/// One poll. `Later` means the caller should drop any write lock and
496/// try again, so the other stream can use the pipe.
497#[cfg(unix)]
498fn poll_out_once(fd: std::os::fd::RawFd, stop: &AtomicBool) -> PollOut {
499    if stop.load(Ordering::Relaxed) {
500        return PollOut::Stop;
501    }
502    let mut poll_fd = libc::pollfd {
503        fd,
504        events: libc::POLLOUT,
505        revents: 0,
506    };
507    // SAFETY: poll_fd is a live one-slot array. The 50ms cap lets the
508    // deadline flag win over a reader that stopped.
509    let rc = unsafe { libc::poll(&mut poll_fd, 1, 50) };
510    if stop.load(Ordering::Relaxed) {
511        return PollOut::Stop;
512    }
513    if rc == 0 {
514        return PollOut::Later;
515    }
516    if rc < 0 {
517        let err = std::io::Error::last_os_error();
518        if err.kind() == std::io::ErrorKind::Interrupted {
519            return PollOut::Later;
520        }
521        return PollOut::Stop;
522    }
523    // macOS kqueue reports `POLLNVAL` for `/dev/null`. The write itself
524    // still succeeds, so treat that as writable.
525    if poll_fd.revents & (libc::POLLNVAL | libc::POLLOUT) != 0 {
526        return PollOut::Ready;
527    }
528    let bad = libc::POLLERR | libc::POLLHUP;
529    if poll_fd.revents & bad != 0 {
530        return PollOut::Stop;
531    }
532    PollOut::Later
533}
534
535/// The deadline line. A full `2>&1` pipe must not block this write.
536pub fn write_timeout_notice() {
537    #[cfg(not(unix))]
538    {
539        eprintln!("child killed after the deadline");
540    }
541    #[cfg(unix)]
542    {
543        let msg = b"child killed after the deadline\n";
544        let fd = std::io::stderr().as_raw_fd();
545        // SAFETY: stderr is open for the life of the process.
546        if unsafe { libc::isatty(fd) } == 1 {
547            eprintln!("child killed after the deadline");
548            return;
549        }
550        let idle = AtomicBool::new(false);
551        for &byte in msg {
552            if !matches!(poll_out_once(fd, &idle), PollOut::Ready) {
553                return;
554            }
555            let buf = [byte];
556            // SAFETY: `buf` is one live byte.
557            let rc = unsafe { libc::write(fd, buf.as_ptr().cast(), 1) };
558            if rc <= 0 {
559                return;
560            }
561        }
562    }
563}
564
565#[cfg(unix)]
566enum ForwardWrite {
567    Wrote(usize),
568    /// `O_NONBLOCK` refused the write. Linux `POLLOUT` means one byte
569    /// fits, so retrying this chunk spins. Callers write one byte or wait.
570    Again,
571}
572
573#[cfg(unix)]
574enum PushNonblock {
575    Wrote(usize),
576    Wait,
577    Stop,
578}
579
580/// Write up to `chunk` bytes. On `EAGAIN`, write one byte. A second
581/// refusal waits. It does not retry the same chunk.
582#[cfg(unix)]
583fn push_nonblock(
584    buf: &[u8],
585    chunk: usize,
586    mut write: impl FnMut(&[u8]) -> Option<ForwardWrite>,
587) -> PushNonblock {
588    if buf.is_empty() {
589        return PushNonblock::Wrote(0);
590    }
591    let take = buf.len().min(chunk.max(1));
592    match write(&buf[..take]) {
593        Some(ForwardWrite::Wrote(n)) if n > 0 => PushNonblock::Wrote(n),
594        Some(ForwardWrite::Again) if take > 1 => match write(&buf[..1]) {
595            Some(ForwardWrite::Wrote(n)) if n > 0 => PushNonblock::Wrote(n),
596            Some(ForwardWrite::Again) => PushNonblock::Wait,
597            _ => PushNonblock::Stop,
598        },
599        Some(ForwardWrite::Again) => PushNonblock::Wait,
600        _ => PushNonblock::Stop,
601    }
602}
603
604#[cfg(all(test, unix))]
605mod push_nonblock_tests {
606    use super::{ForwardWrite, PushNonblock, push_nonblock};
607
608    #[test]
609    fn short_pipe_writes_one_byte_instead_of_retrying_the_chunk() {
610        let data = vec![7u8; 2_000];
611        let mut off = 0;
612        let mut big_writes = 0u32;
613        let mut steps = 0u32;
614        while off < data.len() {
615            steps += 1;
616            assert!(steps < 10_000, "forward spun without progress");
617            match push_nonblock(&data[off..], 512, |slice| {
618                if slice.len() > 1 {
619                    big_writes += 1;
620                    Some(ForwardWrite::Again)
621                } else {
622                    Some(ForwardWrite::Wrote(1))
623                }
624            }) {
625                PushNonblock::Wrote(n) => off += n,
626                PushNonblock::Wait => panic!("one free byte must be written"),
627                PushNonblock::Stop => panic!("forward stopped"),
628            }
629        }
630        assert_eq!(off, data.len());
631        assert!(big_writes < 5_000, "chunk retries ran away: {big_writes}");
632    }
633
634    #[test]
635    fn one_byte_refusal_waits_instead_of_another_chunk() {
636        let mut calls = 0u32;
637        let step = push_nonblock(&[0u8; 512], 512, |slice| {
638            calls += 1;
639            assert!(slice.len() <= 512);
640            Some(ForwardWrite::Again)
641        });
642        assert!(matches!(step, PushNonblock::Wait));
643        assert_eq!(calls, 2, "one chunk attempt, then one byte, then wait");
644    }
645}
646
647/// One `write`. `EINTR` retries. `WouldBlock` asks the caller to wait.
648#[cfg(unix)]
649fn write_once(fd: std::os::fd::RawFd, buf: &[u8]) -> Option<ForwardWrite> {
650    loop {
651        // SAFETY: `buf` is a live slice. The length is the byte count.
652        let rc = unsafe { libc::write(fd, buf.as_ptr().cast(), buf.len()) };
653        if rc > 0 {
654            return Some(ForwardWrite::Wrote(rc as usize));
655        }
656        if rc == 0 {
657            return None;
658        }
659        let err = std::io::Error::last_os_error();
660        if err.kind() == std::io::ErrorKind::Interrupted {
661            continue;
662        }
663        if err.kind() == std::io::ErrorKind::WouldBlock {
664            return Some(ForwardWrite::Again);
665        }
666        return None;
667    }
668}
669
670/// `write` while this fd is non-blocking, then put the old flags back.
671///
672/// `toggle` stays false for a terminal. Its stdin and stdout share one
673/// open-file description, so `O_NONBLOCK` on stdout would make stdin
674/// return `EAGAIN`. Pipe ends do not share that description.
675/// Callers hold [`forward_write_lock`] across the poll and this write.
676/// Two threads that both saw `POLLOUT` would otherwise block in `write`
677/// when the pipe has room for only one `PIPE_BUF`.
678#[cfg(unix)]
679fn forward_write_lock() -> std::sync::MutexGuard<'static, ()> {
680    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
681    LOCK.lock().unwrap_or_else(|err| err.into_inner())
682}
683
684#[cfg(unix)]
685fn write_fd(fd: std::os::fd::RawFd, buf: &[u8], toggle: bool) -> Option<ForwardWrite> {
686    if !toggle {
687        return write_once(fd, buf);
688    }
689    // SAFETY: `F_GETFL` reads this fd's status flags.
690    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
691    if flags < 0 {
692        return None;
693    }
694    let added = flags & libc::O_NONBLOCK == 0;
695    if added {
696        // SAFETY: `flags` came from `F_GETFL` on this fd.
697        let rc = unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) };
698        if rc < 0 {
699            return None;
700        }
701    }
702    let write_result = write_once(fd, buf);
703    if added {
704        // SAFETY: restore the flags this function observed.
705        unsafe { libc::fcntl(fd, libc::F_SETFL, flags) };
706    }
707    write_result
708}
709
710/// A second open of the tty. Its `O_NONBLOCK` is not the shell's stdin.
711#[cfg(unix)]
712struct PrivateOut(std::os::fd::RawFd);
713
714#[cfg(unix)]
715impl Drop for PrivateOut {
716    fn drop(&mut self) {
717        // SAFETY: this fd came from `open` below and is still open.
718        unsafe { libc::close(self.0) };
719    }
720}
721
722/// Linux `/proc/self/fd` opens a new description. If this platform
723/// instead shares flags with `fd`, restore them and give up.
724#[cfg(target_os = "linux")]
725fn open_private_nonblock(fd: std::os::fd::RawFd) -> Option<PrivateOut> {
726    let mut stat = unsafe { std::mem::zeroed::<libc::stat>() };
727    // SAFETY: `stat` is a live object. A regular file must keep its
728    // offset, so only pipes and sockets get a second description.
729    let rc = unsafe { libc::fstat(fd, &mut stat) };
730    if rc != 0 {
731        return None;
732    }
733    let kind = stat.st_mode & libc::S_IFMT;
734    if kind != libc::S_IFIFO && kind != libc::S_IFSOCK {
735        return None;
736    }
737    let path = std::ffi::CString::new(format!("/proc/self/fd/{fd}")).ok()?;
738    // SAFETY: `F_GETFL` reads this fd's status flags.
739    let before = unsafe { libc::fcntl(fd, libc::F_GETFL) };
740    if before < 0 {
741        return None;
742    }
743    // SAFETY: `path` is a NUL-terminated `/proc/self/fd/N`.
744    let opened = unsafe {
745        libc::open(
746            path.as_ptr(),
747            libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
748        )
749    };
750    if opened < 0 {
751        return None;
752    }
753    // SAFETY: same fd as `before`.
754    let after = unsafe { libc::fcntl(fd, libc::F_GETFL) };
755    if before & libc::O_NONBLOCK == 0 && after & libc::O_NONBLOCK != 0 {
756        unsafe {
757            libc::fcntl(fd, libc::F_SETFL, before);
758            libc::close(opened);
759        }
760        return None;
761    }
762    Some(PrivateOut(opened))
763}
764
765#[cfg(unix)]
766fn open_private_tty(fd: std::os::fd::RawFd) -> Option<PrivateOut> {
767    // SAFETY: `isatty` only reads the fd type.
768    if unsafe { libc::isatty(fd) } != 1 {
769        return None;
770    }
771    let mut name = [0 as libc::c_char; 1024];
772    // SAFETY: `name` is a live buffer of that length.
773    let rc = unsafe { libc::ttyname_r(fd, name.as_mut_ptr(), name.len()) };
774    if rc != 0 {
775        return None;
776    }
777    let path = unsafe { std::ffi::CStr::from_ptr(name.as_ptr()) };
778    // SAFETY: `path` is the NUL-terminated tty name just written.
779    let opened = unsafe {
780        libc::open(
781            path.as_ptr(),
782            libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
783        )
784    };
785    if opened < 0 {
786        None
787    } else {
788        Some(PrivateOut(opened))
789    }
790}
791
792#[cfg(unix)]
793fn copy_pipe(
794    mut src: impl std::io::Read + Send + 'static,
795    mut dst: impl std::io::Write + AsRawFd + Send + 'static,
796    stop: Arc<AtomicBool>,
797) -> std::thread::JoinHandle<()> {
798    std::thread::spawn(move || {
799        let fd = dst.as_raw_fd();
800        #[cfg(target_os = "linux")]
801        let private = open_private_tty(fd).or_else(|| open_private_nonblock(fd));
802        #[cfg(not(target_os = "linux"))]
803        let private = open_private_tty(fd);
804        let out_fd = private.as_ref().map(|out| out.0).unwrap_or(fd);
805        // macOS `POLLOUT` already means a 512-byte write will not block,
806        // so pipes there do not need `O_NONBLOCK`. Linux falls back to
807        // the toggle only when a private descriptor is unavailable.
808        // SAFETY: `fd` is the destination stdout or stderr handle.
809        let toggle =
810            cfg!(target_os = "linux") && private.is_none() && unsafe { libc::isatty(fd) } != 1;
811        let chunk = forward_chunk(out_fd);
812        // Push any prefix already sitting in the stdout buffer. Later
813        // writes go to the fd, so a drop flush cannot block after stop.
814        let _ = std::io::Write::flush(&mut dst);
815        let mut buf = [0u8; 16 * 1024];
816        loop {
817            if stop.load(Ordering::Relaxed) {
818                return;
819            }
820            let n = match std::io::Read::read(&mut src, &mut buf) {
821                Ok(0) | Err(_) => break,
822                Ok(n) => n,
823            };
824            let mut off = 0;
825            while off < n {
826                let _guard = forward_write_lock();
827                match poll_out_once(out_fd, &stop) {
828                    PollOut::Stop => return,
829                    PollOut::Later => continue,
830                    PollOut::Ready => {
831                        match push_nonblock(&buf[off..n], chunk, |slice| {
832                            write_fd(out_fd, slice, toggle)
833                        }) {
834                            // A match guard is not exhaustive, so zero is its own arm.
835                            PushNonblock::Wrote(0) | PushNonblock::Stop => return,
836                            PushNonblock::Wait => continue,
837                            PushNonblock::Wrote(wrote) => off += wrote,
838                        }
839                    }
840                }
841            }
842        }
843        if !stop.load(Ordering::Relaxed) {
844            let _ = std::io::Write::flush(&mut dst);
845        }
846    })
847}
848
849#[cfg(unix)]
850fn join_drain(handle: Option<std::thread::JoinHandle<Vec<u8>>>) -> Vec<u8> {
851    handle.and_then(|h| h.join().ok()).unwrap_or_default()
852}
853
854#[cfg(unix)]
855fn join_copy(handle: Option<std::thread::JoinHandle<()>>) {
856    if let Some(h) = handle {
857        let _ = h.join();
858    }
859}
860
861#[cfg(unix)]
862fn copy_finished(handle: &Option<std::thread::JoinHandle<()>>) -> bool {
863    match handle {
864        None => true,
865        Some(handle) => handle.is_finished(),
866    }
867}
868
869/// Stop the copies at `deadline` if a stalled reader is still blocking
870/// them. True means the deadline, not the child, ended the forward.
871#[cfg(unix)]
872fn finish_copies(
873    stop: &AtomicBool,
874    stdout: Option<std::thread::JoinHandle<()>>,
875    stderr: Option<std::thread::JoinHandle<()>>,
876    deadline: Instant,
877) -> bool {
878    let mut forced = false;
879    loop {
880        if copy_finished(&stdout) && copy_finished(&stderr) {
881            break;
882        }
883        if Instant::now() >= deadline {
884            stop.store(true, Ordering::Relaxed);
885            forced = true;
886            break;
887        }
888        std::thread::sleep(Duration::from_millis(10));
889    }
890    join_copy(stdout);
891    join_copy(stderr);
892    forced
893}
894
895/// Inputs for [`doctor_fails`]. Remount is Linux-only. WFP is Windows-only.
896#[derive(Debug, Clone, Copy, PartialEq, Eq)]
897pub struct DoctorFacts {
898    pub kernel_supported: bool,
899    /// `Some` only on Linux. `false` means `workpen run` will not start a child.
900    pub remount_available: Option<bool>,
901    /// `Some(true)` when Windows WFP returned access denied. `None` off Windows.
902    pub wfp_skipped: Option<bool>,
903    /// Probe setup failed, so a child would not start.
904    pub setup_failed: bool,
905}
906
907/// Exit 1 when the kernel is missing, Linux remount is unavailable, or
908/// Windows jail setup failed. WFP skip alone is not a failure.
909#[must_use]
910pub fn doctor_fails(facts: DoctorFacts) -> bool {
911    !facts.kernel_supported || facts.setup_failed || facts.remount_available == Some(false)
912}
913
914/// Probe this machine. Uses a private temp directory, not the user
915/// workspace, and does not plant `.env` or start a user command.
916pub fn collect_doctor_facts() -> DoctorFacts {
917    let kernel_supported = kernel_supported();
918    let dir = private_probe_dir().ok();
919    let _remove = dir.as_ref().map(|path| RemoveProbeDir(path.clone()));
920    #[cfg(target_os = "linux")]
921    let remount_available = Some(linux::dest_remount_available());
922    #[cfg(not(target_os = "linux"))]
923    let remount_available = None;
924    #[cfg(windows)]
925    let (wfp_skipped, setup_failed) = if kernel_supported {
926        match dir.as_deref() {
927            Some(path) => match windows::probe_wfp_skipped(path) {
928                Ok(skipped) => (Some(skipped), false),
929                Err(_) => (None, true),
930            },
931            None => (None, true),
932        }
933    } else {
934        (None, false)
935    };
936    #[cfg(not(windows))]
937    let (wfp_skipped, setup_failed) = (None, false);
938    DoctorFacts {
939        kernel_supported,
940        remount_available,
941        wfp_skipped,
942        setup_failed,
943    }
944}
945
946fn private_probe_dir() -> std::io::Result<PathBuf> {
947    let nanos = std::time::SystemTime::now()
948        .duration_since(std::time::UNIX_EPOCH)
949        .map(|d| d.as_nanos())
950        .unwrap_or(0);
951    let dir = std::env::temp_dir().join(format!("workpen-doctor-{}-{nanos}", std::process::id()));
952    std::fs::create_dir(&dir)?;
953    Ok(dir)
954}
955
956struct RemoveProbeDir(PathBuf);
957
958impl Drop for RemoveProbeDir {
959    fn drop(&mut self) {
960        let _ = std::fs::remove_dir_all(&self.0);
961    }
962}
963
964/// Whether this OS can apply a kernel jail.
965#[must_use]
966pub fn kernel_supported() -> bool {
967    #[cfg(unix)]
968    {
969        nono::Sandbox::is_supported()
970    }
971    #[cfg(windows)]
972    {
973        windows::write_restricted_supported()
974    }
975    #[cfg(not(any(unix, windows)))]
976    {
977        false
978    }
979}
980
981/// Build a process-jail policy. Does not apply it.
982///
983/// Refuses filesystem root and the current user's home directory as the
984/// workspace or as an extra-root. Extra-roots may still be an explicit
985/// `/tmp` or a subdirectory of home.
986///
987/// Dest-deny names default to [`crate::default_secret_denies()`] plus
988/// workspace `agent.lock` extras, resolved under the workspace and
989/// each extra-root (except `/tmp` / `/var/tmp`; those trees are too
990/// large to walk). An extra-root with a cache dir name
991/// (`target`, `node_modules`, `.venv`, `dist`, `__pycache__`)
992/// in any path component uses the glob-name cache walk, same as a
993/// workspace `target/` (no hardlink sibling scan of rustc
994/// artifacts). That includes `--extra-root …/target/debug`.
995/// Missing lock equals defaults. Invalid
996/// lock is [`KernelError::Apply`]. Hosts match [`crate::DestDenyKind`],
997/// not English.
998pub fn process_jail(
999    workspace: impl AsRef<Path>,
1000    extra: impl IntoIterator<Item = impl AsRef<Path>>,
1001) -> Result<KernelPolicy, KernelError> {
1002    let workspace = workspace.as_ref();
1003    let policy =
1004        DenyPolicy::from_workspace(workspace).map_err(|err| KernelError::Apply(err.to_string()))?;
1005    process_jail_with_policy(workspace, extra, &policy)
1006}
1007
1008/// Same as [`process_jail`] with a host [`DenyPolicy`].
1009///
1010/// The host policy wins. Hosts that pass a policy own the merge,
1011/// including whether to load workspace `agent.lock`. This function
1012/// does not read the lock.
1013pub fn process_jail_with_policy(
1014    workspace: impl AsRef<Path>,
1015    extra: impl IntoIterator<Item = impl AsRef<Path>>,
1016    policy: &DenyPolicy,
1017) -> Result<KernelPolicy, KernelError> {
1018    refuse_home_workspace(workspace.as_ref())?;
1019    let extras: Vec<PathBuf> = extra
1020        .into_iter()
1021        .map(|p| p.as_ref().to_path_buf())
1022        .collect();
1023    let mut grants = Vec::new();
1024    add_rw(&mut grants, workspace.as_ref())?;
1025    for extra in &extras {
1026        add_rw(&mut grants, extra)?;
1027    }
1028    for dir in system_read_dirs() {
1029        add_read_if_dir(&mut grants, &dir);
1030    }
1031    // One hardlink-directory scan for the workspace and every extra root.
1032    #[cfg(unix)]
1033    let _hardlink_scans = crate::deny::HardlinkScanScope::new();
1034    let mut dest_denies = collect_workspace_dest_denies(workspace.as_ref(), policy)?;
1035    let mut remaining = DEST_DENY_WALK_LIMIT;
1036    for extra in &extras {
1037        append_extra_dest_denies(extra, policy, &mut dest_denies, &mut remaining)?;
1038    }
1039    if let Some(null_dev) = null_device_grant() {
1040        push_grant(&mut grants, null_dev, KernelAccess::ReadWrite);
1041    }
1042    Ok(KernelPolicy {
1043        grants,
1044        dest_denies,
1045        deny_policy: policy.clone(),
1046        network_blocked: true,
1047        require_dest_hide: false,
1048    })
1049}
1050
1051/// Read-write on the null device file only, when that path is still a
1052/// character device. Missing path and a symlink to a regular file get
1053/// no grant. `/dev` itself stays a read grant.
1054fn null_device_grant() -> Option<PathBuf> {
1055    #[cfg(unix)]
1056    {
1057        let path = PathBuf::from("/dev/null");
1058        if crate::deny::is_null_device(&path) {
1059            return Some(path);
1060        }
1061    }
1062    None
1063}
1064
1065impl KernelPolicy {
1066    pub fn grants(&self) -> &[KernelGrant] {
1067        &self.grants
1068    }
1069
1070    /// Dest-deny paths collected under the workspace and extra-roots.
1071    /// Not a filesystem grant.
1072    pub fn dest_denies(&self) -> &[DestDeny] {
1073        &self.dest_denies
1074    }
1075
1076    /// When `blocked` is false, Unix `to_capability_set` does not call
1077    /// `block_network()`. The default from [`process_jail`] stays blocked.
1078    #[must_use]
1079    pub fn with_network(mut self, blocked: bool) -> Self {
1080        self.network_blocked = blocked;
1081        self
1082    }
1083
1084    /// Read-only grant for one extra directory. Home and filesystem root
1085    /// are refused the same way as a read-write extra root. Dest-deny for
1086    /// that tree is recorded after the allow.
1087    pub fn with_read_root(mut self, path: &Path) -> Result<Self, KernelError> {
1088        add_read_grant(&mut self.grants, path)?;
1089        let mut remaining = DEST_DENY_WALK_LIMIT;
1090        append_extra_dest_denies(
1091            path,
1092            &self.deny_policy,
1093            &mut self.dest_denies,
1094            &mut remaining,
1095        )?;
1096        Ok(self)
1097    }
1098
1099    /// Fail closed when Linux dest-deny remount is skipped.
1100    ///
1101    /// Default `run_child` still starts the child and returns
1102    /// [`KernelApply::RemountSkipped`]. `workpen run` uses this so a
1103    /// child that can open in-tree secrets is not started.
1104    #[must_use]
1105    pub fn with_require_dest_hide(mut self) -> Self {
1106        self.require_dest_hide = true;
1107        self
1108    }
1109
1110    #[cfg(unix)]
1111    fn require_spawn(&self, applied: KernelApply) -> Result<KernelApply, KernelError> {
1112        if self.require_dest_hide {
1113            require_dest_hide(applied)
1114        } else {
1115            require_applied(applied)
1116        }
1117    }
1118
1119    /// Add host dest-deny paths. Existing files are classified (glob or
1120    /// hardlink). Missing paths are still recorded as [`DestDenyKind::DenyGlob`].
1121    pub fn with_dest_deny_paths(
1122        mut self,
1123        paths: impl IntoIterator<Item = impl AsRef<Path>>,
1124    ) -> Self {
1125        for path in paths {
1126            push_dest_deny(
1127                &mut self.dest_denies,
1128                dest_deny_from_path(path.as_ref(), &self.deny_policy),
1129            );
1130        }
1131        self
1132    }
1133
1134    /// True when the policy asked the kernel backend to block sockets.
1135    ///
1136    /// Unix `run_child` passes this to nono `block_network()`. Windows
1137    /// `run_child` wraps the command in a unique helper PE, launches
1138    /// that helper in an AppContainer with no network capabilities, and
1139    /// adds a dynamic WFP BLOCK on the package SID (and the helper
1140    /// APP_ID) when the token can add filters. Fail closed if
1141    /// AppContainer cannot apply. WFP `ERROR_ACCESS_DENIED` (win32 5)
1142    /// is skipped: package filters need an elevated token. The child
1143    /// still starts with AppContainer network deny.
1144    pub fn network_blocked(&self) -> bool {
1145        self.network_blocked
1146    }
1147
1148    /// Apply Landlock/Seatbelt for this process. Irreversible. Not for tests.
1149    ///
1150    /// Uses `SignalMode::AllowAll` so a jailed parent can still signal children.
1151    /// Windows cannot retoken the current process; this stays
1152    /// [`KernelApply::UserspaceOnly`].
1153    pub fn apply(&self) -> Result<KernelApply, KernelError> {
1154        if !kernel_supported() {
1155            return Ok(KernelApply::UserspaceOnly);
1156        }
1157        #[cfg(any(target_os = "linux", target_os = "macos"))]
1158        {
1159            let caps = self.to_capability_set(nono::SignalMode::AllowAll)?;
1160            nono::Sandbox::apply_auto(&caps).map_err(|e| KernelError::Apply(e.to_string()))?;
1161            Ok(KernelApply::Applied)
1162        }
1163        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
1164        {
1165            Ok(KernelApply::UserspaceOnly)
1166        }
1167    }
1168
1169    /// Install Landlock/Seatbelt in the child `pre_exec` hook.
1170    ///
1171    /// Dest-denies `cmd` argv first ([`Self::dest_deny_command`]), same
1172    /// rules as [`Self::run_child`]. Builds the capability set in the
1173    /// parent (allocation is not safe after fork). Uses
1174    /// `SignalMode::Isolated` so the child cannot signal the parent.
1175    /// Does not jail this process. Windows has no `pre_exec`; this stays
1176    /// [`KernelApply::UserspaceOnly`]. Use [`Self::run_child`] to jail a child.
1177    ///
1178    /// On Linux, dest-deny remount skip is [`KernelApply::RemountSkipped`]
1179    /// when dest-deny paths exist and a private mount ns cannot be
1180    /// entered. Extra-root dests still fail-closed. If the parent probe
1181    /// returned [`KernelApply::Applied`], the child fail-closes when
1182    /// enter fails.
1183    ///
1184    /// The hook forks a reaper. After the host waits for the spawned
1185    /// child, call [`Self::finish_pre_exec`] on this same thread. A miss
1186    /// is [`KernelError::Descendants`], not the child status. Call
1187    /// [`Self::discard_pre_exec`] when spawn fails or the host does not
1188    /// wait. [`Self::run_child`] waits and finishes itself.
1189    ///
1190    /// The report is one pipe per thread, not per policy value. A second
1191    /// `apply_pre_exec` on this thread drops an unread report. A wait
1192    /// that resumes on another thread, including after `.await`, must
1193    /// use [`Self::apply_pre_exec_report`] instead. [`Self::finish_pre_exec`]
1194    /// on that other thread is [`KernelError::Descendants`] even when
1195    /// the command had no grandchildren.
1196    pub fn apply_pre_exec(&self, cmd: &mut Command) -> Result<KernelApply, KernelError> {
1197        let (applied, report) = self.apply_pre_exec_dests(cmd, Vec::new())?;
1198        report.stash();
1199        Ok(applied)
1200    }
1201
1202    /// Same hook as [`Self::apply_pre_exec`]. The [`PreExecReport`] owns
1203    /// the reaper pipe and is `Send`.
1204    ///
1205    /// Move the report with the child. [`PreExecReport::finish`] reads
1206    /// it on whichever thread resumed. [`PreExecReport::discard`] and
1207    /// `Drop` close the pipe. This does not store a thread-local, and it
1208    /// does not drop a report the host still holds.
1209    pub fn apply_pre_exec_report(
1210        &self,
1211        cmd: &mut Command,
1212    ) -> Result<(KernelApply, PreExecReport), KernelError> {
1213        self.apply_pre_exec_dests(cmd, Vec::new())
1214    }
1215
1216    /// Read the descendant report for a child spawned after
1217    /// [`Self::apply_pre_exec`] on this same thread.
1218    ///
1219    /// Call this once, after the host's own wait. `Ok(status)` means the
1220    /// reaper tracked every descendant. [`KernelError::Descendants`]
1221    /// means it did not: the report was a miss, the pipe was missing, or
1222    /// the reaper wrote nothing. That includes calling this on a
1223    /// different thread from [`Self::apply_pre_exec`]. Use
1224    /// [`PreExecReport::finish`] to read a report that moved. Pass
1225    /// `timed_out: true` when the host's deadline already fired. The
1226    /// deadline wins and this returns `Ok(status)`, same as
1227    /// [`Self::run_child_timeout`].
1228    ///
1229    /// Closes the report pipe. Leaving it unread holds that pipe until
1230    /// the next [`Self::apply_pre_exec`] on this thread.
1231    pub fn finish_pre_exec(
1232        &self,
1233        status: ExitStatus,
1234        timed_out: bool,
1235    ) -> Result<ExitStatus, KernelError> {
1236        let _ = self;
1237        #[cfg(unix)]
1238        {
1239            finish_reap(status, timed_out).map(|(status, _)| status)
1240        }
1241        #[cfg(not(unix))]
1242        {
1243            let _ = timed_out;
1244            Ok(status)
1245        }
1246    }
1247
1248    /// Drop the thread-local descendant report without reading it.
1249    ///
1250    /// Use this when [`Self::apply_pre_exec`] succeeded but the host did
1251    /// not wait (spawn failed, or the host gave up). The next
1252    /// `apply_pre_exec` also drops an unread pipe. A later
1253    /// [`Self::finish_pre_exec`] on this thread then has no report.
1254    /// [`PreExecReport::discard`] is the same close for a report the
1255    /// host holds.
1256    pub fn discard_pre_exec(&self) {
1257        let _ = self;
1258        #[cfg(unix)]
1259        reaper::discard_report();
1260    }
1261
1262    fn apply_pre_exec_dests(
1263        &self,
1264        cmd: &mut Command,
1265        extra_dests: Vec<PathBuf>,
1266    ) -> Result<(KernelApply, PreExecReport), KernelError> {
1267        self.dest_deny_command(cmd)?;
1268        if !kernel_supported() {
1269            return Ok((KernelApply::UserspaceOnly, PreExecReport::unarmed()));
1270        }
1271        #[cfg(any(target_os = "linux", target_os = "macos"))]
1272        {
1273            let caps = self.to_capability_set(nono::SignalMode::Isolated)?;
1274            let mut dests: Vec<PathBuf> = self.dest_denies.iter().map(|d| d.path.clone()).collect();
1275            dests.extend(extra_dests);
1276            let workspace = self
1277                .grants
1278                .iter()
1279                .find(|g| g.access == KernelAccess::ReadWrite)
1280                .map(|g| g.path.clone())
1281                .unwrap_or_default();
1282            #[cfg(target_os = "linux")]
1283            let remount = linux::remount_status(&dests, &workspace)?;
1284            #[cfg(not(target_os = "linux"))]
1285            let remount = KernelApply::Applied;
1286            #[cfg(target_os = "linux")]
1287            let require_remount = remount == KernelApply::Applied;
1288            // Safety: the set and dest list are built in the parent; the hook
1289            // only applies them and maps failure to io::Error.
1290            // The write fd is captured by value. The parent keeps the
1291            // `OwnedFd`. `fork` gives the child its own copy.
1292            let report = reaper::open_report();
1293            let report_fd = report.write_raw();
1294            let expected_comm = reaper::expected_comm_bytes(cmd.get_program());
1295            unsafe {
1296                use std::os::unix::process::CommandExt;
1297                cmd.pre_exec(move || {
1298                    // Mark inherited descriptors before the reaper fork so a
1299                    // soft limit that cannot be covered fails spawn here.
1300                    reaper::cloexec_inherited_fds()?;
1301                    reaper::supervise_or_continue(report_fd, expected_comm)?;
1302                    #[cfg(target_os = "linux")]
1303                    linux::apply_dest_deny_remounts(&dests, &workspace, require_remount)?;
1304                    #[cfg(not(target_os = "linux"))]
1305                    let _ = (&dests, &workspace);
1306                    apply_child_hardening()?;
1307                    nono::Sandbox::apply_auto(&caps)
1308                        .map_err(|e| std::io::Error::other(e.to_string()))?;
1309                    Ok(())
1310                });
1311            }
1312            Ok((remount, PreExecReport::from_pipe(report)))
1313        }
1314        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
1315        {
1316            let _ = extra_dests;
1317            Ok((KernelApply::UserspaceOnly, PreExecReport::unarmed()))
1318        }
1319    }
1320
1321    /// Spawn `cmd` under the kernel jail and wait for it.
1322    ///
1323    /// Dest-denies the `Command` program plus args with
1324    /// [`crate::check_command_argv`] (same rules as `workpen run`)
1325    /// before spawn. Invalid `-EncodedCommand` is
1326    /// [`crate::DestDenyError::EncodedCommand`] via
1327    /// [`KernelError::DestDeny`]. The child is not started.
1328    ///
1329    /// Unix installs `pre_exec` then `status`. Windows creates a
1330    /// write-restricted token and `CreateProcessAsUserW`. When
1331    /// [`Self::network_blocked`] is set, Windows also wraps the command
1332    /// through a unique helper PE in an AppContainer and a package-SID
1333    /// WFP BLOCK when the token can add filters. WFP win32 5 is skipped
1334    /// (needs admin). If AppContainer or the kernel cannot apply, this
1335    /// returns [`KernelError::Apply`] and does not start the child.
1336    /// [`KernelApply::UserspaceOnly`] stays on [`Self::apply`] /
1337    /// [`Self::apply_pre_exec`] inspect paths only.
1338    ///
1339    /// Windows spawn inherits parent stdio or grants NUL so console
1340    /// children do not block on null handles. [`Command`]
1341    /// [`std::process::Stdio::piped`] is not readable after this wait.
1342    /// Hosts that need captured stdout call [`Self::run_child_output`].
1343    ///
1344    /// Blocking wait has no host-visible kill; use
1345    /// [`Self::run_child_timeout`]. Hosts that need captured stdout use
1346    /// [`Self::run_child_output`].
1347    #[cfg(target_os = "linux")]
1348    fn occupy_and_hook(
1349        &self,
1350        cmd: &mut Command,
1351    ) -> Result<(KernelApply, linux::OccupiedDests), KernelError> {
1352        let occupy = linux::occupy_missing(&self.occupy_roots(), self.deny_policy.globs())
1353            .map_err(|e| KernelError::Apply(e.to_string()))?;
1354        let extra = occupy.paths().to_vec();
1355        let (applied, report) = self.apply_pre_exec_dests(cmd, extra)?;
1356        report.stash();
1357        let applied = self
1358            .require_spawn(applied)
1359            .inspect_err(|_| reaper::discard_report())?;
1360        Ok((applied, occupy))
1361    }
1362
1363    #[cfg(all(unix, not(target_os = "linux")))]
1364    fn hook_ready(&self, cmd: &mut Command) -> Result<KernelApply, KernelError> {
1365        let applied = self.apply_pre_exec(cmd)?;
1366        self.require_spawn(applied)
1367            .inspect_err(|_| reaper::discard_report())
1368    }
1369
1370    #[cfg(target_os = "linux")]
1371    fn occupy_roots(&self) -> Vec<PathBuf> {
1372        self.grants
1373            .iter()
1374            .filter(|g| g.access == KernelAccess::ReadWrite && !is_system_temp_root(&g.path))
1375            .map(|g| g.path.clone())
1376            .collect()
1377    }
1378
1379    pub fn run_child(&self, cmd: Command) -> Result<(KernelApply, ExitStatus), KernelError> {
1380        self.dest_deny_command(&cmd)?;
1381        #[cfg(unix)]
1382        {
1383            if !kernel_supported() {
1384                return Err(KernelError::Apply(
1385                    "kernel jail is not available; child was not started".into(),
1386                ));
1387            }
1388            use std::os::unix::process::CommandExt;
1389
1390            let mut cmd = cmd;
1391            scrub_child_command(&mut cmd);
1392            #[cfg(target_os = "linux")]
1393            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
1394            #[cfg(not(target_os = "linux"))]
1395            let applied = self.hook_ready(&mut cmd)?;
1396            cmd.process_group(0);
1397            let mut child = spawn_jailed(&mut cmd)?;
1398            let (status, _) = reap_process_group(&mut child, None)?;
1399            Ok((applied, status))
1400        }
1401        #[cfg(windows)]
1402        {
1403            if !kernel_supported() {
1404                return Err(KernelError::Apply(
1405                    "write-restricted token is not available".into(),
1406                ));
1407            }
1408            let mut cmd = cmd;
1409            windows::spawn_write_restricted(self, &mut cmd, None)
1410        }
1411        #[cfg(not(any(unix, windows)))]
1412        {
1413            let _ = cmd;
1414            Err(KernelError::Apply(
1415                "no kernel backend on this platform".into(),
1416            ))
1417        }
1418    }
1419
1420    /// Spawn `cmd` under the kernel jail and collect stdout/stderr.
1421    ///
1422    /// Same dest-deny and fail-closed setup as [`Self::run_child`].
1423    /// Windows creates anonymous pipes. Unix inherits stdin and pipes
1424    /// stdout/stderr (`Command::output` would close stdin).
1425    pub fn run_child_output(
1426        &self,
1427        cmd: Command,
1428    ) -> Result<(KernelApply, std::process::Output), KernelError> {
1429        self.dest_deny_command(&cmd)?;
1430        #[cfg(unix)]
1431        {
1432            if !kernel_supported() {
1433                return Err(KernelError::Apply(
1434                    "kernel jail is not available; child was not started".into(),
1435                ));
1436            }
1437            use std::os::unix::process::CommandExt;
1438
1439            let mut cmd = cmd;
1440            scrub_child_command(&mut cmd);
1441            #[cfg(target_os = "linux")]
1442            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
1443            #[cfg(not(target_os = "linux"))]
1444            let applied = self.hook_ready(&mut cmd)?;
1445            cmd.stdin(std::process::Stdio::inherit());
1446            cmd.stdout(std::process::Stdio::piped());
1447            cmd.stderr(std::process::Stdio::piped());
1448            cmd.process_group(0);
1449            let mut child = spawn_jailed(&mut cmd)?;
1450            let stdout = child.stdout.take().map(drain_pipe);
1451            let stderr = child.stderr.take().map(drain_pipe);
1452            let (status, _) = reap_process_group(&mut child, None)?;
1453            let output = std::process::Output {
1454                status,
1455                stdout: join_drain(stdout),
1456                stderr: join_drain(stderr),
1457            };
1458            Ok((applied, output))
1459        }
1460        #[cfg(windows)]
1461        {
1462            if !kernel_supported() {
1463                return Err(KernelError::Apply(
1464                    "write-restricted token is not available".into(),
1465                ));
1466            }
1467            let mut cmd = cmd;
1468            windows::spawn_write_restricted_output(self, &mut cmd, None).map(|(a, o, _)| (a, o))
1469        }
1470        #[cfg(not(any(unix, windows)))]
1471        {
1472            let _ = cmd;
1473            Err(KernelError::Apply(
1474                "no kernel backend on this platform".into(),
1475            ))
1476        }
1477    }
1478
1479    /// Same as [`Self::run_child_output`] with a deadline.
1480    ///
1481    /// Stdout and stderr are drained while waiting so a chatty child
1482    /// cannot fill the pipe and block until this deadline.
1483    ///
1484    /// Returns `(applied, output, timed_out)`. When `timed_out` is true,
1485    /// `output` still holds drained stdout/stderr. [`KernelError::Timeout`]
1486    /// stays a unit variant on [`Self::run_child_timeout`].
1487    pub fn run_child_timeout_output(
1488        &self,
1489        cmd: Command,
1490        timeout: Duration,
1491    ) -> Result<(KernelApply, std::process::Output, bool), KernelError> {
1492        self.dest_deny_command(&cmd)?;
1493        #[cfg(unix)]
1494        {
1495            use std::os::unix::process::CommandExt;
1496
1497            if !kernel_supported() {
1498                return Err(KernelError::Apply(
1499                    "kernel jail is not available; child was not started".into(),
1500                ));
1501            }
1502            let mut cmd = cmd;
1503            scrub_child_command(&mut cmd);
1504            #[cfg(target_os = "linux")]
1505            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
1506            #[cfg(not(target_os = "linux"))]
1507            let applied = self.hook_ready(&mut cmd)?;
1508            cmd.stdout(std::process::Stdio::piped());
1509            cmd.stderr(std::process::Stdio::piped());
1510            cmd.process_group(0);
1511            let child = spawn_jailed_deadline(&mut cmd, Some(timeout))?;
1512            let (output, timed_out) = wait_child_timeout_output(child, timeout)?;
1513            Ok((applied, output, timed_out))
1514        }
1515        #[cfg(windows)]
1516        {
1517            if !kernel_supported() {
1518                return Err(KernelError::Apply(
1519                    "write-restricted token is not available".into(),
1520                ));
1521            }
1522            let mut cmd = cmd;
1523            windows::spawn_write_restricted_output(self, &mut cmd, Some(timeout))
1524        }
1525        #[cfg(not(any(unix, windows)))]
1526        {
1527            let _ = (cmd, timeout);
1528            Err(KernelError::Apply(
1529                "no kernel backend on this platform".into(),
1530            ))
1531        }
1532    }
1533
1534    /// Spawn `cmd` and copy stdout/stderr to this process as they arrive.
1535    ///
1536    /// Unlike [`Self::run_child_output`], this does not buffer the whole
1537    /// stream in a `Vec`. The CLI uses it so a chatty child cannot grow
1538    /// parent RSS without bound. Redirects outside `--root` stay parent
1539    /// writes (Seatbelt/DACL).
1540    pub fn run_child_forward(
1541        &self,
1542        cmd: Command,
1543    ) -> Result<(KernelApply, ExitStatus), KernelError> {
1544        self.dest_deny_command(&cmd)?;
1545        #[cfg(unix)]
1546        {
1547            if !kernel_supported() {
1548                return Err(KernelError::Apply(
1549                    "kernel jail is not available; child was not started".into(),
1550                ));
1551            }
1552            use std::os::unix::process::CommandExt;
1553
1554            let mut cmd = cmd;
1555            scrub_child_command(&mut cmd);
1556            #[cfg(target_os = "linux")]
1557            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
1558            #[cfg(not(target_os = "linux"))]
1559            let applied = self.hook_ready(&mut cmd)?;
1560            cmd.stdin(std::process::Stdio::inherit());
1561            cmd.stdout(std::process::Stdio::piped());
1562            cmd.stderr(std::process::Stdio::piped());
1563            cmd.process_group(0);
1564            let mut child = spawn_jailed(&mut cmd)?;
1565            let stop = forward_stop();
1566            let stdout = child
1567                .stdout
1568                .take()
1569                .map(|p| copy_pipe(p, std::io::stdout(), Arc::clone(&stop)));
1570            let stderr = child
1571                .stderr
1572                .take()
1573                .map(|p| copy_pipe(p, std::io::stderr(), Arc::clone(&stop)));
1574            let (status, _) = reap_process_group(&mut child, None)?;
1575            join_copy(stdout);
1576            join_copy(stderr);
1577            Ok((applied, status))
1578        }
1579        #[cfg(windows)]
1580        {
1581            if !kernel_supported() {
1582                return Err(KernelError::Apply(
1583                    "write-restricted token is not available".into(),
1584                ));
1585            }
1586            let mut cmd = cmd;
1587            windows::spawn_write_restricted_forward(self, &mut cmd, None).map(|(a, s, _)| (a, s))
1588        }
1589        #[cfg(not(any(unix, windows)))]
1590        {
1591            let _ = cmd;
1592            Err(KernelError::Apply(
1593                "no kernel backend on this platform".into(),
1594            ))
1595        }
1596    }
1597
1598    /// Same as [`Self::run_child_forward`] with a deadline.
1599    ///
1600    /// Returns `(applied, status, timed_out)`. Bytes are copied to this
1601    /// process as they arrive. [`KernelError::Timeout`] stays a unit
1602    /// variant on [`Self::run_child_timeout`].
1603    pub fn run_child_timeout_forward(
1604        &self,
1605        cmd: Command,
1606        timeout: Duration,
1607    ) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
1608        self.dest_deny_command(&cmd)?;
1609        #[cfg(unix)]
1610        {
1611            use std::os::unix::process::CommandExt;
1612
1613            if !kernel_supported() {
1614                return Err(KernelError::Apply(
1615                    "kernel jail is not available; child was not started".into(),
1616                ));
1617            }
1618            let mut cmd = cmd;
1619            scrub_child_command(&mut cmd);
1620            #[cfg(target_os = "linux")]
1621            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
1622            #[cfg(not(target_os = "linux"))]
1623            let applied = self.hook_ready(&mut cmd)?;
1624            cmd.stdin(std::process::Stdio::inherit());
1625            cmd.stdout(std::process::Stdio::piped());
1626            cmd.stderr(std::process::Stdio::piped());
1627            cmd.process_group(0);
1628            let child = spawn_jailed_deadline(&mut cmd, Some(timeout))?;
1629            let (status, timed_out) = wait_child_timeout_forward(child, timeout)?;
1630            Ok((applied, status, timed_out))
1631        }
1632        #[cfg(windows)]
1633        {
1634            if !kernel_supported() {
1635                return Err(KernelError::Apply(
1636                    "write-restricted token is not available".into(),
1637                ));
1638            }
1639            let mut cmd = cmd;
1640            windows::spawn_write_restricted_forward(self, &mut cmd, Some(timeout))
1641        }
1642        #[cfg(not(any(unix, windows)))]
1643        {
1644            let _ = (cmd, timeout);
1645            Err(KernelError::Apply(
1646                "no kernel backend on this platform".into(),
1647            ))
1648        }
1649    }
1650
1651    /// Same as [`Self::run_child_forward`] with a PTY for the child.
1652    ///
1653    /// Unix only. Windows returns [`KernelError::Apply`]. stdin/stdout/
1654    /// stderr are the slave. The parent copies the master to this
1655    /// process. `setsid` is the child's process group (no extra
1656    /// `process_group(0)`).
1657    pub fn run_child_forward_pty(
1658        &self,
1659        cmd: Command,
1660    ) -> Result<(KernelApply, ExitStatus), KernelError> {
1661        self.run_child_pty(cmd, None).map(|(a, s, _)| (a, s))
1662    }
1663
1664    /// Same as [`Self::run_child_timeout_forward`] with a PTY.
1665    pub fn run_child_timeout_forward_pty(
1666        &self,
1667        cmd: Command,
1668        timeout: Duration,
1669    ) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
1670        self.run_child_pty(cmd, Some(timeout))
1671    }
1672
1673    fn run_child_pty(
1674        &self,
1675        cmd: Command,
1676        timeout: Option<Duration>,
1677    ) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
1678        self.dest_deny_command(&cmd)?;
1679        #[cfg(unix)]
1680        {
1681            if !kernel_supported() {
1682                return Err(KernelError::Apply(
1683                    "kernel jail is not available; child was not started".into(),
1684                ));
1685            }
1686            let mut cmd = cmd;
1687            scrub_child_command(&mut cmd);
1688            let pty = pty::open_pty().map_err(|e| KernelError::Apply(e.to_string()))?;
1689            // unshare/Landlock before setsid/TIOCSCTTY. Linux userns
1690            // after a controlling TTY can stop the child on SIGTTIN.
1691            #[cfg(target_os = "linux")]
1692            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
1693            #[cfg(not(target_os = "linux"))]
1694            let applied = self.hook_ready(&mut cmd)?;
1695            pty::attach_pty(&mut cmd, pty.slave).map_err(|e| {
1696                reaper::discard_report();
1697                KernelError::Apply(e.to_string())
1698            })?;
1699            let mut child = spawn_jailed_deadline(&mut cmd, timeout)?;
1700            // The spawned pid is the reaper. Foreground the command
1701            // after it becomes a session leader. The child also calls
1702            // tcsetpgrp; this covers the Linux race the other way.
1703            #[cfg(unix)]
1704            if let Some(leader) = reaper::leader_pid(child.id() as libc::pid_t) {
1705                let _ = unsafe { libc::tcsetpgrp(pty.master.as_raw_fd(), leader) };
1706            }
1707            // Command keeps the slave File after spawn. Linux master
1708            // read does not EOF while that fd stays open in the parent.
1709            drop(cmd);
1710            let started = Instant::now();
1711            let stop = forward_stop();
1712            // Linux sends SIGHUP when the last PTY master closes. The
1713            // copy thread can drop its master before wait records the
1714            // child's exit, which turns a finished `cat` into 129.
1715            let master_hold = pty.master.try_clone().map_err(|e| {
1716                reaper::discard_report();
1717                KernelError::Apply(e.to_string())
1718            })?;
1719            let (out_th, master_write) = pty::pump_master(pty.master, &stop).map_err(|e| {
1720                reaper::discard_report();
1721                KernelError::Apply(e.to_string())
1722            })?;
1723            let _stdin_th = pty::pump_stdin(master_write);
1724            let (status, mut timed_out) = reap_process_group(&mut child, timeout)?;
1725            drop(master_hold);
1726            if let Some(limit) = timeout {
1727                if finish_copies(&stop, Some(out_th), None, started + limit) {
1728                    timed_out = true;
1729                }
1730            } else {
1731                join_copy(Some(out_th));
1732            }
1733            Ok((applied, status, timed_out))
1734        }
1735        #[cfg(windows)]
1736        {
1737            let _ = (cmd, timeout);
1738            Err(KernelError::Apply(
1739                "tty is not available on Windows; child was not started".into(),
1740            ))
1741        }
1742        #[cfg(not(any(unix, windows)))]
1743        {
1744            let _ = (cmd, timeout);
1745            Err(KernelError::Apply(
1746                "tty is not available on this platform; child was not started".into(),
1747            ))
1748        }
1749    }
1750
1751    /// Spawn `cmd` under the kernel jail and kill it after `timeout`.
1752    ///
1753    /// On macOS the deadline includes pre-exec. A command that has not
1754    /// reached exec by then is killed, and this returns
1755    /// [`KernelError::Timeout`].
1756    ///
1757    /// Same fail-closed setup as [`Self::run_child`]. Unix places the
1758    /// child in its own process group and `killpg`s that group when the
1759    /// leader exits and again on the deadline. A grandchild that called
1760    /// `setsid` is stopped by the pre_exec reaper before this wait
1761    /// returns. A pid that was not stored is
1762    /// [`KernelError::Descendants`] instead of the child status.
1763    /// Windows waits with a bounded `WaitForSingleObject` and
1764    /// closes the job so `KILL_ON_JOB_CLOSE` stops the child.
1765    pub fn run_child_timeout(
1766        &self,
1767        cmd: Command,
1768        timeout: Duration,
1769    ) -> Result<(KernelApply, ExitStatus), KernelError> {
1770        self.dest_deny_command(&cmd)?;
1771        #[cfg(unix)]
1772        {
1773            use std::os::unix::process::CommandExt;
1774
1775            if !kernel_supported() {
1776                return Err(KernelError::Apply(
1777                    "kernel jail is not available; child was not started".into(),
1778                ));
1779            }
1780            let mut cmd = cmd;
1781            scrub_child_command(&mut cmd);
1782            #[cfg(target_os = "linux")]
1783            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
1784            #[cfg(not(target_os = "linux"))]
1785            let applied = self.hook_ready(&mut cmd)?;
1786            cmd.process_group(0);
1787            let mut child = spawn_jailed_deadline(&mut cmd, Some(timeout))?;
1788            let (status, timed_out) = reap_process_group(&mut child, Some(timeout))?;
1789            if timed_out {
1790                return Err(KernelError::Timeout);
1791            }
1792            Ok((applied, status))
1793        }
1794        #[cfg(windows)]
1795        {
1796            if !kernel_supported() {
1797                return Err(KernelError::Apply(
1798                    "write-restricted token is not available".into(),
1799                ));
1800            }
1801            let mut cmd = cmd;
1802            windows::spawn_write_restricted(self, &mut cmd, Some(timeout))
1803        }
1804        #[cfg(not(any(unix, windows)))]
1805        {
1806            let _ = (cmd, timeout);
1807            Err(KernelError::Apply(
1808                "no kernel backend on this platform".into(),
1809            ))
1810        }
1811    }
1812
1813    #[cfg(unix)]
1814    fn to_capability_set(
1815        &self,
1816        signal: nono::SignalMode,
1817    ) -> Result<nono::CapabilitySet, KernelError> {
1818        let mut caps = nono::CapabilitySet::new();
1819        for grant in &self.grants {
1820            let mode = match grant.access {
1821                KernelAccess::Read => nono::AccessMode::Read,
1822                KernelAccess::ReadWrite => nono::AccessMode::ReadWrite,
1823            };
1824            caps = if grant.path.is_dir() {
1825                caps.allow_path(&grant.path, mode)
1826            } else {
1827                caps.allow_file(&grant.path, mode)
1828            }
1829            .map_err(|e| KernelError::Apply(e.to_string()))?;
1830        }
1831        #[cfg(target_os = "macos")]
1832        {
1833            let rw: Vec<&Path> = self
1834                .grants
1835                .iter()
1836                .filter(|g| g.access == KernelAccess::ReadWrite)
1837                .map(|g| g.path.as_path())
1838                .collect();
1839            add_macos_dest_deny_rules(&mut caps, &self.dest_denies, &rw, self.deny_policy.globs())?;
1840        }
1841        let caps = if self.network_blocked {
1842            caps.block_network()
1843        } else {
1844            caps
1845        };
1846        Ok(caps.set_signal_mode(signal))
1847    }
1848
1849    /// Dest-deny `cmd` argv with the jail [`DenyPolicy`] before spawn.
1850    ///
1851    /// Relative dests resolve against `cmd.current_dir()` when set, else
1852    /// the first ReadWrite grant. Same rules as
1853    /// [`crate::check_command_argv`] on program plus args. A program or
1854    /// argument that is not valid UTF-8 is [`KernelError::DestDeny`]
1855    /// of [`CheckDestError::NonUtf8`] before spawn. Hosts that
1856    /// jail writes in a capture dir still dest-deny argv against the
1857    /// user cwd when they set `current_dir`. Hosts that cannot use
1858    /// [`Self::run_child`] call this, then [`Self::apply_pre_exec`]
1859    /// (which also calls it) or their own spawn. Hosts match
1860    /// [`KernelError::DestDeny`], not English.
1861    pub fn dest_deny_command(&self, cmd: &Command) -> Result<(), KernelError> {
1862        let from_cwd = cmd.get_current_dir();
1863        let from_grant = self
1864            .grants
1865            .iter()
1866            .find(|g| g.access == KernelAccess::ReadWrite)
1867            .map(|g| g.path.as_path());
1868        let workspace = from_cwd.or(from_grant).ok_or_else(|| {
1869            KernelError::Apply("dest-deny argv needs a current_dir or ReadWrite grant".into())
1870        })?;
1871        let argv = command_argv(cmd)?;
1872        crate::check_command_argv(&argv, workspace, &self.deny_policy)?;
1873        Ok(())
1874    }
1875}
1876
1877fn command_argv(cmd: &Command) -> Result<Vec<String>, CheckDestError> {
1878    let mut out = Vec::with_capacity(1 + cmd.get_args().len());
1879    out.push(utf8_arg(cmd.get_program())?);
1880    for arg in cmd.get_args() {
1881        out.push(utf8_arg(arg)?);
1882    }
1883    Ok(out)
1884}
1885
1886fn utf8_arg(arg: &OsStr) -> Result<String, CheckDestError> {
1887    arg.to_str()
1888        .map(str::to_owned)
1889        .ok_or(CheckDestError::NonUtf8)
1890}
1891
1892/// Win32 `ERROR_ACCESS_DENIED`. Package WFP filters need an elevated token.
1893#[cfg(any(windows, test))]
1894pub(crate) const WFP_ERROR_ACCESS_DENIED: u32 = 5;
1895
1896/// True when a WFP engine or filter call returned access denied.
1897#[cfg(any(windows, test))]
1898#[must_use]
1899pub(crate) fn wfp_skip_access_denied(code: u32) -> bool {
1900    code == WFP_ERROR_ACCESS_DENIED
1901}
1902
1903/// Names `run_child` strips from the child environment.
1904#[must_use]
1905pub fn child_env_deny_names() -> &'static [&'static str] {
1906    &[
1907        "LD_PRELOAD",
1908        "DYLD_INSERT_LIBRARIES",
1909        "DYLD_LIBRARY_PATH",
1910        "BASH_ENV",
1911        "ENV",
1912        "NODE_OPTIONS",
1913        "NODE_PATH",
1914        "PYTHONPATH",
1915        "PYTHONHOME",
1916        "PYTHONSTARTUP",
1917        "PERL5OPT",
1918        "RUBYOPT",
1919        "LD_LIBRARY_PATH",
1920        "XAI_API_KEY",
1921        "ANTHROPIC_API_KEY",
1922        "OPENAI_API_KEY",
1923        "AWS_SECRET_ACCESS_KEY",
1924        "AWS_ACCESS_KEY_ID",
1925        "TMPDIR",
1926        "TEMP",
1927        "TMP",
1928    ]
1929}
1930
1931/// True when `name` must not be inherited by the child.
1932///
1933/// Exact denylist names, plus a final `_TOKEN` / `_SECRET` / `_PASSWORD`
1934/// segment and a final `_API_KEY`. The underscore is required.
1935/// `_KEY` alone is not enough: `CACHE_KEY` and `GIT_CONFIG_KEY_0` stay.
1936/// A `_KEY` name that contains `_PUBLIC_` or `_ANON_`, or that ends with
1937/// `_PUBLIC_KEY` or `_PUB_KEY`, stays. `_TOKEN` stays denied even then.
1938#[must_use]
1939pub fn is_denied_child_env(name: impl AsRef<OsStr>) -> bool {
1940    let raw = name.as_ref().to_string_lossy();
1941    if raw.is_empty() {
1942        return false;
1943    }
1944    if child_env_deny_names()
1945        .iter()
1946        .any(|n| raw.eq_ignore_ascii_case(n))
1947    {
1948        return true;
1949    }
1950    let upper = raw.to_ascii_uppercase();
1951    let last = upper.rsplit('_').next().unwrap_or(upper.as_str());
1952    if matches!(last, "TOKEN" | "SECRET" | "PASSWORD") {
1953        return true;
1954    }
1955    upper.ends_with("_API_KEY") && !public_key_env_exception(&upper)
1956}
1957
1958fn public_key_env_exception(upper: &str) -> bool {
1959    upper.contains("_PUBLIC_")
1960        || upper.contains("_ANON_")
1961        || upper.ends_with("_PUBLIC_KEY")
1962        || upper.ends_with("_PUB_KEY")
1963}
1964
1965/// Loader and script-execution names. `--env` cannot put these back.
1966pub(crate) fn is_child_env_loader(name: &OsStr) -> bool {
1967    let raw = name.to_string_lossy();
1968    const LOADERS: &[&str] = &[
1969        "LD_PRELOAD",
1970        "DYLD_INSERT_LIBRARIES",
1971        "DYLD_LIBRARY_PATH",
1972        "BASH_ENV",
1973        "ENV",
1974        "NODE_OPTIONS",
1975        "NODE_PATH",
1976        "PYTHONPATH",
1977        "PYTHONHOME",
1978        "PYTHONSTARTUP",
1979        "PERL5OPT",
1980        "RUBYOPT",
1981        "LD_LIBRARY_PATH",
1982    ];
1983    LOADERS.iter().any(|n| raw.eq_ignore_ascii_case(n))
1984}
1985
1986/// Remove denied inherited names. An explicit `cmd.env` is kept, except loaders.
1987pub fn scrub_child_command(cmd: &mut Command) {
1988    let explicit: Vec<(OsString, bool)> = cmd
1989        .get_envs()
1990        .map(|(key, value)| (key.to_os_string(), value.is_some()))
1991        .collect();
1992    let kept: Vec<OsString> = explicit
1993        .iter()
1994        .filter(|(_, set)| *set)
1995        .map(|(key, _)| key.clone())
1996        .filter(|key| !is_child_env_loader(key))
1997        .collect();
1998    for (key, _) in std::env::vars_os() {
1999        if is_denied_child_env(&key) && !kept.iter().any(|kept| kept == &key) {
2000            cmd.env_remove(&key);
2001        }
2002    }
2003    for (key, set) in &explicit {
2004        if *set && is_child_env_loader(key) {
2005            cmd.env_remove(key);
2006        }
2007    }
2008}
2009
2010/// Pairs for the Windows environment block.
2011///
2012/// `Command::get_envs` omits inherited names after `env_clear`, and
2013/// `env_remove` after `env_clear` does not record the name. A fresh
2014/// `env_remove` is listed only when the child still inherits.
2015#[cfg(any(windows, test))]
2016fn child_env_pairs(cmd: &mut Command) -> Vec<(OsString, OsString)> {
2017    let cleared = command_clears_env(cmd);
2018    let mut pairs: Vec<(OsString, OsString)> = if cleared {
2019        Vec::new()
2020    } else {
2021        std::env::vars_os().collect()
2022    };
2023    let mut explicit_keep = Vec::new();
2024    for (key, value) in cmd.get_envs() {
2025        pairs.retain(|(existing, _)| !env_key_eq(existing, key));
2026        if let Some(value) = value
2027            && !is_child_env_loader(key)
2028        {
2029            explicit_keep.push(key.to_os_string());
2030            pairs.push((key.to_os_string(), value.to_os_string()));
2031        }
2032    }
2033    pairs.retain(|(key, _)| {
2034        !is_denied_child_env(key) || explicit_keep.iter().any(|keep| env_key_eq(keep, key))
2035    });
2036    pairs
2037}
2038
2039#[cfg(any(windows, test))]
2040fn command_clears_env(cmd: &mut Command) -> bool {
2041    let sentinel = fresh_clear_probe(cmd);
2042    cmd.env_remove(&sentinel);
2043    !cmd.get_envs().any(|(key, _)| env_key_eq(key, &sentinel))
2044}
2045
2046#[cfg(any(windows, test))]
2047fn fresh_clear_probe(cmd: &Command) -> OsString {
2048    let mut n = 0u32;
2049    loop {
2050        let name = OsString::from(format!("WP_ENV_CLEAR_PROBE_{n}"));
2051        let in_cmd = cmd.get_envs().any(|(key, _)| env_key_eq(key, &name));
2052        let in_parent = std::env::vars_os().any(|(key, _)| env_key_eq(&key, &name));
2053        if !in_cmd && !in_parent {
2054            return name;
2055        }
2056        n += 1;
2057    }
2058}
2059
2060#[cfg(any(windows, test))]
2061fn env_key_eq(left: &OsStr, right: &OsStr) -> bool {
2062    left.to_string_lossy()
2063        .eq_ignore_ascii_case(&right.to_string_lossy())
2064}
2065
2066/// Insert `--noprofile` and `--norc` after argv0 when the program is bash.
2067///
2068/// When argv0 is `env`/`env.exe`, drop `NAME=value` assignments whose name
2069/// is on the child-env denylist, including leftover tokens inside a `-S` /
2070/// `--split-string` operand, then insert after the first non-flag operand
2071/// that is bash. Walks clustered shorts (`-iC /tmp`) and value flags
2072/// (`-u NAME`, `-f FILE`, `--file FILE`). Attached forms stay one token.
2073///
2074/// When argv0 is `timeout`/`nohup`/`nice`/`time`/`stdbuf` (or `.exe`),
2075/// skip wrapper flags plus the timeout duration or `nice -n N`. If the
2076/// remaining argv starts with env, drop denylist assignments on that env
2077/// argv, then insert after the first bash operand (wrapper bash or env
2078/// bash). An `env`/`env.exe` token after any other prefix is walked the
2079/// same way. Non-bash commands (`timeout 30 echo hi`) stay unchanged.
2080#[must_use]
2081pub fn with_bash_noprofile(
2082    program: impl AsRef<OsStr>,
2083    args: impl IntoIterator<Item = impl AsRef<OsStr>>,
2084) -> (OsString, Vec<OsString>) {
2085    let program = program.as_ref().to_os_string();
2086    let mut args: Vec<OsString> = args
2087        .into_iter()
2088        .map(|a| a.as_ref().to_os_string())
2089        .collect();
2090    if is_env_argv0(&program) {
2091        drop_denied_env_assignments(&mut args, 0);
2092    } else if let Some(i) = first_env_arg(&args) {
2093        drop_denied_env_assignments(&mut args, i + 1);
2094    }
2095    if is_bash_argv0(&program) {
2096        insert_bash_noprofile(&mut args, 0);
2097    } else if is_env_argv0(&program)
2098        && let Some(idx) = first_env_bash_operand(&args)
2099    {
2100        insert_bash_noprofile(&mut args, idx + 1);
2101    } else if let Some(kind) = cmd_wrapper(&program)
2102        && let Some(idx) = first_wrapper_bash_operand(kind, &args)
2103    {
2104        insert_bash_noprofile(&mut args, idx + 1);
2105    } else if let Some(env_i) = first_env_arg(&args)
2106        && let Some(idx) = first_env_bash_operand(&args[env_i + 1..])
2107    {
2108        insert_bash_noprofile(&mut args, env_i + 1 + idx + 1);
2109    }
2110    (program, args)
2111}
2112
2113fn drop_denied_env_assignments(args: &mut Vec<OsString>, mut i: usize) {
2114    let mut options_done = false;
2115    while i < args.len() {
2116        let raw = args[i].to_string_lossy().into_owned();
2117        if !options_done {
2118            if raw == "--" {
2119                options_done = true;
2120                i += 1;
2121                continue;
2122            }
2123            if let Some(skip) = env_flag_skip(&raw) {
2124                rewrite_denied_in_env_s(args, i);
2125                i = i.saturating_add(skip);
2126                continue;
2127            }
2128        }
2129        if let Some(eq) = raw.find('=') {
2130            let name = &raw[..eq];
2131            if !name.is_empty() && is_denied_child_env(name) {
2132                args.remove(i);
2133                continue;
2134            }
2135            i += 1;
2136            continue;
2137        }
2138        break;
2139    }
2140}
2141
2142fn rewrite_denied_in_env_s(args: &mut [OsString], i: usize) {
2143    let raw = args[i].to_string_lossy().into_owned();
2144    if let Some(value) = raw.strip_prefix("--split-string=") {
2145        let dropped = drop_denied_from_split_string(value);
2146        args[i] = OsString::from(format!("--split-string={dropped}"));
2147        return;
2148    }
2149    if raw == "--split-string" {
2150        rewrite_next_s_operand(args, i);
2151        return;
2152    }
2153    if let Some((prefix, attached)) = env_s_cluster(&raw) {
2154        if attached.is_empty() {
2155            rewrite_next_s_operand(args, i);
2156        } else {
2157            let dropped = drop_denied_from_split_string(attached);
2158            args[i] = OsString::from(format!("{prefix}{dropped}"));
2159        }
2160    }
2161}
2162
2163fn rewrite_next_s_operand(args: &mut [OsString], i: usize) {
2164    if let Some(op) = args.get_mut(i + 1) {
2165        let dropped = drop_denied_from_split_string(&op.to_string_lossy());
2166        *op = OsString::from(dropped);
2167    }
2168}
2169
2170/// Clustered `-*S` / `-S` (not `--`). Prefix includes `S`; rest is attached.
2171fn env_s_cluster(arg: &str) -> Option<(&str, &str)> {
2172    if !arg.starts_with('-') || arg.starts_with("--") || arg == "-" {
2173        return None;
2174    }
2175    let rest = &arg[1..];
2176    let mut idx = 0;
2177    for c in rest.chars() {
2178        if c == 'S' {
2179            let prefix_end = 1 + idx + c.len_utf8();
2180            return Some((&arg[..prefix_end], &arg[prefix_end..]));
2181        }
2182        if crate::deny::env_takes_value(c) {
2183            return None;
2184        }
2185        idx += c.len_utf8();
2186    }
2187    None
2188}
2189
2190fn drop_denied_from_split_string(s: &str) -> String {
2191    let tokens: Vec<&str> = s.split_whitespace().collect();
2192    let mut out = Vec::new();
2193    let mut i = 0;
2194    while i < tokens.len() {
2195        let raw = tokens[i];
2196        if raw == "--" || raw == "-" {
2197            out.extend_from_slice(&tokens[i..]);
2198            break;
2199        }
2200        if let Some(skip) = env_flag_skip(raw) {
2201            let end = (i + skip).min(tokens.len());
2202            out.extend_from_slice(&tokens[i..end]);
2203            i = end;
2204            continue;
2205        }
2206        if let Some(eq) = raw.find('=') {
2207            let name = &raw[..eq];
2208            if !name.is_empty() && is_denied_child_env(name) {
2209                i += 1;
2210                continue;
2211            }
2212            out.push(raw);
2213            i += 1;
2214            continue;
2215        }
2216        out.extend_from_slice(&tokens[i..]);
2217        break;
2218    }
2219    out.join(" ")
2220}
2221
2222fn insert_bash_noprofile(args: &mut Vec<OsString>, at: usize) {
2223    let has_noprofile = args[at..].iter().any(|a| a == "--noprofile");
2224    let has_norc = args[at..].iter().any(|a| a == "--norc");
2225    if !has_noprofile {
2226        args.insert(at, OsString::from("--noprofile"));
2227    }
2228    if !has_norc {
2229        let idx = args[at..]
2230            .iter()
2231            .position(|a| a == "--noprofile")
2232            .map(|i| at + i + 1)
2233            .unwrap_or(at);
2234        args.insert(idx, OsString::from("--norc"));
2235    }
2236}
2237
2238fn is_bash_argv0(program: &OsStr) -> bool {
2239    let raw = program.to_string_lossy();
2240    let name = raw.rsplit(['/', '\\']).next().unwrap_or(raw.as_ref());
2241    name.eq_ignore_ascii_case("bash") || name.eq_ignore_ascii_case("bash.exe")
2242}
2243
2244fn is_env_argv0(program: &OsStr) -> bool {
2245    crate::deny::is_env_program(program)
2246}
2247
2248fn first_env_arg(args: &[OsString]) -> Option<usize> {
2249    args.iter().position(|a| is_env_argv0(a.as_os_str()))
2250}
2251
2252fn first_env_bash_operand(args: &[OsString]) -> Option<usize> {
2253    let mut i = 0;
2254    while i < args.len() {
2255        let raw = args[i].to_string_lossy();
2256        if raw == "--" {
2257            return args
2258                .get(i + 1)
2259                .filter(|a| is_bash_argv0(a.as_os_str()))
2260                .map(|_| i + 1);
2261        }
2262        if let Some(skip) = env_flag_skip(&raw) {
2263            i = i.saturating_add(skip);
2264            continue;
2265        }
2266        if raw.contains('=') {
2267            i += 1;
2268            continue;
2269        }
2270        if is_bash_argv0(args[i].as_os_str()) {
2271            return Some(i);
2272        }
2273        return None;
2274    }
2275    None
2276}
2277
2278fn cmd_wrapper(program: &OsStr) -> Option<crate::deny::CmdWrapper> {
2279    crate::deny::cmd_wrapper(program)
2280}
2281
2282fn skip_wrapper_os(kind: crate::deny::CmdWrapper, args: &[OsString]) -> usize {
2283    let raws: Vec<String> = args
2284        .iter()
2285        .map(|a| a.to_string_lossy().into_owned())
2286        .collect();
2287    crate::deny::skip_wrapper_prefix(kind, &raws)
2288}
2289
2290fn first_wrapper_bash_operand(kind: crate::deny::CmdWrapper, args: &[OsString]) -> Option<usize> {
2291    let start = skip_wrapper_os(kind, args);
2292    let rest = args.get(start..)?;
2293    if rest.first().is_some_and(|a| is_bash_argv0(a.as_os_str())) {
2294        return Some(start);
2295    }
2296    if rest.first().is_some_and(|a| is_env_argv0(a.as_os_str())) {
2297        return first_env_bash_operand(&rest[1..]).map(|i| start + 1 + i);
2298    }
2299    None
2300}
2301
2302fn env_flag_skip(arg: &str) -> Option<usize> {
2303    crate::deny::env_flag_skip(arg)
2304}
2305
2306/// Call `spawn` only when token or job setup succeeded.
2307pub fn spawn_after_setup<T>(
2308    setup: Result<T, KernelError>,
2309    spawn: impl FnOnce(T) -> Result<(KernelApply, ExitStatus), KernelError>,
2310) -> Result<(KernelApply, ExitStatus), KernelError> {
2311    spawn(setup?)
2312}
2313
2314/// Refuse a userspace-only inspect result on the spawn path.
2315///
2316/// [`KernelApply::RemountSkipped`] and [`KernelApply::WfpSkipped`] still
2317/// start the child. Hosts that require remount or WFP match those
2318/// variants themselves, or call [`require_dest_hide`].
2319pub fn require_applied(applied: KernelApply) -> Result<KernelApply, KernelError> {
2320    match applied {
2321        KernelApply::Applied | KernelApply::RemountSkipped | KernelApply::WfpSkipped => Ok(applied),
2322        KernelApply::UserspaceOnly => Err(KernelError::Apply(
2323            "kernel jail did not apply; child was not started".into(),
2324        )),
2325    }
2326}
2327
2328/// Refuse a spawn when Linux dest-deny remount did not hide in-tree dests.
2329///
2330/// [`KernelApply::WfpSkipped`] still starts the child (AppContainer is
2331/// the Windows net deny). [`KernelApply::RemountSkipped`] does not.
2332pub fn require_dest_hide(applied: KernelApply) -> Result<KernelApply, KernelError> {
2333    match applied {
2334        KernelApply::Applied | KernelApply::WfpSkipped => Ok(applied),
2335        KernelApply::RemountSkipped => Err(KernelError::Apply(
2336            "dest-deny remount unavailable (unshare, user-namespace id map, or private remount of /); child was not started".into(),
2337        )),
2338        KernelApply::UserspaceOnly => Err(KernelError::Apply(
2339            "kernel jail did not apply; child was not started".into(),
2340        )),
2341    }
2342}
2343
2344const DEST_DENY_WALK_LIMIT: usize = 65_536;
2345/// Duplicated from gc (feature-gated). Do not import `gc::CACHE_DIR_NAMES`.
2346const DEST_DENY_CACHE_DIR_NAMES: &[&str] =
2347    &["target", "node_modules", ".venv", "dist", "__pycache__"];
2348
2349/// Existing dest-deny files and glob directories under `workspace`,
2350/// including hardlink siblings. Each directory is read once per call,
2351/// not once per hardlinked name.
2352///
2353/// Does not apply the jail. Does not follow directory symlinks. Does
2354/// not descend `.git`. Cache trees are walked for dest-deny glob names
2355/// only (no hardlink sibling scan); non-deny rustc artifacts do not
2356/// count toward the entry cap. Walk failure or an entry cap is
2357/// [`KernelError::Root`].
2358pub fn collect_workspace_dest_denies(
2359    workspace: &Path,
2360    policy: &DenyPolicy,
2361) -> Result<Vec<DestDeny>, KernelError> {
2362    collect_workspace_dest_denies_limited(workspace, policy, DEST_DENY_WALK_LIMIT)
2363}
2364
2365/// Same as [`collect_workspace_dest_denies`] with a host-chosen entry cap.
2366pub fn collect_workspace_dest_denies_limited(
2367    workspace: &Path,
2368    policy: &DenyPolicy,
2369    limit: usize,
2370) -> Result<Vec<DestDeny>, KernelError> {
2371    #[cfg(unix)]
2372    let _hardlink_scans = crate::deny::HardlinkScanScope::new();
2373    let mut out = Vec::new();
2374    let mut remaining = limit;
2375    walk_dest_denies(
2376        workspace,
2377        Some(workspace),
2378        policy,
2379        &mut out,
2380        &mut remaining,
2381        limit,
2382    )?;
2383    Ok(out)
2384}
2385
2386fn dest_deny_walk_cap(dir: &Path, limit: usize) -> KernelError {
2387    KernelError::Root(format!(
2388        "dest-deny walk exceeded {limit} entries under {}",
2389        dir.display()
2390    ))
2391}
2392
2393fn dest_deny_walk_io(dir: &Path, err: std::io::Error) -> KernelError {
2394    KernelError::Root(format!("dest-deny walk {}: {err}", dir.display()))
2395}
2396
2397fn entry_file_name(path: &Path) -> &str {
2398    path.file_name().and_then(|n| n.to_str()).unwrap_or("")
2399}
2400
2401fn is_git_dir_name(name: &str) -> bool {
2402    name.eq_ignore_ascii_case(".git")
2403}
2404
2405fn is_dest_deny_cache_dir_name(name: &str) -> bool {
2406    DEST_DENY_CACHE_DIR_NAMES
2407        .iter()
2408        .any(|n| name.eq_ignore_ascii_case(n))
2409}
2410
2411/// Extra-root is a cache tree when any path component is a cache
2412/// dir name. Basename-only misses `--extra-root …/target/debug`.
2413fn extra_root_is_cache_tree(path: &Path) -> bool {
2414    path.components().any(|c| match c {
2415        std::path::Component::Normal(s) => is_dest_deny_cache_dir_name(&s.to_string_lossy()),
2416        _ => false,
2417    })
2418}
2419
2420/// Dest-deny a real directory. Directory symlinks are not followed
2421/// (`false`). Shared so every walk dest-denies the dir before recurse.
2422fn dest_deny_if_real_dir(
2423    path: &Path,
2424    ft: std::fs::FileType,
2425    policy: &DenyPolicy,
2426    out: &mut Vec<DestDeny>,
2427    glob_root: Option<&Path>,
2428) -> bool {
2429    if !ft.is_dir() || ft.is_symlink() {
2430        return false;
2431    }
2432    if let Some(deny) = dest_deny_at_root(path, path.display().to_string(), policy, glob_root) {
2433        push_dest_deny(out, deny);
2434    }
2435    true
2436}
2437
2438fn walk_dest_denies(
2439    dir: &Path,
2440    glob_root: Option<&Path>,
2441    policy: &DenyPolicy,
2442    out: &mut Vec<DestDeny>,
2443    remaining: &mut usize,
2444    limit: usize,
2445) -> Result<(), KernelError> {
2446    if *remaining == 0 {
2447        return Err(dest_deny_walk_cap(dir, limit));
2448    }
2449    let rd = std::fs::read_dir(dir).map_err(|e| dest_deny_walk_io(dir, e))?;
2450    for ent in rd {
2451        let ent = ent.map_err(|e| dest_deny_walk_io(dir, e))?;
2452        let path = ent.path();
2453        let name = entry_file_name(&path);
2454        if is_git_dir_name(name) {
2455            continue;
2456        }
2457        let ft = ent.file_type().map_err(|e| dest_deny_walk_io(&path, e))?;
2458        if is_dest_deny_cache_dir_name(name) && ft.is_dir() && !ft.is_symlink() {
2459            walk_cache_dest_denies(&path, policy, out, remaining, limit)?;
2460            continue;
2461        }
2462        if *remaining == 0 {
2463            return Err(dest_deny_walk_cap(dir, limit));
2464        }
2465        *remaining -= 1;
2466        if dest_deny_if_real_dir(&path, ft, policy, out, glob_root) {
2467            walk_dest_denies(&path, glob_root, policy, out, remaining, limit)?;
2468            continue;
2469        }
2470        if let Some(deny) = dest_deny_at_root(&path, path.display().to_string(), policy, glob_root)
2471        {
2472            push_dest_deny(out, deny);
2473        }
2474    }
2475    Ok(())
2476}
2477
2478fn is_system_read_extra(path: &Path) -> bool {
2479    system_read_dirs()
2480        .iter()
2481        .any(|d| path == d || path.starts_with(d))
2482}
2483
2484/// Dest-deny scan of `/tmp` (and host temp). Immediate dest-deny names
2485/// plus dest-deny directory names. Ordinary subdirectories are walked
2486/// for dest-deny names only (same as cache walk). Do not follow
2487/// directory symlinks. Do not walk every file under `/tmp`.
2488fn collect_system_temp_dest_denies(
2489    extra: &Path,
2490    policy: &DenyPolicy,
2491    out: &mut Vec<DestDeny>,
2492    remaining: &mut usize,
2493    limit: usize,
2494) -> Result<(), KernelError> {
2495    let rd = std::fs::read_dir(extra).map_err(|e| dest_deny_walk_io(extra, e))?;
2496    for ent in rd {
2497        let ent = ent.map_err(|e| dest_deny_walk_io(extra, e))?;
2498        let path = ent.path();
2499        let name = entry_file_name(&path);
2500        if is_git_dir_name(name) {
2501            continue;
2502        }
2503        let ft = ent.file_type().map_err(|e| dest_deny_walk_io(&path, e))?;
2504        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
2505            if is_dest_deny_dir_name(name) {
2506                walk_temp_dest_denies(&path, policy, out, remaining, limit)?;
2507            } else {
2508                collect_temp_dir_dest_names(&path, policy, out, remaining, limit)?;
2509            }
2510            continue;
2511        }
2512        if let Some(deny) = dest_deny_at(&path, path.display().to_string(), policy) {
2513            if *remaining == 0 {
2514                return Err(dest_deny_walk_cap(extra, limit));
2515            }
2516            *remaining -= 1;
2517            push_dest_deny(out, deny);
2518        }
2519    }
2520    Ok(())
2521}
2522
2523fn is_dest_deny_dir_name(name: &str) -> bool {
2524    matches!(
2525        name,
2526        ".ssh" | ".aws" | ".kube" | ".gnupg" | ".docker" | "secrets" | "credentials" | "gateway"
2527    )
2528}
2529
2530fn is_system_temp_root(path: &Path) -> bool {
2531    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
2532        return false;
2533    };
2534    if !name.eq_ignore_ascii_case("tmp") && !name.eq_ignore_ascii_case("temp") {
2535        return false;
2536    }
2537    let Some(parent) = path.parent() else {
2538        return true;
2539    };
2540    parent == Path::new("/")
2541        || parent == Path::new("\\")
2542        || parent.ends_with("private")
2543        || parent.ends_with("var")
2544}
2545
2546/// One extra level under an ordinary `/tmp` subdirectory. Catches
2547/// `/tmp/proj/.env` without walking `/tmp/proj/node_modules`. Dest-deny
2548/// directory names still recurse. Skip unreadable entries.
2549fn collect_temp_dir_dest_names(
2550    dir: &Path,
2551    policy: &DenyPolicy,
2552    out: &mut Vec<DestDeny>,
2553    remaining: &mut usize,
2554    limit: usize,
2555) -> Result<(), KernelError> {
2556    let rd = match std::fs::read_dir(dir) {
2557        Ok(rd) => rd,
2558        Err(_) => return Ok(()),
2559    };
2560    for ent in rd {
2561        let ent = match ent {
2562            Ok(ent) => ent,
2563            Err(_) => continue,
2564        };
2565        let path = ent.path();
2566        let name = entry_file_name(&path);
2567        if is_git_dir_name(name) {
2568            continue;
2569        }
2570        let ft = match ent.file_type() {
2571            Ok(ft) => ft,
2572            Err(_) => continue,
2573        };
2574        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
2575            if is_dest_deny_dir_name(name) {
2576                walk_temp_dest_denies(&path, policy, out, remaining, limit)?;
2577            }
2578            continue;
2579        }
2580        if ft.is_dir() {
2581            continue;
2582        }
2583        if let Some(deny) = dest_deny_at(&path, path.display().to_string(), policy) {
2584            if *remaining == 0 {
2585                return Err(dest_deny_walk_cap(dir, limit));
2586            }
2587            *remaining -= 1;
2588            push_dest_deny(out, deny);
2589        }
2590    }
2591    Ok(())
2592}
2593
2594/// Like [`walk_cache_dest_denies`], but skip unreadable dirs. `/tmp`
2595/// has other-user 0700 trees; those are not a dest-deny walk failure.
2596fn walk_temp_dest_denies(
2597    dir: &Path,
2598    policy: &DenyPolicy,
2599    out: &mut Vec<DestDeny>,
2600    remaining: &mut usize,
2601    limit: usize,
2602) -> Result<(), KernelError> {
2603    let rd = match std::fs::read_dir(dir) {
2604        Ok(rd) => rd,
2605        Err(_) => return Ok(()),
2606    };
2607    for ent in rd {
2608        let ent = match ent {
2609            Ok(ent) => ent,
2610            Err(_) => continue,
2611        };
2612        let path = ent.path();
2613        let name = entry_file_name(&path);
2614        if is_git_dir_name(name) {
2615            continue;
2616        }
2617        let ft = match ent.file_type() {
2618            Ok(ft) => ft,
2619            Err(_) => continue,
2620        };
2621        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
2622            walk_temp_dest_denies(&path, policy, out, remaining, limit)?;
2623            continue;
2624        }
2625        if let Some(deny) = dest_deny_at(&path, path.display().to_string(), policy) {
2626            if *remaining == 0 {
2627                return Err(dest_deny_walk_cap(dir, limit));
2628            }
2629            *remaining -= 1;
2630            push_dest_deny(out, deny);
2631        }
2632    }
2633    Ok(())
2634}
2635
2636/// Walk a cache tree for dest-deny glob names only. Non-deny files are
2637/// not charged to the entry cap. Does not follow directory symlinks.
2638/// Does not canonicalize or hardlink-scan rustc artifacts (`nlink` in
2639/// `target/debug/deps` is O(entries^2) and stalls `run --root` on a
2640/// populated cargo tree).
2641fn walk_cache_dest_denies(
2642    dir: &Path,
2643    policy: &DenyPolicy,
2644    out: &mut Vec<DestDeny>,
2645    remaining: &mut usize,
2646    limit: usize,
2647) -> Result<(), KernelError> {
2648    let rd = std::fs::read_dir(dir).map_err(|e| dest_deny_walk_io(dir, e))?;
2649    for ent in rd {
2650        let ent = ent.map_err(|e| dest_deny_walk_io(dir, e))?;
2651        let path = ent.path();
2652        let name = entry_file_name(&path);
2653        if is_git_dir_name(name) {
2654            continue;
2655        }
2656        let ft = ent.file_type().map_err(|e| dest_deny_walk_io(&path, e))?;
2657        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
2658            walk_cache_dest_denies(&path, policy, out, remaining, limit)?;
2659            continue;
2660        }
2661        if let Some(deny) = dest_deny_glob_only(&path, path.display().to_string(), policy) {
2662            if *remaining == 0 {
2663                return Err(dest_deny_walk_cap(dir, limit));
2664            }
2665            *remaining -= 1;
2666            push_dest_deny(out, deny);
2667        }
2668    }
2669    Ok(())
2670}
2671
2672fn dest_deny_from_path(path: &Path, policy: &DenyPolicy) -> DestDeny {
2673    dest_deny_at(path, path.display().to_string(), policy).unwrap_or(DestDeny {
2674        kind: DestDenyKind::DenyGlob,
2675        path: path.to_path_buf(),
2676        display: path.display().to_string(),
2677        matched: None,
2678    })
2679}
2680
2681fn push_dest_deny(out: &mut Vec<DestDeny>, deny: DestDeny) {
2682    if out
2683        .iter()
2684        .any(|d| d.path == deny.path && d.kind == deny.kind)
2685    {
2686        return;
2687    }
2688    out.push(deny);
2689}
2690
2691/// Seatbelt dest-deny of workspace secrets. Platform rules emit last so
2692/// they win over the workspace ReadWrite allow (nono last-rule-wins).
2693/// Do not use `require-not` inside deny (invalid SBPL).
2694#[cfg(target_os = "macos")]
2695fn add_macos_dest_deny_rules(
2696    caps: &mut nono::CapabilitySet,
2697    denies: &[DestDeny],
2698    rw_roots: &[&Path],
2699    globs: &[String],
2700) -> Result<(), KernelError> {
2701    for deny in denies {
2702        for path in dest_deny_rule_paths(&deny.path) {
2703            let Some(raw) = path.to_str() else {
2704                return Err(KernelError::Apply(format!(
2705                    "dest-deny path is not UTF-8: {}",
2706                    path.display()
2707                )));
2708            };
2709            let escaped = escape_sbpl_literal(raw);
2710            let filter = if path.is_dir() {
2711                format!("subpath \"{escaped}\"")
2712            } else {
2713                format!("literal \"{escaped}\"")
2714            };
2715            for action in macos_dest_deny_actions() {
2716                let rule = format!("(deny {action} ({filter}))");
2717                caps.add_platform_rule(&rule)
2718                    .map_err(|e| KernelError::Apply(e.to_string()))?;
2719            }
2720        }
2721    }
2722    for root in rw_roots {
2723        add_macos_post_create_rules(caps, root, globs)?;
2724    }
2725    Ok(())
2726}
2727
2728/// Name-based denies so a child `touch .env` then `cat .env` is still blocked.
2729#[cfg(target_os = "macos")]
2730fn add_macos_post_create_rules(
2731    caps: &mut nono::CapabilitySet,
2732    workspace: &Path,
2733    globs: &[String],
2734) -> Result<(), KernelError> {
2735    for workspace in dest_deny_rule_paths(workspace) {
2736        let Some(raw) = workspace.to_str() else {
2737            return Err(KernelError::Apply(format!(
2738                "workspace path is not UTF-8: {}",
2739                workspace.display()
2740            )));
2741        };
2742        let prefix = escape_regex_literal(raw);
2743        // One filter only. Combined (subpath)(regex) denied the whole tree.
2744        let mut regexes = macos_post_create_env_regexes(&prefix);
2745        for glob in globs {
2746            // Default `**/.env.*` is replaced by the template-aware segment
2747            // regexes. Any other glob, including a custom dotenv pattern,
2748            // still becomes a Seatbelt regex.
2749            if crate::deny::is_default_env_star_glob(glob) {
2750                continue;
2751            }
2752            if let Some(re) = crate::dest_deny_glob_regex(&prefix, glob) {
2753                regexes.push(re);
2754            }
2755        }
2756        for regex in regexes {
2757            let regex = escape_sbpl_literal(&regex);
2758            for action in macos_dest_deny_actions() {
2759                let rule = format!("(deny {action} (regex \"{regex}\"))");
2760                caps.add_platform_rule(&rule)
2761                    .map_err(|e| KernelError::Apply(e.to_string()))?;
2762            }
2763        }
2764    }
2765    Ok(())
2766}
2767
2768/// As-given path, canonicalize, and `/private` firmlink aliases.
2769/// Used for Seatbelt literals and Linux remount dests under `/tmp` /
2770/// `/var` / `/etc`.
2771#[cfg(any(unix, test))]
2772fn dest_deny_rule_paths(path: &Path) -> Vec<PathBuf> {
2773    let mut out = vec![path.to_path_buf()];
2774    if let Ok(canon) = dunce::canonicalize(path)
2775        && canon != path
2776    {
2777        out.push(canon);
2778    }
2779    let aliases: Vec<PathBuf> = out.iter().filter_map(|p| firmlink_alias(p)).collect();
2780    for alias in aliases {
2781        if !out.iter().any(|p| p == &alias) {
2782            out.push(alias);
2783        }
2784    }
2785    out
2786}
2787
2788/// `/tmp` ↔ `/private/tmp`, `/var` ↔ `/private/var`, `/etc` ↔ `/private/etc`.
2789#[cfg(any(unix, test))]
2790fn firmlink_alias(path: &Path) -> Option<PathBuf> {
2791    let raw = path.to_str()?;
2792    const PAIRS: [(&str, &str); 3] = [
2793        ("/tmp", "/private/tmp"),
2794        ("/var", "/private/var"),
2795        ("/etc", "/private/etc"),
2796    ];
2797    for (public, private) in PAIRS {
2798        if raw == public || raw.starts_with(&format!("{public}/")) {
2799            return Some(PathBuf::from(format!(
2800                "{private}{}",
2801                raw.strip_prefix(public).unwrap_or("")
2802            )));
2803        }
2804        if raw == private || raw.starts_with(&format!("{private}/")) {
2805            return Some(PathBuf::from(format!(
2806                "{public}{}",
2807                raw.strip_prefix(private).unwrap_or("")
2808            )));
2809        }
2810    }
2811    None
2812}
2813
2814#[cfg(target_os = "macos")]
2815fn macos_post_create_env_regexes(prefix: &str) -> Vec<String> {
2816    let star = env_star_segment();
2817    vec![
2818        format!("^{prefix}/[.][Ee][Nn][Vv]$"),
2819        format!("^{prefix}/.*/[.][Ee][Nn][Vv]$"),
2820        format!("^{prefix}/{star}$"),
2821        format!("^{prefix}/.*/{star}$"),
2822    ]
2823}
2824
2825/// One path segment: `.env` or `.env.<tail>` where the tail's last
2826/// dot-segment is not exactly `example`, `sample`, or `template`.
2827#[cfg(target_os = "macos")]
2828fn env_star_segment() -> String {
2829    let last = format!(
2830        "({one}|{two}|{three}|{four}|{five}|{sample}|{example}|{template}|{nine})",
2831        one = "[^.]",
2832        two = "[^.][^.]?",
2833        three = "[^.][^.][^.]?",
2834        four = "[^.][^.][^.][^.]?",
2835        five = "[^.][^.][^.][^.][^.]?",
2836        sample = not_exact_segment("sample"),
2837        example = not_exact_segment("example"),
2838        template = not_exact_segment("template"),
2839        nine = "[^.][^.][^.][^.][^.][^.][^.][^.][^.][^.]*",
2840    );
2841    format!(
2842        "[.][Ee][Nn][Vv]([.]([^.]{plus}\\.)*{last_seg})?",
2843        plus = "+",
2844        last_seg = last
2845    )
2846}
2847
2848#[cfg(target_os = "macos")]
2849fn not_exact_segment(word: &str) -> String {
2850    let mut alts = Vec::new();
2851    let chars: Vec<char> = word.chars().collect();
2852    for (i, ch) in chars.iter().enumerate() {
2853        let mut part = String::new();
2854        for prev in &chars[..i] {
2855            part.push_str(&letter_class(*prev));
2856        }
2857        part.push_str(&neg_letter(*ch));
2858        for _ in 0..(chars.len() - i - 1) {
2859            part.push_str("[^.]");
2860        }
2861        alts.push(part);
2862    }
2863    format!("({})", alts.join("|"))
2864}
2865
2866#[cfg(target_os = "macos")]
2867fn letter_class(ch: char) -> String {
2868    format!("[{}{}]", ch.to_ascii_uppercase(), ch.to_ascii_lowercase())
2869}
2870
2871#[cfg(target_os = "macos")]
2872fn neg_letter(ch: char) -> String {
2873    format!("[^{}{}.]", ch.to_ascii_uppercase(), ch.to_ascii_lowercase())
2874}
2875
2876/// File operations plus `network-outbound`. Seatbelt treats `connect(2)`
2877/// to a Unix socket as network, so a file deny alone still allows it.
2878/// `--net` must not open a socket under a dest-denied path.
2879#[cfg(target_os = "macos")]
2880fn macos_dest_deny_actions() -> &'static [&'static str] {
2881    &[
2882        "file-read*",
2883        "file-write*",
2884        "file-write-data",
2885        "file-write-create",
2886        "file-write-unlink",
2887        "file-write-mode",
2888        "file-write-owner",
2889        "network-outbound",
2890    ]
2891}
2892
2893/// Child-only hardening after remount, before Landlock and exec.
2894/// `RLIMIT_CORE=0` survives exec. Linux dumpable does not.
2895#[cfg(unix)]
2896fn apply_child_hardening() -> std::io::Result<()> {
2897    #[cfg(unix)]
2898    {
2899        let zero = libc::rlimit {
2900            rlim_cur: 0,
2901            rlim_max: 0,
2902        };
2903        // SAFETY: RLIMIT_CORE on this thread, which is the forked child.
2904        if unsafe { libc::setrlimit(libc::RLIMIT_CORE, &zero) } != 0 {
2905            return Err(std::io::Error::last_os_error());
2906        }
2907    }
2908    #[cfg(target_os = "linux")]
2909    {
2910        // SAFETY: PR_SET_DUMPABLE on this thread, the forked child.
2911        if unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) } != 0 {
2912            return Err(std::io::Error::last_os_error());
2913        }
2914    }
2915    #[cfg(target_os = "macos")]
2916    {
2917        const PT_DENY_ATTACH: libc::c_int = 31;
2918        // SAFETY: ptrace PT_DENY_ATTACH on this process, the forked child.
2919        if unsafe { libc::ptrace(PT_DENY_ATTACH, 0, std::ptr::null_mut(), 0) } != 0 {
2920            return Err(std::io::Error::last_os_error());
2921        }
2922    }
2923    Ok(())
2924}
2925
2926#[cfg(target_os = "macos")]
2927fn escape_sbpl_literal(s: &str) -> String {
2928    s.replace('\\', "\\\\").replace('"', "\\\"")
2929}
2930
2931#[cfg(target_os = "macos")]
2932fn escape_regex_literal(s: &str) -> String {
2933    let mut out = String::with_capacity(s.len());
2934    for c in s.chars() {
2935        if matches!(
2936            c,
2937            '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '^' | '$'
2938        ) {
2939            out.push('\\');
2940        }
2941        out.push(c);
2942    }
2943    out
2944}
2945
2946fn refuse_home_workspace(workspace: &Path) -> Result<(), KernelError> {
2947    let resolved = match std::fs::canonicalize(workspace) {
2948        Ok(p) => p,
2949        Err(_) => return Ok(()),
2950    };
2951    if crate::guard::is_user_home_dir(&resolved) {
2952        return Err(KernelError::Home(resolved));
2953    }
2954    Ok(())
2955}
2956
2957fn system_read_dirs() -> Vec<PathBuf> {
2958    #[cfg(unix)]
2959    {
2960        [
2961            "/usr",
2962            "/bin",
2963            "/lib",
2964            "/lib64",
2965            "/sbin",
2966            "/System",
2967            "/Library",
2968            "/dev",
2969            "/proc",
2970            "/etc",
2971            "/opt/homebrew",
2972            "/usr/local",
2973            "/var/select",
2974            "/private/var/select",
2975        ]
2976        .into_iter()
2977        .map(PathBuf::from)
2978        .collect()
2979    }
2980    #[cfg(windows)]
2981    {
2982        let mut dirs = Vec::new();
2983        if let Some(root) = std::env::var_os("SystemRoot") {
2984            let root = PathBuf::from(root);
2985            dirs.push(root.join("System32"));
2986            dirs.push(root);
2987        }
2988        if let Some(pf) = std::env::var_os("ProgramFiles") {
2989            dirs.push(PathBuf::from(pf));
2990        }
2991        dirs
2992    }
2993    #[cfg(not(any(unix, windows)))]
2994    {
2995        Vec::new()
2996    }
2997}
2998
2999fn append_extra_dest_denies(
3000    extra: &Path,
3001    policy: &DenyPolicy,
3002    dest_denies: &mut Vec<DestDeny>,
3003    remaining: &mut usize,
3004) -> Result<(), KernelError> {
3005    #[cfg(unix)]
3006    let _hardlink_scans = crate::deny::HardlinkScanScope::new();
3007    if is_system_read_extra(extra) {
3008        return Ok(());
3009    }
3010    if is_system_temp_root(extra) {
3011        collect_system_temp_dest_denies(
3012            extra,
3013            policy,
3014            dest_denies,
3015            remaining,
3016            DEST_DENY_WALK_LIMIT,
3017        )?;
3018        return Ok(());
3019    }
3020    if extra_root_is_cache_tree(extra) {
3021        walk_cache_dest_denies(extra, policy, dest_denies, remaining, DEST_DENY_WALK_LIMIT)?;
3022        return Ok(());
3023    }
3024    walk_dest_denies(
3025        extra,
3026        None,
3027        policy,
3028        dest_denies,
3029        remaining,
3030        DEST_DENY_WALK_LIMIT,
3031    )
3032}
3033
3034fn add_read_grant(grants: &mut Vec<KernelGrant>, path: &Path) -> Result<(), KernelError> {
3035    let resolved = canonicalize_dir(path)?;
3036    if crate::guard::is_user_home_dir(&resolved) {
3037        return Err(KernelError::Home(resolved));
3038    }
3039    if !is_fs_root(path) && path != resolved.as_path() {
3040        push_grant(grants, path.to_path_buf(), KernelAccess::Read);
3041    }
3042    if let Some(alias) = macos_public_alias(&resolved)
3043        && !is_fs_root(&alias)
3044        && alias != resolved
3045    {
3046        push_grant(grants, alias, KernelAccess::Read);
3047    }
3048    push_grant(grants, resolved, KernelAccess::Read);
3049    Ok(())
3050}
3051
3052fn add_rw(grants: &mut Vec<KernelGrant>, path: &Path) -> Result<(), KernelError> {
3053    let resolved = canonicalize_dir(path)?;
3054    if crate::guard::is_user_home_dir(&resolved) {
3055        return Err(KernelError::Home(resolved));
3056    }
3057    // Grant the path as given so symlink lookups (`/tmp` -> `/private/tmp`) work.
3058    if !is_fs_root(path) && path != resolved.as_path() {
3059        push_grant(grants, path.to_path_buf(), KernelAccess::ReadWrite);
3060    }
3061    // CLI resolve_workspace_root returns canon only. On macOS, `/tmp/ws`
3062    // and `/var/folders/...` still appear on argv as the unprefixed form.
3063    if let Some(alias) = macos_public_alias(&resolved)
3064        && !is_fs_root(&alias)
3065        && alias != resolved
3066    {
3067        push_grant(grants, alias, KernelAccess::ReadWrite);
3068    }
3069    push_grant(grants, resolved, KernelAccess::ReadWrite);
3070    Ok(())
3071}
3072
3073#[cfg(target_os = "macos")]
3074fn macos_public_alias(path: &Path) -> Option<PathBuf> {
3075    let s = path.to_str()?;
3076    s.strip_prefix("/private/")
3077        .map(|rest| PathBuf::from(format!("/{rest}")))
3078}
3079
3080#[cfg(not(target_os = "macos"))]
3081fn macos_public_alias(_path: &Path) -> Option<PathBuf> {
3082    None
3083}
3084
3085fn add_read_if_dir(grants: &mut Vec<KernelGrant>, path: &Path) {
3086    let Ok(meta) = std::fs::metadata(path) else {
3087        return;
3088    };
3089    if !meta.is_dir() {
3090        return;
3091    }
3092    let resolved = std::fs::canonicalize(path).ok();
3093    if resolved.as_ref().is_some_and(|p| is_fs_root(p)) {
3094        return;
3095    }
3096    // Grant the path as given so symlink lookups (`/etc` -> `/private/etc`) work.
3097    if !is_fs_root(path) {
3098        push_grant(grants, path.to_path_buf(), KernelAccess::Read);
3099    }
3100    if let Some(resolved) = resolved {
3101        push_grant(grants, resolved, KernelAccess::Read);
3102    }
3103}
3104
3105fn push_grant(grants: &mut Vec<KernelGrant>, path: PathBuf, access: KernelAccess) {
3106    if let Some(existing) = grants.iter_mut().find(|g| g.path == path) {
3107        if access == KernelAccess::ReadWrite {
3108            existing.access = KernelAccess::ReadWrite;
3109        }
3110        return;
3111    }
3112    grants.push(KernelGrant { path, access });
3113}
3114
3115fn canonicalize_dir(path: &Path) -> Result<PathBuf, KernelError> {
3116    let resolved = std::fs::canonicalize(path)
3117        .map_err(|e| KernelError::Root(format!("{}: {e}", path.display())))?;
3118    if !resolved.is_dir() {
3119        return Err(KernelError::Root(format!(
3120            "{} is not a directory",
3121            path.display()
3122        )));
3123    }
3124    if is_fs_root(&resolved) {
3125        return Err(KernelError::FsRoot(resolved));
3126    }
3127    Ok(resolved)
3128}
3129
3130fn is_fs_root(path: &Path) -> bool {
3131    match path.parent() {
3132        None => true,
3133        Some(parent) => parent.as_os_str().is_empty(),
3134    }
3135}
3136
3137#[cfg(all(test, unix))]
3138mod timeout_deadline_tests {
3139    use std::time::Duration;
3140
3141    use super::{KernelError, timeout_deadline};
3142
3143    #[test]
3144    fn one_second_fits() {
3145        assert!(timeout_deadline(Duration::from_secs(1)).is_ok());
3146    }
3147
3148    #[test]
3149    fn max_seconds_does_not_fit() {
3150        let err = timeout_deadline(Duration::from_secs(u64::MAX)).expect_err("overflow");
3151        assert!(
3152            matches!(err, KernelError::Apply(ref msg) if msg.contains("does not fit")),
3153            "{err:?}"
3154        );
3155    }
3156}
3157
3158#[cfg(test)]
3159mod child_env_pairs_tests {
3160    use super::{child_env_pairs, is_denied_child_env};
3161    use std::ffi::OsString;
3162    use std::process::Command;
3163
3164    fn inherited_marker() -> Option<(OsString, OsString)> {
3165        std::env::vars_os().find(|(name, value)| {
3166            !value.is_empty()
3167                && !is_denied_child_env(name)
3168                && !name.to_string_lossy().eq_ignore_ascii_case("PATH")
3169                && !name.to_string_lossy().eq_ignore_ascii_case("SystemRoot")
3170        })
3171    }
3172
3173    fn has_key(pairs: &[(OsString, OsString)], key: &str) -> bool {
3174        pairs
3175            .iter()
3176            .any(|(name, _)| name.to_string_lossy().eq_ignore_ascii_case(key))
3177    }
3178
3179    #[test]
3180    fn env_clear_drops_inherited_names_and_keeps_explicit_inserts() {
3181        let Some((key, _)) = inherited_marker() else {
3182            return;
3183        };
3184        let name = key.to_string_lossy().into_owned();
3185        let mut cmd = Command::new("cmd");
3186        cmd.env_clear();
3187        if let Some(path) = std::env::var_os("PATH") {
3188            cmd.env("PATH", path);
3189        }
3190        cmd.env("CUSTOM_API_KEY", "kept-explicit");
3191        cmd.env("LD_PRELOAD", "/tmp/nope");
3192        let pairs = child_env_pairs(&mut cmd);
3193        assert!(!has_key(&pairs, &name), "{name} stayed after env_clear");
3194        assert!(
3195            !has_key(&pairs, "SystemRoot"),
3196            "SystemRoot stayed without being set again"
3197        );
3198        if std::env::var_os("PATH").is_some() {
3199            assert!(has_key(&pairs, "PATH"), "explicit PATH was dropped");
3200        }
3201        assert!(
3202            pairs
3203                .iter()
3204                .any(|(k, v)| k == "CUSTOM_API_KEY" && v == "kept-explicit"),
3205            "explicit CUSTOM_API_KEY was dropped after env_clear"
3206        );
3207        assert!(
3208            !has_key(&pairs, "LD_PRELOAD"),
3209            "loader must stay dropped after env_clear"
3210        );
3211    }
3212
3213    #[test]
3214    fn inherited_name_stays_without_env_clear() {
3215        let Some(path) = std::env::var_os("PATH") else {
3216            return;
3217        };
3218        let mut cmd = Command::new("cmd");
3219        let pairs = child_env_pairs(&mut cmd);
3220        assert!(
3221            pairs.iter().any(
3222                |(key, value)| key.to_string_lossy().eq_ignore_ascii_case("PATH") && value == &path
3223            ),
3224            "PATH was dropped from an inheriting command"
3225        );
3226    }
3227}
3228
3229#[cfg(test)]
3230mod noprofile_tests {
3231    use super::with_bash_noprofile;
3232
3233    #[test]
3234    fn env_after_unknown_prefix_inserts_after_bash() {
3235        let (_got, args) = with_bash_noprofile("watch", ["env", "bash", "-c", "true"]);
3236        assert_eq!(args, ["env", "bash", "--noprofile", "--norc", "-c", "true"]);
3237        let (_got, args) =
3238            with_bash_noprofile("watch", ["env", "BASH_ENV=.env", "bash", "-c", "true"]);
3239        assert_eq!(args, ["env", "bash", "--noprofile", "--norc", "-c", "true"]);
3240        let (_got, args) = with_bash_noprofile("watch", ["bash", "-c", "true"]);
3241        assert_eq!(
3242            args,
3243            ["bash", "-c", "true"],
3244            "watch bash without env must not invent noprofile"
3245        );
3246    }
3247}
3248
3249#[cfg(test)]
3250mod combine_spawn_restore_tests {
3251    #[cfg(target_os = "macos")]
3252    use super::macos_post_create_env_regexes;
3253    use super::{
3254        KernelApply, KernelError, WFP_ERROR_ACCESS_DENIED, combine_spawn_restore,
3255        dest_deny_rule_paths, process_jail, require_applied, require_dest_hide,
3256        wfp_skip_access_denied,
3257    };
3258    use std::path::Path;
3259    use std::process::ExitStatus;
3260
3261    fn status(code: i32) -> ExitStatus {
3262        #[cfg(unix)]
3263        {
3264            use std::os::unix::process::ExitStatusExt;
3265            ExitStatus::from_raw(code << 8)
3266        }
3267        #[cfg(windows)]
3268        {
3269            use std::os::windows::process::ExitStatusExt;
3270            ExitStatus::from_raw(code as u32)
3271        }
3272    }
3273
3274    #[test]
3275    fn timeout_wins_over_restore_failure() {
3276        let err = combine_spawn_restore(
3277            Err(KernelError::Timeout),
3278            Err(KernelError::Apply("restore DACL failed (win32 5)".into())),
3279        )
3280        .expect_err("timeout must stay timeout");
3281        assert!(
3282            matches!(err, KernelError::Timeout),
3283            "Timeout plus restore failure must stay Timeout, got {err}"
3284        );
3285    }
3286
3287    #[test]
3288    fn spawn_apply_keeps_apply_and_names_restore() {
3289        let err = combine_spawn_restore(
3290            Err(KernelError::Apply(
3291                "CreateProcessAsUserW failed (win32 5)".into(),
3292            )),
3293            Err(KernelError::Apply("restore DACL failed (win32 5)".into())),
3294        )
3295        .expect_err("combined apply");
3296        let KernelError::Apply(msg) = err else {
3297            panic!("expected Apply, got {err}");
3298        };
3299        assert!(
3300            msg.contains("CreateProcessAsUserW"),
3301            "spawn Apply must not be dropped: {msg}"
3302        );
3303        assert!(
3304            msg.contains("restore DACL"),
3305            "restore failure must be named: {msg}"
3306        );
3307    }
3308
3309    #[test]
3310    fn successful_child_plus_restore_failure_names_exit() {
3311        let err = combine_spawn_restore(
3312            Ok((KernelApply::Applied, status(0))),
3313            Err(KernelError::Apply("restore DACL failed (win32 5)".into())),
3314        )
3315        .expect_err("restore after success");
3316        let KernelError::Restore(msg) = err else {
3317            panic!("expected Restore, got {err}");
3318        };
3319        assert!(
3320            msg.contains("child exited 0"),
3321            "successful child must name exit: {msg}"
3322        );
3323        assert!(
3324            msg.contains("restore DACL"),
3325            "restore failure must be named: {msg}"
3326        );
3327    }
3328
3329    #[test]
3330    fn wfp_access_denied_is_skip_and_other_codes_are_not() {
3331        assert!(wfp_skip_access_denied(WFP_ERROR_ACCESS_DENIED));
3332        assert!(wfp_skip_access_denied(5));
3333        assert!(!wfp_skip_access_denied(0));
3334        assert!(!wfp_skip_access_denied(2));
3335        assert!(!wfp_skip_access_denied(87));
3336    }
3337
3338    #[cfg(target_os = "macos")]
3339    #[test]
3340    fn macos_post_create_env_regexes_match_dot_env_any_case() {
3341        let got = macos_post_create_env_regexes("/ws");
3342        assert_eq!(got.len(), 4, "{got:?}");
3343        assert!(got[0].contains("[.][Ee][Nn][Vv]$"), "{got:?}");
3344        assert!(got[2].contains("[.][Ee][Nn][Vv]"), "{got:?}");
3345        assert!(
3346            !got[2].contains("[.].*$"),
3347            "star regex must not be an open .env.* : {got:?}"
3348        );
3349        assert_env_star_regex_skips_templates(&got[2]);
3350    }
3351
3352    #[cfg(target_os = "macos")]
3353    fn assert_env_star_regex_skips_templates(star_anchored: &str) {
3354        let mut re = unsafe { std::mem::zeroed::<libc::regex_t>() };
3355        let c = std::ffi::CString::new(star_anchored).expect("regex");
3356        let rc =
3357            unsafe { libc::regcomp(&mut re, c.as_ptr(), libc::REG_EXTENDED | libc::REG_NOSUB) };
3358        assert_eq!(rc, 0, "seatbelt env-star regex must compile");
3359        let check = |name: &str, want: bool| {
3360            let path = std::ffi::CString::new(format!("/ws/{name}")).expect("path");
3361            let hit = unsafe { libc::regexec(&re, path.as_ptr(), 0, std::ptr::null_mut(), 0) } == 0;
3362            assert_eq!(
3363                hit, want,
3364                "{name} match={hit} want={want} re={star_anchored}"
3365            );
3366        };
3367        check(".env.local", true);
3368        check(".env.production", true);
3369        check(".ENV.LOCAL", true);
3370        check(".env.example", false);
3371        check(".env.EXAMPLE", false);
3372        check(".env.sample", false);
3373        check(".env.template", false);
3374        check(".env.local.example", false);
3375        check("readme.md", false);
3376        unsafe { libc::regfree(&mut re) };
3377    }
3378
3379    #[test]
3380    fn dest_deny_rule_paths_emits_firmlink_aliases() {
3381        let got = dest_deny_rule_paths(Path::new("/tmp/.env"));
3382        assert!(
3383            got.iter().any(|p| p == Path::new("/tmp/.env")),
3384            "as-given /tmp/.env must stay: {got:?}"
3385        );
3386        assert!(
3387            got.iter().any(|p| p == Path::new("/private/tmp/.env")),
3388            "/tmp/.env must also deny /private/tmp/.env: {got:?}"
3389        );
3390        let got = dest_deny_rule_paths(Path::new("/private/var/folders/x/.env"));
3391        assert!(
3392            got.iter().any(|p| p == Path::new("/var/folders/x/.env")),
3393            "/private/var must also deny /var: {got:?}"
3394        );
3395        let got = dest_deny_rule_paths(Path::new("/etc/ssh/ssh_host_rsa_key"));
3396        assert!(
3397            got.iter()
3398                .any(|p| p == Path::new("/private/etc/ssh/ssh_host_rsa_key")),
3399            "/etc must also deny /private/etc: {got:?}"
3400        );
3401    }
3402
3403    #[test]
3404    fn require_applied_accepts_remount_and_wfp_skip() {
3405        assert_eq!(
3406            require_applied(KernelApply::RemountSkipped).expect("remount skip"),
3407            KernelApply::RemountSkipped
3408        );
3409        assert_eq!(
3410            require_applied(KernelApply::WfpSkipped).expect("wfp skip"),
3411            KernelApply::WfpSkipped
3412        );
3413    }
3414
3415    #[test]
3416    fn require_dest_hide_rejects_remount_skip() {
3417        let err = require_dest_hide(KernelApply::RemountSkipped).expect_err("remount skip");
3418        match err {
3419            KernelError::Apply(msg) => {
3420                assert!(
3421                    msg.contains("remount unavailable"),
3422                    "error must name remount: {msg}"
3423                );
3424                assert!(
3425                    msg.contains("child was not started"),
3426                    "error must say child was not started: {msg}"
3427                );
3428                for phrase in ["unshare", "user-namespace id map", "private remount of /"] {
3429                    assert!(
3430                        msg.contains(phrase),
3431                        "remount refusal must name {phrase}: {msg}"
3432                    );
3433                }
3434            }
3435            other => panic!("expected Apply, got {other}"),
3436        }
3437        assert_eq!(
3438            require_dest_hide(KernelApply::Applied).expect("Applied"),
3439            KernelApply::Applied
3440        );
3441        assert_eq!(
3442            require_dest_hide(KernelApply::WfpSkipped).expect("wfp skip"),
3443            KernelApply::WfpSkipped
3444        );
3445    }
3446
3447    #[test]
3448    fn extra_root_temp_collects_nested_dest_deny_names() {
3449        let ws = tempfile::TempDir::new().expect("ws");
3450        let extra = tempfile::TempDir::new().expect("extra");
3451        let tmp = extra.path().join("private").join("tmp");
3452        let proj = tmp.join("proj");
3453        std::fs::create_dir_all(&proj).expect("proj");
3454        std::fs::write(proj.join(".env"), "SECRET=1\n").expect(".env");
3455        std::fs::write(tmp.join("readme.md"), "ok\n").expect("readme");
3456        let policy = process_jail(ws.path(), [tmp.as_path()]).expect("jail");
3457        assert!(
3458            policy
3459                .dest_denies()
3460                .iter()
3461                .any(|d| d.path.ends_with(Path::new("proj/.env"))
3462                    || d.path.ends_with(Path::new("proj\\.env"))),
3463            "nested extra-root /tmp dest-deny name must be collected: {:?}",
3464            policy.dest_denies()
3465        );
3466        assert!(
3467            !policy
3468                .dest_denies()
3469                .iter()
3470                .any(|d| d.path.ends_with("readme.md")),
3471            "non-deny extra-root file must not be collected"
3472        );
3473    }
3474
3475    #[test]
3476    fn extra_root_temp_collects_ssh_directory() {
3477        let ws = tempfile::TempDir::new().expect("ws");
3478        let extra = tempfile::TempDir::new().expect("extra");
3479        let tmp = extra.path().join("private").join("tmp");
3480        let proj = tmp.join("proj");
3481        let ssh = proj.join(".ssh");
3482        std::fs::create_dir_all(&ssh).expect("proj/.ssh");
3483        std::fs::write(ssh.join("id_ed25519"), "SECRET=1\n").expect("key");
3484        let policy = process_jail(ws.path(), [tmp.as_path()]).expect("jail");
3485        assert!(
3486            policy.dest_denies().iter().any(|d| d.path == ssh),
3487            "extra-root /tmp proj/.ssh directory must dest-deny: {:?}",
3488            policy.dest_denies()
3489        );
3490        assert!(
3491            policy
3492                .dest_denies()
3493                .iter()
3494                .any(|d| d.path == ssh.join("id_ed25519")),
3495            "nested extra-root .ssh file must still dest-deny: {:?}",
3496            policy.dest_denies()
3497        );
3498    }
3499}
3500
3501#[cfg(test)]
3502mod doctor_facts_tests {
3503    use super::{DoctorFacts, doctor_fails};
3504
3505    fn facts(
3506        kernel_supported: bool,
3507        remount_available: Option<bool>,
3508        wfp_skipped: Option<bool>,
3509        setup_failed: bool,
3510    ) -> DoctorFacts {
3511        DoctorFacts {
3512            kernel_supported,
3513            remount_available,
3514            wfp_skipped,
3515            setup_failed,
3516        }
3517    }
3518
3519    #[test]
3520    fn unsupported_kernel_fails() {
3521        assert!(doctor_fails(facts(false, None, None, false)));
3522    }
3523
3524    #[test]
3525    fn wfp_skip_alone_succeeds() {
3526        assert!(!doctor_fails(facts(true, None, Some(true), false)));
3527    }
3528
3529    #[test]
3530    fn wfp_applied_succeeds() {
3531        assert!(!doctor_fails(facts(true, None, Some(false), false)));
3532    }
3533
3534    #[test]
3535    fn linux_remount_unavailable_fails_even_when_kernel_works() {
3536        assert!(doctor_fails(facts(true, Some(false), None, false)));
3537    }
3538
3539    #[test]
3540    fn linux_remount_available_succeeds() {
3541        assert!(!doctor_fails(facts(true, Some(true), None, false)));
3542    }
3543
3544    #[test]
3545    fn setup_failure_fails() {
3546        assert!(doctor_fails(facts(true, None, None, true)));
3547    }
3548}