Skip to main content

lc_tools/sandbox/
local.rs

1// lc-tools/src/sandbox/local.rs
2//! Local process sandbox backend.
3
4use std::time::Instant;
5
6use async_trait::async_trait;
7use tokio::process::Command;
8
9use super::{CodeSandbox, Language, RunResult, SandboxError};
10
11/// Dangerous Python modules that are blocked for security.
12const BLOCKED_PYTHON_IMPORTS: &[&str] = &[
13    "os",
14    "subprocess",
15    "sys",
16    "shutil",
17    "signal",
18    "ctypes",
19    "multiprocessing",
20    "socket",
21    "http.server",
22    "xmlrpc",
23    "pickle",
24    "shelve",
25    "importlib",
26    "code",
27    "codeop",
28    "compileall",
29    "pty",
30    "commands",
31    "pdb",
32    "webbrowser",
33];
34
35/// Check if Python code contains dangerous imports.
36fn contains_dangerous_python_import(code: &str) -> Option<String> {
37    for line in code.lines() {
38        let trimmed = line.trim();
39        if trimmed.starts_with('#') {
40            continue;
41        }
42        let code_part = trimmed.split('#').next().unwrap_or(trimmed);
43        if code_part.contains("import") {
44            for blocked in BLOCKED_PYTHON_IMPORTS {
45                if code_part.contains(&format!("import {}", blocked))
46                    || code_part.contains(&format!("from {} ", blocked))
47                    || code_part.contains(&format!("from {}.", blocked))
48                    || code_part.contains(&format!("from {}import", blocked))
49                {
50                    return Some(blocked.to_string());
51                }
52            }
53        }
54    }
55    None
56}
57
58/// Local process sandbox using `tokio::process::Command`.
59pub struct LocalSandbox {
60    python_path: String,
61    node_path: String,
62}
63
64impl LocalSandbox {
65    /// Create a new local sandbox with auto-detected interpreter paths.
66    pub fn new() -> Self {
67        Self {
68            python_path: Self::find_python(),
69            node_path: "node".to_string(),
70        }
71    }
72
73    /// Use a custom Python interpreter path.
74    pub fn with_python_path(mut self, path: impl Into<String>) -> Self {
75        self.python_path = path.into();
76        self
77    }
78
79    /// Use a custom Node.js runtime path.
80    pub fn with_node_path(mut self, path: impl Into<String>) -> Self {
81        self.node_path = path.into();
82        self
83    }
84
85    /// Auto-detect the Python interpreter on the system.
86    fn find_python() -> String {
87        for candidate in &["python3", "python"] {
88            if std::process::Command::new(candidate)
89                .arg("--version")
90                .output()
91                .is_ok()
92            {
93                return candidate.to_string();
94            }
95        }
96        "python3".to_string()
97    }
98
99    /// Build the command for the given language and code.
100    fn build_command(&self, code: &str, language: Language) -> Result<Command, SandboxError> {
101        match language {
102            Language::Python => {
103                if let Some(blocked) = contains_dangerous_python_import(code) {
104                    return Err(SandboxError::Runtime(format!(
105                        "Code contains dangerous import: '{}'. \
106                         This module is blocked for security in local sandbox.",
107                        blocked
108                    )));
109                }
110                let mut cmd = Command::new(&self.python_path);
111                cmd.arg("-c").arg(code);
112                Ok(cmd)
113            }
114            Language::JavaScript => {
115                let mut cmd = Command::new(&self.node_path);
116                cmd.arg("-e").arg(code);
117                Ok(cmd)
118            }
119            Language::Rust => Err(SandboxError::UnsupportedLanguage(
120                "Rust compilation is not supported by LocalSandbox".to_string(),
121            )),
122        }
123    }
124}
125
126impl Default for LocalSandbox {
127    fn default() -> Self {
128        Self::new()
129    }
130}
131
132#[async_trait]
133impl CodeSandbox for LocalSandbox {
134    async fn run(
135        &self,
136        code: &str,
137        language: Language,
138        timeout_ms: u64,
139    ) -> Result<RunResult, SandboxError> {
140        let mut cmd = self.build_command(code, language)?;
141
142        let start = Instant::now();
143
144        let result =
145            tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), cmd.output())
146                .await
147                .map_err(|_| SandboxError::Timeout(timeout_ms))?
148                .map_err(|e| {
149                    SandboxError::Runtime(format!("failed to execute subprocess: {}", e))
150                })?;
151
152        let execution_time_ms = start.elapsed().as_millis() as u64;
153
154        let stdout = String::from_utf8_lossy(&result.stdout).to_string();
155        let stderr = String::from_utf8_lossy(&result.stderr).to_string();
156        let exit_code = result.status.code().unwrap_or(-1);
157
158        Ok(RunResult {
159            stdout,
160            stderr,
161            exit_code,
162            execution_time_ms,
163        })
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn test_local_sandbox_default() {
173        let sandbox = LocalSandbox::default();
174        assert!(!sandbox.python_path.is_empty());
175        assert_eq!(sandbox.node_path, "node");
176    }
177
178    #[test]
179    fn test_local_sandbox_custom_paths() {
180        let sandbox = LocalSandbox::new()
181            .with_python_path("/usr/bin/python3.11")
182            .with_node_path("/usr/local/bin/node");
183        assert_eq!(sandbox.python_path, "/usr/bin/python3.11");
184        assert_eq!(sandbox.node_path, "/usr/local/bin/node");
185    }
186
187    #[test]
188    fn test_rust_unsupported() {
189        let sandbox = LocalSandbox::new();
190        let result = sandbox.build_command("fn main(){}", Language::Rust);
191        assert!(result.is_err());
192        match result.unwrap_err() {
193            SandboxError::UnsupportedLanguage(msg) => {
194                assert!(msg.contains("Rust"));
195            }
196            other => panic!("expected UnsupportedLanguage, got: {:?}", other),
197        }
198    }
199
200    #[test]
201    fn test_dangerous_python_import_detection() {
202        assert!(contains_dangerous_python_import("import os").is_some());
203        assert!(contains_dangerous_python_import("from sys import path").is_some());
204        assert!(contains_dangerous_python_import("import subprocess").is_some());
205        assert!(contains_dangerous_python_import("import math").is_none());
206        assert!(contains_dangerous_python_import("import json").is_none());
207        assert!(contains_dangerous_python_import("from datetime import datetime").is_none());
208        assert!(contains_dangerous_python_import("# import os").is_none());
209    }
210
211    #[tokio::test]
212    async fn test_python_dangerous_import_blocked() {
213        let sandbox = LocalSandbox::new();
214        let result = sandbox
215            .run("import os; print(os.getcwd())", Language::Python, 10_000)
216            .await;
217        assert!(result.is_err());
218        let err = result.unwrap_err().to_string();
219        assert!(
220            err.contains("dangerous import"),
221            "Expected dangerous import error, got: {}",
222            err
223        );
224    }
225
226    #[tokio::test]
227    async fn test_python_execution_if_available() {
228        let sandbox = LocalSandbox::new();
229        let result = sandbox.run("print(1 + 2)", Language::Python, 10_000).await;
230
231        match result {
232            Ok(run_result) => {
233                if run_result.exit_code == 0 {
234                    assert!(
235                        run_result.stdout.trim() == "3",
236                        "expected '3', got '{}'",
237                        run_result.stdout.trim()
238                    );
239                }
240            }
241            Err(SandboxError::Runtime(msg)) => {
242                eprintln!("Python not available (expected in some CI): {}", msg);
243            }
244            Err(other) => panic!("unexpected error: {:?}", other),
245        }
246    }
247
248    #[tokio::test]
249    async fn test_javascript_execution_if_available() {
250        let sandbox = LocalSandbox::new();
251        let result = sandbox
252            .run("console.log(1 + 2)", Language::JavaScript, 10_000)
253            .await;
254
255        match result {
256            Ok(run_result) => {
257                if run_result.exit_code == 0 {
258                    assert!(
259                        run_result.stdout.trim() == "3",
260                        "expected '3', got '{}'",
261                        run_result.stdout.trim()
262                    );
263                }
264            }
265            Err(SandboxError::Runtime(msg)) => {
266                eprintln!("Node.js not available (expected in some CI): {}", msg);
267            }
268            Err(other) => panic!("unexpected error: {:?}", other),
269        }
270    }
271
272    #[tokio::test]
273    async fn test_rust_execution_unsupported() {
274        let sandbox = LocalSandbox::new();
275        let result = sandbox.run("fn main(){}", Language::Rust, 10_000).await;
276        assert!(result.is_err());
277        match result.unwrap_err() {
278            SandboxError::UnsupportedLanguage(_) => {}
279            other => panic!("expected UnsupportedLanguage, got: {:?}", other),
280        }
281    }
282
283    #[tokio::test]
284    async fn test_execution_timeout() {
285        let sandbox = LocalSandbox::new();
286        let result = sandbox
287            .run("import time; time.sleep(10)", Language::Python, 100)
288            .await;
289
290        match result {
291            Err(SandboxError::Timeout(ms)) => {
292                assert_eq!(ms, 100);
293            }
294            Ok(_) => {
295                // Python not available, code didn't run — acceptable
296            }
297            Err(other) => panic!("expected Timeout, got: {:?}", other),
298        }
299    }
300
301    #[tokio::test]
302    async fn test_execution_time_is_recorded() {
303        let sandbox = LocalSandbox::new();
304        let result = sandbox.run("print('hi')", Language::Python, 10_000).await;
305
306        if let Ok(run_result) = result {
307            assert!(run_result.execution_time_ms < 10_000);
308        }
309    }
310
311    #[tokio::test]
312    async fn test_stderr_captured() {
313        let sandbox = LocalSandbox::new();
314        let result = sandbox
315            .run(
316                "import sys; print('error', file=sys.stderr)",
317                Language::Python,
318                10_000,
319            )
320            .await;
321
322        if let Ok(run_result) = result {
323            if run_result.exit_code == 0 {
324                assert!(
325                    run_result.stderr.contains("error"),
326                    "stderr should contain 'error', got: '{}'",
327                    run_result.stderr
328                );
329            }
330        }
331    }
332}