Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(sandbox): extract native jail into its own module

Steven Enamakelf08eac8eecda
diff --git a/crates/openhuman-core/src/sandbox/mod.rs b/crates/openhuman-core/src/sandbox/mod.rs
index 457d5d2679..a9eb79eb3d 100644
--- a/crates/openhuman-core/src/sandbox/mod.rs
+++ b/crates/openhuman-core/src/sandbox/mod.rs
@@ -13,6 +13,7 @@
pub mod docker;
pub(crate) mod local_grants;
pub(crate) mod native_jail;
+pub(crate) mod shell_exec;
pub mod ops;
pub mod schemas;
pub mod types;
diff --git a/crates/openhuman-core/src/sandbox/native_jail.rs b/crates/openhuman-core/src/sandbox/native_jail.rs
index 0bc810e1b1..41cc08780e 100644
--- a/crates/openhuman-core/src/sandbox/native_jail.rs
+++ b/crates/openhuman-core/src/sandbox/native_jail.rs
@@ -3,7 +3,7 @@
use std::{collections::HashMap, ffi::OsString, path::Path, time::Duration};
#[cfg(feature = "modules")]
-use std::{collections::BTreeMap, ffi::OsStr};
+use std::collections::BTreeMap;
use super::types::{SandboxExecResult, SandboxPolicy, SandboxStatus};
use crate::config::Config;
@@ -111,159 +111,53 @@ async fn execute_owned(
anyhow::bail!("requested Landlock sandbox is unavailable");
}
- let resource = tinybox::reserve(config, contract::ReserveRequest::Resource)
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox could not reserve a native jail resource"))?;
- let result = async {
- let workspace = path_string(&policy.workspace_root, "sandbox workspace")?;
- tinybox::create(
- config,
- contract::CreateRequest {
- resource: resource.clone(),
- backend: "passthrough".to_owned(),
- host: contract::HostConfig::Local,
- workspace: contract::Workspace::Directory(workspace),
- network: contract::NetworkPolicy::default(),
- resources: contract::ResourceLimits::default(),
- ports: Vec::new(),
- env: BTreeMap::new(),
- },
- )
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox could not create a native jail resource"))?;
-
- let scratch = super::ops::CallDir::create(
- super::ops::sandbox_scratch_root(&policy.state_dir),
- "scratch",
- )?;
- let (env, read_write) = execution_environment(policy, extra_env, &scratch.path)?;
- let jail = jail_request(policy, read_write)?;
- let process = tinybox::reserve(config, contract::ReserveRequest::Process(resource.clone()))
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox could not reserve a native jail process"))?;
- let exec = shell_exec_request(
- process,
- &resource,
- command,
- working_dir,
- env,
- &policy.state_dir,
- timeout,
- false,
- Some(jail),
- )?;
- let process = tinybox::start_shell_exec(config, exec)
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox could not start the native jailed process"))?;
-
- collect_process(config, process, timeout).await
- }
- .await;
- let close = tinybox::close(config, resource).await;
- match (result, close) {
- (Ok(output), Ok(())) => Ok(output),
- (Err(error), Ok(())) => Err(error),
- (Ok(_), Err(_)) => anyhow::bail!("TinyBox did not acknowledge native jail cleanup"),
- (Err(error), Err(_)) => Err(error),
- }
+ let mut run = super::shell_exec::NativeShellRun::new(
+ command,
+ working_dir,
+ &policy.state_dir,
+ timeout,
+ );
+ run.workspace = policy.workspace_root.clone();
+ run.env = approved_environment(extra_env)?;
+ run.isolate_network = true;
+ // TinyBox adds its own per-call scratch directory to the writable grants and
+ // points TMPDIR, TMP and TEMP at it unless the caller overrides them.
+ run.jail = Some(jail_request(policy)?);
+ super::shell_exec::run(config, run).await
}
+/// The caller's environment overrides, which must be UTF-8 to cross the bus.
#[cfg(feature = "modules")]
-fn execution_environment(
- policy: &SandboxPolicy,
+fn approved_environment(
extra_env: &HashMap<OsString, OsString>,
- scratch: &Path,
-) -> anyhow::Result<(BTreeMap<String, String>, Vec<String>)> {
- let mut env = BTreeMap::new();
- for name in super::ops::SANDBOX_ENV_PASSTHROUGH {
- if let Some(value) = std::env::var_os(name) {
- env.insert(
- (*name).to_owned(),
- value
- .into_string()
- .map_err(|_| anyhow::anyhow!("sandbox environment is not UTF-8"))?,
- );
- }
- }
- for (name, value) in extra_env {
- let name = name
- .to_str()
- .ok_or_else(|| anyhow::anyhow!("sandbox environment name is not UTF-8"))?;
- let value = value
- .to_str()
- .ok_or_else(|| anyhow::anyhow!("sandbox environment value is not UTF-8"))?;
- env.insert(name.to_owned(), value.to_owned());
- }
-
- let scratch = path_string(scratch, "sandbox scratch directory")?;
- let read_write = policy
- .read_write_mounts
+) -> anyhow::Result<BTreeMap<String, String>> {
+ extra_env
.iter()
- .map(|path| path_string(path, "read-write grant"))
- .chain(std::iter::once(Ok(scratch.clone())))
- .collect::<anyhow::Result<Vec<_>>>()?;
- if !extra_env.contains_key(OsStr::new("TMPDIR")) {
- env.insert("TMPDIR".to_owned(), scratch.clone());
- }
- if !extra_env.contains_key(OsStr::new("TEMP")) {
- env.insert("TEMP".to_owned(), scratch.clone());
- }
- if !extra_env.contains_key(OsStr::new("TMP")) {
- env.insert("TMP".to_owned(), scratch);
- }
- Ok((env, read_write))
-}
-
-/// Map a host-authorized command onto TinyBox's `StartShellExec` request.
-///
-/// TinyBox selects the shell (cmd or bash with pipefail), builds the safe child
-/// environment and owns the scratch directory; the host supplies only the
-/// command, working directory, approved environment overrides and policy.
-#[cfg(feature = "modules")]
-#[allow(clippy::too_many_arguments)]
-fn shell_exec_request(
- process: contract::ResourceId,
- resource: &contract::ResourceId,
- command: &str,
- working_dir: &Path,
- extra_env: BTreeMap<String, String>,
- state_dir: &Path,
- timeout: Duration,
- preserve_pipeline_status: bool,
- jail: Option<contract::NativeJailConfig>,
-) -> anyhow::Result<contract::ShellExecRequest> {
- Ok(contract::ShellExecRequest {
- process,
- resource: resource.clone(),
- shell: contract::SelectShellRequest {
- command: command.to_owned(),
- preserve_pipeline_status,
- runtime_path: None,
- python_utf8: false,
- },
- cwd: Some(path_string(working_dir, "sandbox working directory")?),
- extra_env,
- state_dir: path_string(state_dir, "sandbox state directory")?,
- timeout_ms: u64::try_from(timeout.as_millis())
- .unwrap_or(u64::MAX)
- .max(1),
- stdin: None,
- jail,
- })
+ .map(|(name, value)| {
+ let name = name
+ .to_str()
+ .ok_or_else(|| anyhow::anyhow!("sandbox environment name is not UTF-8"))?;
+ let value = value
+ .to_str()
+ .ok_or_else(|| anyhow::anyhow!("sandbox environment value is not UTF-8"))?;
+ Ok((name.to_owned(), value.to_owned()))
+ })
+ .collect()
}
#[cfg(feature = "modules")]
-fn jail_request(
- policy: &SandboxPolicy,
- read_write: Vec<String>,
-) -> anyhow::Result<contract::NativeJailConfig> {
+fn jail_request(policy: &SandboxPolicy) -> anyhow::Result<contract::NativeJailConfig> {
Ok(contract::NativeJailConfig {
read_only: policy
.read_only_mounts
.iter()
.map(|path| path_string(path, "read-only grant"))
.collect::<anyhow::Result<Vec<_>>>()?,
- read_write,
+ read_write: policy
+ .read_write_mounts
+ .iter()
+ .map(|path| path_string(path, "read-write grant"))
+ .collect::<anyhow::Result<Vec<_>>>()?,
allow_net: policy.allow_network,
allow_subprocess: true,
enforcement: contract::JailEnforcement::Enforced,
@@ -272,87 +166,7 @@ fn jail_request(
}
#[cfg(feature = "modules")]
-async fn collect_process(
- config: &Config,
- process: contract::ProcessRef,
- timeout: Duration,
-) -> anyhow::Result<SandboxExecResult> {
- use contract::{ExecutionFailure, ExecutionState, OutputStream};
-
- let deadline = tokio::time::Instant::now() + timeout;
- let mut cursor = 0;
- let mut stdout = Vec::new();
- let mut stderr = Vec::new();
- let mut requested_cancel = false;
- let timed_out = loop {
- if !requested_cancel && tokio::time::Instant::now() >= deadline {
- tinybox::cancel(config, process.clone())
- .await
- .map_err(|_| {
- anyhow::anyhow!("TinyBox could not acknowledge process cancellation")
- })?;
- requested_cancel = true;
- }
- let batch = tinybox::read_output(config, process.clone(), cursor)
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox could not read native jail output"))?;
- if !batch.chunks.is_empty() && batch.next_sequence <= cursor {
- anyhow::bail!("TinyBox returned an invalid native jail output cursor");
- }
- let has_chunks = !batch.chunks.is_empty();
- let state = batch.state;
- for chunk in batch.chunks {
- match chunk.stream {
- OutputStream::Stdout => stdout.extend_from_slice(&chunk.bytes),
- OutputStream::Stderr => stderr.extend_from_slice(&chunk.bytes),
- }
- }
- cursor = batch.next_sequence;
- match state {
- ExecutionState::Running => tokio::time::sleep(Duration::from_millis(20)).await,
- ExecutionState::Exited { .. } if has_chunks => continue,
- ExecutionState::Exited { exit_code } => {
- tinybox::release_output(config, process)
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox could not release native jail output"))?;
- return Ok(SandboxExecResult {
- exit_code,
- stdout: String::from_utf8_lossy(&stdout).into_owned(),
- stderr: String::from_utf8_lossy(&stderr).into_owned(),
- timed_out: false,
- });
- }
- ExecutionState::Cancelled if has_chunks => continue,
- ExecutionState::Cancelled => break requested_cancel,
- ExecutionState::Failed {
- code: ExecutionFailure::CleanupFailed,
- } => anyhow::bail!("TinyBox retained native process cleanup for retry"),
- ExecutionState::Failed { .. } => {
- anyhow::bail!("TinyBox native jailed execution failed")
- }
- }
- };
- tinybox::release_output(config, process)
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox could not release native jail output"))?;
- Ok(SandboxExecResult {
- exit_code: -1,
- stdout: String::from_utf8_lossy(&stdout).into_owned(),
- stderr: if timed_out {
- format!("Command timed out after {}s", timeout.as_secs())
- } else {
- String::from_utf8_lossy(&stderr).into_owned()
- },
- timed_out,
- })
-}
-
-#[cfg(feature = "modules")]
-fn path_string(path: &Path, label: &str) -> anyhow::Result<String> {
- path.to_str()
- .map(str::to_owned)
- .ok_or_else(|| anyhow::anyhow!("{label} path is not UTF-8"))
-}
+use super::shell_exec::path_string;
#[cfg(test)]
#[path = "native_jail_tests.rs"]