1use 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
56const MAX_OUTPUT_BYTES: usize = 1_024 * 1_024;
58
59const 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
71const 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#[derive(Debug, Clone)]
105pub struct ProcessConfig {
106 pub rustc_path: String,
108 pub python_path: String,
110 pub node_path: String,
112 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
131pub struct ProcessBackend {
166 config: ProcessConfig,
167 enforcer: Option<Box<dyn SandboxEnforcer>>,
168 policy: Option<SandboxPolicy>,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum IsolationClass {
177 SubprocessOnly,
182 OsEnforced,
185}
186
187impl ProcessBackend {
188 pub fn new(config: ProcessConfig) -> Self {
193 Self { config, enforcer: None, policy: None }
194 }
195
196 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 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
236impl 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 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 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 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 #[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 self.run_command(Command::new(&bin_path), request, Some(dir.path())).await
367 }
368
369 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 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 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 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 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 pub fn toolchain_env() -> Vec<(String, OsString)> {
451 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 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 let mut owned_scratch: Option<tempfile::TempDir> = None;
508
509 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 let mut policy = policy.clone();
522 policy
523 .allowed_paths
524 .push(AllowedPath { path: scratch.clone(), mode: AccessMode::ReadWrite });
525 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 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 if let Some(policy) = &self.policy {
564 cmd.envs(policy.network.proxy_env());
565 }
566 cmd.kill_on_drop(true);
567
568 #[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 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 if let Ok(path) = std::env::var("PATH") {
641 env.insert("PATH".to_string(), path);
642 }
643 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 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 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 #[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 #[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 #[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 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 assert!(result.stdout.contains("MY_TEST_VAR=test_value"), "stdout: {}", result.stdout);
816 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}