mod backend;
mod child;
mod container;
pub mod container_ipc;
mod domain;
mod env;
mod grants;
pub mod host;
mod ipc;
mod launch;
mod route;
mod ssh;
pub mod stdio;
#[cfg(all(test, unix))]
mod tests;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use askama::Template;
use executor_core::{AnyExecutor, Executor};
pub use backend::Backend;
pub use child::{ChildExit, Descendants, SandboxedChild};
pub use domain::{
AnyDomainApprover, ApproveAllDomains, DenyAllDomains, DomainApprover, DomainRequest,
};
pub use env::{EnvSource, LaunchInfo};
pub use grants::{GitDirAccess, GrantSnapshot, Grants};
#[cfg(all(unix, feature = "jobserver"))]
pub use host::resolved;
pub use host::{LocalSpawn, TreeLifetime};
#[cfg(test)]
pub use ipc::fixture as ipc_fixture;
pub use ipc::{AnyIpcProvider, IpcProvider};
#[cfg(not(windows))]
pub use launch::shell_arguments;
pub use launch::{ContainerLaunch, HostLaunch, RemoteLaunch};
pub use route::{HostRoute, HostRouteError};
use crate::network_policy::CompiledNetworkPolicy;
use crate::process_tree::ProcessScanner;
#[derive(Debug, thiserror::Error)]
pub enum SpawnError {
#[error("sandbox setup failed: {0}")]
Setup(String),
#[error("failed to start the process: {0}")]
Start(String),
#[error("the {backend} backend cannot honour {what}")]
Unsupported {
backend: &'static str,
what: &'static str,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Pipe {
#[default]
Null,
Piped,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stdio {
pub stdin: Pipe,
pub stdout: Pipe,
pub stderr: Pipe,
}
impl Default for Stdio {
fn default() -> Self {
Self {
stdin: Pipe::Null,
stdout: Pipe::Piped,
stderr: Pipe::Piped,
}
}
}
#[derive(Template)]
#[template(path = "null_stdin.sh", escape = "none")]
struct NullStdinTemplate<'a> {
script: &'a str,
}
pub fn script_reading(stdin: Pipe, script: String) -> Result<String, SpawnError> {
match stdin {
Pipe::Piped => Ok(script),
Pipe::Null => NullStdinTemplate { script: &script }
.render()
.map_err(|error| SpawnError::Setup(error.to_string())),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpawnCommand {
Program {
program: String,
args: Vec<String>,
},
Script(String),
}
#[derive(Debug, Clone)]
pub enum SpawnGrant {
Host(heel::Grant),
Container {
path: crate::ContainerPath,
access: heel::Access,
},
}
pub struct SpawnSpec {
pub(crate) command: SpawnCommand,
pub(crate) env: Vec<(String, String)>,
pub(crate) cwd: Option<PathBuf>,
pub(crate) stdio: Stdio,
pub(crate) grants: Vec<SpawnGrant>,
pub(crate) ipc: Option<heel::IpcRouter>,
pub(crate) lifetime: TreeLifetime,
pub(crate) info: LaunchInfo,
}
impl std::fmt::Debug for SpawnSpec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SpawnSpec")
.field("command", &self.command)
.field("cwd", &self.cwd)
.field("stdio", &self.stdio)
.finish_non_exhaustive()
}
}
impl SpawnSpec {
#[must_use]
pub fn new(program: impl Into<String>) -> Self {
Self::of(SpawnCommand::Program {
program: program.into(),
args: Vec::new(),
})
}
#[must_use]
pub fn script(source: impl Into<String>) -> Self {
Self::of(SpawnCommand::Script(source.into()))
}
fn of(command: SpawnCommand) -> Self {
Self {
command,
env: Vec::new(),
cwd: None,
stdio: Stdio::default(),
grants: Vec::new(),
ipc: None,
lifetime: TreeLifetime::Background,
info: LaunchInfo::default(),
}
}
#[must_use]
pub fn launch_info(mut self, info: LaunchInfo) -> Self {
self.info = info;
self
}
#[must_use]
pub fn args(mut self, more: impl IntoIterator<Item = impl Into<String>>) -> Self {
let SpawnCommand::Program { args, .. } = &mut self.command else {
panic!("a script takes no arguments");
};
args.extend(more.into_iter().map(Into::into));
self
}
#[must_use]
pub fn env(mut self, env: impl IntoIterator<Item = (String, String)>) -> Self {
self.env.extend(env);
self
}
#[must_use]
pub fn grants(mut self, grants: impl IntoIterator<Item = SpawnGrant>) -> Self {
self.grants.extend(grants);
self
}
#[must_use]
pub fn ipc(mut self, router: Option<heel::IpcRouter>) -> Self {
self.ipc = router;
self
}
#[must_use]
pub const fn lifetime(mut self, lifetime: TreeLifetime) -> Self {
self.lifetime = lifetime;
self
}
#[must_use]
pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
#[must_use]
pub const fn stdio(mut self, stdio: Stdio) -> Self {
self.stdio = stdio;
self
}
}
#[derive(Clone)]
struct SandboxInner {
backend: Backend,
executor: Arc<AnyExecutor>,
working_dir: PathBuf,
grants: Grants,
fixed_grants: Vec<heel::Grant>,
environment: Vec<(String, String)>,
env_source: Option<Arc<dyn EnvSource>>,
space_environment: Vec<(String, PathBuf)>,
write_denylist: Option<heel::WriteDenylist>,
network: Option<CompiledNetworkPolicy>,
approver: Option<AnyDomainApprover>,
audit: Option<heel::NetworkAuditLog>,
priority: heel::ProcessPriority,
agent: Option<Arc<str>>,
scanner: ProcessScanner,
unconfined: bool,
ssh_client: crate::ssh::SshClient,
}
#[derive(Clone)]
pub struct Sandbox {
inner: Arc<SandboxInner>,
}
impl std::fmt::Debug for Sandbox {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Sandbox")
.field("working_dir", &self.inner.working_dir)
.field("agent", &self.inner.agent)
.finish_non_exhaustive()
}
}
impl Sandbox {
#[must_use]
pub fn new(
backend: Backend,
executor: impl Executor + 'static,
working_dir: impl Into<PathBuf>,
) -> Self {
Self {
inner: Arc::new(SandboxInner {
backend,
executor: Arc::new(AnyExecutor::new(executor)),
working_dir: working_dir.into(),
grants: Grants::new(),
fixed_grants: Vec::new(),
environment: Vec::new(),
env_source: None,
space_environment: Vec::new(),
write_denylist: None,
network: None,
approver: None,
audit: None,
priority: heel::ProcessPriority::default(),
agent: None,
scanner: ProcessScanner::default(),
unconfined: false,
ssh_client: crate::ssh::SshClient::default(),
}),
}
}
fn edit(mut self, edit: impl FnOnce(&mut SandboxInner)) -> Self {
edit(Arc::make_mut(&mut self.inner));
self
}
#[must_use]
pub fn with_grants(self, grants: Grants) -> Self {
self.edit(|inner| inner.grants = grants)
}
#[must_use]
pub fn with_fixed_grants(self, grants: Vec<heel::Grant>) -> Self {
self.edit(|inner| inner.fixed_grants = grants)
}
#[must_use]
pub fn with_environment(self, environment: Vec<(String, String)>) -> Self {
self.edit(|inner| inner.environment = environment)
}
#[must_use]
pub fn with_env_source(self, source: impl EnvSource + 'static) -> Self {
self.edit(|inner| inner.env_source = Some(Arc::new(source)))
}
pub(crate) fn with_space_environment(self, environment: Vec<(String, PathBuf)>) -> Self {
self.edit(|inner| inner.space_environment = environment)
}
#[must_use]
pub fn with_write_denylist(self, denylist: heel::WriteDenylist) -> Self {
self.edit(|inner| inner.write_denylist = Some(denylist))
}
#[must_use]
pub fn with_network_policy(self, policy: CompiledNetworkPolicy) -> Self {
self.edit(|inner| inner.network = Some(policy))
}
#[must_use]
pub fn with_domain_approver(self, approver: impl DomainApprover + 'static) -> Self {
self.edit(|inner| inner.approver = Some(AnyDomainApprover::new(approver)))
}
#[must_use]
pub fn with_audit_log(self, log: heel::NetworkAuditLog) -> Self {
self.edit(|inner| inner.audit = Some(log))
}
#[must_use]
pub fn with_priority(self, priority: heel::ProcessPriority) -> Self {
self.edit(|inner| inner.priority = priority)
}
#[must_use]
pub fn with_agent(self, agent: impl Into<String>) -> Self {
let agent: Arc<str> = Arc::from(agent.into());
self.edit(|inner| inner.agent = Some(agent))
}
#[must_use]
pub fn derived(&self, own: GrantSnapshot) -> Self {
let grants = self.inner.grants.derived(own);
self.clone().edit(|inner| {
inner.grants = grants;
inner.agent = None;
inner.space_environment = Vec::new();
})
}
#[must_use]
pub fn grants(&self) -> &Grants {
&self.inner.grants
}
#[must_use]
pub fn working_dir(&self) -> &Path {
&self.inner.working_dir
}
#[must_use]
pub fn with_working_dir(self, working_dir: impl Into<PathBuf>) -> Self {
self.edit(|inner| inner.working_dir = working_dir.into())
}
#[must_use]
pub fn with_backend(self, backend: Backend) -> Self {
self.edit(|inner| inner.backend = backend)
}
pub(crate) fn host_heel(&self) -> Option<&heel::HeelBinary> {
match &self.inner.backend {
Backend::Host { heel } => Some(heel),
Backend::Container { .. } | Backend::Ssh { .. } => None,
}
}
pub(crate) fn executor(&self) -> Arc<AnyExecutor> {
Arc::clone(&self.inner.executor)
}
pub(crate) fn backend(&self) -> &Backend {
&self.inner.backend
}
pub(crate) fn priority(&self) -> heel::ProcessPriority {
self.inner.priority
}
pub(crate) fn unconfined(&self) -> Self {
self.clone().edit(|inner| inner.unconfined = true)
}
pub(crate) fn with_scanner(self, scanner: ProcessScanner) -> Self {
self.edit(|inner| inner.scanner = scanner)
}
pub(crate) fn with_ssh_client(self, client: crate::ssh::SshClient) -> Self {
self.edit(|inner| inner.ssh_client = client)
}
pub async fn spawn(&self, spec: SpawnSpec) -> Result<SandboxedChild, SpawnError> {
match &self.inner.backend {
Backend::Host { .. } => self.spawn_host(spec).await,
Backend::Container { runtime, launch } => self.spawn_container(runtime, launch, spec),
Backend::Ssh {
server,
heel,
launch,
} => self.spawn_ssh(server, heel.as_deref(), launch, spec).await,
}
}
}