Skip to main content

aither_sandbox/spawn/
host.rs

1//! The host backend: a process under heel's sandbox on this machine.
2
3use std::any::Any;
4use std::path::{Path, PathBuf};
5
6use executor_core::Executor;
7use heel::{
8    Access, Audited, Grant, IpcRouter, NetworkPolicy, ResolvedPath, SandboxConfig, SecurityConfig,
9    StdioConfig,
10};
11
12use super::child::{ChildExit, Descendants, KillHandle, SandboxedChild, Streams, exit_watch};
13use super::domain::DomainGate;
14use super::stdio::{read_chunks, write_chunks};
15use super::{
16    Backend, LaunchInfo, Pipe, Sandbox, SpawnCommand, SpawnError, SpawnGrant, SpawnSpec, Stdio,
17};
18#[cfg(target_os = "linux")]
19use crate::process_tree::JobProcess;
20use crate::process_tree::{JobMarker, JobTree};
21use crate::stdin_watch::{FeedCounter, LocalStdinProbe, StdinWatchSignal};
22use crate::terminal::{LocalChild, LocalStdinWatch, wait_for_local_process_exit};
23
24/// How long a job's descendants may outlive its top-level process, which
25/// decides how a Linux job is supervised.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum TreeLifetime {
28    /// None: the caller ends the survivors.
29    Foreground,
30    /// All of them: the job lasts until its whole tree has exited.
31    Background,
32}
33
34/// A process spawned on the host: the child, the handle that ends its tree
35/// and heel's sandbox, whose drop ends the processes under it.
36pub struct LocalSpawn {
37    pub(crate) child: LocalChild,
38    pub(crate) tree: JobTree,
39    /// Kept alive for as long as the process runs.
40    pub(crate) sandbox: Box<dyn Any + Send>,
41}
42
43/// The object a spelled path names, in the spelling a resolved grant checks:
44/// canonicalized, without the verbatim prefix Windows adds; an 8.3 alias or a
45/// symlinked component does not name the same object.
46pub fn resolved(path: &Path) -> heel::Result<ResolvedPath> {
47    ResolvedPath::new(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()))
48}
49
50/// The grants that let git work in a granted linked worktree: its common git
51/// directory, with the access `git_dir` gives a writable worktree's (the
52/// session's own for the main agent, read for a child). The directory is the
53/// repository's, outside the worktree, and a strict sandbox reads only what
54/// is granted. Only a pointer git's back-links confirm
55/// ([`crate::subagent::confirmed_common_dir`]) grants anything, because the
56/// `.git` file sits in a directory the session can write.
57pub async fn linked_worktree_grants(
58    writable: &[PathBuf],
59    readable: &[PathBuf],
60    git_dir: crate::GitDirAccess,
61) -> heel::Result<Vec<Grant>> {
62    let mut grants = Vec::new();
63    for (path, access) in writable
64        .iter()
65        .map(|path| (path, git_dir.writable_worktree_access()))
66        .chain(readable.iter().map(|path| (path, Access::READ)))
67    {
68        if let Some(common) = crate::subagent::confirmed_common_dir(path).await {
69            grants.push(Grant::new(resolved(&common)?, access));
70        }
71    }
72    Ok(grants)
73}
74
75/// The paths a host sandbox must not read: heel's credential table plus the
76/// embedder's `denied` absolute paths. Everything else stays readable.
77#[cfg(not(windows))]
78fn read_denylist(denied: &[PathBuf]) -> heel::ReadDenylist {
79    denied
80        .iter()
81        .fold(heel::ReadDenylist::credentials(), |denylist, path| {
82            denylist.deny(path)
83        })
84}
85
86const fn stdio_config(pipe: Pipe) -> StdioConfig {
87    match pipe {
88        Pipe::Null => StdioConfig::Null,
89        Pipe::Piped => StdioConfig::Piped,
90    }
91}
92
93/// What a launch needs besides heel's configuration.
94struct Launch {
95    program: String,
96    args: Vec<String>,
97    env: Vec<(String, String)>,
98    cwd: Option<PathBuf>,
99    stdio: Stdio,
100    lifetime: TreeLifetime,
101    marker: JobMarker,
102}
103
104impl Sandbox {
105    fn heel_binary(&self) -> Result<&heel::HeelBinary, SpawnError> {
106        match &self.inner.backend {
107            Backend::Host { heel } => Ok(heel),
108            Backend::Container { .. } | Backend::Ssh { .. } => Err(SpawnError::Setup(
109                "a local spawn needs the host backend".into(),
110            )),
111        }
112    }
113
114    /// The canonical spelling of the working directory: a symlink in it fails
115    /// heel's own resolution, which does not follow a link a sandboxed
116    /// process could have planted.
117    fn canonical_working_dir(&self) -> PathBuf {
118        std::fs::canonicalize(&self.inner.working_dir)
119            .unwrap_or_else(|_| self.inner.working_dir.clone())
120    }
121
122    /// The environment of a host spawn: the sandbox's own, its source's, its
123    /// space's, then the spec's, each overriding the one before.
124    fn host_environment(
125        &self,
126        spec_env: Vec<(String, String)>,
127        info: &LaunchInfo,
128    ) -> Result<Vec<(String, String)>, SpawnError> {
129        let mut env = self.inner.environment.clone();
130        if let Some(source) = &self.inner.env_source {
131            env.extend(source.env(info));
132        }
133        for (name, path) in &self.inner.space_environment {
134            let value = path.to_str().ok_or_else(|| {
135                SpawnError::Setup(format!(
136                    "{} is not UTF-8, so the variable {name} cannot name it",
137                    path.display()
138                ))
139            })?;
140            env.push((name.clone(), value.to_owned()));
141        }
142        env.extend(spec_env);
143        Ok(env)
144    }
145
146    /// The grants a confined spawn carries: the embedder's fixed ones, every
147    /// live writable path with write and execute access (a sandboxed process
148    /// can already run anything it writes through an interpreter, and builds
149    /// must execute their own outputs), every readable path with read access,
150    /// the common git directory of a granted linked worktree, and the spec's
151    /// own.
152    async fn confined_grants(
153        &self,
154        snapshot: &super::GrantSnapshot,
155        extra: Vec<Grant>,
156    ) -> Result<Vec<Grant>, SpawnError> {
157        let setup = |error: heel::Error| SpawnError::Setup(error.to_string());
158        let mut grants = self.inner.fixed_grants.clone();
159        for (path, access) in snapshot
160            .writable
161            .iter()
162            .map(|path| (path, Access::WRITE | Access::EXEC))
163            .chain(snapshot.readable.iter().map(|path| (path, Access::READ)))
164        {
165            // A grant deleted since it was made grants nothing, and the
166            // sandbox cannot resolve it.
167            if matches!(path.try_exists(), Ok(false)) {
168                continue;
169            }
170            grants.push(Grant::new(resolved(path).map_err(setup)?, access));
171        }
172        grants.extend(
173            linked_worktree_grants(&snapshot.writable, &snapshot.readable, snapshot.git_dir)
174                .await
175                .map_err(setup)?,
176        );
177        grants.extend(extra);
178        Ok(grants)
179    }
180
181    fn confined_config<N: NetworkPolicy>(
182        &self,
183        policy: N,
184        grants: Vec<Grant>,
185        snapshot: &super::GrantSnapshot,
186        heel: heel::HeelBinary,
187        ipc: Option<IpcRouter>,
188    ) -> SandboxConfig<N> {
189        let builder = SandboxConfig::builder().network(policy);
190        // The Windows backend refuses a write denylist rather than run
191        // weaker, and the same holds for the read denylist: reads are open
192        // everywhere except the credential table and the embedder's
193        // additions.
194        #[cfg(not(windows))]
195        let builder = {
196            let builder = match &self.inner.write_denylist {
197                Some(denylist) => builder.write_denylist(denylist.clone()),
198                None => builder,
199            };
200            builder
201                .filesystem_strict(false)
202                .read_denylist(read_denylist(&snapshot.read_denied))
203        };
204        #[cfg(windows)]
205        let _ = snapshot;
206        let builder = builder
207            .working_dir(self.canonical_working_dir())
208            .grants(grants)
209            .heel_binary(heel)
210            .security(SecurityConfig::interactive())
211            // The session's own processes run their build outputs: anything
212            // written here could already run through an interpreter.
213            .executable_working_dir(true)
214            .priority(self.inner.priority);
215        #[cfg(target_os = "linux")]
216        let builder = builder.supervised_spawn(true);
217        // `ipc` changes the builder's type, so both arms build where they are.
218        match ipc {
219            Some(router) => builder.ipc(router).build(),
220            None => builder.build(),
221        }
222    }
223
224    fn unconfined_config(
225        &self,
226        heel: heel::HeelBinary,
227        ipc: Option<IpcRouter>,
228    ) -> SandboxConfig<heel::HostAccess> {
229        // Host access is approved execution: the user runs the script
230        // themselves in every respect except IPC plumbing, so no credential
231        // or filesystem protection may apply.
232        let builder = SandboxConfig::builder()
233            .working_dir(self.canonical_working_dir())
234            .host_access()
235            .heel_binary(heel)
236            .executable_working_dir(true)
237            .priority(self.inner.priority);
238        #[cfg(target_os = "linux")]
239        let builder = builder.supervised_spawn(true);
240        match ipc {
241            Some(router) => builder.ipc(router).build(),
242            None => builder.build(),
243        }
244    }
245
246    /// Starts `spec` on the host under heel and hands back the raw child, for
247    /// an embedder that supervises the job itself.
248    pub(crate) async fn spawn_local(&self, spec: SpawnSpec) -> Result<LocalSpawn, SpawnError> {
249        let heel = self.heel_binary()?.clone();
250        let SpawnSpec {
251            command,
252            env,
253            cwd,
254            stdio,
255            grants: extra_grants,
256            ipc,
257            lifetime,
258            info,
259        } = spec;
260        // A process on the host is a program: only a container or a server
261        // has a managed shell to run a script in.
262        let SpawnCommand::Program { program, args } = command else {
263            return Err(SpawnError::Unsupported {
264                backend: "host",
265                what: "a script",
266            });
267        };
268        let extra_grants = extra_grants
269            .into_iter()
270            .map(|grant| match grant {
271                SpawnGrant::Host(grant) => Ok(grant),
272                SpawnGrant::Container { .. } => Err(SpawnError::Unsupported {
273                    backend: "host",
274                    what: "a grant on a container path",
275                }),
276            })
277            .collect::<Result<Vec<_>, _>>()?;
278        let marker = JobMarker::new();
279        let mut env = self.host_environment(env, &info)?;
280        env.push(marker.entry());
281        let launch = Launch {
282            program,
283            args,
284            env,
285            cwd,
286            stdio,
287            lifetime,
288            marker,
289        };
290        if self.inner.unconfined {
291            let config = self.unconfined_config(heel, ipc);
292            return self.launch(config, launch).await;
293        }
294        let snapshot = self.inner.grants.snapshot();
295        let grants = self.confined_grants(&snapshot, extra_grants).await?;
296        let gate = DomainGate {
297            lists: self.inner.network.clone(),
298            approver: self.inner.approver.clone(),
299            agent: self.inner.agent.clone(),
300        };
301        if let Some(log) = self.inner.audit.clone() {
302            let config =
303                self.confined_config(Audited::new(gate, log), grants, &snapshot, heel, ipc);
304            self.launch(config, launch).await
305        } else {
306            let config = self.confined_config(gate, grants, &snapshot, heel, ipc);
307            self.launch(config, launch).await
308        }
309    }
310
311    async fn launch<N: NetworkPolicy + 'static>(
312        &self,
313        config: SandboxConfig<N>,
314        launch: Launch,
315    ) -> Result<LocalSpawn, SpawnError> {
316        let sandbox = heel::Sandbox::with_config_and_executor(config, self.inner.executor.clone())
317            .await
318            .map_err(|error| SpawnError::Setup(error.to_string()))?;
319        let Launch {
320            program,
321            args,
322            env,
323            cwd,
324            stdio,
325            lifetime,
326            marker,
327        } = launch;
328        let mut command = sandbox.command(program);
329        if let Some(cwd) = cwd {
330            command = command.current_dir(cwd);
331        }
332        let command = command
333            .args(args)
334            .envs(env)
335            .stdin(stdio_config(stdio.stdin))
336            .stdout(stdio_config(stdio.stdout))
337            .stderr(stdio_config(stdio.stderr));
338        let start = |error: heel::Error| SpawnError::Start(error.to_string());
339
340        // On Linux the sandbox was built with `supervised_spawn(true)`, so the
341        // command runs under `heel supervise`: a child subreaper inside the
342        // sandbox that owns the whole tree however its members change
343        // session, group or environment.
344        #[cfg(target_os = "linux")]
345        {
346            let _ = marker;
347            let reap_timeout = crate::terminal::SUPERVISED_REAP_TIMEOUT;
348            let child = match lifetime {
349                TreeLifetime::Foreground => LocalChild::Foreground(
350                    command
351                        .spawn_supervised(heel::supervisor::Foreground { reap_timeout })
352                        .await
353                        .map_err(start)?,
354                ),
355                TreeLifetime::Background => LocalChild::Background(
356                    command
357                        .spawn_supervised(heel::supervisor::Background { reap_timeout })
358                        .await
359                        .map_err(start)?,
360                ),
361            };
362            let tree = JobTree::supervised(child.tree_control());
363            Ok(LocalSpawn {
364                child,
365                tree,
366                sandbox: Box::new(sandbox),
367            })
368        }
369
370        // Everywhere else the root's process group is watched through the
371        // process table, keyed by the job's marker.
372        #[cfg(not(target_os = "linux"))]
373        {
374            let _ = lifetime;
375            let child = command.spawn().await.map_err(start)?;
376            let tree = JobTree::spawn(
377                &self.inner.executor,
378                self.inner.scanner.clone(),
379                child.id(),
380                &marker,
381            );
382            Ok(LocalSpawn {
383                child: LocalChild::Plain(child),
384                tree,
385                sandbox: Box::new(sandbox),
386            })
387        }
388    }
389
390    pub(super) async fn spawn_host(&self, spec: SpawnSpec) -> Result<SandboxedChild, SpawnError> {
391        let stdio = spec.stdio;
392        let lifetime = spec.lifetime;
393        let LocalSpawn {
394            mut child,
395            tree,
396            sandbox,
397        } = self.spawn_local(spec).await?;
398        let id = child.id();
399
400        let mut streams = Streams::default();
401        let mut stdin_watch = None;
402        if stdio.stdin == Pipe::Piped
403            && let Some(stdin) = child.take_stdin()
404        {
405            let feed = FeedCounter::default();
406            let (signal_tx, signal_rx) = async_channel::unbounded();
407            match LocalStdinProbe::new(id, &stdin) {
408                Ok(probe) => {
409                    stdin_watch = Some(LocalStdinWatch::new(probe, feed.clone(), signal_tx));
410                }
411                // The watch cannot run: say so once, as a running watch would.
412                Err(error) => {
413                    let _ = signal_tx.try_send(StdinWatchSignal::Failed(error.to_string()));
414                }
415            }
416            streams.stdin_blocked = Some(signal_rx);
417            streams.stdin = Some(write_chunks(stdin, feed));
418        }
419        if stdio.stdout == Pipe::Piped
420            && let Some(stdout) = child.take_stdout()
421        {
422            streams.stdout = Some(pump(stdout));
423        }
424        if stdio.stderr == Pipe::Piped
425            && let Some(stderr) = child.take_stderr()
426        {
427            streams.stderr = Some(pump(stderr));
428        }
429
430        let (setter, watch) = exit_watch();
431        let watched = tree.clone();
432        self.inner
433            .executor
434            .spawn(async move {
435                // Dropping heel's sandbox ends the processes under it.
436                let _sandbox = sandbox;
437                let (exit, descendants) =
438                    wait_for_exit(&mut child, &watched, lifetime, stdin_watch).await;
439                setter.finish(exit, descendants);
440            })
441            .detach();
442        Ok(SandboxedChild::new(
443            id,
444            streams,
445            KillHandle::Tree(tree),
446            watch,
447        ))
448    }
449}
450
451/// Moves a pipe to a channel of chunks that closes at its end.
452fn pump(file: std::fs::File) -> async_channel::Receiver<Vec<u8>> {
453    let (tx, rx) = async_channel::unbounded();
454    read_chunks(file, move |chunk| {
455        if let Some(chunk) = chunk {
456            let _ = tx.send_blocking(chunk);
457        }
458    });
459    rx
460}
461
462/// Waits until the root process has exited and then ends its descendants as
463/// `lifetime` says: a foreground child's are killed, a background child's
464/// waited for. The root stays unreaped until its tree is gone, so its pid and
465/// process group stay reserved while the job's descendants are tracked by
466/// them.
467async fn wait_for_exit(
468    child: &mut LocalChild,
469    tree: &JobTree,
470    lifetime: TreeLifetime,
471    stdin_watch: Option<LocalStdinWatch>,
472) -> (ChildExit, Descendants) {
473    let exited = match wait_for_local_process_exit(child, stdin_watch).await {
474        Ok(exited) => exited,
475        Err(error) => {
476            tree.finish().await;
477            return (
478                ChildExit::Failed(error.to_string()),
479                Descendants::Unobserved,
480            );
481        }
482    };
483    let mut killed = Vec::new();
484    let ended = match lifetime {
485        TreeLifetime::Foreground => tree
486            .kill_descendants()
487            .await
488            .map(|processes| killed = processes),
489        TreeLifetime::Background => tree.wait_descendants_exit().await,
490    };
491    // The task ends first: afterwards the root's pid may belong to anyone.
492    tree.finish().await;
493    let status = match exited {
494        Some(status) => Ok(status),
495        None => child
496            .wait_reported()
497            .await
498            .map(|(status, report)| {
499                // A supervised foreground job's teardown killed what it found.
500                #[cfg(target_os = "linux")]
501                if let Some(report) = report {
502                    killed.extend(report.killed.into_iter().map(|process| JobProcess {
503                        pid: process.pid,
504                        name: process.name,
505                    }));
506                }
507                #[cfg(not(target_os = "linux"))]
508                let _ = report;
509                status
510            })
511            .map_err(|error| error.to_string()),
512    };
513    // A kill that failed ended an unknown part of the tree, so what it did
514    // name is not the whole of it; Windows sees no descendants at all.
515    let descendants = if cfg!(windows) || ended.is_err() {
516        Descendants::Unobserved
517    } else {
518        Descendants::Killed(killed)
519    };
520    let exit = match (ended, status) {
521        (Ok(()), Ok(status)) => ChildExit::Exited(status),
522        (Err(error), _) => ChildExit::Failed(error.to_string()),
523        (Ok(()), Err(error)) => ChildExit::Failed(error),
524    };
525    (exit, descendants)
526}