The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix: resolve Windows sandbox review findings
Steven Enamakel4195d17a3b54
diff --cc crates/openhuman-cli/Cargo.tomlindex 73854b9550,ba9c6054fc..0450166998--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@@ -209,18 -195,6 +195,18 @@@ path = "../../tests/composio_list_toolsname = "cwd_jail_e2e"path = "../../tests/cwd_jail_e2e.rs"+[[test]]+name = "windows_sandbox_env_e2e"+path = "../../tests/windows_sandbox_env_e2e.rs"++[[test]]+name = "domain_modules_e2e"- path = "../../tests/domain_modules_e2e.rs"++path = "../../tests/in_process/domain_modules_e2e.rs"++[[test]]+name = "embeddings_rpc_e2e"- path = "../../tests/embeddings_rpc_e2e.rs"++path = "../../tests/in_process/embeddings_rpc_e2e.rs"+[[test]]name = "inference_provider_e2e"path = "../../tests/inference_provider_e2e.rs"diff --cc crates/openhuman-core/src/agent/platform_shell.rsindex 148bc35d47,82981648e8..01dc475baa--- a/crates/openhuman-core/src/agent/platform_shell.rs+++ b/crates/openhuman-core/src/agent/platform_shell.rs@@@ -29,71 -29,6 +29,81 @@@use std::path::Path;+/// Environment variables a Windows child process needs before it can run at+/// all, beyond the functional allow-list each launcher already forwards.+///+/// Every sanitized spawn path in the core calls `env_clear()` and re-forwards+/// only what it names, so this list is what makes a cleared Windows environment+/// bootable. These are forwarded from the parent environment, never synthesised+/// or hard-coded: a name the parent does not have is simply not set.+///+/// Measured consequences of omitting them (Windows 11, `SystemRoot` absent from+/// an otherwise-valid child environment):+///+/// - `node.exe` aborts during startup with+/// `Assertion failed: ncrypto::CSPRNG(nullptr, 0)` (exit 134), because the+/// OS random provider cannot initialise without a system directory.+/// - `powershell.exe` exits with `Internal Windows PowerShell error. Loading+/// managed Windows PowerShell failed with error 8009001d.`+/// - `cmd.exe` leaves `%SystemRoot%`/`%TEMP%`/`%USERPROFILE%` unexpanded. It+/// does *not* repair them for its own children, so a wrapper shell cannot+/// rescue a stripped environment.+///+/// `COMSPEC` and `PATHEXT` are here because `cmd.exe` needs `PATHEXT` to resolve+/// the `.cmd`/`.bat` shims that npm, npx and the Git toolchain are installed+/// as; `TEMP`/`TMP`/`USERPROFILE`/`APPDATA`/`LOCALAPPDATA` because tooling+/// writes scratch and reads config from them; the `ProgramFiles*` trio because+/// installers and SDK locators probe them.+///+/// Single source of truth: keep every launcher's allow-list a superset of this+/// (enforced by `windows_bootstrap_vars_are_forwarded_everywhere`), and add a+/// launcher to that test rather than inventing a sixth list.+pub const WINDOWS_PROCESS_ENV_VARS: &[&str] = &[+ "SystemRoot",+ "WINDIR",+ "COMSPEC",+ "PATHEXT",+ "TEMP",+ "TMP",+ "USERPROFILE",+ "APPDATA",+ "LOCALAPPDATA",+ "ProgramFiles",+ "ProgramFiles(x86)",+ "ProgramW6432",+];++/// Assert that a launcher's environment allow-list covers every Windows+/// process-bootstrap variable.+///+/// Each launcher guards its own list with this, so a new launcher cannot+/// silently ship a `env_clear()` that produces an unbootable Windows child.+/// The failure this prevents is not a clean error: the child aborts inside the+/// OS crypto provider (`node` → `ncrypto::CSPRNG` assertion, `powershell` →+/// `8009001d`), and the harness reports it as a mysterious exit code rather+/// than a missing environment variable.+#[track_caller]+pub fn assert_forwards_windows_bootstrap(allowlist: &[&str], launcher: &str) {+ for var in WINDOWS_PROCESS_ENV_VARS {+ assert!(+ allowlist.contains(var),+ "{launcher} clears the child environment but does not forward \+ `{var}`; a Windows child spawned without it aborts during crypto \+ init. Add it to the allow-list."+ );+ }+}+++/// Add Windows bootstrap variables to a host child. Keep these out of the++/// sandbox policy because that policy is also forwarded into Linux containers.++pub fn forward_windows_bootstrap_env(cmd: &mut tokio::process::Command) {++ for var in WINDOWS_PROCESS_ENV_VARS {++ if let Ok(val) = std::env::var(var) {++ cmd.env(var, val);++ }++ }++}++/// Whether the Unix arm prefixes `set -o pipefail`.#[derive(Clone, Copy, PartialEq, Eq)]enum PipeFail {diff --cc crates/openhuman-core/src/sandbox/ops.rsindex d4b7b05e66,84a0d60806..99ed1fd713--- a/crates/openhuman-core/src/sandbox/ops.rs+++ b/crates/openhuman-core/src/sandbox/ops.rs@@@ -16,53 -17,31 +17,51 @@@ use std::path::{Path, PathBuf}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 [`execute_local_jail`] call `env_clear()` and- /// re-forward only what is named here. The `WINDOWS_PROCESS_ENV_VARS` entries- /// are therefore not decoration — without them a Windows child cannot- /// initialise the OS crypto provider, and it fails in a way that looks nothing- /// like a missing environment variable (`node` aborts with the- /// `ncrypto::CSPRNG` assertion, `powershell` with `8009001d`).++/// 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 four tool launchers (`shell`, `node_exec`,+/// `npm_exec`, `python_exec`) each carry their own copy 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 this was the only list+/// that mattered for the main agent. Keep it a superset of+/// [`crate::agent::platform_shell::WINDOWS_PROCESS_ENV_VARS`] —+/// `sandbox_env_forwards_windows_bootstrap_vars` and+/// `tests/windows_sandbox_env_e2e.rs` enforce that.+///+/// On Linux and macOS these names simply do not resolve in the parent+/// environment, so forwarding them is a no-op there.pub const SANDBOX_ENV_PASSTHROUGH: &[&str] = &[- "PATH",- "HOME",- "TERM",- "LANG",- "LC_ALL",- "LC_CTYPE",- "USER",- "SHELL",- "TMPDIR",- // Windows process bootstrap — see `crate::agent::platform_shell`.- "SystemRoot",- "WINDIR",- "COMSPEC",- "PATHEXT",- "TEMP",- "TMP",- "USERPROFILE",- "APPDATA",- "LOCALAPPDATA",- "ProgramFiles",- "ProgramFiles(x86)",- "ProgramW6432",+ "PATH", "HOME", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "USER", "SHELL", "TMPDIR",];+ /// Host switch that turns the agent sandbox off for the whole process.+ ///+ /// For hosts that already isolate the core (a container, a CI or benchmark+ /// task image, a VM): the OS jail confines commands to the action dir, which+ /// breaks work such as installing packages or editing `/etc` that the outer+ /// isolation already permits. `off`, `none`, `0`, `false` or `disabled`+ /// (case-insensitive) disable it; anything else, or unset, leaves it on.+ pub const SANDBOX_OFF_ENV: &str = "OPENHUMAN_SANDBOX";++ /// Whether `value` (the `OPENHUMAN_SANDBOX` setting) disables the sandbox.+ pub fn sandbox_off_value(value: Option<&str>) -> bool {+ matches!(+ value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),+ Some("off" | "none" | "0" | "false" | "disabled")+ )+ }++ fn sandbox_disabled_by_host() -> bool {+ sandbox_off_value(std::env::var(SANDBOX_OFF_ENV).ok().as_deref())+ }+/// Resolve a `SandboxPolicy` from the agent's `SandboxMode`, the/// session origin, and the global runtime config.///@@@ -254,6 -262,6 +282,7 @@@ async fn execute_unsandboxedcmd.env(var, val);}}++ platform_shell::forward_windows_bootstrap_env(&mut cmd);for (k, v) in extra_env {cmd.env(k, v);}@@@ -311,6 -390,7 +411,8 @@@ async fn execute_local_jailcmd.env(var, val);}}++ platform_shell::forward_windows_bootstrap_env(&mut cmd);+ cmd.env("TMPDIR", &scratch.path);for (k, v) in extra_env {cmd.env(k, v);}diff --cc crates/openhuman-core/src/sandbox/ops_tests.rsindex ead2a40c7e,374ced5cb8..082e8dd546--- a/crates/openhuman-core/src/sandbox/ops_tests.rs+++ b/crates/openhuman-core/src/sandbox/ops_tests.rs@@@ -309,28 -322,322 +322,339 @@@ fn local_status_is_ready_for_a_real_jai}}+// ── Windows child environment ────────────────────────────────────────────────+//+// `execute_unsandboxed` and `execute_local_jail` both call `env_clear()` and+// re-forward only `SANDBOX_ENV_PASSTHROUGH`. On Windows that list has to carry+// the process-bootstrap variables or the child cannot initialise the OS crypto+// provider — `node` dies with `Assertion failed: ncrypto::CSPRNG(nullptr, 0)`+// (exit 134) and `powershell` with `8009001d`. Both read as opaque failures to+// the agent, which is how the original defect shipped: the four tool launchers'+// allow-lists were fixed, the sandbox allow-list — the one the `sandboxed`+// orchestrator actually routes through — was not.+- #[test]- fn sandbox_env_forwards_windows_bootstrap_vars() {- crate::agent::platform_shell::assert_forwards_windows_bootstrap(- SANDBOX_ENV_PASSTHROUGH,- "sandbox::ops::SANDBOX_ENV_PASSTHROUGH",- );- }-+// What a real child actually receives is covered end-to-end in+// `tests/windows_sandbox_env_e2e.rs`, which spawns through `execute_in_sandbox`+// and asserts on the child's own environment. It lives there because the probe+// has to be a Rust `CreateProcess` spawn: `node`'s own `child_process.spawn`+// silently injects `SystemRoot`, so a JavaScript probe reports a stripped+// environment as healthy.+ // ── #6961: local-jail output capture stays out of the user's project ─────────++ #[cfg(unix)]+ fn local_policy(action_dir: &Path, state_dir: &Path) -> SandboxPolicy {+ let policy = resolve_sandbox_policy(+ SandboxMode::Sandboxed,+ action_dir,+ state_dir,+ &RuntimeConfig::default(),+ false,+ );+ assert_eq!(policy.backend, SandboxBackendKind::Local);+ policy+ }++ #[cfg(unix)]+ async fn run_local(policy: &SandboxPolicy, command: &str) -> SandboxExecResult {+ execute_in_sandbox(+ policy,+ command,+ &policy.workspace_root,+ HashMap::new(),+ Duration::from_secs(20),+ )+ .await+ .unwrap()+ }++ #[cfg(unix)]+ fn entries(dir: &Path) -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir(dir)+ .map(|rd| {+ rd.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect()+ })+ .unwrap_or_default();+ names.sort();+ names+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn local_jail_writes_no_capture_files_into_the_workspace_root() {+ let action = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let policy = local_policy(action.path(), state.path());++ // `ls -A` runs inside the root while the capture is live, so it sees+ // anything the capture put there (this is what `git status` saw).+ let during = run_local(&policy, "ls -A; echo to-stderr >&2").await;++ assert!(during.success(), "stderr: {}", during.stderr);+ assert_eq!(during.stdout, "", "root was not empty while running");+ assert_eq!(during.stderr, "to-stderr\n");+ assert!(+ entries(action.path()).is_empty(),+ "root was not empty after"+ );+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn concurrent_local_jail_runs_keep_their_outputs_separate() {+ let action = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let policy = local_policy(action.path(), state.path());++ let (a, b) = tokio::join!(+ run_local(&policy, "echo a1; echo a-err >&2; sleep 0.4; echo a2"),+ run_local(&policy, "echo b1; echo b-err >&2; sleep 0.4; echo b2"),+ );++ assert_eq!(+ (a.stdout.as_str(), a.stderr.as_str()),+ ("a1\na2\n", "a-err\n")+ );+ assert_eq!(+ (b.stdout.as_str(), b.stderr.as_str()),+ ("b1\nb2\n", "b-err\n")+ );+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn local_jail_captures_under_the_state_dir_and_removes_the_call_dir() {+ let action = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let mut policy = local_policy(action.path(), state.path());+ let capture_root = sandbox_capture_root(state.path());+ assert_eq!(+ capture_root,+ state.path().join("artifacts").join("sandbox-capture")+ );+ // A real jail grants only the per-call dir, so the command cannot list the+ // capture root on its own; grant it read-only so this test can look.+ std::fs::create_dir_all(&capture_root).unwrap();+ policy.read_only_mounts.push(capture_root.clone());++ // While running, exactly one per-call dir holding both streams exists.+ let during = run_local(&policy, &format!("ls '{}'/*", capture_root.display())).await;+ assert!(during.success(), "stderr: {}", during.stderr);+ assert_eq!(during.stdout, "stderr\nstdout\n");++ assert!(+ entries(&capture_root).is_empty(),+ "per-call capture dir left behind: {:?}",+ entries(&capture_root)+ );+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn local_jail_removes_the_call_dir_when_the_spawn_fails() {+ let cwd = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ // A jail root that does not exist makes the jail refuse to spawn.+ let policy = local_policy(&cwd.path().join("missing-root"), state.path());++ let err = execute_in_sandbox(+ &policy,+ "true",+ cwd.path(),+ HashMap::new(),+ Duration::from_secs(5),+ )+ .await+ .unwrap_err();++ assert!(+ err.to_string().contains("Failed to spawn jailed process"),+ "{err}"+ );+ assert!(entries(&sandbox_capture_root(state.path())).is_empty());+ }++ // ── tinybox `unsupported` backend is not a jail ──────────────────────────────++ #[test]+ fn local_status_is_inactive_for_the_unsupported_backend() {+ assert_eq!(+ local_status_for_backend(cwd_jail::detect::UNSUPPORTED_BACKEND_NAME),+ SandboxStatus::Inactive,+ "`pick_backend` answers `unsupported` when no OS jail exists and the host then runs \+ commands through the no-op fallback; `Ready` would claim confinement that is absent"+ );+ }++ // ── tinybox#23: with a real jail, everyday commands still work ───────────────+ //+ // These run a real Landlock jail and skip (loudly) where the kernel has none,+ // so they never fail a host that cannot confine.++ #[cfg(target_os = "linux")]+ fn landlock_in_force() -> bool {+ let backend = cwd_jail::default_backend();+ let ok = backend.name() == "landlock" && backend.is_available();+ if !ok {+ eprintln!(+ "SKIP: no Landlock on this host (backend = {})",+ backend.name()+ );+ }+ ok+ }++ #[cfg(target_os = "linux")]+ fn host_has(program: &str) -> bool {+ std::process::Command::new("sh")+ .arg("-c")+ .arg(format!("command -v {program}"))+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn landlock_jail_runs_cargo_and_mktemp_but_blocks_writes_outside() {+ if !landlock_in_force() {+ return;+ }+ let action = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let outside = tempfile::tempdir().unwrap();+ let policy = local_policy(action.path(), state.path());++ // Cargo records the executable for the active build toolchain. Use it+ // directly so this check exercises Cargo inside the jail: a rustup proxy+ // on PATH can try to initialize a different HOME in a CI container.+ let cargo = Path::new(env!("CARGO"));+ if cargo.is_file() {+ let quoted_cargo = format!("'{}'", cargo.to_string_lossy().replace('\'', "'\\''"));+ let r = run_local(&policy, &format!("{quoted_cargo} --version")).await;+ assert!(r.success(), "cargo failed under the jail: {}", r.stderr);+ assert!(r.stdout.starts_with("cargo "), "stdout: {}", r.stdout);+ } else {+ eprintln!("SKIP cargo: build toolchain executable is absent on this host");+ }++ // `/tmp` is not granted; `mktemp` lands in the per-call TMPDIR scratch dir.+ let r = run_local(&policy, "mktemp").await;+ assert!(r.success(), "mktemp failed under the jail: {}", r.stderr);+ assert!(+ r.stdout+ .trim()+ .starts_with(sandbox_scratch_root(state.path()).to_str().unwrap()),+ "mktemp should land in the scratch dir, got {:?}",+ r.stdout+ );+ assert!(+ entries(&sandbox_scratch_root(state.path())).is_empty(),+ "per-call scratch dir left behind"+ );++ // The jail still confines: writing outside the root fails.+ let target = outside.path().join("pwned");+ let r = run_local(&policy, &format!("echo x > '{}'", target.display())).await;+ assert!(!r.success(), "write outside the root must fail");+ assert!(!target.exists(), "the jail let a write escape");++ // ...while the workspace root itself stays writable.+ let r = run_local(&policy, "echo ok > inside.txt").await;+ assert!(r.success(), "stderr: {}", r.stderr);+ assert!(action.path().join("inside.txt").exists());+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn landlock_jail_denies_proc_unless_the_toggle_is_on() {+ if !landlock_in_force() {+ return;+ }+ let action = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let policy = local_policy(action.path(), state.path());+ let denied = run_local(&policy, "cat /proc/self/environ > /dev/null").await;+ assert!(!denied.success(), "/proc must be off by default");++ let config = RuntimeConfig {+ local_jail: crate::config::LocalJailConfig {+ allow_proc: true,+ ..Default::default()+ },+ ..RuntimeConfig::default()+ };+ let policy = resolve_sandbox_policy(+ SandboxMode::Sandboxed,+ action.path(),+ state.path(),+ &config,+ false,+ );+ let allowed = run_local(&policy, "cat /proc/self/environ > /dev/null").await;+ assert!(allowed.success(), "stderr: {}", allowed.stderr);+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn landlock_jail_cannot_read_the_users_ssh_directory() {+ if !landlock_in_force() {+ return;+ }+ let Some(ssh) = dirs::home_dir()+ .map(|h| h.join(".ssh"))+ .filter(|p| p.is_dir())+ else {+ eprintln!("SKIP: no ~/.ssh on this host");+ return;+ };+ let action = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let policy = local_policy(action.path(), state.path());+ let r = run_local(&policy, &format!("ls '{}'", ssh.display())).await;+ assert!(!r.success(), "~/.ssh must stay unreachable from the jail");+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn local_handle_status_matches_the_backend_actually_in_force() {+ let action = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let handle = create_sandbox_backend(&local_policy(action.path(), state.path())).await;+ let name = handle.backend_id.clone().unwrap();+ let unconfined =+ name == cwd_jail::NOOP_BACKEND_NAME || name == cwd_jail::detect::UNSUPPORTED_BACKEND_NAME;+ assert_eq!(+ handle.status,+ if unconfined {+ SandboxStatus::Inactive+ } else {+ SandboxStatus::Ready+ },+ "backend = {name}"+ );+ }++ #[test]+ fn sandbox_off_value_accepts_off_spellings() {+ for v in ["off", "OFF", " none ", "0", "false", "Disabled"] {+ assert!(+ sandbox_off_value(Some(v)),+ "{v:?} should disable the sandbox"+ );+ }+ }++ #[test]+ fn sandbox_off_value_keeps_sandbox_on_otherwise() {+ for v in [+ None,+ Some(""),+ Some("on"),+ Some("1"),+ Some("true"),+ Some("local"),+ ] {+ assert!(!sandbox_off_value(v), "{v:?} must leave the sandbox on");+ }+ }diff --cc crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rsindex 30c51a322e,30c51a322e..059e42a84e--- a/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs+++ b/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs@@@ -75,10 -75,10 +75,8 @@@ fn resolve_cwd_allows_relative_subdir(#[test]fn safe_env_vars_include_windows_process_essentials() {-- for var in ["SystemRoot", "COMSPEC", "PATHEXT", "TEMP", "USERPROFILE"] {-- assert!(-- SAFE_ENV_VARS.contains(&var),-- "{var} must be forwarded for Windows child processes"-- );-- }++ crate::agent::platform_shell::assert_forwards_windows_bootstrap(++ SAFE_ENV_VARS,++ "npm_exec::SAFE_ENV_VARS",++ );}diff --cc crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rsindex f72e8e4ca2,c012a38fec..cbbbbae6b5--- a/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs@@@ -618,10 -618,10 +618,8 @@@ fn shell_safe_env_vars_includes_essenti#[test]fn shell_safe_env_vars_include_windows_process_essentials() {-- for var in ["SystemRoot", "COMSPEC", "PATHEXT", "TEMP", "USERPROFILE"] {-- assert!(-- SAFE_ENV_VARS.contains(&var),-- "{var} must be forwarded for Windows child processes"-- );-- }++ crate::agent::platform_shell::assert_forwards_windows_bootstrap(++ SAFE_ENV_VARS,++ "shell::SAFE_ENV_VARS",++ );}diff --cc tests/windows_sandbox_env_e2e.rsindex 408584e94c,0000000000..a7a8fad532mode 100644,000000..100644--- a/tests/windows_sandbox_env_e2e.rs+++ b/tests/windows_sandbox_env_e2e.rs@@@ -1,214 -1,0 +1,230 @@@+//! Windows child-environment e2e for OpenHuman's own sandbox execution path.+//!+//! Both `sandbox::ops` exec functions call `Command::env_clear()` and re-forward+//! only `SANDBOX_ENV_PASSTHROUGH`, so that list is the entire environment a+//! sandboxed child gets. This test measures what a real child sees when spawned+//! through `execute_in_sandbox` — the same function the `shell`, `node_exec`,+//! `npm_exec` and `python_exec` tools route into whenever the active agent is+//! `SandboxMode::Sandboxed` (which the built-in `orchestrator` is).+//!+//! The defect this pins: the list carried no Windows process-bootstrap+//! variables. A child without `SystemRoot` cannot initialise the OS crypto+//! provider, and the failures are opaque to the agent rather than diagnostic:+//!+//! - `node.exe` aborts at startup — `Assertion failed: ncrypto::CSPRNG(nullptr, 0)`, exit 134.+//! - `powershell.exe` exits with `Internal Windows PowerShell error. Loading+//! managed Windows PowerShell failed with error 8009001d.`+//!+//! Note on method: these must be spawned from Rust. `node`'s own+//! `child_process.spawn` (libuv) injects `SystemRoot` into the child, and a+//! probe driven through `cmd.exe` from JavaScript reports it as present, so a+//! JS harness cannot observe the stripping at all.++use std::collections::HashMap;+use std::time::Duration;++use openhuman_core::agent::harness::definition::SandboxMode;+use openhuman_core::config::RuntimeConfig;+use openhuman_core::sandbox::ops::{+ execute_in_sandbox, resolve_sandbox_policy, SANDBOX_ENV_PASSTHROUGH,+};++/// Run `command` through OpenHuman's sandbox execution path under `mode`.+async fn run_in_sandbox(+ mode: SandboxMode,+ command: &str,+) -> openhuman_core::sandbox::types::SandboxExecResult {+ let tempdir = tempfile::tempdir().expect("tempdir");- let policy = resolve_sandbox_policy(mode, tempdir.path(), &RuntimeConfig::default(), false);++ let policy = resolve_sandbox_policy(++ mode,++ tempdir.path(),++ tempdir.path(),++ &RuntimeConfig::default(),++ false,++ );+ execute_in_sandbox(+ &policy,+ command,+ tempdir.path(),+ HashMap::new(),+ Duration::from_secs(120),+ )+ .await+ .unwrap_or_else(|e| panic!("execute_in_sandbox({mode:?}) failed to run the command: {e}"))+}++/// Every allow-list that clears the child environment must cover the Windows+/// bootstrap set. Runs on every OS: the list is platform-independent by design,+/// and on Unix the extra names simply never resolve in the parent environment.+#[test]+fn sandbox_allowlist_covers_windows_bootstrap() {+ openhuman_core::agent::platform_shell::assert_forwards_windows_bootstrap(+ SANDBOX_ENV_PASSTHROUGH,+ "sandbox::ops::SANDBOX_ENV_PASSTHROUGH",+ );+}++#[cfg(windows)]+fn env_probe_command() -> &'static str {+ "echo SR=[%SystemRoot%] TEMP=[%TEMP%] UP=[%USERPROFILE%] PATH=[%PATH%]"+}++/// `cmd.exe` prints `%SystemRoot%` *verbatim* when the variable is absent, which+/// makes non-expansion the assertion. A resolved value is also required, so a+/// child that echoes nothing cannot pass.+#[cfg(windows)]+fn assert_bootstrap_env_resolved(result: &openhuman_core::sandbox::types::SandboxExecResult) {+ assert!(+ result.success(),+ "child exited {} with stderr {:?}",+ result.exit_code,+ result.stderr+ );+ for name in ["SystemRoot", "TEMP", "USERPROFILE", "PATH"] {+ assert!(+ !result.stdout.contains(&format!("%{name}%")),+ "`{name}` reached the child unexpanded, so it is not in the \+ forwarded environment; stdout {:?}",+ result.stdout+ );+ }+ let system_root = bracketed(&result.stdout, "SR=").unwrap_or_default();+ assert!(+ system_root.contains(':'),+ "`SystemRoot` did not resolve to a directory; stdout {:?}",+ result.stdout+ );+ assert!(+ !bracketed(&result.stdout, "UP=")+ .unwrap_or_default()+ .is_empty(),+ "`USERPROFILE` resolved to nothing; stdout {:?}",+ result.stdout+ );+}++#[cfg(windows)]+fn bracketed(stdout: &str, prefix: &str) -> Option<String> {+ let tail = stdout.split(prefix).nth(1)?;+ Some(tail.split(']').next()?.trim().to_string())+}++/// The unsandboxed exec path (`SandboxMode::None`), which shares the+/// allow-list with the jail path and has no OS-jail dependency.+#[cfg(windows)]+#[tokio::test]+async fn unsandboxed_child_receives_windows_bootstrap_env() {+ let result = run_in_sandbox(SandboxMode::None, env_probe_command()).await;+ assert_bootstrap_env_resolved(&result);+}++/// The route the built-in orchestrator actually takes:+/// `SandboxMode::Sandboxed` → `SandboxBackendKind::Local` →+/// `execute_local_jail`.+#[cfg(windows)]+#[tokio::test]+async fn sandboxed_child_receives_windows_bootstrap_env() {+ let result = run_in_sandbox(SandboxMode::Sandboxed, env_probe_command()).await;+ assert_bootstrap_env_resolved(&result);+}++/// The reported Node failure, end to end through OpenHuman's spawn code:+/// `node -e` must reach the crypto provider and print random bytes.+#[cfg(windows)]+#[tokio::test]+async fn node_crypto_runs_through_sandbox_path() {+ if !tool_available("node") {+ eprintln!("skipping node_crypto_runs_through_sandbox_path: `node` is not on PATH");+ return;+ }++ let result = run_in_sandbox(+ SandboxMode::None,+ r#"node -e "console.log('SR=' + process.env.SystemRoot); console.log(require('crypto').randomBytes(8).toString('hex'))""#,+ )+ .await;++ assert!(+ !result.stderr.contains("ncrypto"),+ "node's OS random provider failed to initialise — the child \+ environment is missing Windows bootstrap variables; stderr {:?}",+ result.stderr+ );+ assert!(+ result.success(),+ "node aborted through the sandbox path (exit {}); stderr {:?}",+ result.exit_code,+ result.stderr+ );+ assert!(+ result+ .stdout+ .lines()+ .any(|line| line.trim().len() == 16+ && line.trim().chars().all(|c| c.is_ascii_hexdigit())),+ "no random bytes were printed; stdout {:?}",+ result.stdout+ );+}++/// The reported PowerShell failure: `8009001d` when the child has no system+/// directory to load its crypto provider from.+#[cfg(windows)]+#[tokio::test]+async fn powershell_runs_through_sandbox_path() {+ if !tool_available("powershell") {+ eprintln!("skipping powershell_runs_through_sandbox_path: `powershell` is not on PATH");+ return;+ }++ let result = run_in_sandbox(+ SandboxMode::None,+ "powershell -NoProfile -Command [guid]::NewGuid().ToString()",+ )+ .await;++ assert!(+ !result.stderr.contains("8009001d"),+ "PowerShell could not load managed PowerShell — the child environment \+ is missing Windows bootstrap variables; stderr {:?}",+ result.stderr+ );+ assert!(+ result.success(),+ "powershell failed through the sandbox path (exit {}); stderr {:?}",+ result.exit_code,+ result.stderr+ );+ let guid: String = result+ .stdout+ .trim()+ .chars()+ .filter(|c| c.is_ascii_hexdigit() || *c == '-')+ .collect();+ assert!(+ guid.len() >= 36,+ "no GUID was produced by the child; stdout {:?}",+ result.stdout+ );+}++#[cfg(windows)]+fn tool_available(program: &str) -> bool {++ let args = if program.eq_ignore_ascii_case("powershell") {++ vec![++ "-NoProfile",++ "-NonInteractive",++ "-Command",++ "$PSVersionTable.PSVersion.ToString()",++ ]++ } else {++ vec!["--version"]++ };+ std::process::Command::new(program)- .arg("--version")++ .args(args)+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .map(|s| s.success())+ .unwrap_or(false)+}