Skip to main content

vtcode_safety/sandboxing/
debug.rs

1//! Debug utilities for testing sandbox configurations.
2//!
3//! Following the Codex pattern: "codex debug seatbelt and codex debug landlock
4//! let you test arbitrary commands through the sandbox."
5
6use std::path::Path;
7use std::process::Stdio;
8
9use anyhow::{Context, Result};
10use tokio::process::Command;
11
12use super::{CommandSpec, LinuxSandboxLauncher, SandboxManager, SandboxPolicy, SandboxType};
13
14/// Result of a sandbox debug test.
15#[derive(Debug)]
16pub struct SandboxDebugResult {
17    /// Whether the command succeeded.
18    success: bool,
19    /// Standard error.
20    stderr: String,
21    /// Whether the sandbox was actually applied.
22    sandbox_active: bool,
23}
24
25impl SandboxDebugResult {
26    /// Create a result indicating sandbox is not available.
27    fn unavailable(sandbox_type: SandboxType) -> Self {
28        Self {
29            success: false,
30            stderr: format!("Sandbox type {sandbox_type:?} is not available on this platform"),
31            sandbox_active: false,
32        }
33    }
34}
35
36/// Debug sandbox configuration by running a test command.
37///
38/// This allows testing sandbox restrictions without affecting production execution.
39#[expect(
40    unused_results,
41    reason = "Command builder methods configure the owned process command and return a fluent mutable reference."
42)]
43pub async fn debug_sandbox(
44    sandbox_type: SandboxType,
45    policy: &SandboxPolicy,
46    command: &[String],
47    cwd: &Path,
48    linux_launcher: Option<&LinuxSandboxLauncher>,
49) -> Result<SandboxDebugResult> {
50    if !sandbox_type.is_available() {
51        return Ok(SandboxDebugResult::unavailable(sandbox_type));
52    }
53
54    if command.is_empty() {
55        anyhow::bail!("Command cannot be empty");
56    }
57
58    let program = command.first().context("Command cannot be empty")?;
59    let args = command.get(1..).unwrap_or_default().to_vec();
60    let spec = CommandSpec::new(program).with_args(args).with_cwd(cwd);
61
62    let manager = SandboxManager::new();
63    let exec_env = manager
64        .transform(spec, policy, cwd, linux_launcher)
65        .context("Failed to transform command for sandbox")?;
66
67    let mut cmd = Command::new(&exec_env.program);
68    cmd.args(&exec_env.args)
69        .current_dir(&exec_env.cwd)
70        .envs(&exec_env.env)
71        .stdout(Stdio::piped())
72        .stderr(Stdio::piped());
73
74    let output = cmd.output().await.context("Failed to execute sandboxed command")?;
75
76    Ok(SandboxDebugResult {
77        success: output.status.success(),
78        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
79        sandbox_active: exec_env.sandbox_active,
80    })
81}
82
83/// Test if a specific path is writable under the given sandbox policy.
84pub async fn test_path_writable(
85    policy: &SandboxPolicy,
86    test_path: &Path,
87    cwd: &Path,
88    linux_launcher: Option<&LinuxSandboxLauncher>,
89) -> Result<bool> {
90    let test_file = test_path.join(".vtcode_sandbox_test");
91    let test_command = vec![
92        "sh".to_string(),
93        "-c".to_string(),
94        format!("touch '{}' && rm -f '{}'", test_file.display(), test_file.display()),
95    ];
96
97    let result = debug_sandbox(SandboxType::platform_default(), policy, &test_command, cwd, linux_launcher).await?;
98
99    Ok(result.success)
100}
101
102/// Test if network access is blocked under the given sandbox policy.
103pub async fn test_network_blocked(
104    policy: &SandboxPolicy,
105    cwd: &Path,
106    linux_launcher: Option<&LinuxSandboxLauncher>,
107) -> Result<bool> {
108    let test_command = vec![
109        "sh".to_string(),
110        "-c".to_string(),
111        "curl -s --connect-timeout 2 https://example.com > /dev/null 2>&1".to_string(),
112    ];
113
114    let result = debug_sandbox(SandboxType::platform_default(), policy, &test_command, cwd, linux_launcher).await?;
115
116    Ok(!result.success)
117}
118
119/// Get a human-readable summary of sandbox capabilities for the current platform.
120pub fn sandbox_capabilities_summary() -> String {
121    let mut summary = String::new();
122
123    summary.push_str("VT Code Sandbox Capabilities\n");
124    summary.push_str("=============================\n\n");
125
126    summary.push_str(&format!("Platform default: {:?}\n\n", SandboxType::platform_default()));
127
128    summary.push_str("Available sandbox types:\n");
129    for sandbox_type in [
130        SandboxType::MacosSeatbelt,
131        SandboxType::LinuxLandlock,
132        SandboxType::WindowsRestrictedToken,
133    ] {
134        let available = if sandbox_type.is_available() { "✓" } else { "✗" };
135        summary.push_str(&format!("  {available} {sandbox_type:?}\n"));
136    }
137
138    summary.push_str("\nSandbox policies:\n");
139    summary.push_str("  - ReadOnly: Read files, no writes except /dev/null, optional network policy\n");
140    summary.push_str("  - WorkspaceWrite: Read all, write to workspace, optional network allowlist\n");
141    summary.push_str("  - DangerFullAccess: No restrictions (use with caution)\n");
142
143    summary.push_str("\nSecurity features:\n");
144    summary.push_str("  - Sensitive path blocking (~/.ssh, ~/.aws, etc.)\n");
145    summary.push_str("  - .git directory write protection\n");
146    summary.push_str("  - Environment variable sanitization\n");
147    summary.push_str("  - Seccomp syscall filtering (Linux)\n");
148    summary.push_str("  - Resource limits (memory, PIDs, disk, CPU)\n");
149
150    summary
151}
152
153/// Debug subcommand types for CLI integration.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum DebugSubcommand {
156    /// Test macOS Seatbelt sandbox.
157    Seatbelt,
158    /// Test Linux Landlock sandbox.
159    Landlock,
160    /// Show sandbox capabilities.
161    Capabilities,
162}
163
164impl DebugSubcommand {
165    /// Get the sandbox type for this debug subcommand.
166    fn sandbox_type(&self) -> SandboxType {
167        match self {
168            Self::Seatbelt => SandboxType::MacosSeatbelt,
169            Self::Landlock => SandboxType::LinuxLandlock,
170            Self::Capabilities => SandboxType::platform_default(),
171        }
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn test_capabilities_summary() {
181        let summary = sandbox_capabilities_summary();
182        assert!(summary.contains("VT Code Sandbox Capabilities"));
183        assert!(summary.contains("Platform default"));
184        assert!(summary.contains("ReadOnly"));
185        assert!(summary.contains("WorkspaceWrite"));
186    }
187
188    #[test]
189    fn test_debug_subcommand() {
190        assert_eq!(DebugSubcommand::Seatbelt.sandbox_type(), SandboxType::MacosSeatbelt);
191        assert_eq!(DebugSubcommand::Landlock.sandbox_type(), SandboxType::LinuxLandlock);
192    }
193
194    #[tokio::test]
195    async fn test_debug_sandbox_unavailable() {
196        let result = SandboxDebugResult::unavailable(SandboxType::LinuxLandlock);
197        assert!(!result.success);
198        assert!(!result.sandbox_active);
199        assert!(result.stderr.contains("not available"));
200    }
201}