use super::SandboxPolicy;
use crate::config::SandboxConfig;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::io::{Read, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
const DOCKER_KILL_TIMEOUT: Duration = Duration::from_secs(10);
const CONTAINER_WORKDIR: &str = "/workspace";
const ENV_ALLOWLIST_COMMON: &[&str] = &["PATH", "LANG", "LC_ALL", "PYTHONIOENCODING", "PYTHONUTF8"];
const ENV_ALLOWLIST_WINDOWS: &[&str] = &[
"PATHEXT",
"SYSTEMROOT",
"WINDIR",
"COMSPEC",
"TEMP",
"TMP",
"HOMEDRIVE",
"HOMEPATH",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"NUMBER_OF_PROCESSORS",
"PROCESSOR_ARCHITECTURE",
"OS",
];
const ENV_ALLOWLIST_POSIX: &[&str] = &[
"HOME",
"USER",
"LOGNAME",
"SHELL",
"TMPDIR",
"TERM",
"TZ",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
"REQUESTS_CA_BUNDLE",
"CURL_CA_BUNDLE",
"NODE_EXTRA_CA_CERTS",
];
const ENV_ALLOWLIST_PREFIXES: &[&str] = &["LC_", "XDG_"];
const SECRET_MARKERS: &[&str] = &[
"TOKEN",
"SECRET",
"PASSWORD",
"PASSWD",
"CREDENTIAL",
"API_KEY",
];
const SECRET_SUFFIXES: &[&str] = &["_KEY"];
pub fn env_allowlist() -> Vec<&'static str> {
let platform = if cfg!(windows) {
ENV_ALLOWLIST_WINDOWS
} else {
ENV_ALLOWLIST_POSIX
};
ENV_ALLOWLIST_COMMON
.iter()
.chain(platform)
.copied()
.collect()
}
pub fn is_secret_name(name: &str) -> bool {
let upper = name.to_uppercase();
SECRET_MARKERS.iter().any(|marker| upper.contains(marker))
|| SECRET_SUFFIXES.iter().any(|suffix| upper.ends_with(suffix))
}
pub fn scrubbed_env(
passthrough: &[String],
environment: impl IntoIterator<Item = (OsString, OsString)>,
) -> BTreeMap<OsString, OsString> {
let normalize = |name: &str| {
if cfg!(windows) {
name.to_uppercase()
} else {
name.to_owned()
}
};
let current: BTreeMap<String, OsString> = environment
.into_iter()
.filter_map(|(name, value)| Some((normalize(name.to_str()?), value)))
.collect();
let allowed = env_allowlist();
let mut env = BTreeMap::new();
for (name, value) in ¤t {
let listed = allowed.contains(&name.as_str());
let family = ENV_ALLOWLIST_PREFIXES
.iter()
.any(|prefix| name.starts_with(prefix))
&& !is_secret_name(name);
if listed || family {
env.insert(OsString::from(name), value.clone());
}
}
for name in passthrough {
if is_secret_name(name) {
continue;
}
if let Some(value) = current.get(&normalize(name)) {
env.insert(OsString::from(normalize(name)), value.clone());
}
}
env.entry(OsString::from("PYTHONIOENCODING"))
.or_insert_with(|| OsString::from("utf-8"));
env
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecResult {
pub returncode: i32,
pub stdout: String,
pub stderr: String,
pub timed_out: bool,
}
impl ExecResult {
pub fn ok(&self) -> bool {
self.returncode == 0 && !self.timed_out
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecRequest {
Shell(String),
Argv(Vec<String>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Executor {
Subprocess,
Docker(DockerExecutor),
}
impl Executor {
pub fn name(&self) -> &'static str {
match self {
Self::Subprocess => "subprocess",
Self::Docker(_) => "docker",
}
}
pub fn run(
&self,
policy: &SandboxPolicy,
request: &ExecRequest,
stdin: Option<&str>,
secrets: &[(String, String)],
) -> std::io::Result<ExecResult> {
match self {
Self::Subprocess => run_subprocess(policy, request, stdin, secrets),
Self::Docker(docker) => Ok(docker.run(policy, request, stdin, secrets)),
}
}
pub fn python_argv(&self) -> Vec<String> {
let interpreter = match self {
Self::Docker(_) => "python",
Self::Subprocess if cfg!(windows) => "python",
Self::Subprocess => "python3",
};
vec![interpreter.to_owned(), "-I".to_owned(), "-".to_owned()]
}
}
pub fn build_executor(config: &SandboxConfig) -> (Executor, Option<String>) {
if config.mode != crate::config::SandboxMode::Docker {
return (Executor::Subprocess, None);
}
if docker_available() {
return (Executor::Docker(DockerExecutor::new(config)), None);
}
(
Executor::Subprocess,
Some(
"Docker requested but not available; falling back to the subprocess sandbox."
.to_owned(),
),
)
}
pub fn docker_available() -> bool {
let Ok(mut child) = Command::new("docker")
.arg("info")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
else {
return false;
};
let deadline = Instant::now() + Duration::from_secs(10);
loop {
match child.try_wait() {
Ok(Some(status)) => return status.success(),
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
_ => {
let _ = child.kill();
let _ = child.wait();
return false;
}
}
}
}
fn decode(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes)
.replace("\r\n", "\n")
.replace('\r', "\n")
}
fn encode(text: &str) -> Vec<u8> {
if cfg!(windows) {
text.replace('\n', "\r\n").into_bytes()
} else {
text.as_bytes().to_vec()
}
}
fn command_for(request: &ExecRequest) -> Command {
match request {
ExecRequest::Shell(line) => shell_command(line),
ExecRequest::Argv(argv) => {
let mut command = Command::new(&argv[0]);
command.args(&argv[1..]);
command
}
}
}
#[cfg(windows)]
fn shell_command(line: &str) -> Command {
use std::os::windows::process::CommandExt;
let comspec = std::env::var_os("COMSPEC").unwrap_or_else(|| OsString::from("cmd.exe"));
let mut command = Command::new(comspec);
command.raw_arg(format!("/c \"{line}\""));
command
}
#[cfg(not(windows))]
fn shell_command(line: &str) -> Command {
let mut command = Command::new("/bin/sh");
command.arg("-c").arg(line);
command
}
#[cfg(windows)]
fn new_process_group(command: &mut Command) {
use std::os::windows::process::CommandExt;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
command.creation_flags(CREATE_NEW_PROCESS_GROUP);
}
#[cfg(unix)]
fn new_process_group(command: &mut Command) {
use std::os::unix::process::CommandExt;
command.process_group(0);
}
#[cfg(not(any(windows, unix)))]
fn new_process_group(_command: &mut Command) {}
fn kill_process_tree(child: &mut Child) {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
let pid = child.id().to_string();
let tree_kill = if cfg!(windows) {
Command::new("taskkill")
.args(["/T", "/F", "/PID", &pid])
.output()
} else {
Command::new("kill")
.args(["-KILL", "--", &format!("-{pid}")])
.output()
};
drop(tree_kill);
let _ = child.kill();
}
pub const MAX_CAPTURE_BYTES: u64 = 8 * 1024 * 1024;
fn reader<R: Read + Send + 'static>(pipe: R, sender: mpsc::Sender<(usize, Vec<u8>)>, index: usize) {
std::thread::spawn(move || {
let _ = sender.send((index, capture(pipe)));
});
}
fn drain(
receiver: &mpsc::Receiver<(usize, Vec<u8>)>,
outputs: &mut [Option<Vec<u8>>; 2],
wait: Duration,
) {
let deadline = Instant::now() + wait;
while outputs.iter().any(Option::is_none) {
match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
Ok((index, bytes)) => outputs[index] = Some(bytes),
Err(_) => break,
}
}
}
fn capture(mut pipe: impl Read) -> Vec<u8> {
let mut bytes = Vec::new();
let _ = (&mut pipe).take(MAX_CAPTURE_BYTES).read_to_end(&mut bytes);
let _ = std::io::copy(&mut pipe, &mut std::io::sink());
bytes
}
fn exit_code(status: std::process::ExitStatus) -> i32 {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
if let Some(signal) = status.signal() {
return -signal;
}
}
status.code().unwrap_or(-1)
}
pub fn run_subprocess(
policy: &SandboxPolicy,
request: &ExecRequest,
stdin: Option<&str>,
secrets: &[(String, String)],
) -> std::io::Result<ExecResult> {
let mut command = command_for(request);
let mut env = scrubbed_env(&policy.env_passthrough, std::env::vars_os());
for (name, value) in secrets {
let name = if cfg!(windows) {
name.to_uppercase()
} else {
name.clone()
};
env.insert(OsString::from(name), OsString::from(value));
}
command
.current_dir(super::plain_path(policy.workspace()))
.env_clear()
.envs(env)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
new_process_group(&mut command);
let mut child = command.spawn()?;
let input = stdin.map(encode).unwrap_or_default();
if let Some(mut pipe) = child.stdin.take() {
std::thread::spawn(move || {
let _ = pipe.write_all(&input);
});
}
let (sender, receiver) = mpsc::channel();
if let Some(pipe) = child.stdout.take() {
reader(pipe, sender.clone(), 0);
}
if let Some(pipe) = child.stderr.take() {
reader(pipe, sender, 1);
}
let deadline = Instant::now() + policy.timeout;
let mut outputs: [Option<Vec<u8>>; 2] = [None, None];
let mut status = None;
loop {
while let Ok((index, bytes)) = receiver.try_recv() {
outputs[index] = Some(bytes);
}
if status.is_none() {
status = child.try_wait()?;
}
if let (Some(status), [Some(_), Some(_)]) = (status, &outputs) {
let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
return Ok(ExecResult {
returncode: exit_code(status),
stdout: policy.truncate(decode(&stdout)),
stderr: policy.truncate(decode(&stderr)),
timed_out: false,
});
}
if Instant::now() >= deadline {
break;
}
std::thread::sleep(Duration::from_millis(10));
}
kill_process_tree(&mut child);
drain(&receiver, &mut outputs, DRAIN_TIMEOUT);
let _ = child.wait();
let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
let seconds = policy.timeout.as_secs();
Ok(ExecResult {
returncode: 124,
stdout: policy.truncate(decode(&stdout)),
stderr: format!(
"{}\n[timed out after {seconds}s]",
policy.truncate(decode(&stderr))
),
timed_out: true,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DockerExecutor {
pub image: String,
pub memory: String,
pub cpus: String,
pub network: bool,
}
impl DockerExecutor {
pub fn new(config: &SandboxConfig) -> Self {
Self {
image: config.docker_image.clone(),
memory: config.docker_memory.clone(),
cpus: config.docker_cpus.clone(),
network: config.docker_network,
}
}
pub fn build_command(
&self,
workspace: &Path,
request: &ExecRequest,
name: Option<&str>,
) -> Vec<String> {
self.build_command_with_env(workspace, request, name, &[])
}
pub fn build_command_with_env(
&self,
workspace: &Path,
request: &ExecRequest,
name: Option<&str>,
env_names: &[&str],
) -> Vec<String> {
let mut command: Vec<String> = [
"docker",
"run",
"--rm",
"-i",
"--memory",
&self.memory,
"--cpus",
&self.cpus,
"--pids-limit",
"256",
"--cap-drop",
"ALL",
"--cap-add",
"CHOWN",
"--cap-add",
"DAC_OVERRIDE",
"--cap-add",
"FOWNER",
"--cap-add",
"FSETID",
"--cap-add",
"SETUID",
"--cap-add",
"SETGID",
"--security-opt",
"no-new-privileges",
"-w",
CONTAINER_WORKDIR,
"-v",
]
.iter()
.map(|part| (*part).to_owned())
.collect();
command.push(format!("{}:{CONTAINER_WORKDIR}", mount_source(workspace)));
if !self.network {
command.extend(["--network".to_owned(), "none".to_owned()]);
}
if let Some(name) = name {
command.extend(["--name".to_owned(), name.to_owned()]);
}
for env_name in env_names {
command.extend(["-e".to_owned(), (*env_name).to_owned()]);
}
command.push(self.image.clone());
match request {
ExecRequest::Shell(line) => {
command.extend(["sh".to_owned(), "-c".to_owned(), line.clone()]);
}
ExecRequest::Argv(argv) => command.extend(argv.iter().cloned()),
}
command
}
fn run(
&self,
policy: &SandboxPolicy,
request: &ExecRequest,
stdin: Option<&str>,
secrets: &[(String, String)],
) -> ExecResult {
let name = format!("agent86-{}", crate::turn::new_session_id());
let env_names: Vec<&str> = secrets.iter().map(|(name, _)| name.as_str()).collect();
let argv =
self.build_command_with_env(policy.workspace(), request, Some(&name), &env_names);
let mut command = Command::new(&argv[0]);
command
.args(&argv[1..])
.envs(secrets.iter().map(|(name, value)| (name, value)))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = match command.spawn() {
Ok(child) => child,
Err(error) => {
return ExecResult {
returncode: 127,
stdout: String::new(),
stderr: format!("docker not found: {error}"),
timed_out: false,
};
}
};
let input = stdin.map(encode).unwrap_or_default();
if let Some(mut pipe) = child.stdin.take() {
std::thread::spawn(move || {
let _ = pipe.write_all(&input);
});
}
let (sender, receiver) = mpsc::channel();
if let Some(pipe) = child.stdout.take() {
reader(pipe, sender.clone(), 0);
}
if let Some(pipe) = child.stderr.take() {
reader(pipe, sender, 1);
}
let deadline = Instant::now() + policy.timeout;
let mut outputs: [Option<Vec<u8>>; 2] = [None, None];
loop {
while let Ok((index, bytes)) = receiver.try_recv() {
outputs[index] = Some(bytes);
}
if let (Ok(Some(status)), [Some(_), Some(_)]) = (child.try_wait(), &outputs) {
let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
return ExecResult {
returncode: exit_code(status),
stdout: policy.truncate(decode(&stdout)),
stderr: policy.truncate(decode(&stderr)),
timed_out: false,
};
}
if Instant::now() >= deadline {
break;
}
std::thread::sleep(Duration::from_millis(10));
}
let _ = child.kill();
let _ = child.wait();
let killed = kill_container(&name);
let note = if killed {
""
} else {
" (container may still be running)"
};
drain(&receiver, &mut outputs, DRAIN_TIMEOUT);
let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
let stderr = policy.truncate(decode(&stderr));
let timed_out = format!("[timed out after {}s]{note}", policy.timeout.as_secs());
ExecResult {
returncode: 124,
stdout: policy.truncate(decode(&stdout)),
stderr: if stderr.is_empty() {
timed_out
} else {
format!("{stderr}\n{timed_out}")
},
timed_out: true,
}
}
}
fn kill_container(name: &str) -> bool {
let Ok(mut child) = Command::new("docker")
.args(["kill", name])
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
else {
return false;
};
let deadline = Instant::now() + DOCKER_KILL_TIMEOUT;
loop {
match child.try_wait() {
Ok(Some(status)) => return status.success(),
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
_ => {
let _ = child.kill();
return false;
}
}
}
}
pub fn mount_source(workspace: &Path) -> String {
let text = super::display_path(workspace).replace('\\', "/");
let bytes = text.as_bytes();
if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
format!("/{}{}", (bytes[0] as char).to_ascii_lowercase(), &text[2..])
} else {
text
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Counted<R> {
inner: R,
read: u64,
}
impl<R: Read> Read for Counted<R> {
fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
let count = self.inner.read(buffer)?;
self.read += count as u64;
Ok(count)
}
}
#[test]
fn a_flood_of_output_is_kept_to_the_cap_and_the_rest_drained() {
let total = MAX_CAPTURE_BYTES * 3;
let mut pipe = Counted {
inner: std::io::repeat(b'y').take(total),
read: 0,
};
let kept = capture(&mut pipe);
assert_eq!(kept.len() as u64, MAX_CAPTURE_BYTES);
assert_eq!(
pipe.read, total,
"everything was read, so the child never blocks"
);
assert_eq!(capture(&b"short"[..]), b"short");
}
#[test]
fn a_pipe_still_held_after_a_timeout_does_not_wipe_the_one_that_finished() {
let (sender, receiver) = mpsc::channel();
sender.send((0, b"partial output".to_vec())).unwrap();
let _held = sender;
let mut outputs = [None, None];
drain(&receiver, &mut outputs, Duration::from_millis(50));
assert_eq!(outputs[0].as_deref(), Some(&b"partial output"[..]));
assert_eq!(outputs[1], None);
}
}