Skip to main content

aither_sandbox/spawn/
mod.rs

1//! The spawn layer: start a process under a sandbox.
2//!
3//! A [`Sandbox`] is one per home environment. It holds the live [`Grants`],
4//! the environment, the network lists and their [`DomainApprover`], and a
5//! [`Backend`] saying where processes run. [`Sandbox::spawn`] starts a
6//! [`SpawnSpec`] on that backend and answers a [`SandboxedChild`] whose
7//! [`kill`](SandboxedChild::kill) ends the whole process tree.
8//!
9//! What the sandbox enforces per backend:
10//!
11//! - [`Backend::Host`]: heel's sandbox, with the grants, the environment, the
12//!   write and read denylists, the process priority and the network lists
13//!   with their approver, whose answer is enforced per connection.
14//! - [`Backend::Container`]: the process runs in the container, which is its
15//!   boundary. A [derived](Sandbox::derived) sandbox, a child's, is
16//!   additionally confined inside the container to its own writable grants.
17//!   The environment reaches it as exports of the script.
18//! - [`Backend::Ssh`]: the process runs on the server under the server's own
19//!   `heel`, with the tools the embedder prepared there. Grants and the
20//!   host-side environment never reach another machine.
21
22mod backend;
23mod child;
24mod container;
25pub mod container_ipc;
26mod domain;
27mod env;
28mod grants;
29pub mod host;
30mod ipc;
31mod launch;
32mod route;
33mod ssh;
34pub mod stdio;
35#[cfg(all(test, unix))]
36mod tests;
37
38use std::path::{Path, PathBuf};
39use std::sync::Arc;
40
41use askama::Template;
42use executor_core::{AnyExecutor, Executor};
43
44pub use backend::Backend;
45pub use child::{ChildExit, Descendants, SandboxedChild};
46pub use domain::{
47    AnyDomainApprover, ApproveAllDomains, DenyAllDomains, DomainApprover, DomainRequest,
48};
49pub use env::{EnvSource, LaunchInfo};
50pub use grants::{GitDirAccess, GrantSnapshot, Grants};
51#[cfg(all(unix, feature = "jobserver"))]
52pub use host::resolved;
53pub use host::{LocalSpawn, TreeLifetime};
54#[cfg(test)]
55pub use ipc::fixture as ipc_fixture;
56pub use ipc::{AnyIpcProvider, IpcProvider};
57#[cfg(not(windows))]
58pub use launch::shell_arguments;
59pub use launch::{ContainerLaunch, HostLaunch, RemoteLaunch};
60pub use route::{HostRoute, HostRouteError};
61
62use crate::network_policy::CompiledNetworkPolicy;
63use crate::process_tree::ProcessScanner;
64
65/// Why a process could not be spawned.
66#[derive(Debug, thiserror::Error)]
67pub enum SpawnError {
68    /// The sandbox, or the backend it runs on, could not be set up: a grant
69    /// cannot be resolved, the heel binary is unusable, the server has no
70    /// `heel`, a path has no counterpart in the container.
71    #[error("sandbox setup failed: {0}")]
72    Setup(String),
73    /// The process could not be started.
74    #[error("failed to start the process: {0}")]
75    Start(String),
76    /// The spec asks for something the backend cannot honour, and the
77    /// process is not started without it.
78    #[error("the {backend} backend cannot honour {what}")]
79    Unsupported {
80        /// The backend that refused.
81        backend: &'static str,
82        /// What the spec asked for.
83        what: &'static str,
84    },
85}
86
87/// Whether a standard stream of a spawned process is piped to its handle.
88#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
89pub enum Pipe {
90    /// Connected to the null device: no input, or output dropped. A stdin of
91    /// the null device is the same on every backend, so a program that picks
92    /// its input by what its stdin is — `rg` searching the directory rather
93    /// than a pipe — behaves alike on all of them.
94    #[default]
95    Null,
96    /// Connected to the [`SandboxedChild`]'s channel for the stream.
97    Piped,
98}
99
100/// The standard streams of a spawned process. The default pipes `stdout` and
101/// `stderr` and gives `stdin` nothing.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct Stdio {
104    /// The process's standard input.
105    pub stdin: Pipe,
106    /// The process's standard output.
107    pub stdout: Pipe,
108    /// The process's standard error.
109    pub stderr: Pipe,
110}
111
112impl Default for Stdio {
113    fn default() -> Self {
114        Self {
115            stdin: Pipe::Null,
116            stdout: Pipe::Piped,
117            stderr: Pipe::Piped,
118        }
119    }
120}
121
122#[derive(Template)]
123#[template(path = "null_stdin.sh", escape = "none")]
124struct NullStdinTemplate<'a> {
125    script: &'a str,
126}
127
128/// `script` for a backend whose processes always start on a stdin pipe —
129/// a container exec's attached stream, an SSH session's channel — reading
130/// `stdin`: a script whose stdin is [`Pipe::Null`] reads the null device, as
131/// a process on the host does.
132///
133/// # Errors
134/// Fails when the redirect cannot render.
135pub fn script_reading(stdin: Pipe, script: String) -> Result<String, SpawnError> {
136    match stdin {
137        Pipe::Piped => Ok(script),
138        Pipe::Null => NullStdinTemplate { script: &script }
139            .render()
140            .map_err(|error| SpawnError::Setup(error.to_string())),
141    }
142}
143
144/// What a spawned process runs.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum SpawnCommand {
147    /// A program with its arguments.
148    Program {
149        /// The program to run.
150        program: String,
151        /// Its arguments.
152        args: Vec<String>,
153    },
154    /// A script for the backend's managed shell, which only the container
155    /// and SSH backends have: a host sandbox names no shell, so spawning a
156    /// script on it fails with [`SpawnError::Unsupported`]. A caller that
157    /// wants a script on the host spawns its shell as a program, or runs it
158    /// through a [`Shell`](crate::Shell).
159    ///
160    /// A script is one level of quoting for a server's login shell, which
161    /// parses the command line first; a program that runs the shell would
162    /// need two.
163    Script(String),
164}
165
166/// An access a process is granted beyond the sandbox's own grants, named
167/// where the backend that honours it sees the path.
168#[derive(Debug, Clone)]
169pub enum SpawnGrant {
170    /// A resolved path on the host; only the host backend honours it.
171    Host(heel::Grant),
172    /// A path inside the container; only the container backend honours it.
173    /// It widens only a [derived](Sandbox::derived) sandbox's confinement:
174    /// any other process already has the whole container.
175    Container {
176        /// The path, as the container spells it.
177        path: crate::ContainerPath,
178        /// What the process may do with it.
179        access: heel::Access,
180    },
181}
182
183/// A process to start under a [`Sandbox`].
184pub struct SpawnSpec {
185    pub(crate) command: SpawnCommand,
186    pub(crate) env: Vec<(String, String)>,
187    pub(crate) cwd: Option<PathBuf>,
188    pub(crate) stdio: Stdio,
189    /// Grants this one process needs beyond the sandbox's (a command's
190    /// jobserver fifo).
191    pub(crate) grants: Vec<SpawnGrant>,
192    /// The commands the process may call back into the host with.
193    pub(crate) ipc: Option<heel::IpcRouter>,
194    /// Whether the backend ends the processes the top-level one leaves.
195    pub(crate) lifetime: TreeLifetime,
196    /// What the launch is, for the sandbox's [`EnvSource`] to read.
197    pub(crate) info: LaunchInfo,
198}
199
200impl std::fmt::Debug for SpawnSpec {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        f.debug_struct("SpawnSpec")
203            .field("command", &self.command)
204            .field("cwd", &self.cwd)
205            .field("stdio", &self.stdio)
206            .finish_non_exhaustive()
207    }
208}
209
210impl SpawnSpec {
211    /// A process running `program` with no arguments, in the sandbox's
212    /// working directory, with the default [`Stdio`].
213    #[must_use]
214    pub fn new(program: impl Into<String>) -> Self {
215        Self::of(SpawnCommand::Program {
216            program: program.into(),
217            args: Vec::new(),
218        })
219    }
220
221    /// A process running `source` in the managed shell the backend was given
222    /// the programs of, with the default [`Stdio`]. Only the container and
223    /// SSH backends have a managed shell to run it in: a spawn on the host
224    /// names a program.
225    #[must_use]
226    pub fn script(source: impl Into<String>) -> Self {
227        Self::of(SpawnCommand::Script(source.into()))
228    }
229
230    fn of(command: SpawnCommand) -> Self {
231        Self {
232            command,
233            env: Vec::new(),
234            cwd: None,
235            stdio: Stdio::default(),
236            grants: Vec::new(),
237            ipc: None,
238            lifetime: TreeLifetime::Background,
239            info: LaunchInfo::default(),
240        }
241    }
242
243    /// Says what this launch is, for the sandbox's [`EnvSource`] to read:
244    /// the job, the call and the mode it runs in.
245    #[must_use]
246    pub fn launch_info(mut self, info: LaunchInfo) -> Self {
247        self.info = info;
248        self
249    }
250
251    /// Appends arguments.
252    ///
253    /// # Panics
254    /// Panics on a script, which takes none.
255    #[must_use]
256    pub fn args(mut self, more: impl IntoIterator<Item = impl Into<String>>) -> Self {
257        let SpawnCommand::Program { args, .. } = &mut self.command else {
258            panic!("a script takes no arguments");
259        };
260        args.extend(more.into_iter().map(Into::into));
261        self
262    }
263
264    /// Adds environment for this process alone; it overrides the sandbox's
265    /// environment and its [`EnvSource`].
266    #[must_use]
267    pub fn env(mut self, env: impl IntoIterator<Item = (String, String)>) -> Self {
268        self.env.extend(env);
269        self
270    }
271
272    /// Grants this process alone beyond the sandbox's. A grant is named
273    /// where the backend that honours it sees the path: a backend refuses
274    /// the [`SpawnGrant`] it cannot honour, and a server honours none.
275    #[must_use]
276    pub fn grants(mut self, grants: impl IntoIterator<Item = SpawnGrant>) -> Self {
277        self.grants.extend(grants);
278        self
279    }
280
281    /// Lets the process call the commands of `router` back on the host. The
282    /// host serves it in process; a container is reached over a listener at
283    /// its [host route](crate::ContainerShellRuntime::host_route); a server
284    /// has no way back, so its backend refuses it.
285    #[must_use]
286    pub fn ipc(mut self, router: Option<heel::IpcRouter>) -> Self {
287        self.ipc = router;
288        self
289    }
290
291    /// Sets how long the process's descendants may outlive it. The default
292    /// is [`TreeLifetime::Background`]: the child lasts until its whole tree
293    /// has exited, and its piped stdin is watched
294    /// ([`SandboxedChild::take_stdin_blocked`]); a container child's watch
295    /// runs, and costs a probe in the container, even when stdin is not
296    /// piped. SSH keeps the default for either value, as it cannot see the
297    /// tree.
298    #[must_use]
299    pub const fn lifetime(mut self, lifetime: TreeLifetime) -> Self {
300        self.lifetime = lifetime;
301        self
302    }
303
304    /// Starts the process in `cwd`, a path on the host the sandbox runs on
305    /// (for a container, one under a [mount](crate::ContainerShellRuntime::with_workspace_mount)).
306    #[must_use]
307    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
308        self.cwd = Some(cwd.into());
309        self
310    }
311
312    /// Sets the standard streams.
313    #[must_use]
314    pub const fn stdio(mut self, stdio: Stdio) -> Self {
315        self.stdio = stdio;
316        self
317    }
318}
319
320#[derive(Clone)]
321struct SandboxInner {
322    backend: Backend,
323    executor: Arc<AnyExecutor>,
324    working_dir: PathBuf,
325    grants: Grants,
326    fixed_grants: Vec<heel::Grant>,
327    environment: Vec<(String, String)>,
328    env_source: Option<Arc<dyn EnvSource>>,
329    /// Variables naming directories inside a subagent's own space, by their
330    /// host paths: the layer between the source and a spec's own variables.
331    space_environment: Vec<(String, PathBuf)>,
332    write_denylist: Option<heel::WriteDenylist>,
333    network: Option<CompiledNetworkPolicy>,
334    approver: Option<AnyDomainApprover>,
335    audit: Option<heel::NetworkAuditLog>,
336    priority: heel::ProcessPriority,
337    agent: Option<Arc<str>>,
338    scanner: ProcessScanner,
339    unconfined: bool,
340    ssh_client: crate::ssh::SshClient,
341}
342
343/// One home environment's sandbox: grants, environment, network policy and
344/// the [`Backend`] processes run on. Cheap to clone; clones share the live
345/// grants.
346#[derive(Clone)]
347pub struct Sandbox {
348    inner: Arc<SandboxInner>,
349}
350
351impl std::fmt::Debug for Sandbox {
352    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353        f.debug_struct("Sandbox")
354            .field("working_dir", &self.inner.working_dir)
355            .field("agent", &self.inner.agent)
356            .finish_non_exhaustive()
357    }
358}
359
360impl Sandbox {
361    /// A sandbox on `backend` whose processes start in `working_dir`, with no
362    /// grants, no environment of its own and no network lists: every domain
363    /// is open to the approver, which denies it until
364    /// [`with_domain_approver`](Self::with_domain_approver) gives one.
365    ///
366    /// `executor` runs the tasks that watch spawned processes and heel's
367    /// proxy.
368    #[must_use]
369    pub fn new(
370        backend: Backend,
371        executor: impl Executor + 'static,
372        working_dir: impl Into<PathBuf>,
373    ) -> Self {
374        Self {
375            inner: Arc::new(SandboxInner {
376                backend,
377                executor: Arc::new(AnyExecutor::new(executor)),
378                working_dir: working_dir.into(),
379                grants: Grants::new(),
380                fixed_grants: Vec::new(),
381                environment: Vec::new(),
382                env_source: None,
383                space_environment: Vec::new(),
384                write_denylist: None,
385                network: None,
386                approver: None,
387                audit: None,
388                priority: heel::ProcessPriority::default(),
389                agent: None,
390                scanner: ProcessScanner::default(),
391                unconfined: false,
392                ssh_client: crate::ssh::SshClient::default(),
393            }),
394        }
395    }
396
397    fn edit(mut self, edit: impl FnOnce(&mut SandboxInner)) -> Self {
398        edit(Arc::make_mut(&mut self.inner));
399        self
400    }
401
402    /// Uses `grants` as the sandbox's live grants; the sandbox sees every
403    /// change made through any clone of the handle.
404    #[must_use]
405    pub fn with_grants(self, grants: Grants) -> Self {
406        self.edit(|inner| inner.grants = grants)
407    }
408
409    /// Heel grants every spawn on the host carries ahead of the live
410    /// [`Grants`]: the directories the embedder's tools and toolchains live
411    /// in, and what its `PATH` lists.
412    #[must_use]
413    pub fn with_fixed_grants(self, grants: Vec<heel::Grant>) -> Self {
414        self.edit(|inner| inner.fixed_grants = grants)
415    }
416
417    /// The environment every spawn on the host starts with: the session's
418    /// `HOME`, temporary and cache directories, `PATH` and toolchain
419    /// variables. It never reaches a container or an SSH server, whose
420    /// filesystems differ.
421    #[must_use]
422    pub fn with_environment(self, environment: Vec<(String, String)>) -> Self {
423        self.edit(|inner| inner.environment = environment)
424    }
425
426    /// Environment resolved at each spawn, on the host and in a container;
427    /// never on an SSH server, so host-side values such as secrets never
428    /// reach another machine.
429    #[must_use]
430    pub fn with_env_source(self, source: impl EnvSource + 'static) -> Self {
431        self.edit(|inner| inner.env_source = Some(Arc::new(source)))
432    }
433
434    /// The variables of a subagent's space: each names a directory inside
435    /// it, by its host path. They override the environment and its source
436    /// and yield to a spec's own variables; a container sees each directory
437    /// through its workspace mount, and an SSH server none.
438    pub(crate) fn with_space_environment(self, environment: Vec<(String, PathBuf)>) -> Self {
439        self.edit(|inner| inner.space_environment = environment)
440    }
441
442    /// The paths a spawn on the host must not write, however they are
443    /// granted. Not supported on Windows, whose backend refuses a denylist
444    /// rather than run weaker, so it is not applied there.
445    #[must_use]
446    pub fn with_write_denylist(self, denylist: heel::WriteDenylist) -> Self {
447        self.edit(|inner| inner.write_denylist = Some(denylist))
448    }
449
450    /// The network lists: a host they allow or deny is decided without the
451    /// approver.
452    #[must_use]
453    pub fn with_network_policy(self, policy: CompiledNetworkPolicy) -> Self {
454        self.edit(|inner| inner.network = Some(policy))
455    }
456
457    /// Decides the connections the network lists leave open.
458    #[must_use]
459    pub fn with_domain_approver(self, approver: impl DomainApprover + 'static) -> Self {
460        self.edit(|inner| inner.approver = Some(AnyDomainApprover::new(approver)))
461    }
462
463    /// Records every network decision of a spawn on the host in `log`.
464    #[must_use]
465    pub fn with_audit_log(self, log: heel::NetworkAuditLog) -> Self {
466        self.edit(|inner| inner.audit = Some(log))
467    }
468
469    /// Lowers the scheduling priority of what the sandbox spawns on the host,
470    /// inherited by everything it starts. A container's image needs its own
471    /// `heel` for a non-normal priority; an SSH server's priority is its own.
472    #[must_use]
473    pub fn with_priority(self, priority: heel::ProcessPriority) -> Self {
474        self.edit(|inner| inner.priority = priority)
475    }
476
477    /// Labels the agent this sandbox serves; the label is the `agent` of
478    /// every [`DomainRequest`].
479    #[must_use]
480    pub fn with_agent(self, agent: impl Into<String>) -> Self {
481        let agent: Arc<str> = Arc::from(agent.into());
482        self.edit(|inner| inner.agent = Some(agent))
483    }
484
485    /// A child's sandbox: the same backend, environment and network policy,
486    /// grants [derived](Grants::derived) from this sandbox's with `own`, and
487    /// no agent label until [`with_agent`](Self::with_agent) gives one. It
488    /// cannot widen this sandbox: its grants never reach it, and a container
489    /// confines its processes to its own writable grants. The variables of
490    /// this sandbox's space are not the child's, which has a space of its
491    /// own.
492    #[must_use]
493    pub fn derived(&self, own: GrantSnapshot) -> Self {
494        let grants = self.inner.grants.derived(own);
495        self.clone().edit(|inner| {
496            inner.grants = grants;
497            inner.agent = None;
498            inner.space_environment = Vec::new();
499        })
500    }
501
502    /// The sandbox's live grants.
503    #[must_use]
504    pub fn grants(&self) -> &Grants {
505        &self.inner.grants
506    }
507
508    /// The directory processes start in unless their spec says otherwise.
509    #[must_use]
510    pub fn working_dir(&self) -> &Path {
511        &self.inner.working_dir
512    }
513
514    /// The same sandbox starting its processes in `working_dir`.
515    #[must_use]
516    pub fn with_working_dir(self, working_dir: impl Into<PathBuf>) -> Self {
517        self.edit(|inner| inner.working_dir = working_dir.into())
518    }
519
520    /// The same sandbox on `backend`: the grants, environment and network
521    /// policy are kept.
522    #[must_use]
523    pub fn with_backend(self, backend: Backend) -> Self {
524        self.edit(|inner| inner.backend = backend)
525    }
526
527    /// The `heel` binary of a sandbox on the host.
528    pub(crate) fn host_heel(&self) -> Option<&heel::HeelBinary> {
529        match &self.inner.backend {
530            Backend::Host { heel } => Some(heel),
531            Backend::Container { .. } | Backend::Ssh { .. } => None,
532        }
533    }
534
535    /// The executor the sandbox's tasks run on.
536    pub(crate) fn executor(&self) -> Arc<AnyExecutor> {
537        Arc::clone(&self.inner.executor)
538    }
539
540    /// Where the sandbox's processes run.
541    pub(crate) fn backend(&self) -> &Backend {
542        &self.inner.backend
543    }
544
545    /// The scheduling priority of the sandbox's processes.
546    pub(crate) fn priority(&self) -> heel::ProcessPriority {
547        self.inner.priority
548    }
549
550    /// The same sandbox without confinement: a host spawn takes host access,
551    /// ignoring the grants and denylists and the network lists.
552    pub(crate) fn unconfined(&self) -> Self {
553        self.clone().edit(|inner| inner.unconfined = true)
554    }
555
556    /// Reads process tables through `scanner`, shared with the embedder's
557    /// job registry.
558    pub(crate) fn with_scanner(self, scanner: ProcessScanner) -> Self {
559        self.edit(|inner| inner.scanner = scanner)
560    }
561
562    /// Reaches SSH servers through `client` instead of the default one.
563    pub(crate) fn with_ssh_client(self, client: crate::ssh::SshClient) -> Self {
564        self.edit(|inner| inner.ssh_client = client)
565    }
566
567    /// Starts `spec` on the sandbox's backend, under its grants and network
568    /// policy as they are now: a change made to the live grants applies to
569    /// the next spawn, never to a process already running.
570    ///
571    /// # Errors
572    /// Returns an error when the sandbox cannot be set up for the spawn or
573    /// the process cannot be started.
574    pub async fn spawn(&self, spec: SpawnSpec) -> Result<SandboxedChild, SpawnError> {
575        match &self.inner.backend {
576            Backend::Host { .. } => self.spawn_host(spec).await,
577            Backend::Container { runtime, launch } => self.spawn_container(runtime, launch, spec),
578            Backend::Ssh {
579                server,
580                heel,
581                launch,
582            } => self.spawn_ssh(server, heel.as_deref(), launch, spec).await,
583        }
584    }
585}