vtcode_safety/sandboxing/
debug.rs1use std::path::Path;
7use std::process::Stdio;
8
9use anyhow::{Context, Result};
10use tokio::process::Command;
11
12use super::{CommandSpec, SandboxManager, SandboxPolicy, SandboxType};
13
14#[derive(Debug)]
16pub struct SandboxDebugResult {
17 success: bool,
19 exit_code: Option<i32>,
21 stdout: String,
23 stderr: String,
25 sandbox_type: SandboxType,
27 sandbox_active: bool,
29}
30
31impl SandboxDebugResult {
32 fn unavailable(sandbox_type: SandboxType) -> Self {
34 Self {
35 success: false,
36 exit_code: None,
37 stdout: String::new(),
38 stderr: format!("Sandbox type {sandbox_type:?} is not available on this platform"),
39 sandbox_type,
40 sandbox_active: false,
41 }
42 }
43}
44
45pub async fn debug_sandbox(
49 sandbox_type: SandboxType,
50 policy: &SandboxPolicy,
51 command: &[String],
52 cwd: &Path,
53 sandbox_executable: Option<&Path>,
54) -> Result<SandboxDebugResult> {
55 if !sandbox_type.is_available() {
56 return Ok(SandboxDebugResult::unavailable(sandbox_type));
57 }
58
59 if command.is_empty() {
60 anyhow::bail!("Command cannot be empty");
61 }
62
63 let spec = CommandSpec::new(&command[0]).with_args(command[1..].to_vec()).with_cwd(cwd);
64
65 let manager = SandboxManager::new();
66 let exec_env = manager
67 .transform(spec, policy, cwd, sandbox_executable)
68 .context("Failed to transform command for sandbox")?;
69
70 let mut cmd = Command::new(&exec_env.program);
71 cmd.args(&exec_env.args)
72 .current_dir(&exec_env.cwd)
73 .envs(&exec_env.env)
74 .stdout(Stdio::piped())
75 .stderr(Stdio::piped());
76
77 let output = cmd.output().await.context("Failed to execute sandboxed command")?;
78
79 Ok(SandboxDebugResult {
80 success: output.status.success(),
81 exit_code: output.status.code(),
82 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
83 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
84 sandbox_type: exec_env.sandbox_type,
85 sandbox_active: exec_env.sandbox_active,
86 })
87}
88
89pub async fn test_path_writable(
91 policy: &SandboxPolicy,
92 test_path: &Path,
93 cwd: &Path,
94 sandbox_executable: Option<&Path>,
95) -> Result<bool> {
96 let test_file = test_path.join(".vtcode_sandbox_test");
97 let test_command = vec![
98 "sh".to_string(),
99 "-c".to_string(),
100 format!("touch '{}' && rm -f '{}'", test_file.display(), test_file.display()),
101 ];
102
103 let result = debug_sandbox(SandboxType::platform_default(), policy, &test_command, cwd, sandbox_executable).await?;
104
105 Ok(result.success)
106}
107
108pub async fn test_network_blocked(
110 policy: &SandboxPolicy,
111 cwd: &Path,
112 sandbox_executable: Option<&Path>,
113) -> Result<bool> {
114 let test_command = vec![
115 "sh".to_string(),
116 "-c".to_string(),
117 "curl -s --connect-timeout 2 https://example.com > /dev/null 2>&1".to_string(),
118 ];
119
120 let result = debug_sandbox(SandboxType::platform_default(), policy, &test_command, cwd, sandbox_executable).await?;
121
122 Ok(!result.success)
123}
124
125pub fn sandbox_capabilities_summary() -> String {
127 let mut summary = String::new();
128
129 summary.push_str("VT Code Sandbox Capabilities\n");
130 summary.push_str("=============================\n\n");
131
132 summary.push_str(&format!("Platform default: {:?}\n\n", SandboxType::platform_default()));
133
134 summary.push_str("Available sandbox types:\n");
135 for sandbox_type in [
136 SandboxType::MacosSeatbelt,
137 SandboxType::LinuxLandlock,
138 SandboxType::WindowsRestrictedToken,
139 ] {
140 let available = if sandbox_type.is_available() { "✓" } else { "✗" };
141 summary.push_str(&format!(" {available} {sandbox_type:?}\n"));
142 }
143
144 summary.push_str("\nSandbox policies:\n");
145 summary.push_str(" - ReadOnly: Read files, no writes except /dev/null, optional network policy\n");
146 summary.push_str(" - WorkspaceWrite: Read all, write to workspace, optional network allowlist\n");
147 summary.push_str(" - DangerFullAccess: No restrictions (use with caution)\n");
148
149 summary.push_str("\nSecurity features:\n");
150 summary.push_str(" - Sensitive path blocking (~/.ssh, ~/.aws, etc.)\n");
151 summary.push_str(" - .git directory write protection\n");
152 summary.push_str(" - Environment variable sanitization\n");
153 summary.push_str(" - Seccomp syscall filtering (Linux)\n");
154 summary.push_str(" - Resource limits (memory, PIDs, disk, CPU)\n");
155
156 summary
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum DebugSubcommand {
162 Seatbelt,
164 Landlock,
166 Capabilities,
168}
169
170impl DebugSubcommand {
171 fn sandbox_type(&self) -> SandboxType {
173 match self {
174 Self::Seatbelt => SandboxType::MacosSeatbelt,
175 Self::Landlock => SandboxType::LinuxLandlock,
176 Self::Capabilities => SandboxType::platform_default(),
177 }
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn test_capabilities_summary() {
187 let summary = sandbox_capabilities_summary();
188 assert!(summary.contains("VT Code Sandbox Capabilities"));
189 assert!(summary.contains("Platform default"));
190 assert!(summary.contains("ReadOnly"));
191 assert!(summary.contains("WorkspaceWrite"));
192 }
193
194 #[test]
195 fn test_debug_subcommand() {
196 assert_eq!(DebugSubcommand::Seatbelt.sandbox_type(), SandboxType::MacosSeatbelt);
197 assert_eq!(DebugSubcommand::Landlock.sandbox_type(), SandboxType::LinuxLandlock);
198 }
199
200 #[tokio::test]
201 async fn test_debug_sandbox_unavailable() {
202 let result = SandboxDebugResult::unavailable(SandboxType::LinuxLandlock);
203 assert!(!result.success);
204 assert!(!result.sandbox_active);
205 assert!(result.stderr.contains("not available"));
206 }
207}