Skip to main content

lean_ctx_ext/core/
sandbox.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::collections::HashMap;
3#[cfg(unix)]
4use std::os::unix::process::CommandExt;
5use std::process::Command;
6
7#[derive(Debug, Clone)]
8pub struct SandboxResult {
9    pub stdout: String,
10    pub stderr: String,
11    pub exit_code: i32,
12    pub language: String,
13    pub duration_ms: u64,
14}
15
16const TIMEOUT_SECS: u64 = 30;
17const MAX_OUTPUT_BYTES: usize = 32_768;
18/// Upper bound on the `code` payload. Generous for real scripts while preventing an
19/// agent from forcing a multi-megabyte temp-file write / interpreter argv → memory abuse.
20const MAX_CODE_BYTES: usize = 256 * 1024;
21
22/// Runs a snippet in the sandbox runtime of `language`.
23///
24/// A run does not leave processes behind (Q13, Unix, in the `lean-ctx`
25/// binary): whatever the snippet started in its process group is ended when
26/// the run is over — after a normal exit before the output is collected, on a
27/// timeout with the snippet itself — and when this process is gone.
28pub fn execute(language: &str, code: &str, timeout_secs: Option<u64>) -> SandboxResult {
29    execute_in(language, code, timeout_secs, None)
30}
31
32/// Same as [`execute`], but runs the snippet in `cwd` (GH #1666).
33///
34/// A caller that already resolved a working directory — `ctx_shell` rerouting
35/// an interpreter heredoc, for one — must be able to hand it over. Without
36/// this, the snippet inherited the server process's directory while the rest
37/// of the same tool call ran in `cwd`, so relative paths in the snippet
38/// resolved against a different tree and quietly hit the wrong files.
39pub fn execute_in(
40    language: &str,
41    code: &str,
42    timeout_secs: Option<u64>,
43    cwd: Option<&std::path::Path>,
44) -> SandboxResult {
45    if code.len() > MAX_CODE_BYTES {
46        return SandboxResult {
47            stdout: String::new(),
48            stderr: format!(
49                "Code exceeds the {MAX_CODE_BYTES}-byte limit ({} bytes). Split it into smaller scripts.",
50                code.len()
51            ),
52            exit_code: 1,
53            language: language.to_string(),
54            duration_ms: 0,
55        };
56    }
57
58    let timeout = timeout_secs.unwrap_or(TIMEOUT_SECS);
59    let start = std::time::Instant::now();
60
61    let Some(runtime) = resolve_runtime(language) else {
62        return SandboxResult {
63            stdout: String::new(),
64            stderr: format!(
65                "Unsupported language: {language}. Supported: javascript, typescript, python, shell, ruby, go, rust, php, perl, r, elixir"
66            ),
67            exit_code: 1,
68            language: language.to_string(),
69            duration_ms: 0,
70        };
71    };
72
73    let sandbox_level = std::env::var("LEAN_CTX_SANDBOX_LEVEL")
74        .ok()
75        .and_then(|v| v.parse::<u8>().ok())
76        .unwrap_or_else(|| crate::core::config::Config::load().sandbox_level);
77
78    if sandbox_level >= 1 && cfg!(target_os = "macos") {
79        let result = seatbelt_execute(&runtime, code, timeout, cwd);
80        let duration_ms = start.elapsed().as_millis() as u64;
81        return match result {
82            Ok((stdout, stderr, exit_code)) => SandboxResult {
83                stdout: truncate_output(&stdout),
84                stderr: truncate_smart(&stderr, 2048),
85                exit_code,
86                language: language.to_string(),
87                duration_ms,
88            },
89            Err(e) => SandboxResult {
90                stdout: String::new(),
91                stderr: format!("Seatbelt execution error: {e}"),
92                exit_code: 1,
93                language: language.to_string(),
94                duration_ms,
95            },
96        };
97    } else if sandbox_level >= 1 {
98        #[cfg(target_os = "linux")]
99        {
100            let result = landlock_execute(&runtime, code, timeout, cwd);
101            let duration_ms = start.elapsed().as_millis() as u64;
102            return match result {
103                Ok((stdout, stderr, exit_code)) => SandboxResult {
104                    stdout: truncate_output(&stdout),
105                    stderr: truncate_smart(&stderr, 2048),
106                    exit_code,
107                    language: language.to_string(),
108                    duration_ms,
109                },
110                Err(e) => SandboxResult {
111                    stdout: String::new(),
112                    stderr: format!("Landlock execution error: {e}"),
113                    exit_code: 1,
114                    language: language.to_string(),
115                    duration_ms,
116                },
117            };
118        }
119
120        // An explicitly requested OS sandbox that this platform cannot provide
121        // must not silently degrade to unsandboxed execution
122        // (GHSA-rxv5-4c3x-g4q6 B).
123        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
124        {
125            return sandbox_unavailable(language, start);
126        }
127    }
128
129    let result = if runtime.needs_temp_file {
130        execute_with_file(&runtime, code, timeout, cwd)
131    } else {
132        execute_with_stdin(&runtime, code, timeout, cwd)
133    };
134
135    let duration_ms = start.elapsed().as_millis() as u64;
136
137    match result {
138        Ok((stdout, stderr, code)) => SandboxResult {
139            stdout: truncate_output(&stdout),
140            stderr: truncate_smart(&stderr, 2048),
141            exit_code: code,
142            language: language.to_string(),
143            duration_ms,
144        },
145        Err(e) => SandboxResult {
146            stdout: String::new(),
147            stderr: format!("Execution error: {e}"),
148            exit_code: 1,
149            language: language.to_string(),
150            duration_ms,
151        },
152    }
153}
154
155pub fn batch_execute(items: &[(String, String)]) -> Vec<SandboxResult> {
156    batch_execute_in(items, None)
157}
158
159/// Same as [`batch_execute`], but every task runs in `cwd`.
160pub fn batch_execute_in(
161    items: &[(String, String)],
162    cwd: Option<&std::path::Path>,
163) -> Vec<SandboxResult> {
164    items
165        .iter()
166        .map(|(lang, code)| execute_in(lang, code, None, cwd))
167        .collect()
168}
169
170/// Whether `language` resolves to the shell runtime. Every alias must take
171/// the `ctx_shell` allowlist preflight (GHSA-rxv5-4c3x-g4q6 B), so callers
172/// use this instead of comparing against `"shell"`.
173#[must_use]
174pub fn is_shell_language(language: &str) -> bool {
175    matches!(language.to_lowercase().as_str(), "shell" | "bash" | "sh")
176}
177
178/// Refusal for `sandbox_level >= 1` on a platform without an OS sandbox.
179#[cfg_attr(any(target_os = "macos", target_os = "linux"), allow(dead_code))]
180fn sandbox_unavailable(language: &str, start: std::time::Instant) -> SandboxResult {
181    SandboxResult {
182        stdout: String::new(),
183        stderr: "sandbox_level >= 1 is configured but no OS sandbox is available on this \
184                 platform; refusing to run the code unsandboxed. Set sandbox_level = 0 to \
185                 accept unsandboxed execution."
186            .to_string(),
187        exit_code: 1,
188        language: language.to_string(),
189        duration_ms: start.elapsed().as_millis() as u64,
190    }
191}
192
193struct RuntimeConfig {
194    command: String,
195    args: Vec<String>,
196    needs_temp_file: bool,
197    file_extension: String,
198    env: HashMap<String, String>,
199}
200
201/// The language `language` runs as (one of [`supported_languages`]), after
202/// aliases (`py`, `node`, `bash`, …) and case; `None` when unsupported.
203pub fn canonical_language(language: &str) -> Option<&'static str> {
204    Some(match language.to_lowercase().as_str() {
205        "javascript" | "js" | "node" => "javascript",
206        "typescript" | "ts" => "typescript",
207        "python" | "py" => "python",
208        "shell" | "bash" | "sh" => "shell",
209        "ruby" | "rb" => "ruby",
210        "go" | "golang" => "go",
211        "rust" | "rs" => "rust",
212        "php" => "php",
213        "perl" | "pl" => "perl",
214        "r" => "r",
215        "elixir" | "ex" => "elixir",
216        _ => return None,
217    })
218}
219
220fn resolve_runtime(language: &str) -> Option<RuntimeConfig> {
221    match canonical_language(language)? {
222        "javascript" => Some(RuntimeConfig {
223            command: find_binary(&["bun", "node"])?,
224            args: vec!["-e".to_string()],
225            needs_temp_file: false,
226            file_extension: "js".to_string(),
227            env: HashMap::new(),
228        }),
229        "typescript" => Some(RuntimeConfig {
230            command: find_binary(&["bun", "npx"])?,
231            args: if which_exists("bun") {
232                vec!["-e".to_string()]
233            } else {
234                vec!["tsx".to_string(), "-e".to_string()]
235            },
236            needs_temp_file: false,
237            file_extension: "ts".to_string(),
238            env: HashMap::new(),
239        }),
240        "python" => Some(RuntimeConfig {
241            command: find_binary(&["python3", "python"])?,
242            args: vec!["-c".to_string()],
243            needs_temp_file: false,
244            file_extension: "py".to_string(),
245            env: HashMap::from([("PYTHONDONTWRITEBYTECODE".into(), "1".into())]),
246        }),
247        lang if is_shell_language(lang) => {
248            #[cfg(target_os = "windows")]
249            {
250                Some(RuntimeConfig {
251                    command: "cmd".to_string(),
252                    args: vec!["/C".to_string()],
253                    needs_temp_file: false,
254                    file_extension: "bat".to_string(),
255                    env: HashMap::new(),
256                })
257            }
258            #[cfg(not(target_os = "windows"))]
259            {
260                Some(RuntimeConfig {
261                    command: find_binary(&["bash", "sh"])?,
262                    args: vec!["-c".to_string()],
263                    needs_temp_file: false,
264                    file_extension: "sh".to_string(),
265                    env: HashMap::new(),
266                })
267            }
268        }
269        "ruby" => Some(RuntimeConfig {
270            command: find_binary(&["ruby"])?,
271            args: vec!["-e".to_string()],
272            needs_temp_file: false,
273            file_extension: "rb".to_string(),
274            env: HashMap::new(),
275        }),
276        "go" => Some(RuntimeConfig {
277            command: find_binary(&["go"])?,
278            args: vec!["run".to_string()],
279            needs_temp_file: true,
280            file_extension: "go".to_string(),
281            env: HashMap::new(),
282        }),
283        "rust" => Some(RuntimeConfig {
284            command: "rustc_script".to_string(),
285            args: vec![],
286            needs_temp_file: true,
287            file_extension: "rs".to_string(),
288            env: HashMap::new(),
289        }),
290        "php" => Some(RuntimeConfig {
291            command: find_binary(&["php"])?,
292            args: vec!["-r".to_string()],
293            needs_temp_file: false,
294            file_extension: "php".to_string(),
295            env: HashMap::new(),
296        }),
297        "perl" => Some(RuntimeConfig {
298            command: find_binary(&["perl"])?,
299            args: vec!["-e".to_string()],
300            needs_temp_file: false,
301            file_extension: "pl".to_string(),
302            env: HashMap::new(),
303        }),
304        "r" => Some(RuntimeConfig {
305            command: find_binary(&["Rscript"])?,
306            args: vec!["-e".to_string()],
307            needs_temp_file: false,
308            file_extension: "R".to_string(),
309            env: HashMap::new(),
310        }),
311        "elixir" => Some(RuntimeConfig {
312            command: find_binary(&["elixir"])?,
313            args: vec!["-e".to_string()],
314            needs_temp_file: false,
315            file_extension: "exs".to_string(),
316            env: HashMap::new(),
317        }),
318        _ => None,
319    }
320}
321
322fn seatbelt_execute(
323    runtime: &RuntimeConfig,
324    code: &str,
325    timeout: u64,
326    cwd: Option<&std::path::Path>,
327) -> Result<(String, String, i32), String> {
328    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
329    let _ = std::fs::create_dir_all(&tmp_dir);
330
331    let env_pairs: Vec<(String, String)> = runtime
332        .env
333        .iter()
334        .map(|(k, v)| (k.clone(), v.clone()))
335        .collect();
336
337    if runtime.needs_temp_file {
338        let suffix = format!(".{}", runtime.file_extension);
339        let tmp = tempfile::Builder::new()
340            .prefix("exec_")
341            .suffix(&suffix)
342            .tempfile_in(&tmp_dir)
343            .map_err(|e| format!("Failed to create temp file: {e}"))?;
344        let file_path = tmp.into_temp_path();
345        std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
346
347        let mut allowed = vec![file_path.to_path_buf()];
348        // The profile denies by default, so a working directory the caller
349        // chose has to be granted explicitly — otherwise the snippet starts
350        // there and cannot read a thing (#1666). Write permission is
351        // deliberately not granted: that boundary belongs to sandbox_level.
352        if let Some(dir) = cwd {
353            allowed.push(dir.to_path_buf());
354        }
355        let allowed_refs: Vec<&std::path::Path> =
356            allowed.iter().map(std::path::PathBuf::as_path).collect();
357        let file_str = file_path.to_string_lossy().to_string();
358
359        let mut args: Vec<&str> = runtime
360            .args
361            .iter()
362            .map(std::string::String::as_str)
363            .collect();
364        args.push(&file_str);
365
366        let result = super::sandbox_seatbelt::execute_sandboxed(
367            &runtime.command,
368            &args,
369            &allowed_refs,
370            &env_pairs,
371            timeout,
372            cwd,
373        );
374        let _ = std::fs::remove_file(&file_path);
375        result
376    } else {
377        let mut args: Vec<&str> = runtime
378            .args
379            .iter()
380            .map(std::string::String::as_str)
381            .collect();
382        args.push(code);
383        let allowed: Vec<std::path::PathBuf> =
384            cwd.map(|d| vec![d.to_path_buf()]).unwrap_or_default();
385        let allowed_refs: Vec<&std::path::Path> =
386            allowed.iter().map(std::path::PathBuf::as_path).collect();
387        super::sandbox_seatbelt::execute_sandboxed(
388            &runtime.command,
389            &args,
390            &allowed_refs,
391            &env_pairs,
392            timeout,
393            cwd,
394        )
395    }
396}
397
398#[cfg(target_os = "linux")]
399fn landlock_execute(
400    runtime: &RuntimeConfig,
401    code: &str,
402    timeout: u64,
403    cwd: Option<&std::path::Path>,
404) -> Result<(String, String, i32), String> {
405    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
406    let _ = std::fs::create_dir_all(&tmp_dir);
407
408    let env_pairs: Vec<(String, String)> = runtime
409        .env
410        .iter()
411        .map(|(k, v)| (k.clone(), v.clone()))
412        .collect();
413
414    if runtime.needs_temp_file {
415        let suffix = format!(".{}", runtime.file_extension);
416        let tmp = tempfile::Builder::new()
417            .prefix("exec_")
418            .suffix(&suffix)
419            .tempfile_in(&tmp_dir)
420            .map_err(|e| format!("Failed to create temp file: {e}"))?;
421        let file_path = tmp.into_temp_path();
422        std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
423
424        let mut allowed = vec![file_path.to_path_buf()];
425        if let Some(dir) = cwd {
426            allowed.push(dir.to_path_buf());
427        }
428        let allowed_refs: Vec<&std::path::Path> =
429            allowed.iter().map(std::path::PathBuf::as_path).collect();
430        let file_str = file_path.to_string_lossy().to_string();
431
432        let mut args: Vec<&str> = runtime
433            .args
434            .iter()
435            .map(std::string::String::as_str)
436            .collect();
437        args.push(&file_str);
438
439        let result = super::sandbox_landlock::execute_sandboxed(
440            &runtime.command,
441            &args,
442            &allowed_refs,
443            &env_pairs,
444            timeout,
445            cwd,
446        );
447        let _ = std::fs::remove_file(&file_path);
448        result
449    } else {
450        let mut args: Vec<&str> = runtime
451            .args
452            .iter()
453            .map(std::string::String::as_str)
454            .collect();
455        args.push(code);
456        let allowed: Vec<std::path::PathBuf> =
457            cwd.map(|d| vec![d.to_path_buf()]).unwrap_or_default();
458        let allowed_refs: Vec<&std::path::Path> =
459            allowed.iter().map(std::path::PathBuf::as_path).collect();
460        super::sandbox_landlock::execute_sandboxed(
461            &runtime.command,
462            &args,
463            &allowed_refs,
464            &env_pairs,
465            timeout,
466            cwd,
467        )
468    }
469}
470
471const SANDBOX_ENV_ALLOWLIST: &[&str] = &[
472    "PATH",
473    "HOME",
474    "USER",
475    "LANG",
476    "LC_ALL",
477    "TERM",
478    "TMPDIR",
479    "TMP",
480    "TEMP",
481    "SYSTEMROOT",
482    "WINDIR",
483    "SystemDrive",
484];
485
486fn apply_sandbox_env(cmd: &mut Command, runtime: &RuntimeConfig) {
487    cmd.env_clear();
488    for key in SANDBOX_ENV_ALLOWLIST {
489        if let Ok(val) = std::env::var(key) {
490            cmd.env(key, val);
491        }
492    }
493    for (k, v) in &runtime.env {
494        cmd.env(k, v);
495    }
496    cmd.env("LEAN_CTX_SANDBOX", "1");
497}
498
499/// Run the child in `cwd` when the caller resolved one (GH #1666).
500///
501/// A directory that no longer exists would make `spawn` fail with a message
502/// about the *command*, which reads as a missing interpreter. Falling back to
503/// the inherited directory is not an option either — running somewhere other
504/// than the caller asked, without saying so, is the bug this exists to fix —
505/// so an unusable directory is reported as itself.
506fn apply_cwd(cmd: &mut Command, cwd: Option<&std::path::Path>) -> Result<(), String> {
507    let Some(dir) = cwd else { return Ok(()) };
508    if !dir.is_dir() {
509        return Err(format!(
510            "working directory does not exist: {}",
511            dir.display()
512        ));
513    }
514    cmd.current_dir(dir);
515    Ok(())
516}
517
518fn execute_with_stdin(
519    runtime: &RuntimeConfig,
520    code: &str,
521    timeout: u64,
522    cwd: Option<&std::path::Path>,
523) -> Result<(String, String, i32), String> {
524    let mut cmd = Command::new(&runtime.command);
525    apply_cwd(&mut cmd, cwd)?;
526    for arg in &runtime.args {
527        cmd.arg(arg);
528    }
529    cmd.arg(code);
530    apply_sandbox_env(&mut cmd, runtime);
531    run_runtime_command(cmd, timeout)
532}
533
534/// All level-zero interpreter, compiler and compiled-program launches pass
535/// here. A protected MCP process must delegate even when optional sandboxing
536/// is disabled; it must never spawn a child with access to its context store.
537fn run_runtime_command(mut cmd: Command, timeout: u64) -> Result<(String, String, i32), String> {
538    #[cfg(unix)]
539    {
540        use crate::core::protected_execution::{Mode, launch_mode};
541        match launch_mode()? {
542            Mode::Brokered(client) => {
543                let executable = resolve_program_path(&cmd)?;
544                let executable = executable.to_str().ok_or("runtime path is not UTF-8")?;
545                let args: Vec<&str> = cmd
546                    .get_args()
547                    .map(|arg| arg.to_str().ok_or("runtime argument is not UTF-8"))
548                    .collect::<Result<_, _>>()?;
549                let env: Vec<(String, String)> = cmd
550                    .get_envs()
551                    .filter_map(|(key, value)| value.map(|value| (key, value)))
552                    .map(|(key, value)| {
553                        Ok((
554                            key.to_str()
555                                .ok_or("runtime environment key is not UTF-8")?
556                                .to_owned(),
557                            value
558                                .to_str()
559                                .ok_or("runtime environment value is not UTF-8")?
560                                .to_owned(),
561                        ))
562                    })
563                    .collect::<Result<_, String>>()?;
564                return client.session_program(
565                    executable,
566                    &args,
567                    &env,
568                    timeout,
569                    cmd.get_current_dir(),
570                );
571            }
572            Mode::Sandboxed(_) => {
573                return Err("runtime execution must use the supervised program channel".into());
574            }
575            Mode::Direct => {}
576        }
577    }
578    #[cfg(not(unix))]
579    let _protected = crate::core::protected_store::protected_child_prefix()?;
580    // GH #1347: isolate child into its own process group so an interactive
581    // shell (bash -ic) cannot SIGTSTP the MCP server, and close stdin to
582    // prevent terminal job-control attempts.
583    cmd.stdin(std::process::Stdio::null());
584    cmd.stdout(std::process::Stdio::piped());
585    cmd.stderr(std::process::Stdio::piped());
586    #[cfg(unix)]
587    cmd.process_group(0);
588
589    let program = cmd.get_program().to_string_lossy().into_owned();
590    let output = wait_with_timeout(&mut cmd, timeout, |e| {
591        format!("Failed to spawn {program}: {e}")
592    })?;
593    Ok((
594        crate::shell::decode_output(&output.stdout),
595        crate::shell::decode_output(&output.stderr),
596        crate::shell::exit_status::exit_code(output.status),
597    ))
598}
599
600#[cfg(unix)]
601fn resolve_program_path(cmd: &Command) -> Result<std::path::PathBuf, String> {
602    use std::os::unix::fs::PermissionsExt;
603    let program = std::path::Path::new(cmd.get_program());
604    if program.is_absolute() {
605        return Ok(program.to_path_buf());
606    }
607    let cwd = cmd
608        .get_current_dir()
609        .map(std::path::Path::to_path_buf)
610        .unwrap_or(std::env::current_dir().map_err(|_| "runtime working directory unavailable")?);
611    if program.components().count() > 1 {
612        return Ok(cwd.join(program));
613    }
614    let path = cmd
615        .get_envs()
616        .find(|(key, _)| *key == "PATH")
617        .and_then(|(_, value)| value.map(std::ffi::OsStr::to_os_string))
618        .or_else(|| std::env::var_os("PATH"))
619        .ok_or("runtime PATH unavailable")?;
620    for directory in std::env::split_paths(&path) {
621        let directory = if directory.is_absolute() {
622            directory
623        } else {
624            cwd.join(directory)
625        };
626        let candidate = directory.join(program);
627        if candidate
628            .metadata()
629            .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
630        {
631            // Preserve argv[0] for shims such as rustup's rustc symlink.
632            return Ok(candidate);
633        }
634    }
635    Err("runtime executable unavailable".into())
636}
637
638fn execute_with_file(
639    runtime: &RuntimeConfig,
640    code: &str,
641    timeout: u64,
642    cwd: Option<&std::path::Path>,
643) -> Result<(String, String, i32), String> {
644    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
645    let _ = std::fs::create_dir_all(&tmp_dir);
646
647    let suffix = format!(".{}", runtime.file_extension);
648    let tmp = tempfile::Builder::new()
649        .prefix("exec_")
650        .suffix(&suffix)
651        .tempfile_in(&tmp_dir)
652        .map_err(|e| format!("Failed to create temp file: {e}"))?;
653    let file_path = tmp.into_temp_path();
654
655    std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
656
657    let result = if runtime.command == "rustc_script" {
658        execute_rust(&file_path, timeout, cwd)
659    } else {
660        let mut cmd = Command::new(&runtime.command);
661        apply_cwd(&mut cmd, cwd)?;
662        for arg in &runtime.args {
663            cmd.arg(arg);
664        }
665        cmd.arg(&file_path);
666        apply_sandbox_env(&mut cmd, runtime);
667        run_runtime_command(cmd, timeout)
668    };
669
670    let _ = std::fs::remove_file(&file_path);
671    result
672}
673
674fn execute_rust(
675    source_path: &std::path::Path,
676    timeout: u64,
677    cwd: Option<&std::path::Path>,
678) -> Result<(String, String, i32), String> {
679    let binary_path = source_path.with_extension("");
680
681    let mut compile_cmd = Command::new("rustc");
682    compile_cmd.arg(source_path).arg("-o").arg(&binary_path);
683    compile_cmd.env_clear();
684    for key in SANDBOX_ENV_ALLOWLIST {
685        if let Ok(val) = std::env::var(key) {
686            compile_cmd.env(key, val);
687        }
688    }
689    compile_cmd.env("LEAN_CTX_SANDBOX", "1");
690
691    let (_, stderr, code) = run_runtime_command(compile_cmd, timeout)?;
692
693    if code != 0 {
694        let _ = std::fs::remove_file(&binary_path);
695        return Ok((String::new(), stderr, code));
696    }
697
698    let mut run_cmd = Command::new(&binary_path);
699    apply_cwd(&mut run_cmd, cwd)?;
700    run_cmd.env_clear();
701    for key in SANDBOX_ENV_ALLOWLIST {
702        if let Ok(val) = std::env::var(key) {
703            run_cmd.env(key, val);
704        }
705    }
706    run_cmd.env("LEAN_CTX_SANDBOX", "1");
707    let result = run_runtime_command(run_cmd, timeout);
708    let _ = std::fs::remove_file(&binary_path);
709    result
710}
711
712/// Lets go of the run's process guard: it ends what is left of the command's
713/// process group and is reaped.
714#[cfg(unix)]
715fn let_go_of_guard(guard: &mut Option<crate::shell::containment::CallGuard>) {
716    if let Some(guard) = guard.take() {
717        let ended = guard.finish();
718        if ended != crate::shell::containment::GuardOutcome::Ended {
719            tracing::warn!("sandbox run: the end of its process group is {ended:?}");
720        }
721    }
722}
723
724fn wait_with_timeout(
725    cmd: &mut Command,
726    timeout_secs: u64,
727    spawn_error: impl FnOnce(std::io::Error) -> String,
728) -> Result<std::process::Output, String> {
729    // #1920: contain the whole tree, so a timeout on Windows ends what the
730    // snippet started instead of only the interpreter.
731    crate::shell::process_tree::ProcessTree::prepare(cmd);
732    // Q13 (Unix): the command leads its own process group (`process_group(0)`
733    // in the only caller) and has a guard on that group, which ends it when
734    // this run is over or this process is gone. The command's program is
735    // executed only once the guard is ready: a caller that dies in between
736    // leaves nothing running, and a run that cannot get a guard never
737    // started. `None` for the guard: this process is not the `lean-ctx`
738    // binary.
739    #[cfg(unix)]
740    let (mut child, mut guard) = {
741        use crate::shell::containment::Refusal;
742        match crate::shell::containment::start_guarded_child(cmd) {
743            Ok(started) => started,
744            Err(Refusal::NotStarted(error)) => return Err(spawn_error(error)),
745            Err(Refusal::NotLeader) => {
746                return Err(
747                    "Execution could not be contained: the process does not lead a group of its own"
748                        .to_string(),
749                );
750            }
751            Err(Refusal::NoGuard(reason)) => {
752                return Err(format!("Execution could not be contained: {reason}"));
753            }
754        }
755    };
756    #[cfg(not(unix))]
757    let mut child = cmd.spawn().map_err(spawn_error)?;
758    let tree = crate::shell::process_tree::ProcessTree::start(&mut child)?;
759    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
760
761    loop {
762        match child.try_wait() {
763            Ok(Some(_)) => {
764                tree.release();
765                // What the command left running in its group is ended before
766                // the output is collected, so a leftover that holds the pipes
767                // cannot keep this call waiting.
768                #[cfg(unix)]
769                let_go_of_guard(&mut guard);
770                return child.wait_with_output().map_err(|e| e.to_string());
771            }
772            Ok(None) => {
773                if std::time::Instant::now() > deadline {
774                    tree.kill(&mut child);
775                    #[cfg(unix)]
776                    let_go_of_guard(&mut guard);
777                    // GH #1504: after killing, drain whatever the child wrote
778                    // before the timeout so partial output is preserved instead
779                    // of being silently discarded.
780                    if let Ok(mut output) = child.wait_with_output() {
781                        output.stderr.extend_from_slice(
782                            format!("\n[lean-ctx] Execution timed out after {timeout_secs}s")
783                                .as_bytes(),
784                        );
785                        return Ok(output);
786                    }
787                    return Err(format!("Execution timed out after {timeout_secs}s"));
788                }
789                std::thread::sleep(std::time::Duration::from_millis(50));
790            }
791            Err(e) => {
792                tree.kill(&mut child);
793                #[cfg(unix)]
794                let_go_of_guard(&mut guard);
795                let _ = child.wait();
796                return Err(e.to_string());
797            }
798        }
799    }
800}
801
802fn find_binary(candidates: &[&str]) -> Option<String> {
803    for name in candidates {
804        if which_exists(name) {
805            return Some(name.to_string());
806        }
807    }
808    None
809}
810
811fn which_exists(name: &str) -> bool {
812    crate::core::pathutil::find_on_path(name).is_some()
813}
814
815fn truncate_output(output: &str) -> String {
816    if output.len() <= MAX_OUTPUT_BYTES {
817        return output.to_string();
818    }
819    crate::core::recovery::with_original_pointer(
820        "ctx_execute",
821        "stdout",
822        output,
823        truncate_smart(output, MAX_OUTPUT_BYTES),
824    )
825}
826
827fn truncate_smart(output: &str, max_bytes: usize) -> String {
828    if output.len() <= max_bytes {
829        return output.to_string();
830    }
831
832    let lines: Vec<&str> = output.lines().collect();
833    let total_lines = lines.len();
834
835    let head_count = (total_lines * 60) / 100;
836    let tail_count = total_lines - head_count;
837
838    let head: Vec<&str> = lines.iter().take(head_count).copied().collect();
839    let tail: Vec<&str> = lines
840        .iter()
841        .skip(total_lines - tail_count)
842        .copied()
843        .collect();
844
845    let head_text = head.join("\n");
846    let tail_text = tail.join("\n");
847
848    if head_text.len() + tail_text.len() + 100 > max_bytes {
849        let half = max_bytes / 2;
850        let h = &output[..output.floor_char_boundary(half.min(output.len()))];
851        let t_start = output.ceil_char_boundary(output.len().saturating_sub(half));
852        let t = &output[t_start..];
853        let skipped = output.len() - h.len() - t.len();
854        return format!("{h}\n\n... [{skipped} bytes truncated — showing head + tail] ...\n\n{t}");
855    }
856
857    let skipped_lines = total_lines - head_count - tail_count;
858    let skipped_bytes = output.len() - head_text.len() - tail_text.len();
859    format!(
860        "{head_text}\n\n... [{skipped_lines} lines / {skipped_bytes} bytes truncated — showing first {head_count} + last {tail_count} lines] ...\n\n{tail_text}"
861    )
862}
863
864pub fn supported_languages() -> &'static [&'static str] {
865    &[
866        "javascript",
867        "typescript",
868        "python",
869        "shell",
870        "ruby",
871        "go",
872        "rust",
873        "php",
874        "perl",
875        "r",
876        "elixir",
877    ]
878}
879
880#[cfg(test)]
881pub mod tests {
882    use super::*;
883
884    fn python_available() -> bool {
885        find_binary(&["python3", "python"]).is_some()
886    }
887
888    #[cfg(target_os = "macos")]
889    #[test]
890    fn level_zero_interpreters_and_compilers_require_the_protected_channel() {
891        let _lock = crate::core::data_dir::test_env_lock();
892        let isolation = crate::core::data_dir::isolated_data_dir();
893        let _session =
894            crate::core::protected_store::pin_synthetic_session(isolation.path()).unwrap();
895        let runtime = RuntimeConfig {
896            command: "/bin/sh".into(),
897            args: vec!["-c".into()],
898            needs_temp_file: false,
899            file_extension: "sh".into(),
900            env: HashMap::new(),
901        };
902        let stdin_error = execute_with_stdin(&runtime, "printf bypass", 1, None).unwrap_err();
903        assert!(
904            stdin_error.contains("supervised execution channel"),
905            "{stdin_error}"
906        );
907        let file_error = execute_with_file(&runtime, "printf bypass", 1, None).unwrap_err();
908        assert!(
909            file_error.contains("supervised execution channel"),
910            "{file_error}"
911        );
912        let source = tempfile::Builder::new().suffix(".rs").tempfile().unwrap();
913        std::fs::write(source.path(), "fn main() {}\n").unwrap();
914        let rust_error = execute_rust(source.path(), 1, None).unwrap_err();
915        assert!(
916            rust_error.contains("supervised execution channel"),
917            "{rust_error}"
918        );
919        assert!(!source.path().with_extension("").exists());
920    }
921
922    #[test]
923    fn execute_python_hello() {
924        let _lock = crate::core::data_dir::test_env_lock();
925        if !python_available() {
926            return;
927        }
928        let result = execute("python", "print('hello sandbox')", None);
929        assert_eq!(result.exit_code, 0);
930        assert!(result.stdout.contains("hello sandbox"));
931    }
932
933    /// GH #1666: a snippet must run where the caller said, because relative
934    /// paths inside it are resolved there. The `cwd: None` half of this test is
935    /// the pre-fix behaviour — it is what made a script edit the project root
936    /// while the caller was working in a worktree, and report success.
937    #[test]
938    #[cfg(not(target_os = "windows"))]
939    fn execute_in_resolves_relative_paths_against_the_given_directory() {
940        let _lock = crate::core::data_dir::test_env_lock();
941        let dir = tempfile::tempdir().expect("tempdir");
942        std::fs::write(dir.path().join("only-here.txt"), "x").expect("write marker");
943
944        let scoped = execute_in("shell", "cat only-here.txt", None, Some(dir.path()));
945        assert_eq!(scoped.exit_code, 0, "stderr: {}", scoped.stderr);
946        assert!(scoped.stdout.contains('x'), "{scoped:?}");
947
948        // Without a cwd the same relative path resolves somewhere else, which
949        // is exactly what the reported bug did silently.
950        let unscoped = execute_in("shell", "cat only-here.txt", None, None);
951        assert_ne!(
952            unscoped.exit_code, 0,
953            "precondition: the marker is only reachable from the given directory"
954        );
955    }
956
957    /// A directory that cannot be entered is reported as itself. Falling back
958    /// to the inherited directory would reinstate the silent wrong-tree run.
959    #[test]
960    #[cfg(not(target_os = "windows"))]
961    fn execute_in_reports_a_missing_directory_instead_of_falling_back() {
962        let _lock = crate::core::data_dir::test_env_lock();
963        let dir = tempfile::tempdir().expect("tempdir");
964        let missing = dir.path().join("does-not-exist");
965
966        let result = execute_in("shell", "pwd", None, Some(&missing));
967        assert_ne!(result.exit_code, 0, "{result:?}");
968        assert!(
969            result.stderr.contains("working directory does not exist"),
970            "{result:?}"
971        );
972    }
973
974    #[test]
975    #[cfg(not(target_os = "windows"))]
976    fn execute_shell_echo() {
977        let _lock = crate::core::data_dir::test_env_lock();
978        let result = execute("shell", "echo 'test output'", None);
979        assert_eq!(result.exit_code, 0);
980        assert!(result.stdout.contains("test output"));
981    }
982
983    /// Q13: a sandbox run does not leave processes behind. A background
984    /// child of the snippet is ended before the output is returned.
985    #[test]
986    #[cfg(unix)]
987    fn a_run_ends_what_its_snippet_left_running() {
988        crate::shell::containment::tests::run_external_fixture(
989            module_path!(),
990            "left_running_fixture",
991        );
992    }
993
994    /// Body of the test above; runs in a fixture process group of its own
995    /// that is ended when this returns or an assertion fails. The snippet's
996    /// background child is in the snippet's group, not the fixture's: if a
997    /// regression leaves it, it expires by itself (20 s).
998    #[test]
999    #[ignore = "fixture body of a_run_ends_what_its_snippet_left_running"]
1000    #[cfg(unix)]
1001    fn left_running_fixture() {
1002        let fixture = crate::shell::containment::tests::external_fixture();
1003        let _lock = crate::core::data_dir::test_env_lock();
1004        let result = execute(
1005            "shell",
1006            "sleep 20 >/dev/null 2>&1 &\necho \"LEFT $!\"",
1007            Some(20),
1008        );
1009        assert_eq!(result.exit_code, 0, "{}", result.stderr);
1010        let pid = crate::ipc::process::parse_pid_file(
1011            result
1012                .stdout
1013                .lines()
1014                .find_map(|line| line.strip_prefix("LEFT "))
1015                .expect("the snippet names its background child"),
1016        )
1017        .expect("the snippet printed a valid PID");
1018        // The guard has finished before `execute` returns; what remains is the
1019        // reap of the killed child by the system.
1020        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1021        // Validated probe: a 0 or wrapped PID is never handed to kill(2).
1022        while crate::ipc::process::is_alive(pid) {
1023            assert!(
1024                std::time::Instant::now() < deadline,
1025                "a background child of the snippet outlived the run"
1026            );
1027            std::thread::sleep(std::time::Duration::from_millis(20));
1028        }
1029        fixture.complete();
1030    }
1031
1032    /// Q13: a sandbox run's command is not executed before its guard is
1033    /// ready. A caller killed in between leaves nothing running, and the
1034    /// command's program never ran.
1035    #[test]
1036    #[cfg(unix)]
1037    fn a_run_never_starts_before_its_guard_is_ready() {
1038        crate::shell::containment::tests::run_external_fixture(
1039            module_path!(),
1040            "run_caller_killed_fixture",
1041        );
1042    }
1043
1044    /// Body of the test above: the stand-in below is killed between "the
1045    /// command's process exists" and "attach its guard".
1046    #[test]
1047    #[ignore = "fixture body of a_run_never_starts_before_its_guard_is_ready"]
1048    #[cfg(unix)]
1049    fn run_caller_killed_fixture() {
1050        let fixture = crate::shell::containment::tests::external_fixture();
1051        crate::shell::containment::tests::caller_killed_before_its_guard(
1052            module_path!(),
1053            "run_caller_standin",
1054        );
1055        fixture.complete();
1056    }
1057
1058    /// Stands in for a process in the middle of a sandbox run.
1059    #[test]
1060    #[ignore = "stand-in caller of run_caller_killed_fixture"]
1061    #[cfg(unix)]
1062    fn run_caller_standin() {
1063        use std::os::unix::process::CommandExt as _;
1064        let marker = crate::shell::containment::tests::caller_standin_marker();
1065        let mut command = std::process::Command::new("sh");
1066        command
1067            .args([
1068                "-c",
1069                &format!("echo ran > '{}'; sleep 60", marker.display()),
1070            ])
1071            .stdin(std::process::Stdio::null())
1072            .stdout(std::process::Stdio::piped())
1073            .stderr(std::process::Stdio::piped())
1074            .process_group(0);
1075        let _ = super::wait_with_timeout(&mut command, 60, |error| error.to_string());
1076    }
1077
1078    #[test]
1079    fn execute_unsupported_language() {
1080        let result = execute("brainfuck", "++++", None);
1081        assert_eq!(result.exit_code, 1);
1082        assert!(result.stderr.contains("Unsupported language"));
1083    }
1084
1085    #[test]
1086    fn execute_rejects_oversized_code() {
1087        let huge = "a".repeat(MAX_CODE_BYTES + 1);
1088        let result = execute("python", &huge, None);
1089        assert_eq!(result.exit_code, 1);
1090        assert!(result.stderr.contains("exceeds the"));
1091    }
1092
1093    #[cfg(windows)]
1094    #[test]
1095    fn sandbox_env_preserves_system_drive() {
1096        let expected =
1097            std::env::var_os("SystemDrive").expect("SystemDrive must be defined on Windows");
1098
1099        let runtime = RuntimeConfig {
1100            command: "cmd".to_string(),
1101            args: Vec::new(),
1102            needs_temp_file: false,
1103            file_extension: "bat".to_string(),
1104            env: HashMap::new(),
1105        };
1106
1107        let mut cmd = Command::new("cmd");
1108        apply_sandbox_env(&mut cmd, &runtime);
1109
1110        let preserved = cmd.get_envs().any(|(key, value)| {
1111            key.to_string_lossy().eq_ignore_ascii_case("SystemDrive")
1112                && value == Some(expected.as_os_str())
1113        });
1114
1115        assert!(
1116            preserved,
1117            "Windows sandbox child environment must preserve SystemDrive"
1118        );
1119    }
1120
1121    #[test]
1122    fn execute_python_error() {
1123        let _lock = crate::core::data_dir::test_env_lock();
1124        if !python_available() {
1125            return;
1126        }
1127        let result = execute("python", "raise ValueError('test error')", None);
1128        assert_ne!(result.exit_code, 0);
1129        assert!(result.stderr.contains("ValueError"));
1130    }
1131
1132    #[test]
1133    fn execute_with_timeout() {
1134        let _lock = crate::core::data_dir::test_env_lock();
1135        if !python_available() {
1136            return;
1137        }
1138        let result = execute("python", "import time; time.sleep(60)", Some(1));
1139        assert_ne!(result.exit_code, 0);
1140        assert!(
1141            result.stderr.contains("timed out"),
1142            "stderr should mention timeout: {}",
1143            result.stderr
1144        );
1145    }
1146
1147    /// GH #1504: partial stdout emitted before a timeout must be preserved.
1148    #[test]
1149    fn timeout_preserves_partial_output() {
1150        let _lock = crate::core::data_dir::test_env_lock();
1151        if !python_available() {
1152            return;
1153        }
1154        let result = execute(
1155            "python",
1156            "import sys; sys.stdout.write('PARTIAL_1504'); sys.stdout.flush(); import time; time.sleep(60)",
1157            Some(2),
1158        );
1159        assert_ne!(result.exit_code, 0);
1160        assert!(
1161            result.stdout.contains("PARTIAL_1504"),
1162            "partial stdout before timeout must be preserved, got: {:?}",
1163            result.stdout
1164        );
1165        assert!(
1166            result.stderr.contains("timed out"),
1167            "stderr should mention timeout: {}",
1168            result.stderr
1169        );
1170    }
1171
1172    #[test]
1173    fn truncate_preserves_head_and_tail() {
1174        let lines: Vec<String> = (0..100)
1175            .map(|i| format!("line {i}: some content here"))
1176            .collect();
1177        let output = lines.join("\n");
1178        let truncated = truncate_smart(&output, 500);
1179        assert!(truncated.contains("line 0:"));
1180        assert!(truncated.contains("line 99:"));
1181        assert!(truncated.contains("truncated"));
1182    }
1183
1184    #[test]
1185    fn supported_languages_list() {
1186        let langs = supported_languages();
1187        assert!(langs.contains(&"python"));
1188        assert!(langs.contains(&"javascript"));
1189        assert!(langs.contains(&"rust"));
1190        assert_eq!(langs.len(), 11);
1191    }
1192
1193    #[test]
1194    fn sandbox_env_is_set() {
1195        let _lock = crate::core::data_dir::test_env_lock();
1196        if !python_available() {
1197            return;
1198        }
1199        let result = execute(
1200            "python",
1201            "import os; print(os.environ.get('LEAN_CTX_SANDBOX', 'missing'))",
1202            None,
1203        );
1204        assert_eq!(result.exit_code, 0);
1205        assert!(result.stdout.contains('1'));
1206    }
1207
1208    #[test]
1209    #[cfg(not(target_os = "windows"))]
1210    fn batch_execute_multiple() {
1211        let _lock = crate::core::data_dir::test_env_lock();
1212        let items = vec![
1213            ("python".to_string(), "print(1+1)".to_string()),
1214            ("shell".to_string(), "echo hello".to_string()),
1215        ];
1216        let results = batch_execute(&items);
1217        assert_eq!(results.len(), 2);
1218        assert!(results[0].stdout.contains('2'));
1219        assert!(results[1].stdout.contains("hello"));
1220    }
1221}