Skip to main content

adk_sandbox/
process.rs

1//! [`ProcessBackend`] — subprocess-based code execution via `tokio::process::Command`.
2//!
3//! This backend spawns child processes to execute code in various languages.
4//! It enforces timeout and environment isolation, reads output under a byte cap
5//! while the process runs, and kills the execution's process group on timeout
6//! and on exit. On its own it does **not** enforce memory limits, network
7//! isolation, or filesystem isolation; attach an OS enforcer with
8//! [`ProcessBackend::with_sandbox`] for those.
9//!
10//! # Supported Languages
11//!
12//! | Language   | Execution Strategy                                    |
13//! |------------|-------------------------------------------------------|
14//! | Rust       | Write to temp file → compile with `rustc` → run binary |
15//! | Python     | Write to temp file → run with `python3`               |
16//! | JavaScript | Write to temp file → run with `node`                  |
17//! | TypeScript | Write to temp file → run with `node` (same as JS)     |
18//! | Command    | Execute code as `sh -c "<code>"`                      |
19//! | Wasm       | Not supported — use `WasmBackend` instead            |
20//!
21//! # Example
22//!
23//! ```rust,ignore
24//! use adk_sandbox::{ProcessBackend, ExecRequest, Language, SandboxBackend};
25//! use std::time::Duration;
26//! use std::collections::HashMap;
27//!
28//! let backend = ProcessBackend::default();
29//! let request = ExecRequest {
30//!     language: Language::Python,
31//!     code: "print('hello')".to_string(),
32//!     stdin: None,
33//!     timeout: Duration::from_secs(30),
34//!     memory_limit_mb: None,
35//!     env: HashMap::new(),
36//! };
37//! let result = backend.execute(request).await?;
38//! assert_eq!(result.stdout.trim(), "hello");
39//! ```
40
41use std::ffi::{OsStr, OsString};
42use std::path::Path;
43use std::time::Instant;
44
45use async_trait::async_trait;
46use tokio::process::Command;
47use tracing::{Span, instrument};
48
49use crate::backend::{BackendCapabilities, EnforcedLimits, SandboxBackend};
50use crate::child_io::{collect_output, note_truncation, truncate_utf8};
51use crate::error::SandboxError;
52use crate::sandbox::command::resolve_program;
53use crate::sandbox::{AccessMode, AllowedPath, SandboxEnforcer, SandboxPolicy, sandboxed_command};
54use crate::types::{ExecRequest, ExecResult, Language};
55
56/// Maximum output size in bytes (1 MB).
57const MAX_OUTPUT_BYTES: usize = 1_024 * 1_024;
58
59/// Host variables exposed only while compiling Rust on non-Windows platforms.
60const NON_WINDOWS_TOOLCHAIN_ENV_KEYS: &[&str] = &[
61    "PATH",
62    "DEVELOPER_DIR",
63    "SDKROOT",
64    "HOME",
65    "TMPDIR",
66    "RUSTUP_HOME",
67    "CARGO_HOME",
68    "RUSTUP_TOOLCHAIN",
69];
70
71/// Host variables exposed only while compiling Rust with the MSVC toolchain.
72///
73/// `LIB` is the linker's library search path. The remaining Windows-specific
74/// values support temporary files, system DLL discovery, and rustup's default
75/// toolchain location without copying the full developer-shell environment.
76const WINDOWS_TOOLCHAIN_ENV_KEYS: &[&str] = &[
77    "PATH",
78    "LIB",
79    "LIBPATH",
80    "INCLUDE",
81    "SystemRoot",
82    "TEMP",
83    "TMP",
84    "USERPROFILE",
85    "RUSTUP_HOME",
86    "RUSTUP_TOOLCHAIN",
87];
88
89/// Configuration for [`ProcessBackend`].
90///
91/// Provides paths to language runtimes. Defaults use bare command names
92/// that rely on `PATH` resolution.
93///
94/// # Example
95///
96/// ```rust
97/// use adk_sandbox::ProcessConfig;
98///
99/// let config = ProcessConfig {
100///     rustc_path: "/usr/local/bin/rustc".to_string(),
101///     ..ProcessConfig::default()
102/// };
103/// ```
104#[derive(Debug, Clone)]
105pub struct ProcessConfig {
106    /// Path to the Rust compiler. Default: `"rustc"`.
107    pub rustc_path: String,
108    /// Path to the Python 3 interpreter. Default: `"python3"`.
109    pub python_path: String,
110    /// Path to the Node.js runtime. Default: `"node"`.
111    pub node_path: String,
112    /// Maximum bytes retained from each of stdout and stderr. Default: 1 MiB.
113    ///
114    /// The limit is applied as the pipes are read, so it bounds memory rather than only the
115    /// reported output. Excess is drained and discarded, and the returned text carries a
116    /// truncation notice.
117    pub max_output_bytes: usize,
118}
119
120impl Default for ProcessConfig {
121    fn default() -> Self {
122        Self {
123            rustc_path: "rustc".to_string(),
124            python_path: "python3".to_string(),
125            node_path: "node".to_string(),
126            max_output_bytes: MAX_OUTPUT_BYTES,
127        }
128    }
129}
130
131/// Subprocess-based sandbox backend.
132///
133/// Executes code by spawning child processes with `tokio::process::Command`.
134/// Enforces timeout via `tokio::time::timeout` and environment isolation
135/// via `env_clear()`. Optionally enforces filesystem and network isolation
136/// when a [`SandboxEnforcer`] is configured via [`with_sandbox()`](Self::with_sandbox).
137///
138/// # Example
139///
140/// ```rust
141/// use adk_sandbox::{ProcessBackend, SandboxBackend};
142///
143/// let backend = ProcessBackend::default();
144/// assert_eq!(backend.name(), "process");
145/// ```
146///
147/// # With OS-level sandbox
148///
149/// ```rust,ignore
150/// use adk_sandbox::{ProcessBackend, ProcessConfig, SandboxPolicyBuilder, get_enforcer};
151///
152/// let enforcer = get_enforcer()?;
153/// let policy = SandboxPolicyBuilder::new()
154///     .allow_read("/usr/lib")
155///     .allow_read_write("/tmp/work")
156///     .build();
157///
158/// let backend = ProcessBackend::with_sandbox(
159///     ProcessConfig::default(),
160///     enforcer,
161///     policy,
162/// );
163/// assert!(backend.capabilities().enforced_limits.filesystem_write_isolation);
164/// ```
165pub struct ProcessBackend {
166    config: ProcessConfig,
167    enforcer: Option<Box<dyn SandboxEnforcer>>,
168    policy: Option<SandboxPolicy>,
169}
170
171/// How much isolation a backend actually provides.
172///
173/// Reported so a caller can tell the two apart rather than assuming the stronger one
174/// because the crate is named `adk-sandbox`.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum IsolationClass {
177    /// A child process with a cleared environment, a timeout, and its own process group.
178    ///
179    /// The OS applies no further restriction: the code can read the host filesystem and
180    /// reach the network. This is what [`ProcessBackend::default`] provides.
181    SubprocessOnly,
182    /// A child process wrapped by an OS enforcer — Seatbelt or bubblewrap
183    /// — under a [`SandboxPolicy`].
184    OsEnforced,
185}
186
187impl ProcessBackend {
188    /// Creates a new `ProcessBackend` with the given configuration.
189    ///
190    /// The result is [`IsolationClass::SubprocessOnly`] until an enforcer and policy are
191    /// attached; see [`ProcessBackend::isolation`].
192    pub fn new(config: ProcessConfig) -> Self {
193        Self { config, enforcer: None, policy: None }
194    }
195
196    /// How much isolation this backend applies.
197    ///
198    /// Check this before treating execution as sandboxed. Without an enforcer *and* a
199    /// policy, execution is subprocess isolation only.
200    pub fn isolation(&self) -> IsolationClass {
201        match (self.enforcer.is_some(), self.policy.is_some()) {
202            (true, true) => IsolationClass::OsEnforced,
203            _ => IsolationClass::SubprocessOnly,
204        }
205    }
206
207    /// Creates a new `ProcessBackend` with OS-level sandbox enforcement.
208    ///
209    /// All executions through this backend will be sandboxed with the given
210    /// policy. The enforcer wraps commands with platform-specific restrictions
211    /// (Seatbelt on macOS, bubblewrap on Linux). The Windows restricted-token enforcer
212    /// cannot be applied here and fails the execution.
213    ///
214    /// Each execution runs in a fresh scratch directory holding its source file
215    /// and compiler output. That directory becomes the working directory and is
216    /// granted read-write on top of the policy, since the enforcers deny every
217    /// path the policy does not name.
218    ///
219    /// If different tools need different policies, create multiple
220    /// `ProcessBackend` instances.
221    pub fn with_sandbox(
222        config: ProcessConfig,
223        enforcer: Box<dyn SandboxEnforcer>,
224        policy: SandboxPolicy,
225    ) -> Self {
226        Self { config, enforcer: Some(enforcer), policy: Some(policy) }
227    }
228}
229
230impl Default for ProcessBackend {
231    fn default() -> Self {
232        Self::new(ProcessConfig::default())
233    }
234}
235
236// ProcessBackend can't derive Debug because Box<dyn SandboxEnforcer> doesn't impl Debug.
237impl std::fmt::Debug for ProcessBackend {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        f.debug_struct("ProcessBackend")
240            .field("config", &self.config)
241            .field("enforcer", &self.enforcer.as_ref().map(|e| e.name()))
242            .field("policy", &self.policy)
243            .finish()
244    }
245}
246
247#[async_trait]
248impl SandboxBackend for ProcessBackend {
249    fn name(&self) -> &str {
250        "process"
251    }
252
253    fn capabilities(&self) -> BackendCapabilities {
254        let has_enforcer = self.enforcer.is_some();
255        let denies_network = self.policy.as_ref().is_some_and(|p| p.network.restricts());
256
257        BackendCapabilities {
258            supported_languages: vec![
259                Language::Rust,
260                Language::Python,
261                Language::JavaScript,
262                Language::TypeScript,
263                Language::Command,
264            ],
265            isolation_class: if has_enforcer {
266                "process+sandbox".to_string()
267            } else {
268                "process".to_string()
269            },
270            enforced_limits: EnforcedLimits {
271                timeout: true,
272                memory: false,
273                network_isolation: has_enforcer && denies_network,
274                filesystem_write_isolation: has_enforcer,
275                // Linux bubblewrap builds a filesystem namespace and the macOS Seatbelt
276                // profile is deny-by-default, so both confine reads to the policy's paths
277                // plus the system runtime. The Windows enforcer is not implemented.
278                filesystem_read_isolation: has_enforcer
279                    && cfg!(any(target_os = "linux", target_os = "macos")),
280                environment_isolation: true,
281            },
282        }
283    }
284
285    #[instrument(
286        skip_all,
287        fields(
288            backend = "process",
289            language = %request.language,
290            exit_code,
291            duration_ms,
292        )
293    )]
294    async fn execute(&self, request: ExecRequest) -> Result<ExecResult, SandboxError> {
295        if let Some(limit) = request.memory_limit_mb {
296            tracing::debug!(
297                memory_limit_mb = limit,
298                "memory limit not enforced by process backend"
299            );
300        }
301
302        match request.language {
303            Language::Rust => self.execute_rust(&request).await,
304            Language::Python => self.execute_python(&request).await,
305            Language::JavaScript | Language::TypeScript => self.execute_javascript(&request).await,
306            Language::Command => self.execute_command(&request).await,
307            Language::Wasm => Err(SandboxError::InvalidRequest(
308                "Wasm execution is not supported by ProcessBackend. Use WasmBackend instead."
309                    .to_string(),
310            )),
311        }
312    }
313}
314
315impl ProcessBackend {
316    /// Executes Rust code: write to temp file → compile with rustc → run binary.
317    async fn execute_rust(&self, request: &ExecRequest) -> Result<ExecResult, SandboxError> {
318        let dir = tempfile::tempdir()?;
319        let src_path = dir.path().join("main.rs");
320        let bin_path = dir.path().join("main");
321
322        std::fs::write(&src_path, &request.code)?;
323
324        // Compile through the same path as execution. Building the command here and
325        // calling `output()` directly skipped the enforcer, the timeout, and the
326        // process group — and Rust compilation is not inert: `include_str!` and
327        // procedural macros read files and can run arbitrary code at compile time, so
328        // the compiler needs the same boundary as the binary it produces.
329        let toolchain_env = Self::toolchain_env();
330        #[cfg(windows)]
331        let has_msvc_library_path =
332            toolchain_env.iter().any(|(key, _)| key.eq_ignore_ascii_case("LIB"));
333
334        let compile_result = {
335            let mut cmd = Command::new(&self.config.rustc_path);
336            // Cargo applies the workspace's rust-lld setting, but this direct rustc
337            // invocation does not read .cargo/config.toml. Hosted Windows runners put
338            // Git's GNU `link.exe` ahead of MSVC on PATH, so naming rust-lld prevents
339            // rustc from launching the unrelated Unix utility.
340            #[cfg(windows)]
341            cmd.arg("-Clinker=rust-lld");
342            cmd.arg(&src_path).arg("-o").arg(&bin_path);
343            self.run_command_with_env(cmd, request, &toolchain_env, Some(dir.path())).await?
344        };
345
346        #[cfg(windows)]
347        let compile_result = {
348            let mut result = compile_result;
349            if result.exit_code != 0 && !has_msvc_library_path {
350                result.stderr.push_str(
351                    "\nWindows Rust linking requires the MSVC Build Tools and Windows SDK. \
352                     Install the `Desktop development with C++` workload; ProcessBackend could \
353                     not discover its LIB paths from this host.",
354                );
355            }
356            result
357        };
358
359        if compile_result.exit_code != 0 {
360            Span::current().record("exit_code", compile_result.exit_code);
361            Span::current().record("duration_ms", compile_result.duration.as_millis() as u64);
362            return Ok(compile_result);
363        }
364
365        // Run the compiled binary
366        self.run_command(Command::new(&bin_path), request, Some(dir.path())).await
367    }
368
369    /// Executes Python code: write to temp file → run with python3.
370    async fn execute_python(&self, request: &ExecRequest) -> Result<ExecResult, SandboxError> {
371        let dir = tempfile::tempdir()?;
372        let src_path = dir.path().join("script.py");
373        std::fs::write(&src_path, &request.code)?;
374
375        let mut cmd = Command::new(&self.config.python_path);
376        cmd.arg(&src_path);
377        self.run_command(cmd, request, Some(dir.path())).await
378    }
379
380    /// Executes JavaScript code: write to temp file → run with node.
381    async fn execute_javascript(&self, request: &ExecRequest) -> Result<ExecResult, SandboxError> {
382        let dir = tempfile::tempdir()?;
383        let src_path = dir.path().join("script.js");
384        std::fs::write(&src_path, &request.code)?;
385
386        let mut cmd = Command::new(&self.config.node_path);
387        cmd.arg(&src_path);
388        self.run_command(cmd, request, Some(dir.path())).await
389    }
390
391    /// Executes a raw shell command via the platform shell.
392    async fn execute_command(&self, request: &ExecRequest) -> Result<ExecResult, SandboxError> {
393        #[cfg(windows)]
394        let cmd = {
395            use std::os::windows::process::CommandExt;
396
397            let mut c = Command::new("cmd");
398            c.arg("/D").arg("/C");
399            // `cmd.exe` does not follow CommandLineToArgvW escaping. In particular,
400            // Command::arg turns embedded quotes into `\"`, which makes a quoted
401            // executable path part of the program name. The command is already an
402            // explicitly requested shell program, so pass it with cmd's own syntax.
403            c.as_std_mut().raw_arg(&request.code);
404            c
405        };
406        #[cfg(not(windows))]
407        let cmd = {
408            let mut c = Command::new("sh");
409            c.arg("-c").arg(&request.code);
410            c
411        };
412        self.run_command(cmd, request, None).await
413    }
414
415    /// Shared execution logic: env isolation, stdin piping, timeout, output capture.
416    ///
417    /// When a [`SandboxEnforcer`] is configured, the command is wrapped with
418    /// platform-specific sandbox restrictions before spawning.
419    async fn run_command(
420        &self,
421        cmd: Command,
422        request: &ExecRequest,
423        scratch_dir: Option<&Path>,
424    ) -> Result<ExecResult, SandboxError> {
425        self.run_command_with_env(cmd, request, &[], scratch_dir).await
426    }
427
428    /// Variables a compiler needs to find its own tools.
429    ///
430    /// `rustc` shells out to a platform linker and resolves it through the environment.
431    /// The MSVC linker also reads `LIB` to find the Windows and C runtime libraries.
432    /// With the environment cleared it cannot link at all, so compilation gets a small
433    /// platform-specific allowlist. On Windows, missing values are discovered from the
434    /// installed Visual Studio Build Tools and Windows SDK.
435    ///
436    /// This widens what the compile phase can see compared with the run phase. An OS
437    /// enforcer is what constrains it; see [`ProcessBackend::isolation`].
438    ///
439    /// Callers that invoke `rustc` themselves apply this after `env_clear()`, so
440    /// compile-time macros such as `env!` and `option_env!` see only these variables.
441    ///
442    /// # Example
443    ///
444    /// ```rust
445    /// use adk_sandbox::ProcessBackend;
446    ///
447    /// let environment = ProcessBackend::toolchain_env();
448    /// assert!(environment.iter().all(|(key, _)| key != "OPENAI_API_KEY"));
449    /// ```
450    pub fn toolchain_env() -> Vec<(String, OsString)> {
451        // RUSTUP_TOOLCHAIN matters as much as RUSTUP_HOME: `rustc` on PATH is usually a rustup
452        // shim, and without it the shim ignores the caller's selection and resolves
453        // `rust-toolchain.toml` instead. That either compiles with a different toolchain than the
454        // caller intended, or — when the pinned one is not installed — tries to download it and
455        // fails against the sandbox's network denial, reporting "syncing channel updates" from
456        // what looks like a compile error.
457        let keys =
458            if cfg!(windows) { WINDOWS_TOOLCHAIN_ENV_KEYS } else { NON_WINDOWS_TOOLCHAIN_ENV_KEYS };
459
460        let environment: Vec<(String, OsString)> = keys
461            .iter()
462            .filter_map(|key| std::env::var_os(key).map(|value| ((*key).to_string(), value)))
463            .collect();
464
465        #[cfg(windows)]
466        let mut environment = environment;
467
468        #[cfg(windows)]
469        if !environment.iter().any(|(key, _)| key.eq_ignore_ascii_case("LIB"))
470            && let Some(linker) = find_msvc_tools::find(std::env::consts::ARCH, "link.exe")
471        {
472            for (key, value) in linker.get_envs() {
473                let Some(value) = value else {
474                    continue;
475                };
476                let Some(allowed_key) = WINDOWS_TOOLCHAIN_ENV_KEYS
477                    .iter()
478                    .find(|allowed| key.eq_ignore_ascii_case(OsStr::new(allowed)))
479                else {
480                    continue;
481                };
482                if !environment
483                    .iter()
484                    .any(|(existing, _)| existing.eq_ignore_ascii_case(allowed_key))
485                {
486                    environment.push(((*allowed_key).to_string(), value.to_os_string()));
487                }
488            }
489        }
490
491        environment
492    }
493
494    /// Shared execution logic, with `extra_env` applied below policy and request values.
495    ///
496    /// `scratch_dir` is the execution's own temporary directory (source file, compiler
497    /// output). Under an enforcer the sandboxed process is granted read-write access to it
498    /// and starts in it; executions that bring none get a fresh one.
499    async fn run_command_with_env(
500        &self,
501        cmd: Command,
502        request: &ExecRequest,
503        extra_env: &[(String, OsString)],
504        scratch_dir: Option<&Path>,
505    ) -> Result<ExecResult, SandboxError> {
506        // Keeps a scratch directory created here alive until the execution ends.
507        let mut owned_scratch: Option<tempfile::TempDir> = None;
508
509        // Resolve a bare program name against the caller's PATH *before* clearing the
510        // environment. Clearing first leaves the child with no PATH, and program
511        // resolution then fails with ENOENT — so a backend configured with `"rustc"`,
512        // `"python3"`, or `"node"` could not execute anything at all.
513        let mut cmd = if let (Some(enforcer), Some(policy)) = (&self.enforcer, &self.policy) {
514            let scratch = match scratch_dir {
515                Some(dir) => dir.to_path_buf(),
516                None => owned_scratch.insert(tempfile::tempdir()?).path().to_path_buf(),
517            };
518            // The enforcers deny every path the policy does not name, and the execution's
519            // own files live in the scratch directory. It is created per execution and holds
520            // nothing from the host, so granting it widens nothing.
521            let mut policy = policy.clone();
522            policy
523                .allowed_paths
524                .push(AllowedPath { path: scratch.clone(), mode: AccessMode::ReadWrite });
525            // `sandboxed_command` finds an Xcode shim through the policy's PATH; the child's
526            // PATH is the request's when it sets one. The environment itself is applied below.
527            if let Some(path) = request.env.get("PATH") {
528                policy.env.insert("PATH".to_string(), path.clone());
529            }
530
531            let std_cmd = cmd.as_std();
532            let args: Vec<OsString> = std_cmd.get_args().map(OsStr::to_owned).collect();
533            sandboxed_command(enforcer.as_ref(), std_cmd.get_program(), &args, &policy, &scratch)?
534        } else {
535            match resolve_program(cmd.as_std().get_program()) {
536                Some(resolved) => {
537                    let args: Vec<OsString> =
538                        cmd.as_std().get_args().map(OsStr::to_owned).collect();
539                    let mut resolved_cmd = Command::new(resolved);
540                    resolved_cmd.args(&args);
541                    resolved_cmd
542                }
543                None => cmd,
544            }
545        };
546
547        // Environment precedence: the policy supplies defaults for every execution, and
548        // the request overrides them per call. `SandboxPolicy::env` was previously
549        // ignored entirely, so a policy that set variables silently supplied none.
550        cmd.env_clear();
551        for (k, v) in extra_env {
552            cmd.env(k, v);
553        }
554        if let Some(policy) = &self.policy {
555            for (k, v) in &policy.env {
556                cmd.env(k, v);
557            }
558        }
559        for (k, v) in &request.env {
560            cmd.env(k, v);
561        }
562        // Last, so neither the policy nor the request routes around the egress proxy.
563        if let Some(policy) = &self.policy {
564            cmd.envs(policy.network.proxy_env());
565        }
566        cmd.kill_on_drop(true);
567
568        // Give each execution its own process group. `kill_on_drop` only
569        // targets the immediate child, which is not enough for shell tools:
570        // compilers, scripts, and background jobs can otherwise survive a
571        // timeout. Descendants inherit this group unless they deliberately
572        // detach, so the group is killed on timeout and again on exit.
573        #[cfg(unix)]
574        {
575            use std::os::unix::process::CommandExt;
576            cmd.as_std_mut().process_group(0);
577        }
578
579        cmd.stdout(std::process::Stdio::piped());
580        cmd.stderr(std::process::Stdio::piped());
581
582        if request.stdin.is_some() {
583            cmd.stdin(std::process::Stdio::piped());
584        } else {
585            cmd.stdin(std::process::Stdio::null());
586        }
587
588        let start = Instant::now();
589        let child = cmd.spawn()?;
590
591        // Both pipes are read concurrently with the cap applied as the bytes arrive, and stdin
592        // is written alongside them inside the timeout.
593        let cap = self.config.max_output_bytes;
594        let stdin = request.stdin.as_ref().map(|input| input.as_bytes().to_vec());
595        let output = collect_output(child, stdin, request.timeout, cap).await;
596        let duration = start.elapsed();
597
598        match output {
599            Ok(Some(captured)) => {
600                let exit_code = captured.status.code().unwrap_or(-1);
601                if captured.stdout_truncated || captured.stderr_truncated {
602                    tracing::warn!(
603                        max_output_bytes = cap,
604                        stdout.truncated = captured.stdout_truncated,
605                        stderr.truncated = captured.stderr_truncated,
606                        "sandbox output exceeded the cap and was truncated"
607                    );
608                }
609                let stdout =
610                    note_truncation(truncate_utf8(captured.stdout, cap), captured.stdout_truncated);
611                let stderr =
612                    note_truncation(truncate_utf8(captured.stderr, cap), captured.stderr_truncated);
613
614                Span::current().record("exit_code", exit_code);
615                Span::current().record("duration_ms", duration.as_millis() as u64);
616
617                Ok(ExecResult { stdout, stderr, exit_code, duration })
618            }
619            Ok(None) => {
620                Span::current().record("duration_ms", duration.as_millis() as u64);
621                Err(SandboxError::Timeout { timeout: request.timeout })
622            }
623            Err(e) => {
624                Err(SandboxError::ExecutionFailed(format!("failed to wait for child process: {e}")))
625            }
626        }
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633    use std::collections::HashMap;
634    use std::time::Duration;
635
636    fn make_request(language: Language, code: &str) -> ExecRequest {
637        let mut env = HashMap::new();
638        // ProcessBackend clears the environment (REQ-SBX-023), so tests that
639        // invoke interpreters by name need PATH to resolve them.
640        if let Ok(path) = std::env::var("PATH") {
641            env.insert("PATH".to_string(), path);
642        }
643        // Windows processes need SYSTEMROOT for DLL loading and basic operation.
644        if let Ok(sr) = std::env::var("SYSTEMROOT") {
645            env.insert("SYSTEMROOT".to_string(), sr);
646        }
647        ExecRequest {
648            language,
649            code: code.to_string(),
650            stdin: None,
651            timeout: Duration::from_secs(30),
652            memory_limit_mb: None,
653            env,
654        }
655    }
656
657    #[tokio::test]
658    async fn test_python_execution() {
659        let backend = ProcessBackend::default();
660        let request = make_request(Language::Python, "print('hello')");
661        let result = backend.execute(request).await.unwrap();
662        assert!(result.stdout.contains("hello"), "stdout: {}", result.stdout);
663        assert_eq!(result.exit_code, 0);
664    }
665
666    #[tokio::test]
667    async fn test_javascript_execution() {
668        // Skip if node is not available (e.g. minimal CI images)
669        if std::process::Command::new("node").arg("--version").output().is_err() {
670            eprintln!("skipping test_javascript_execution: node not found");
671            return;
672        }
673        let backend = ProcessBackend::default();
674        let mut request = make_request(Language::JavaScript, "console.log('hello')");
675        // node.exe takes from one to over thirty seconds to start on a loaded Windows runner,
676        // so a finite budget races its startup; `test_timeout_enforcement` covers the timeout.
677        request.timeout = Duration::MAX;
678        let result = backend.execute(request).await.unwrap();
679        assert!(result.stdout.contains("hello"), "stdout: {}", result.stdout);
680        assert_eq!(result.exit_code, 0);
681    }
682
683    #[tokio::test]
684    async fn test_command_execution() {
685        let backend = ProcessBackend::default();
686        let request = make_request(Language::Command, "echo hello");
687        let result = backend.execute(request).await.unwrap();
688        assert!(result.stdout.contains("hello"), "stdout: {}", result.stdout);
689        assert_eq!(result.exit_code, 0);
690    }
691
692    #[tokio::test]
693    #[cfg(windows)]
694    async fn test_command_supports_quoted_script_paths() {
695        let directory = tempfile::tempdir().unwrap();
696        let script = directory.path().join("quoted helper.cmd");
697        std::fs::write(&script, "@echo quoted-path-ok\r\n").unwrap();
698
699        let backend = ProcessBackend::default();
700        let request = make_request(Language::Command, &format!("\"{}\"", script.display()));
701        let result = backend.execute(request).await.unwrap();
702
703        assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr);
704        assert!(result.stdout.contains("quoted-path-ok"), "stdout: {}", result.stdout);
705    }
706
707    #[tokio::test]
708    async fn test_timeout_enforcement() {
709        let backend = ProcessBackend::default();
710        let code =
711            if cfg!(windows) { "ping -n 11 127.0.0.1".to_string() } else { "sleep 10".to_string() };
712        let mut request = make_request(Language::Command, &code);
713        request.timeout = Duration::from_secs(1);
714        let result = backend.execute(request).await;
715        assert!(
716            matches!(result, Err(SandboxError::Timeout { .. })),
717            "expected Timeout, got: {result:?}"
718        );
719    }
720
721    #[tokio::test]
722    #[cfg(unix)]
723    async fn test_timeout_terminates_background_descendants() {
724        let backend = ProcessBackend::default();
725        let directory = tempfile::tempdir().unwrap();
726        let marker = directory.path().join("escaped-child");
727        let escaped_marker = marker.to_string_lossy().replace('\'', "'\\''");
728        let code = format!("(sleep 1; touch '{escaped_marker}') & wait");
729        let mut request = make_request(Language::Command, &code);
730        request.timeout = Duration::from_millis(100);
731
732        let result = backend.execute(request).await;
733        assert!(matches!(result, Err(SandboxError::Timeout { .. })));
734        tokio::time::sleep(Duration::from_millis(1_200)).await;
735        assert!(!marker.exists(), "a background descendant survived the execution timeout");
736    }
737
738    /// A `nohup … &` descendant must not outlive an execution that exits normally.
739    #[tokio::test]
740    #[cfg(unix)]
741    async fn test_normal_exit_terminates_background_descendants() {
742        let backend = ProcessBackend::default();
743        let directory = tempfile::tempdir().unwrap();
744        let marker = directory.path().join("escaped-child");
745        let escaped_marker = marker.to_string_lossy().replace('\'', "'\\''");
746        let code = format!(
747            "nohup sh -c 'sleep 1; touch \"$0\"' '{escaped_marker}' >/dev/null 2>&1 & echo done"
748        );
749
750        let result = backend.execute(make_request(Language::Command, &code)).await.unwrap();
751        assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr);
752        assert_eq!(result.stdout.trim(), "done");
753
754        tokio::time::sleep(Duration::from_millis(1_500)).await;
755        assert!(!marker.exists(), "a background descendant survived a normal exit");
756    }
757
758    /// Stdin larger than a pipe buffer reaches a child that writes output before reading.
759    ///
760    /// Writing all of stdin before the output readers started deadlocked here: the child
761    /// blocked on a full stdout pipe, the backend on a full stdin pipe, outside the timeout.
762    #[tokio::test]
763    #[cfg(unix)]
764    async fn test_large_stdin_does_not_deadlock_against_output() {
765        let backend = ProcessBackend::default();
766        let mut request = make_request(Language::Command, "head -c 262144 /dev/zero; wc -c");
767        request.stdin = Some("s".repeat(512 * 1_024));
768
769        let result = tokio::time::timeout(Duration::from_secs(60), backend.execute(request))
770            .await
771            .expect("the execution deadlocked")
772            .expect("the execution completes");
773
774        assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr);
775        assert!(
776            result.stdout.trim_end().ends_with("524288"),
777            "stdin was not fully delivered: {:?}",
778            &result.stdout[result.stdout.len().saturating_sub(32)..]
779        );
780    }
781
782    /// A child that never reads its stdin is still bounded by the request timeout.
783    #[tokio::test]
784    #[cfg(unix)]
785    async fn test_unread_stdin_is_bounded_by_the_timeout() {
786        let backend = ProcessBackend::default();
787        let mut request = make_request(Language::Command, "sleep 30");
788        request.stdin = Some("s".repeat(4 * 1_024 * 1_024));
789        request.timeout = Duration::from_millis(300);
790
791        let started = std::time::Instant::now();
792        let result = backend.execute(request).await;
793
794        assert!(matches!(result, Err(SandboxError::Timeout { .. })), "got: {result:?}");
795        assert!(started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed());
796    }
797
798    #[tokio::test]
799    #[cfg(not(windows))]
800    async fn test_environment_isolation() {
801        let backend = ProcessBackend::default();
802        let mut env = HashMap::new();
803        env.insert("MY_TEST_VAR".to_string(), "test_value".to_string());
804        let request = ExecRequest {
805            language: Language::Command,
806            // Use absolute path to env since PATH won't be set
807            code: "/usr/bin/env".to_string(),
808            stdin: None,
809            timeout: Duration::from_secs(10),
810            memory_limit_mb: None,
811            env,
812        };
813        let result = backend.execute(request).await.unwrap();
814        // The only env var should be MY_TEST_VAR
815        assert!(result.stdout.contains("MY_TEST_VAR=test_value"), "stdout: {}", result.stdout);
816        // Common inherited vars like HOME should NOT be present
817        assert!(
818            !result.stdout.contains("HOME="),
819            "HOME should not be inherited: {}",
820            result.stdout
821        );
822    }
823
824    #[tokio::test]
825    #[cfg(windows)]
826    async fn test_environment_isolation() {
827        let backend = ProcessBackend::default();
828        let mut env = HashMap::new();
829        env.insert("MY_TEST_VAR".to_string(), "test_value".to_string());
830        let request = ExecRequest {
831            language: Language::Command,
832            code: "set MY_TEST_VAR".to_string(),
833            stdin: None,
834            timeout: Duration::from_secs(10),
835            memory_limit_mb: None,
836            env,
837        };
838        let result = backend.execute(request).await.unwrap();
839        assert!(result.stdout.contains("MY_TEST_VAR=test_value"), "stdout: {}", result.stdout);
840    }
841
842    #[tokio::test]
843    async fn test_nonzero_exit_code() {
844        let backend = ProcessBackend::default();
845        let code = if cfg!(windows) { "exit /b 42" } else { "exit 42" };
846        let request = make_request(Language::Command, code);
847        let result = backend.execute(request).await.unwrap();
848        assert_eq!(result.exit_code, 42);
849    }
850
851    #[tokio::test]
852    async fn test_wasm_returns_invalid_request() {
853        let backend = ProcessBackend::default();
854        let request = make_request(Language::Wasm, "");
855        let result = backend.execute(request).await;
856        assert!(
857            matches!(result, Err(SandboxError::InvalidRequest(_))),
858            "expected InvalidRequest, got: {result:?}"
859        );
860    }
861
862    #[test]
863    fn test_capabilities() {
864        let backend = ProcessBackend::default();
865        let caps = backend.capabilities();
866        assert_eq!(caps.isolation_class, "process");
867        assert!(caps.enforced_limits.timeout);
868        assert!(caps.enforced_limits.environment_isolation);
869        assert!(!caps.enforced_limits.memory);
870        assert!(!caps.enforced_limits.network_isolation);
871        assert!(!caps.enforced_limits.filesystem_write_isolation);
872        assert!(!caps.enforced_limits.filesystem_read_isolation);
873        assert!(caps.supported_languages.contains(&Language::Rust));
874        assert!(caps.supported_languages.contains(&Language::Python));
875        assert!(caps.supported_languages.contains(&Language::JavaScript));
876        assert!(caps.supported_languages.contains(&Language::TypeScript));
877        assert!(caps.supported_languages.contains(&Language::Command));
878        assert!(!caps.supported_languages.contains(&Language::Wasm));
879    }
880
881    #[test]
882    fn test_name() {
883        let backend = ProcessBackend::default();
884        assert_eq!(backend.name(), "process");
885    }
886
887    #[test]
888    fn test_process_config_default() {
889        let config = ProcessConfig::default();
890        assert_eq!(config.rustc_path, "rustc");
891        assert_eq!(config.python_path, "python3");
892        assert_eq!(config.node_path, "node");
893    }
894
895    #[test]
896    fn windows_compiler_environment_is_a_minimal_allowlist() {
897        assert_eq!(
898            WINDOWS_TOOLCHAIN_ENV_KEYS,
899            &[
900                "PATH",
901                "LIB",
902                "LIBPATH",
903                "INCLUDE",
904                "SystemRoot",
905                "TEMP",
906                "TMP",
907                "USERPROFILE",
908                "RUSTUP_HOME",
909                "RUSTUP_TOOLCHAIN",
910            ]
911        );
912    }
913}