Skip to content

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

fix(sandbox): allow shell jobs to run inside the native jail

Steven Enamakelc64c9d835ebd
diff --git a/crates/openhuman-core/src/cron/scheduler/shell_job.rs b/crates/openhuman-core/src/cron/scheduler/shell_job.rs
index 238aa55490..58a67c5ec2 100644
--- a/crates/openhuman-core/src/cron/scheduler/shell_job.rs
+++ b/crates/openhuman-core/src/cron/scheduler/shell_job.rs
@@ -3,11 +3,7 @@
use crate::config::Config;
use crate::security::SecurityPolicy;
-#[cfg(test)]
-use std::process::Stdio;
use tinyflows_schedule::types::CronJob;
-#[cfg(test)]
-use tokio::time;
use tokio::time::Duration;
pub(super) const SHELL_JOB_TIMEOUT_SECS: u64 = 120;
@@ -168,69 +164,33 @@ pub(super) async fn run_job_command_with_timeout(
);
}
- #[cfg(test)]
- {
- // Scheduler unit fixtures do not load a native TinyBox artifact. The
- // production branch below always uses the module-owned process path;
- // the released-artifact fixture covers that bus lifecycle directly.
- let child = match crate::agent::platform_shell::build_tokio_command_preserving_pipe_status(
- &job.command,
- )
- .current_dir(&config.action_dir)
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .kill_on_drop(true)
- .spawn()
- {
- Ok(child) => child,
- Err(_) => return (false, "Command execution is unavailable.".to_owned()),
- };
- return match time::timeout(timeout, child.wait_with_output()).await {
- Ok(Ok(output)) => {
- let stdout = String::from_utf8_lossy(&output.stdout);
- let stderr = String::from_utf8_lossy(&output.stderr);
- let combined = format!(
- "status={}\nstdout:\n{}\nstderr:\n{}",
- output.status,
- stdout.trim(),
- stderr.trim()
- );
- (output.status.success(), combined)
- }
- Ok(Err(_)) => (false, "Command execution failed.".to_owned()),
- Err(_) => (
- false,
- format!("job timed out after {}s", timeout.as_secs_f64()),
- ),
- };
- }
-
- #[cfg(not(test))]
+ // Cron keeps host execution semantics (the host's own network, no jail)
+ // and a pipeline's default exit status: retries are spent on it.
+ let output = match crate::sandbox::shell_exec::run_host(
+ config,
+ &job.command,
+ &config.action_dir,
+ &config.workspace_dir,
+ std::collections::BTreeMap::new(),
+ timeout,
+ true,
+ )
+ .await
{
- let output = match crate::sandbox::native_jail::execute_passthrough(
- config,
- &job.command,
- &config.action_dir,
- timeout,
- )
- .await
- {
- Ok(output) => output,
- Err(_) => return (false, "Command execution is unavailable.".to_owned()),
- };
- if output.timed_out {
- return (
- false,
- format!("job timed out after {}s", timeout.as_secs_f64()),
- );
- }
- let combined = format!(
- "status=exit status: {}\nstdout:\n{}\nstderr:\n{}",
- output.exit_code,
- output.stdout.trim(),
- output.stderr.trim()
+ Ok(output) => output,
+ Err(_) => return (false, "Command execution is unavailable.".to_owned()),
+ };
+ if output.timed_out {
+ return (
+ false,
+ format!("job timed out after {}s", timeout.as_secs_f64()),
);
- (output.success(), combined)
}
+ let combined = format!(
+ "status=exit status: {}\nstdout:\n{}\nstderr:\n{}",
+ output.exit_code,
+ output.stdout.trim(),
+ output.stderr.trim()
+ );
+ (output.success(), combined)
}
diff --git a/crates/openhuman-core/src/sandbox/native_jail_tests.rs b/crates/openhuman-core/src/sandbox/native_jail_tests.rs
index b62b5e394b..6054b2dfa6 100644
--- a/crates/openhuman-core/src/sandbox/native_jail_tests.rs
+++ b/crates/openhuman-core/src/sandbox/native_jail_tests.rs
@@ -20,48 +20,12 @@ fn jail_status_is_ready_only_above_the_isolation_floor() {
);
}
-#[cfg(feature = "modules")]
-#[test]
-fn shell_exec_request_delegates_shell_selection_to_the_module() -> anyhow::Result<()> {
- let resource = contract::ResourceId("known-resource".to_owned());
- let process = contract::ResourceId("known-process".to_owned());
- let cwd = tempfile::tempdir()?;
- let state = tempfile::tempdir()?;
- let env = BTreeMap::from([("LANG".to_owned(), "C".to_owned())]);
- let request = shell_exec_request(
- process.clone(),
- &resource,
- "printf 'one two'",
- cwd.path(),
- env.clone(),
- state.path(),
- Duration::from_secs(7),
- true,
- None,
- )?;
-
- assert_eq!(request.process, process);
- assert_eq!(request.resource, resource);
- assert_eq!(request.shell.command, "printf 'one two'");
- assert!(request.shell.preserve_pipeline_status);
- assert_eq!(request.shell.runtime_path, None);
- assert!(!request.shell.python_utf8);
- assert_eq!(request.cwd.as_deref(), cwd.path().to_str());
- assert_eq!(request.extra_env, env);
- assert_eq!(request.state_dir, state.path().to_str().unwrap());
- assert_eq!(request.timeout_ms, 7_000);
- assert_eq!(request.stdin, None);
- assert!(request.jail.is_none());
- Ok(())
-}
-
#[cfg(feature = "modules")]
#[test]
fn native_jail_request_preserves_grants_and_requires_enforcement() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
let readonly = tempfile::tempdir()?;
let readwrite = tempfile::tempdir()?;
- let scratch = tempfile::tempdir()?;
let policy = SandboxPolicy {
backend: super::super::types::SandboxBackendKind::Local,
workspace_root: root.path().to_path_buf(),
@@ -72,17 +36,11 @@ fn native_jail_request_preserves_grants_and_requires_enforcement() -> anyhow::Re
env_passthrough: Vec::new(),
docker_overrides: None,
};
- let (_, writable_roots) = execution_environment(&policy, &HashMap::new(), scratch.path())?;
- let request = jail_request(&policy, writable_roots)?;
+ let request = jail_request(&policy)?;
assert_eq!(request.read_only, [readonly.path().to_str().unwrap()]);
- assert_eq!(
- request.read_write,
- [
- readwrite.path().to_str().unwrap(),
- scratch.path().to_str().unwrap()
- ]
- );
+ // TinyBox appends its own per-call scratch directory to the writable grants.
+ assert_eq!(request.read_write, [readwrite.path().to_str().unwrap()]);
assert!(!request.allow_net);
assert!(request.allow_subprocess);
assert_eq!(request.enforcement, contract::JailEnforcement::Enforced);
@@ -92,36 +50,30 @@ fn native_jail_request_preserves_grants_and_requires_enforcement() -> anyhow::Re
#[cfg(feature = "modules")]
#[test]
-fn native_jail_environment_keeps_the_sandbox_allowlist_and_scratch_grant() -> anyhow::Result<()> {
- let root = tempfile::tempdir()?;
- let scratch = tempfile::tempdir()?;
- let policy = SandboxPolicy {
- backend: super::super::types::SandboxBackendKind::Local,
- workspace_root: root.path().to_path_buf(),
- state_dir: root.path().to_path_buf(),
- read_only_mounts: Vec::new(),
- read_write_mounts: Vec::new(),
- allow_network: true,
- env_passthrough: Vec::new(),
- docker_overrides: None,
- };
+fn approved_environment_carries_only_the_callers_overrides() -> anyhow::Result<()> {
let extra = HashMap::from([(OsString::from("CUSTOM_SAFE"), OsString::from("value"))]);
- let (env, read_write) = execution_environment(&policy, &extra, scratch.path())?;
+ let env = approved_environment(&extra)?;
+ // The module builds the safe snapshot and the scratch TMPDIR itself; the
+ // host forwards nothing of the parent environment.
+ assert_eq!(env.len(), 1);
assert_eq!(env.get("CUSTOM_SAFE").map(String::as_str), Some("value"));
- assert_eq!(
- env.get("TMPDIR").map(String::as_str),
- scratch.path().to_str()
- );
- assert!(read_write
- .iter()
- .any(|path| path == scratch.path().to_str().unwrap()));
- assert!(!env
- .keys()
- .any(|name| name.contains("TOKEN") || name.contains("SECRET")));
+ assert!(approved_environment(&HashMap::new())?.is_empty());
Ok(())
}
+#[cfg(all(feature = "modules", unix))]
+#[test]
+fn approved_environment_refuses_values_the_bus_cannot_carry() {
+ use std::os::unix::ffi::OsStringExt;
+
+ let extra = HashMap::from([(
+ OsString::from("RAW"),
+ OsString::from_vec(b"before-\xff-after".to_vec()),
+ )]);
+ assert!(approved_environment(&extra).is_err());
+}
+
#[cfg(feature = "modules")]
#[tokio::test]
async fn disabled_tinybox_module_never_falls_back_to_host_execution() -> anyhow::Result<()> {
@@ -171,6 +123,25 @@ impl Drop for BundledModulesRestore {
}
}
+/// Turns the unit-test shell fixture off for the released-artifact test.
+#[cfg(all(feature = "modules", target_os = "linux"))]
+struct LiveModule;
+
+#[cfg(all(feature = "modules", target_os = "linux"))]
+impl LiveModule {
+ fn enable() -> Self {
+ super::super::shell_exec::USE_FIXTURE.store(false, std::sync::atomic::Ordering::SeqCst);
+ Self
+ }
+}
+
+#[cfg(all(feature = "modules", target_os = "linux"))]
+impl Drop for LiveModule {
+ fn drop(&mut self) {
+ super::super::shell_exec::USE_FIXTURE.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+}
+
#[cfg(all(feature = "modules", target_os = "linux"))]
#[tokio::test]
#[ignore = "requires the verified TinyBox v0.1.20 archive and a supported Linux jail"]
@@ -219,6 +190,8 @@ async fn released_tinybox_runs_a_native_jail_through_the_pinned_loader() -> anyh
.await
.map_err(|_| anyhow::anyhow!("the pinned TinyBox release could not be admitted"))?;
+ // Drive the real bus lifecycle for the unjailed runs below too.
+ let _live = LiveModule::enable();
let workspace = tempfile::tempdir()?;
let state = tempfile::tempdir()?;
let policy = SandboxPolicy {
@@ -262,31 +235,40 @@ async fn released_tinybox_runs_a_native_jail_through_the_pinned_loader() -> anyh
"all terminal output batches are read"
);
- let output = execute_passthrough(
+ let output = super::super::shell_exec::run_host(
&config,
"printf cron-module-ok; printf cron-stderr >&2",
workspace.path(),
+ state.path(),
+ BTreeMap::new(),
Duration::from_secs(10),
+ true,
)
.await?;
assert!(output.success());
assert_eq!(output.stdout, "cron-module-ok");
assert_eq!(output.stderr, "cron-stderr");
- let output = execute_passthrough(
+ let output = super::super::shell_exec::run_host(
&config,
"false | true",
workspace.path(),
+ state.path(),
+ BTreeMap::new(),
Duration::from_secs(10),
+ true,
)
.await?;
assert!(output.success(), "cron preserves default pipeline status");
- let output = execute_passthrough(
+ let output = super::super::shell_exec::run_host(
&config,
"sleep 10",
workspace.path(),
+ state.path(),
+ BTreeMap::new(),
Duration::from_millis(50),
+ true,
)
.await?;
assert!(output.timed_out, "cron timeout is acknowledged by TinyBox");
diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs
index b2caff3059..cf678c9b0d 100644
--- a/crates/openhuman-core/src/sandbox/ops.rs
+++ b/crates/openhuman-core/src/sandbox/ops.rs
@@ -15,19 +15,12 @@ use std::time::Duration;
/// Safe environment variables forwarded into sandboxed execution.
///
-/// This list is the *entire* environment a sandboxed child gets: both
-/// [`execute_unsandboxed`] and the TinyBox native jail adapter call `env_clear()` and
-/// re-forward only what is named here. Windows process-bootstrap variables are
-/// added only in the host spawn paths below; keeping them out of this policy
-/// prevents Windows paths from being passed into Linux Docker containers.
-///
-/// They were missing when this defect was found, and it survived the first
-/// round of fixes because the tool launchers now share the shell and flows code-runner paths rather than
-/// carrying separate copies of the allow-list and
-/// had already been patched: the built-in `orchestrator` runs with
-/// `sandbox_mode = "sandboxed"`, and all four tools divert to
-/// [`crate::sandbox`] *before* reaching those lists, so the host spawn paths
-/// below are the ones that must add the Windows-only bootstrap set.
+/// This is the Docker container's host-environment allowlist and the set the
+/// TinyBox module's own safe snapshot starts from for every native shell child
+/// ([`execute_unsandboxed`] and the native jail adapter): the module reads these
+/// names from the parent and adds the Windows process-bootstrap variables
+/// itself. Keeping the bootstrap names out of this policy prevents Windows paths
+/// from being passed into Linux Docker containers.
pub const SANDBOX_ENV_PASSTHROUGH: &[&str] = &[
"PATH", "HOME", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "USER", "SHELL", "TMPDIR",
];
diff --git a/crates/openhuman-core/src/sandbox/shell_exec_tests.rs b/crates/openhuman-core/src/sandbox/shell_exec_tests.rs
new file mode 100644
index 0000000000..918664cdfc
--- /dev/null
+++ b/crates/openhuman-core/src/sandbox/shell_exec_tests.rs
@@ -0,0 +1,122 @@
+//! Request mapping for the module's native shell member.
+
+use super::*;
+
+fn run_in(cwd: &std::path::Path, state: &std::path::Path) -> NativeShellRun {
+ NativeShellRun::new("printf 'one two'", cwd, state, Duration::from_secs(7))
+}
+
+#[cfg(feature = "modules")]
+#[test]
+fn shell_exec_request_delegates_shell_selection_to_the_module() -> anyhow::Result<()> {
+ let resource = contract::ResourceId("known-resource".to_owned());
+ let process = contract::ResourceId("known-process".to_owned());
+ let cwd = tempfile::tempdir()?;
+ let state = tempfile::tempdir()?;
+ let mut run = run_in(cwd.path(), state.path());
+ run.env = BTreeMap::from([("LANG".to_owned(), "C".to_owned())]);
+ run.preserve_pipeline_status = true;
+
+ let request = shell_exec_request(process.clone(), &resource, run)?;
+
+ assert_eq!(request.process, process);
+ assert_eq!(request.resource, resource);
+ assert_eq!(request.shell.command, "printf 'one two'");
+ assert!(request.shell.preserve_pipeline_status);
+ assert_eq!(request.shell.runtime_path, None);
+ assert!(!request.shell.python_utf8);
+ assert!(!request.hide_window);
+ assert_eq!(request.cwd.as_deref(), cwd.path().to_str());
+ assert_eq!(
+ request.extra_env,
+ BTreeMap::from([("LANG".to_owned(), "C".to_owned())])
+ );
+ assert_eq!(request.state_dir, state.path().to_str().unwrap());
+ assert_eq!(request.timeout_ms, 7_000);
+ assert_eq!(request.stdin, None);
+ assert!(request.jail.is_none());
+ Ok(())
+}
+
+#[cfg(feature = "modules")]
+#[test]
+fn shell_exec_request_forwards_python_utf8_and_window_suppression() -> anyhow::Result<()> {
+ let dir = tempfile::tempdir()?;
+ let mut run = run_in(dir.path(), dir.path());
+ run.python_utf8 = true;
+ run.hide_window = true;
+ let request = shell_exec_request(
+ contract::ResourceId("p".to_owned()),
+ &contract::ResourceId("r".to_owned()),
+ run,
+ )?;
+ assert!(request.shell.python_utf8);
+ assert!(request.hide_window);
+ Ok(())
+}
+
+/// The module rejects a budget over twenty-four hours, so an "unbounded" caller
+/// gets the ceiling rather than a refused request; zero still runs for 1 ms.
+#[cfg(feature = "modules")]
+#[test]
+fn shell_exec_request_keeps_the_runtime_budget_inside_the_contract_bounds() -> anyhow::Result<()> {
+ let dir = tempfile::tempdir()?;
+ let mut budgets = Vec::new();
+ for timeout in [Duration::ZERO, Duration::from_secs(10 * 86_400)] {
+ let mut run = run_in(dir.path(), dir.path());
+ run.timeout = timeout;
+ let request = shell_exec_request(
+ contract::ResourceId("p".to_owned()),
+ &contract::ResourceId("r".to_owned()),
+ run,
+ )?;
+ budgets.push(request.timeout_ms);
+ }
+ assert_eq!(budgets, [1, 86_400_000]);
+ Ok(())
+}
+
+#[cfg(feature = "modules")]
+#[test]
+fn a_non_utf8_working_directory_is_refused_before_the_bus() {
+ #[cfg(unix)]
+ {
+ use std::os::unix::ffi::OsStrExt;
+ let bad = std::path::Path::new(std::ffi::OsStr::from_bytes(b"/tmp/\xff"));
+ let state = std::path::Path::new("/tmp");
+ let mut run = run_in(state, state);
+ run.cwd = bad.to_path_buf();
+ assert!(shell_exec_request(
+ contract::ResourceId("p".to_owned()),
+ &contract::ResourceId("r".to_owned()),
+ run,
+ )
+ .is_err());
+ }
+}
+
+#[cfg(feature = "modules")]
+#[tokio::test]
+async fn a_disabled_module_never_falls_back_to_a_host_shell_for_a_jailed_run() {
+ // The unjailed test fixture must not weaken the jail's refusal.
+ let dir = tempfile::tempdir().unwrap();
+ let marker = dir.path().join("must-not-run");
+ let mut config = crate::config::Config::default();
+ config.modules.enabled = false;
+ let mut shell = NativeShellRun::new(
+ &format!("touch '{}'", marker.display()),
+ dir.path(),
+ dir.path(),
+ Duration::from_secs(5),
+ );
+ shell.jail = Some(contract::NativeJailConfig {
+ read_only: Vec::new(),
+ read_write: Vec::new(),
+ allow_net: false,
+ allow_subprocess: true,
+ enforcement: contract::JailEnforcement::Enforced,
+ require_process_isolation: true,
+ });
+ assert!(run(&config, shell).await.is_err());
+ assert!(!marker.exists());
+}