Skip to main content

microclaw_engine/internal/tool_runtime/
sandbox.rs

1use std::collections::HashMap;
2use std::path::{Component, Path, PathBuf};
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::Arc;
5use std::time::Duration;
6
7use anyhow::{bail, Context, Result};
8use async_trait::async_trait;
9
10use crate::internal::tool_runtime::command_runner::{build_command, shell_command};
11use serde::{Deserialize, Serialize};
12
13fn default_sandbox_mode() -> SandboxMode {
14    SandboxMode::Off
15}
16
17fn default_sandbox_backend() -> SandboxBackend {
18    SandboxBackend::Auto
19}
20
21fn default_sandbox_image() -> String {
22    "ubuntu:25.10".to_string()
23}
24
25fn default_sandbox_container_prefix() -> String {
26    "microclaw-sandbox".to_string()
27}
28
29fn default_sandbox_no_network() -> bool {
30    true
31}
32
33fn default_sandbox_require_runtime() -> bool {
34    true
35}
36
37fn default_sandbox_mount_allowlist_path() -> Option<String> {
38    None
39}
40
41fn default_sandbox_security_profile() -> SecurityProfile {
42    SecurityProfile::Hardened
43}
44
45fn default_sandbox_cap_add() -> Vec<String> {
46    Vec::new()
47}
48
49fn default_sandbox_credential_env_allowlist() -> Vec<String> {
50    Vec::new()
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "snake_case")]
55pub enum SandboxMode {
56    Off,
57    All,
58}
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum SandboxBackend {
63    Auto,
64    Docker,
65    Podman,
66    /// The operating system's own sandbox: bubblewrap on Linux, Seatbelt on
67    /// macOS (see [`crate::internal::tool_runtime::local_sandbox`]).
68    Local,
69}
70
71/// Container security profile controlling Linux capabilities and privilege escalation.
72///
73/// - `Hardened`: `--cap-drop ALL --security-opt no-new-privileges` (most restrictive; apt/chown/su will fail)
74/// - `Standard`: Docker default capabilities (apt/chown/su work normally)
75/// - `Privileged`: `--privileged` flag (full host-level access; use for debugging only)
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum SecurityProfile {
79    Hardened,
80    Standard,
81    Privileged,
82}
83
84impl std::fmt::Display for SecurityProfile {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        match self {
87            SecurityProfile::Hardened => write!(f, "hardened"),
88            SecurityProfile::Standard => write!(f, "standard"),
89            SecurityProfile::Privileged => write!(f, "privileged"),
90        }
91    }
92}
93
94#[derive(Clone, Debug, Serialize, Deserialize)]
95pub struct SandboxConfig {
96    #[serde(default = "default_sandbox_mode")]
97    pub mode: SandboxMode,
98    #[serde(default = "default_sandbox_backend")]
99    pub backend: SandboxBackend,
100    #[serde(default = "default_sandbox_image")]
101    pub image: String,
102    #[serde(default = "default_sandbox_container_prefix")]
103    pub container_prefix: String,
104    #[serde(default = "default_sandbox_no_network")]
105    pub no_network: bool,
106    #[serde(default = "default_sandbox_require_runtime")]
107    pub require_runtime: bool,
108    #[serde(default = "default_sandbox_mount_allowlist_path")]
109    pub mount_allowlist_path: Option<String>,
110    #[serde(default = "default_sandbox_security_profile")]
111    pub security_profile: SecurityProfile,
112    #[serde(default = "default_sandbox_cap_add")]
113    pub cap_add: Vec<String>,
114    #[serde(default)]
115    pub memory_limit: Option<String>,
116    #[serde(default)]
117    pub cpu_quota: Option<f64>,
118    #[serde(default)]
119    pub pids_limit: Option<u32>,
120    /// Credential-like environment variables are withheld from container
121    /// processes unless their exact name appears here. Dotenv files are parsed
122    /// on the host and are never mounted or passed wholesale to the container.
123    #[serde(default = "default_sandbox_credential_env_allowlist")]
124    pub credential_env_allowlist: Vec<String>,
125    /// `local` backend: extra directories commands may write, besides the
126    /// working directory, the temp directory and common tool caches.
127    #[serde(default)]
128    pub writable_roots: Vec<String>,
129}
130
131impl Default for SandboxConfig {
132    fn default() -> Self {
133        Self {
134            mode: default_sandbox_mode(),
135            backend: default_sandbox_backend(),
136            image: default_sandbox_image(),
137            container_prefix: default_sandbox_container_prefix(),
138            no_network: default_sandbox_no_network(),
139            require_runtime: default_sandbox_require_runtime(),
140            mount_allowlist_path: default_sandbox_mount_allowlist_path(),
141            security_profile: default_sandbox_security_profile(),
142            cap_add: default_sandbox_cap_add(),
143            memory_limit: None,
144            cpu_quota: None,
145            pids_limit: None,
146            credential_env_allowlist: default_sandbox_credential_env_allowlist(),
147            writable_roots: Vec::new(),
148        }
149    }
150}
151
152#[derive(Debug, Clone)]
153pub struct SandboxExecOptions {
154    pub timeout: Duration,
155    pub working_dir: Option<PathBuf>,
156    #[allow(clippy::zero_sized_map_values)]
157    pub envs: HashMap<String, String>,
158    pub env_files: Vec<PathBuf>,
159}
160
161#[derive(Debug, Clone)]
162pub struct SandboxExecResult {
163    pub stdout: String,
164    pub stderr: String,
165    pub exit_code: i32,
166}
167
168#[async_trait]
169pub trait Sandbox: Send + Sync {
170    fn backend_name(&self) -> &'static str;
171    fn is_real(&self) -> bool {
172        true
173    }
174    async fn ensure_ready(&self, session_key: &str) -> Result<()>;
175    async fn exec(
176        &self,
177        session_key: &str,
178        command: &str,
179        opts: &SandboxExecOptions,
180    ) -> Result<SandboxExecResult>;
181}
182
183pub struct NoSandbox;
184
185/// Runs commands on the host under the OS sandbox (`backend: local`).
186pub struct LocalSandbox {
187    kind: crate::internal::tool_runtime::local_sandbox::LocalSandboxKind,
188    policy: crate::internal::tool_runtime::local_sandbox::LocalPolicy,
189}
190
191impl LocalSandbox {
192    /// `None` when this machine has no working OS sandbox.
193    pub fn detect(config: &SandboxConfig, working_dir: &Path) -> Option<Self> {
194        use crate::internal::tool_runtime::local_sandbox::{detect, LocalPolicy};
195        let kind = detect()?;
196        let extra: Vec<PathBuf> = config
197            .writable_roots
198            .iter()
199            .map(|p| PathBuf::from(shellexpand::tilde(p).into_owned()))
200            .collect();
201        Some(Self {
202            kind,
203            policy: LocalPolicy::for_workspace(working_dir, &extra, !config.no_network),
204        })
205    }
206
207    /// The command line that runs `command` in `cwd` under this sandbox.
208    pub fn command_spec(
209        &self,
210        command: &str,
211        cwd: &Path,
212    ) -> crate::internal::tool_runtime::command_runner::CommandSpec {
213        crate::internal::tool_runtime::local_sandbox::wrap(
214            self.kind,
215            &self.policy,
216            &shell_command(command),
217            cwd,
218        )
219    }
220}
221
222#[async_trait]
223impl Sandbox for LocalSandbox {
224    fn backend_name(&self) -> &'static str {
225        self.kind.name()
226    }
227
228    async fn ensure_ready(&self, _session_key: &str) -> Result<()> {
229        Ok(())
230    }
231
232    async fn exec(
233        &self,
234        _session_key: &str,
235        command: &str,
236        opts: &SandboxExecOptions,
237    ) -> Result<SandboxExecResult> {
238        let cwd = opts
239            .working_dir
240            .clone()
241            .unwrap_or_else(|| self.policy.workspace.clone());
242        exec_host_spec(&self.command_spec(command, &cwd), opts).await
243    }
244}
245
246#[async_trait]
247impl Sandbox for NoSandbox {
248    fn backend_name(&self) -> &'static str {
249        "none"
250    }
251
252    fn is_real(&self) -> bool {
253        false
254    }
255
256    async fn ensure_ready(&self, _session_key: &str) -> Result<()> {
257        Ok(())
258    }
259
260    async fn exec(
261        &self,
262        _session_key: &str,
263        command: &str,
264        opts: &SandboxExecOptions,
265    ) -> Result<SandboxExecResult> {
266        exec_host_command(command, opts).await
267    }
268}
269
270/// An additional bind mount to expose inside the sandbox container.
271#[derive(Debug, Clone)]
272pub struct ExtraMount {
273    pub host_path: PathBuf,
274    pub read_only: bool,
275}
276
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278enum ContainerRuntime {
279    Docker,
280    Podman,
281}
282
283impl ContainerRuntime {
284    fn cli(self) -> &'static str {
285        match self {
286            ContainerRuntime::Docker => "docker",
287            ContainerRuntime::Podman => "podman",
288        }
289    }
290
291    fn label(self) -> &'static str {
292        match self {
293            ContainerRuntime::Docker => "docker",
294            ContainerRuntime::Podman => "podman",
295        }
296    }
297}
298
299fn pick_runtime(
300    backend: SandboxBackend,
301    docker_available: bool,
302    podman_available: bool,
303) -> Option<ContainerRuntime> {
304    match backend {
305        SandboxBackend::Auto => docker_available.then_some(ContainerRuntime::Docker),
306        SandboxBackend::Docker => docker_available.then_some(ContainerRuntime::Docker),
307        SandboxBackend::Podman => podman_available.then_some(ContainerRuntime::Podman),
308        SandboxBackend::Local => None,
309    }
310}
311
312fn resolve_runtime(backend: SandboxBackend) -> Option<ContainerRuntime> {
313    pick_runtime(
314        backend,
315        runtime_available("docker"),
316        runtime_available("podman"),
317    )
318}
319
320pub fn runtime_available_for_backend(backend: SandboxBackend) -> bool {
321    if backend == SandboxBackend::Local {
322        return crate::internal::tool_runtime::local_sandbox::detect().is_some();
323    }
324    resolve_runtime(backend).is_some()
325}
326
327pub fn selected_runtime_cli(backend: SandboxBackend) -> Option<&'static str> {
328    resolve_runtime(backend).map(ContainerRuntime::cli)
329}
330
331pub struct DockerSandbox {
332    runtime: ContainerRuntime,
333    config: SandboxConfig,
334    mount_dir: PathBuf,
335    extra_mounts: Vec<ExtraMount>,
336}
337
338impl DockerSandbox {
339    fn new(
340        runtime: ContainerRuntime,
341        config: SandboxConfig,
342        mount_dir: PathBuf,
343        extra_mounts: Vec<ExtraMount>,
344    ) -> Self {
345        Self {
346            runtime,
347            config,
348            mount_dir,
349            extra_mounts,
350        }
351    }
352
353    fn container_name(&self, session_key: &str) -> String {
354        format!(
355            "{}-{}",
356            self.config.container_prefix,
357            sanitize_segment(session_key)
358        )
359    }
360
361    fn resource_args(&self) -> Vec<String> {
362        let mut args = Vec::new();
363        if let Some(mem) = &self.config.memory_limit {
364            args.extend(["--memory".to_string(), mem.clone()]);
365        }
366        if let Some(cpu) = self.config.cpu_quota {
367            args.extend(["--cpus".to_string(), cpu.to_string()]);
368        }
369        if let Some(pids) = self.config.pids_limit {
370            args.extend(["--pids-limit".to_string(), pids.to_string()]);
371        }
372        args
373    }
374
375    fn security_args(&self) -> Vec<String> {
376        let mut args = Vec::new();
377        match self.config.security_profile {
378            SecurityProfile::Hardened => {
379                args.extend([
380                    "--cap-drop".to_string(),
381                    "ALL".to_string(),
382                    "--security-opt".to_string(),
383                    "no-new-privileges".to_string(),
384                ]);
385                for cap in &self.config.cap_add {
386                    args.extend(["--cap-add".to_string(), cap.clone()]);
387                }
388            }
389            SecurityProfile::Standard => {
390                for cap in &self.config.cap_add {
391                    args.extend(["--cap-add".to_string(), cap.clone()]);
392                }
393            }
394            SecurityProfile::Privileged => {
395                args.push("--privileged".to_string());
396            }
397        }
398        args
399    }
400}
401
402#[async_trait]
403impl Sandbox for DockerSandbox {
404    fn backend_name(&self) -> &'static str {
405        self.runtime.label()
406    }
407
408    async fn ensure_ready(&self, session_key: &str) -> Result<()> {
409        let name = self.container_name(session_key);
410        let inspect = tokio::process::Command::new(self.runtime.cli())
411            .args(["inspect", "--format", "{{.State.Running}}", &name])
412            .output()
413            .await;
414        if let Ok(out) = inspect {
415            let stdout = String::from_utf8_lossy(&out.stdout);
416            if out.status.success() && stdout.trim() == "true" {
417                return Ok(());
418            }
419        }
420
421        let mut args = vec![
422            "run".to_string(),
423            "-d".to_string(),
424            "--name".to_string(),
425            name.clone(),
426        ];
427        args.extend(self.security_args());
428        if self.config.no_network {
429            args.push("--network=none".to_string());
430        }
431        args.extend(self.resource_args());
432        let mount = self.mount_dir.display().to_string();
433        args.extend(["-v".to_string(), format!("{mount}:{mount}:rw")]);
434        for em in &self.extra_mounts {
435            let p = em.host_path.display().to_string();
436            let mode = if em.read_only { "ro" } else { "rw" };
437            args.extend(["-v".to_string(), format!("{p}:{p}:{mode}")]);
438        }
439        args.push(self.config.image.clone());
440        args.extend(["sleep".to_string(), "infinity".to_string()]);
441
442        let out = tokio::process::Command::new(self.runtime.cli())
443            .args(&args)
444            .output()
445            .await
446            .with_context(|| format!("failed to run {}", self.runtime.cli()))?;
447        if !out.status.success() {
448            let stderr = String::from_utf8_lossy(&out.stderr);
449            bail!("{} run failed: {}", self.runtime.cli(), stderr.trim());
450        }
451        Ok(())
452    }
453
454    async fn exec(
455        &self,
456        session_key: &str,
457        command: &str,
458        opts: &SandboxExecOptions,
459    ) -> Result<SandboxExecResult> {
460        let name = self.container_name(session_key);
461        let mut args = vec!["exec".to_string()];
462
463        if let Some(dir) = &opts.working_dir {
464            args.extend(["-w".to_string(), dir.display().to_string()]);
465        }
466        for (k, v) in sandbox_environment(opts, &self.config.credential_env_allowlist) {
467            args.extend(["-e".to_string(), format!("{k}={v}")]);
468        }
469        args.push(name);
470        args.extend(["sh".to_string(), "-c".to_string(), command.to_string()]);
471        let child = tokio::process::Command::new(self.runtime.cli())
472            .args(&args)
473            .stdout(std::process::Stdio::piped())
474            .stderr(std::process::Stdio::piped())
475            .stdin(std::process::Stdio::null())
476            .spawn()
477            .with_context(|| format!("failed to spawn {} exec", self.runtime.cli()))?;
478        match tokio::time::timeout(opts.timeout, child.wait_with_output()).await {
479            Ok(Ok(output)) => Ok(SandboxExecResult {
480                stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
481                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
482                exit_code: output.status.code().unwrap_or(-1),
483            }),
484            Ok(Err(e)) => bail!("{} exec failed: {e}", self.runtime.cli()),
485            Err(_) => bail!(
486                "{} exec timed out after {} seconds",
487                self.runtime.cli(),
488                opts.timeout.as_secs()
489            ),
490        }
491    }
492}
493
494pub struct SandboxRouter {
495    config: SandboxConfig,
496    backend: Arc<dyn Sandbox>,
497    /// Set when the backend is the local OS sandbox (also wraps background
498    /// processes).
499    local: Option<Arc<LocalSandbox>>,
500    warned_missing_runtime: AtomicBool,
501}
502
503impl SandboxRouter {
504    pub fn new(config: SandboxConfig, working_dir: &Path, extra_mounts: Vec<ExtraMount>) -> Self {
505        if config.backend == SandboxBackend::Local {
506            let local = if config.mode == SandboxMode::Off {
507                None
508            } else {
509                LocalSandbox::detect(&config, working_dir).map(Arc::new)
510            };
511            let backend: Arc<dyn Sandbox> = match &local {
512                Some(local) => local.clone(),
513                None => Arc::new(NoSandbox),
514            };
515            return Self {
516                config,
517                backend,
518                local,
519                warned_missing_runtime: AtomicBool::new(false),
520            };
521        }
522        let mount_dir = resolve_mount_dir(working_dir, &config);
523        let backend: Arc<dyn Sandbox> = match resolve_runtime(config.backend) {
524            Some(runtime) => Arc::new(DockerSandbox::new(
525                runtime,
526                config.clone(),
527                mount_dir,
528                extra_mounts,
529            )),
530            None => Arc::new(NoSandbox),
531        };
532        Self {
533            config,
534            backend,
535            local: None,
536            warned_missing_runtime: AtomicBool::new(false),
537        }
538    }
539
540    #[cfg(test)]
541    fn with_backend_for_tests(config: SandboxConfig, backend: Arc<dyn Sandbox>) -> Self {
542        Self {
543            config,
544            backend,
545            local: None,
546            warned_missing_runtime: AtomicBool::new(false),
547        }
548    }
549
550    /// The local OS sandbox, when that is the active backend. Background
551    /// processes are spawned through it.
552    pub fn local(&self) -> Option<&LocalSandbox> {
553        self.local.as_deref()
554    }
555
556    pub fn mode(&self) -> SandboxMode {
557        self.config.mode
558    }
559
560    pub fn backend_name(&self) -> &'static str {
561        self.backend.backend_name()
562    }
563
564    pub fn runtime_available(&self) -> bool {
565        self.backend.is_real()
566    }
567
568    pub async fn exec(
569        &self,
570        session_key: &str,
571        command: &str,
572        opts: &SandboxExecOptions,
573    ) -> Result<SandboxExecResult> {
574        if self.config.mode == SandboxMode::Off {
575            return exec_host_command(command, opts).await;
576        }
577        if !self.backend.is_real() {
578            if self.config.require_runtime {
579                bail!("sandbox is enabled but no container runtime is available");
580            }
581            if !self.warned_missing_runtime.swap(true, Ordering::Relaxed) {
582                tracing::warn!(
583                    "sandbox enabled but no container runtime available, falling back to host"
584                );
585            }
586            return exec_host_command(command, opts).await;
587        }
588        self.backend.ensure_ready(session_key).await?;
589        self.backend.exec(session_key, command, opts).await
590    }
591}
592
593fn sandbox_environment(
594    opts: &SandboxExecOptions,
595    credential_allowlist: &[String],
596) -> HashMap<String, String> {
597    let mut env = HashMap::new();
598    for env_file in &opts.env_files {
599        if let Ok(content) = std::fs::read_to_string(env_file) {
600            for (key, value) in crate::internal::tool_runtime::env_file::parse_dotenv(&content) {
601                if sandbox_env_allowed(&key, credential_allowlist) {
602                    env.insert(key, value);
603                }
604            }
605        }
606    }
607    for (key, value) in &opts.envs {
608        if sandbox_env_allowed(key, credential_allowlist) {
609            env.insert(key.clone(), value.clone());
610        }
611    }
612    env
613}
614
615fn sandbox_env_allowed(name: &str, credential_allowlist: &[String]) -> bool {
616    if credential_allowlist
617        .iter()
618        .any(|allowed| allowed.eq_ignore_ascii_case(name))
619    {
620        return true;
621    }
622    !looks_like_credential_env(name)
623}
624
625fn looks_like_credential_env(name: &str) -> bool {
626    let normalized = name.to_ascii_uppercase();
627    [
628        "API_KEY",
629        "ACCESS_KEY",
630        "PRIVATE_KEY",
631        "SECRET",
632        "TOKEN",
633        "PASSWORD",
634        "PASSWD",
635        "CREDENTIAL",
636        "AUTHORIZATION",
637    ]
638    .iter()
639    .any(|marker| normalized.contains(marker))
640}
641
642pub async fn exec_host_command(
643    command: &str,
644    opts: &SandboxExecOptions,
645) -> Result<SandboxExecResult> {
646    exec_host_spec(&shell_command(command), opts).await
647}
648
649async fn exec_host_spec(
650    spec: &crate::internal::tool_runtime::command_runner::CommandSpec,
651    opts: &SandboxExecOptions,
652) -> Result<SandboxExecResult> {
653    let mut cmd = build_command(spec, opts.working_dir.as_deref());
654    for env_file in &opts.env_files {
655        if let Ok(content) = std::fs::read_to_string(env_file) {
656            for (k, v) in crate::internal::tool_runtime::env_file::parse_dotenv(&content) {
657                cmd.env(k, v);
658            }
659        }
660    }
661    for (k, v) in &opts.envs {
662        cmd.env(k, v);
663    }
664    cmd.stdout(std::process::Stdio::piped());
665    cmd.stderr(std::process::Stdio::piped());
666    cmd.stdin(std::process::Stdio::null());
667    let child = cmd.spawn().context("failed to start shell command")?;
668    match tokio::time::timeout(opts.timeout, child.wait_with_output()).await {
669        Ok(Ok(output)) => Ok(SandboxExecResult {
670            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
671            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
672            exit_code: output.status.code().unwrap_or(-1),
673        }),
674        Ok(Err(e)) => bail!("failed to run command: {e}"),
675        Err(_) => bail!("command timed out after {} seconds", opts.timeout.as_secs()),
676    }
677}
678
679fn runtime_available(cli: &str) -> bool {
680    std::process::Command::new(cli)
681        .arg("info")
682        .stdout(std::process::Stdio::null())
683        .stderr(std::process::Stdio::null())
684        .status()
685        .is_ok_and(|s| s.success())
686}
687
688fn resolve_mount_dir(working_dir: &Path, config: &SandboxConfig) -> PathBuf {
689    let _ = std::fs::create_dir_all(working_dir);
690    let canonical =
691        std::fs::canonicalize(working_dir).unwrap_or_else(|_| working_dir.to_path_buf());
692    if let Err(err) = validate_mount_dir(&canonical, config) {
693        tracing::warn!(
694            path = %canonical.display(),
695            error = %err,
696            "sandbox mount dir failed validation; falling back to raw working dir"
697        );
698        working_dir.to_path_buf()
699    } else {
700        canonical
701    }
702}
703
704fn sanitize_segment(input: &str) -> String {
705    let mut out = String::with_capacity(input.len());
706    for c in input.chars() {
707        if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
708            out.push(c.to_ascii_lowercase());
709        } else {
710            out.push('-');
711        }
712    }
713    if out.is_empty() {
714        "default".into()
715    } else {
716        out
717    }
718}
719
720const MOUNT_BLOCKED_COMPONENTS: &[&str] = &[
721    ".ssh", ".gnupg", ".aws", ".azure", ".gcloud", ".kube", ".docker",
722];
723
724const MOUNT_BLOCKED_FILENAMES: &[&str] = &[
725    ".env",
726    ".env.local",
727    ".env.production",
728    ".env.development",
729    ".netrc",
730    ".npmrc",
731    "id_rsa",
732    "id_ed25519",
733    "credentials",
734    "private_key",
735];
736
737fn validate_mount_dir(path: &Path, config: &SandboxConfig) -> Result<()> {
738    if contains_symlink_component(path)? {
739        bail!("mount path contains symlink component");
740    }
741    if has_sensitive_mount_component(path) {
742        bail!("mount path contains sensitive component");
743    }
744    validate_mount_allowlist(path, config)
745}
746
747fn contains_symlink_component(path: &Path) -> Result<bool> {
748    let mut cur = PathBuf::new();
749    for comp in path.components() {
750        match comp {
751            Component::RootDir => {
752                cur.push(Path::new("/"));
753            }
754            Component::Prefix(prefix) => cur.push(prefix.as_os_str()),
755            Component::Normal(part) => {
756                cur.push(part);
757                let meta = std::fs::symlink_metadata(&cur)
758                    .with_context(|| format!("failed to stat mount path '{}'", cur.display()))?;
759                if meta.file_type().is_symlink() {
760                    return Ok(true);
761                }
762            }
763            Component::CurDir | Component::ParentDir => {}
764        }
765    }
766    Ok(false)
767}
768
769fn has_sensitive_mount_component(path: &Path) -> bool {
770    for component in path.components() {
771        let Component::Normal(segment) = component else {
772            continue;
773        };
774        let part = segment.to_string_lossy().to_string();
775        if MOUNT_BLOCKED_COMPONENTS.contains(&part.as_str()) {
776            return true;
777        }
778        if MOUNT_BLOCKED_FILENAMES.contains(&part.as_str()) {
779            return true;
780        }
781    }
782    false
783}
784
785fn default_allowlist_path() -> Option<PathBuf> {
786    let home = std::env::var_os("HOME")
787        .map(PathBuf::from)
788        .or_else(|| std::env::var_os("USERPROFILE").map(PathBuf::from))?;
789    Some(home.join(".microclaw/sandbox-mount-allowlist.txt"))
790}
791
792fn validate_mount_allowlist(path: &Path, config: &SandboxConfig) -> Result<()> {
793    let allowlist_path = config
794        .mount_allowlist_path
795        .as_ref()
796        .map(PathBuf::from)
797        .or_else(|| std::env::var_os("MICROCLAW_SANDBOX_MOUNT_ALLOWLIST").map(PathBuf::from))
798        .or_else(default_allowlist_path);
799    let Some(file_path) = allowlist_path else {
800        return Ok(());
801    };
802    if !file_path.exists() {
803        return Ok(());
804    }
805    let content = std::fs::read_to_string(&file_path)
806        .with_context(|| format!("failed reading mount allowlist '{}'", file_path.display()))?;
807    let mut allowed_roots = Vec::new();
808    for raw in content.lines() {
809        let line = raw.trim();
810        if line.is_empty() || line.starts_with('#') {
811            continue;
812        }
813        let candidate = PathBuf::from(line);
814        let canonical = std::fs::canonicalize(&candidate).unwrap_or(candidate);
815        allowed_roots.push(canonical);
816    }
817    if allowed_roots.is_empty() {
818        // Keep compatibility: treat empty allowlist as disabled.
819        return Ok(());
820    }
821    if allowed_roots.iter().any(|root| path.starts_with(root)) {
822        Ok(())
823    } else {
824        bail!(
825            "mount path '{}' is not allowed by '{}'",
826            path.display(),
827            file_path.display()
828        )
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835    use std::time::Duration;
836
837    #[test]
838    fn test_sanitize_segment() {
839        assert_eq!(sanitize_segment("Web:10001"), "web-10001");
840    }
841
842    #[test]
843    fn test_router_default_backend_name() {
844        let router = SandboxRouter::new(SandboxConfig::default(), Path::new("./tmp"), vec![]);
845        let name = router.backend_name();
846        assert!(name == "docker" || name == "podman" || name == "none");
847    }
848
849    #[tokio::test]
850    async fn test_router_falls_back_to_host_when_runtime_missing_and_not_required() {
851        let cfg = SandboxConfig {
852            mode: SandboxMode::All,
853            backend: SandboxBackend::Auto,
854            require_runtime: false,
855            ..SandboxConfig::default()
856        };
857        let router = SandboxRouter::with_backend_for_tests(cfg, Arc::new(NoSandbox));
858        let opts = SandboxExecOptions {
859            timeout: Duration::from_secs(2),
860            working_dir: None,
861            envs: HashMap::new(),
862            env_files: Vec::new(),
863        };
864        #[cfg(target_os = "windows")]
865        let command = "Write-Output -NoEnumerate microclaw-smoke";
866        #[cfg(not(target_os = "windows"))]
867        let command = "printf microclaw-smoke";
868
869        let out = router.exec("chat-1", command, &opts).await;
870        let out = out.expect("expected host fallback execution");
871        assert_eq!(out.exit_code, 0);
872        assert_eq!(out.stdout.trim_end(), "microclaw-smoke");
873    }
874
875    #[tokio::test]
876    async fn test_router_fails_closed_when_runtime_required_and_missing() {
877        let cfg = SandboxConfig {
878            mode: SandboxMode::All,
879            backend: SandboxBackend::Auto,
880            require_runtime: true,
881            ..SandboxConfig::default()
882        };
883        let router = SandboxRouter::with_backend_for_tests(cfg, Arc::new(NoSandbox));
884        let opts = SandboxExecOptions {
885            timeout: Duration::from_secs(2),
886            working_dir: None,
887            envs: HashMap::new(),
888            env_files: Vec::new(),
889        };
890        let err = router.exec("chat-1", "echo hi", &opts).await.unwrap_err();
891        assert!(err
892            .to_string()
893            .contains("sandbox is enabled but no container runtime is available"));
894    }
895
896    #[test]
897    fn test_pick_runtime_matrix() {
898        assert_eq!(
899            pick_runtime(SandboxBackend::Auto, true, true),
900            Some(ContainerRuntime::Docker)
901        );
902        assert_eq!(pick_runtime(SandboxBackend::Auto, false, true), None);
903        assert_eq!(pick_runtime(SandboxBackend::Auto, false, false), None);
904        assert_eq!(
905            pick_runtime(SandboxBackend::Docker, true, false),
906            Some(ContainerRuntime::Docker)
907        );
908        assert_eq!(pick_runtime(SandboxBackend::Docker, false, true), None);
909        assert_eq!(
910            pick_runtime(SandboxBackend::Podman, false, true),
911            Some(ContainerRuntime::Podman)
912        );
913        assert_eq!(pick_runtime(SandboxBackend::Podman, true, false), None);
914    }
915
916    #[test]
917    fn sandbox_environment_withholds_credentials_by_default() {
918        let dir = tempfile::tempdir().unwrap();
919        let env_file = dir.path().join("plugin.env");
920        std::fs::write(
921            &env_file,
922            "PUBLIC_MODE=fast\nSERVICE_API_KEY=do-not-forward\n",
923        )
924        .unwrap();
925        let opts = SandboxExecOptions {
926            timeout: Duration::from_secs(1),
927            working_dir: None,
928            envs: HashMap::from([
929                ("LANG".to_string(), "C.UTF-8".to_string()),
930                ("AUTH_TOKEN".to_string(), "secret".to_string()),
931            ]),
932            env_files: vec![env_file],
933        };
934
935        let env = sandbox_environment(&opts, &[]);
936
937        assert_eq!(env.get("PUBLIC_MODE").map(String::as_str), Some("fast"));
938        assert_eq!(env.get("LANG").map(String::as_str), Some("C.UTF-8"));
939        assert!(!env.contains_key("SERVICE_API_KEY"));
940        assert!(!env.contains_key("AUTH_TOKEN"));
941    }
942
943    #[test]
944    fn sandbox_environment_forwards_explicitly_allowed_credential() {
945        let opts = SandboxExecOptions {
946            timeout: Duration::from_secs(1),
947            working_dir: None,
948            envs: HashMap::from([("PLUGIN_TOKEN".to_string(), "secret".to_string())]),
949            env_files: Vec::new(),
950        };
951
952        let env = sandbox_environment(&opts, &["plugin_token".to_string()]);
953
954        assert_eq!(env.get("PLUGIN_TOKEN").map(String::as_str), Some("secret"));
955    }
956}