use std::collections::BTreeMap;
use std::os::fd::OwnedFd;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use ag_contracts::{HostCacheSharing, TurnNotice};
use ag_harness::RunEventKind;
use ag_harness::bash::{BashConfig, BashError};
use ag_harness::event::Item;
use ag_harness::sandbox::{IfUnavailable, Sandbox, SandboxUnavailableReason, SandboxWarning};
use rustix::fs::{self, AtFlags, FileType, Mode, OFlags};
use super::cargo_cache::TrustedCargoCache;
use super::config::{agentty_home, chatgpt_auth_file};
pub(crate) const SESSION_SANDBOX: Sandbox = Sandbox::Native {
if_unavailable: IfUnavailable::Unsandboxed,
};
pub(crate) const UTILITY_SANDBOX: Sandbox = Sandbox::Native {
if_unavailable: IfUnavailable::Refuse,
};
const CARGO_HOME_DIRECTORY: &str = "cargo";
const CARGO_CONFIG_FILES: [&str; 2] = ["config.toml", "config"];
const CARGO_TRUSTED_FILES: [&str; 4] = ["config.toml", "config", "credentials.toml", "credentials"];
const DISCARDED_CARGO_ENTRY: &str = ".agentty-discarded-cargo-entry";
const CARGO_SHARED_DIRECTORIES: [&str; 2] = ["registry", "git"];
const CARGO_SHARED_LOCKS: [&str; 2] = [".package-cache", ".package-cache-mutate"];
const CARGO_AUTO_CLEAN: (&str, &str) = ("CARGO_CACHE_AUTO_CLEAN_FREQUENCY", "never");
const CACHE_ENVIRONMENT: [(&str, &str); 6] = [
("CARGO_HOME", CARGO_HOME_DIRECTORY),
("GOCACHE", "go-build"),
("GOMODCACHE", "go-mod"),
("PIP_CACHE_DIR", "pip"),
("XDG_CACHE_HOME", "cache"),
("npm_config_cache", "npm"),
];
const AGENTTY_PRIVATE_DIRECTORIES: [&str; 3] = ["auth", "db", "tmp"];
const APPLICATION: &str = "the application";
#[derive(Clone, Debug, Eq, PartialEq)]
enum CargoCacheSource {
PerSession,
Project(TrustedCargoCache),
Host(PathBuf),
}
pub(crate) struct CommandSandbox {
cargo: CargoCacheSource,
hidden: Vec<PathBuf>,
host_cache_directories: Vec<PathBuf>,
host_cache_files: Vec<PathBuf>,
not_shared: Vec<String>,
shared_environment: BTreeMap<&'static str, PathBuf>,
temporary_directory: PathBuf,
}
impl CommandSandbox {
pub(crate) async fn prepare(
data_root: &Path,
temporary_directory: PathBuf,
workspace: &Path,
environment: &BTreeMap<String, String>,
cargo_cache: Option<TrustedCargoCache>,
host_caches: HostCacheSharing,
) -> Result<Self, String> {
let host_config = Self::host_cargo_config(workspace, environment).await;
if let Some(cargo_cache) = &cargo_cache {
let _ = tokio::fs::create_dir_all(cargo_cache.hidden_path()).await;
}
let mut sandbox = Self::new(data_root, temporary_directory.clone(), environment);
if let Some(cargo_cache) = &cargo_cache {
sandbox.hidden.push(cargo_cache.hidden_path().to_path_buf());
}
let host_cargo = Self::host_cargo_home(environment).filter(|_| host_caches.is_shared());
let directory = temporary_directory;
let worktree = workspace.to_path_buf();
let taken = std::iter::once(workspace.to_path_buf())
.chain(sandbox.hidden.iter().cloned())
.collect::<Vec<_>>();
let limits_environment = environment.clone();
let project_cache = cargo_cache.clone();
let (cargo, limits) = tokio::task::spawn_blocking(move || {
let mut limits = ShareLimits::new(&limits_environment, &taken);
let mut cargo_limits = limits.clone();
let cargo = match host_cargo {
Some(home) if Self::prepare_host_cargo(&home, &mut cargo_limits) => {
limits = cargo_limits;
CargoCacheSource::Host(home)
}
_ => project_cache.map_or(CargoCacheSource::PerSession, CargoCacheSource::Project),
};
Self::reset_cargo_home(&directory, host_config.as_deref(), &cargo, &worktree)
.map(|()| (cargo, limits))
})
.await
.map_err(std::io::Error::other)
.flatten()
.map_err(|error| format!("Failed to prepare the sandbox Cargo directory: {error}"))?;
if let CargoCacheSource::Host(home) = &cargo {
sandbox.host_cache_directories = CARGO_SHARED_DIRECTORIES
.iter()
.map(|name| home.join(name))
.collect();
sandbox.host_cache_files = CARGO_SHARED_LOCKS
.iter()
.map(|name| home.join(name))
.collect();
} else if host_caches.is_shared() {
sandbox.not_shared.push("Cargo".to_string());
}
sandbox.cargo = cargo;
if host_caches.is_shared() {
sandbox.share_tool_caches(environment, limits).await;
}
Ok(sandbox)
}
pub(crate) fn shares_host_caches(&self) -> bool {
!self.host_cache_directories.is_empty() || !self.host_cache_files.is_empty()
}
pub(crate) fn notice(&self) -> Option<TurnNotice> {
(!self.not_shared.is_empty()).then(|| TurnNotice::HostCachesNotShared {
caches: self.not_shared.clone(),
})
}
pub(crate) fn new(
data_root: &Path,
temporary_directory: PathBuf,
environment: &BTreeMap<String, String>,
) -> Self {
let agentty_files = agentty_home(environment)
.into_iter()
.flat_map(|home| AGENTTY_PRIVATE_DIRECTORIES.map(|directory| home.join(directory)));
let hidden = std::iter::once(data_root.to_path_buf())
.chain(chatgpt_auth_file(environment))
.chain(agentty_files)
.filter_map(|path| std::path::absolute(path).ok())
.collect();
Self {
cargo: CargoCacheSource::PerSession,
hidden,
host_cache_directories: Vec::new(),
host_cache_files: Vec::new(),
not_shared: Vec::new(),
shared_environment: BTreeMap::new(),
temporary_directory,
}
}
pub(crate) fn grant(&self, config: BashConfig) -> Result<BashConfig, BashError> {
let mut config = config
.with_full_disk_read()?
.with_write(PathBuf::from("."))?
.with_network()
.with_temporary_directory(self.temporary_directory.clone())?;
for path in &self.hidden {
config = config.with_hidden_path(path.clone())?;
}
for path in &self.host_cache_directories {
config = config.with_host_cache_directory(path.clone())?;
}
for path in &self.host_cache_files {
config = config.with_host_cache_file(path.clone())?;
}
for (name, directory) in CACHE_ENVIRONMENT {
let value = self
.shared_environment
.get(name)
.cloned()
.unwrap_or_else(|| self.temporary_directory.join(directory));
config = config.with_environment(name.to_string(), value.display().to_string())?;
}
if matches!(self.cargo, CargoCacheSource::Host(_)) {
let (name, value) = CARGO_AUTO_CLEAN;
config = config.with_environment(name.to_string(), value.to_string())?;
}
Ok(config)
}
async fn share_tool_caches(
&mut self,
environment: &BTreeMap<String, String>,
mut limits: ShareLimits,
) {
for (variable, name, cache) in Self::host_tool_caches(environment, std::env::consts::OS) {
let Ok(metadata) = tokio::fs::symlink_metadata(&cache).await else {
continue;
};
let resolved = tokio::fs::canonicalize(&cache).await.ok();
match resolved {
Some(resolved) if metadata.is_dir() && limits.claim(&resolved) => {
self.host_cache_directories.push(resolved.clone());
self.shared_environment.insert(variable, resolved);
}
_ => self.not_shared.push(name.to_string()),
}
}
}
fn host_cargo_home(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
environment
.get("CARGO_HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.or_else(|| {
environment
.get("HOME")
.map(|home| Path::new(home).join(".cargo"))
})
}
fn prepare_host_cargo(home: &Path, limits: &mut ShareLimits) -> bool {
limits.in_home(&ShareLimits::resolve_nearest(home))
&& std::fs::create_dir_all(home).is_ok()
&& CARGO_SHARED_DIRECTORIES
.iter()
.all(|name| Self::host_entry(&home.join(name), true, limits))
&& CARGO_SHARED_LOCKS
.iter()
.all(|name| Self::host_entry(&home.join(name), false, limits))
}
fn host_entry(path: &Path, directory: bool, limits: &mut ShareLimits) -> bool {
Self::create_host_entry(path, directory)
&& std::fs::canonicalize(path).is_ok_and(|resolved| limits.claim(&resolved))
}
fn create_host_entry(path: &Path, directory: bool) -> bool {
if std::fs::symlink_metadata(path)
.is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)
{
let _ = if directory {
std::fs::create_dir(path)
} else {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map(drop)
};
}
std::fs::symlink_metadata(path).is_ok_and(|metadata| {
if directory {
metadata.is_dir()
} else {
metadata.is_file() && metadata.nlink() == 1
}
})
}
fn host_tool_caches(
environment: &BTreeMap<String, String>,
platform: &str,
) -> Vec<(&'static str, &'static str, PathBuf)> {
let absolute = |name: &str| {
environment
.get(name)
.map(PathBuf::from)
.filter(|path| path.is_absolute())
};
let home = absolute("HOME");
let xdg_cache = absolute("XDG_CACHE_HOME");
let user_cache = if platform == "macos" {
home.as_ref().map(|home| home.join("Library/Caches"))
} else {
xdg_cache
.clone()
.or_else(|| home.as_ref().map(|home| home.join(".cache")))
};
let go_path = environment
.get("GOPATH")
.and_then(|value| std::env::split_paths(value).next())
.filter(|path| path.is_absolute())
.or_else(|| home.as_ref().map(|home| home.join("go")));
let caches = [
(
"GOMODCACHE",
"Go modules",
absolute("GOMODCACHE").or_else(|| go_path.map(|path| path.join("pkg/mod"))),
),
(
"GOCACHE",
"Go build",
absolute("GOCACHE").or_else(|| user_cache.map(|cache| cache.join("go-build"))),
),
(
"PIP_CACHE_DIR",
"pip",
absolute("PIP_CACHE_DIR").or_else(|| {
xdg_cache.map(|cache| cache.join("pip")).or_else(|| {
let base = if platform == "macos" {
"Library/Caches/pip"
} else {
".cache/pip"
};
home.as_ref().map(|home| home.join(base))
})
}),
),
(
"npm_config_cache",
"npm",
absolute("npm_config_cache")
.or_else(|| absolute("NPM_CONFIG_CACHE"))
.or_else(|| home.as_ref().map(|home| home.join(".npm"))),
),
];
caches
.into_iter()
.filter_map(|(variable, name, cache)| Some((variable, name, cache?)))
.collect()
}
fn reset_cargo_home(
temporary_directory: &Path,
host_config: Option<&Path>,
source: &CargoCacheSource,
worktree: &Path,
) -> std::io::Result<()> {
std::fs::create_dir_all(temporary_directory)?;
let temporary = fs::open(temporary_directory, Self::directory_flags(), Mode::empty())?;
let planted = fs::statat(&temporary, CARGO_HOME_DIRECTORY, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|stat| !FileType::from_raw_mode(stat.st_mode).is_dir());
if planted {
fs::unlinkat(&temporary, CARGO_HOME_DIRECTORY, AtFlags::empty())?;
}
let _ = fs::mkdirat(&temporary, CARGO_HOME_DIRECTORY, Mode::RWXU);
let cargo = fs::openat(
&temporary,
CARGO_HOME_DIRECTORY,
Self::directory_flags(),
Mode::empty(),
)?;
Self::clear_cargo_home(temporary_directory, &temporary, &cargo, host_config)?;
Self::link_shared_cargo(temporary_directory, &temporary, &cargo, source)?;
if let CargoCacheSource::Project(cargo_cache) = source {
cargo_cache.copy_into(&cargo, worktree);
}
Ok(())
}
pub(super) fn directory_flags() -> OFlags {
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
}
fn clear_cargo_home(
temporary_directory: &Path,
temporary: &OwnedFd,
cargo: &OwnedFd,
host_config: Option<&Path>,
) -> std::io::Result<()> {
for name in CARGO_TRUSTED_FILES {
match fs::statat(cargo, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) if FileType::from_raw_mode(stat.st_mode).is_dir() => {
Self::discard(temporary_directory, temporary, cargo, name)?;
}
Ok(_) => fs::unlinkat(cargo, name, AtFlags::empty())?,
Err(_) => {}
}
}
if let Some(config) = host_config {
let _ = fs::symlinkat(config, cargo, CARGO_CONFIG_FILES[0]);
}
Ok(())
}
fn discard(
temporary_directory: &Path,
temporary: &OwnedFd,
cargo: &OwnedFd,
name: &str,
) -> std::io::Result<()> {
let discarded = temporary_directory.join(DISCARDED_CARGO_ENTRY);
Self::remove_discarded(&discarded)?;
fs::renameat(cargo, name, temporary, DISCARDED_CARGO_ENTRY)?;
Self::remove_discarded(&discarded)
}
fn link_shared_cargo(
temporary_directory: &Path,
temporary: &OwnedFd,
cargo: &OwnedFd,
source: &CargoCacheSource,
) -> std::io::Result<()> {
for name in CARGO_SHARED_DIRECTORIES.iter().chain(&CARGO_SHARED_LOCKS) {
let existing = fs::statat(cargo, *name, AtFlags::SYMLINK_NOFOLLOW)
.ok()
.map(|stat| FileType::from_raw_mode(stat.st_mode));
let host = match source {
CargoCacheSource::Host(host) => Some(host),
CargoCacheSource::PerSession | CargoCacheSource::Project(_) => None,
};
match (existing, host) {
(Some(FileType::Directory), Some(_)) => {
Self::discard(temporary_directory, temporary, cargo, name)?;
}
(Some(FileType::Symlink), _) | (Some(_), Some(_)) => {
fs::unlinkat(cargo, *name, AtFlags::empty())?;
}
_ => {}
}
if let Some(host) = host {
fs::symlinkat(host.join(name), cargo, *name)?;
}
}
Ok(())
}
fn remove_discarded(path: &Path) -> std::io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_dir() => std::fs::remove_dir_all(path),
Ok(_) => std::fs::remove_file(path),
Err(_) => Ok(()),
}
}
async fn host_cargo_config(
workspace: &Path,
environment: &BTreeMap<String, String>,
) -> Option<PathBuf> {
let cargo_home = Self::host_cargo_home(environment)?;
let found_from_workspace = cargo_home.file_name() == Some(".cargo".as_ref())
&& cargo_home
.parent()
.is_some_and(|parent| workspace.starts_with(parent));
if found_from_workspace {
return None;
}
for name in CARGO_CONFIG_FILES {
let config = cargo_home.join(name);
if tokio::fs::metadata(&config)
.await
.is_ok_and(|metadata| metadata.is_file())
{
return Some(config);
}
}
None
}
}
#[derive(Clone)]
struct ShareLimits {
home: Option<PathBuf>,
program_directories: Vec<PathBuf>,
taken: Vec<PathBuf>,
}
impl ShareLimits {
fn new(environment: &BTreeMap<String, String>, taken: &[PathBuf]) -> Self {
let resolve = |path: PathBuf| std::fs::canonicalize(&path).unwrap_or(path);
let home = environment
.get("HOME")
.map(PathBuf::from)
.filter(|home| home.is_absolute())
.map(resolve);
let program_directories = environment
.get("PATH")
.into_iter()
.flat_map(std::env::split_paths)
.filter(|directory| directory.is_absolute())
.map(resolve)
.collect();
let taken = taken
.iter()
.map(|path| Self::resolve_nearest(path))
.collect();
Self {
home,
program_directories,
taken,
}
}
fn claim(&mut self, cache: &Path) -> bool {
let allowed = self.allows(cache);
if allowed {
self.taken.push(cache.to_path_buf());
}
allowed
}
fn resolve_nearest(path: &Path) -> PathBuf {
path.ancestors()
.find_map(|ancestor| {
let base = std::fs::canonicalize(ancestor).ok()?;
Some(base.join(path.strip_prefix(ancestor).ok()?))
})
.unwrap_or_default()
}
fn allows(&self, cache: &Path) -> bool {
let git = cache.components().any(|part| {
part.as_os_str()
.as_encoded_bytes()
.eq_ignore_ascii_case(b".git")
});
self.in_home(cache)
&& !git
&& !self
.program_directories
.iter()
.chain(&self.taken)
.any(|limit| cache.starts_with(limit) || limit.starts_with(cache))
}
fn in_home(&self, path: &Path) -> bool {
self.home.as_ref().is_some_and(|home| {
path.starts_with(home) && path != home && !path.starts_with(home.join("Library"))
})
}
}
#[must_use = "a helper process must return this exit code from `main` at once"]
pub fn dispatch_sandbox_helper() -> Option<ExitCode> {
ag_harness::sandbox::dispatch()
}
pub(crate) fn notice(event: &RunEventKind) -> Option<TurnNotice> {
match event {
RunEventKind::SandboxUnavailable(warning) => Some(unavailable(warning)),
RunEventKind::ItemCompleted {
item: Item::ToolCall(call),
..
} if call.likely_sandbox_denial => Some(TurnNotice::LikelySandboxDenial),
_ => None,
}
}
fn unavailable(warning: &SandboxWarning) -> TurnNotice {
let message = match warning.reason {
SandboxUnavailableReason::UnixSocketsUnsupported => warning.message.clone(),
_ => format!("Commands run without the sandbox. {}", warning.message),
};
TurnNotice::SandboxUnavailable {
message,
remedy: warning.remedy.replace(APPLICATION, "Agentty"),
}
}
#[cfg(test)]
#[path = "sandbox_test.rs"]
mod tests;