1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
//! Sandbox mode for restricting tool operations.
//!
//! When enabled, only whitelisted commands may be executed by the bash tool,
//! and file write/edit operations are restricted to paths within the project directory.
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// Configuration for sandbox mode.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SandboxConfig {
/// Whether sandbox restrictions are active.
pub enabled: bool,
/// Commands allowed in the bash tool (matched by prefix, e.g. `"cargo"` allows `"cargo build"`).
pub allowed_commands: Vec<String>,
/// Paths (directories) where file write/edit operations are permitted.
/// Paths are normalized and checked via prefix matching.
pub writable_paths: Vec<String>,
}
impl SandboxConfig {
/// Create a disabled sandbox config.
pub fn disabled() -> Self {
Self::default()
}
/// Create an enabled sandbox config with the given project directory as the sole writable path
/// and a default set of safe commands.
pub fn for_project(project_dir: &Path) -> Self {
Self {
enabled: true,
allowed_commands: vec![
"cargo".into(),
"rustc".into(),
"npm".into(),
"node".into(),
"python".into(),
"git".into(),
"ls".into(),
"cat".into(),
"head".into(),
"tail".into(),
"grep".into(),
"find".into(),
"wc".into(),
"sort".into(),
"uniq".into(),
"diff".into(),
"echo".into(),
"pwd".into(),
"which".into(),
"env".into(),
"test".into(),
"true".into(),
"false".into(),
"mkdir".into(),
"cp".into(),
"mv".into(),
"touch".into(),
],
writable_paths: vec![project_dir.to_string_lossy().to_string()],
}
}
/// Check whether a bash command is allowed in sandbox mode.
///
/// Returns `Ok(())` if sandbox is disabled or the command is whitelisted.
/// Returns `Err` with a human-readable message if blocked.
pub fn check_command(&self, command: &str) -> Result<(), String> {
if !self.enabled {
return Ok(());
}
let trimmed = command.trim();
if trimmed.is_empty() {
return Ok(());
}
// Extract the base command (first word, stripping any env var prefix)
let base_cmd = extract_base_command(trimmed);
if self
.allowed_commands
.iter()
.any(|allowed| base_cmd == allowed.as_str())
{
return Ok(());
}
Err(format!(
"Sandbox: command '{}' is not in the allowed list. Allowed: {:?}",
base_cmd, self.allowed_commands
))
}
/// Check whether a file path is writable in sandbox mode.
///
/// Returns `Ok(())` if sandbox is disabled or the path is within a writable directory.
/// Returns `Err` with a human-readable message if blocked.
pub fn check_writable_path(&self, path: &Path) -> Result<(), String> {
if !self.enabled {
return Ok(());
}
// Normalize the path for comparison
let normalized = normalize_path(path);
for writable in &self.writable_paths {
let writable_normalized = normalize_path(Path::new(writable));
if normalized.starts_with(&writable_normalized) {
return Ok(());
}
}
Err(format!(
"Sandbox: path '{}' is not within writable directories. Writable: {:?}",
path.display(),
self.writable_paths
))
}
}
/// Extract the base command name from a shell command string.
///
/// Handles:
/// - Leading env var assignments: `FOO=bar cmd args` -> `cmd`
/// - Leading path: `/usr/bin/cmd args` -> `cmd`
/// - Simple commands: `cmd args` -> `cmd`
fn extract_base_command(command: &str) -> &str {
let mut parts = command.split_whitespace();
// Skip env var assignments (KEY=VALUE)
let cmd = loop {
match parts.next() {
Some(part) if part.contains('=') && !part.starts_with('-') => continue,
Some(part) => break part,
None => return "",
}
};
// Strip path prefix: `/usr/bin/cargo` -> `cargo`
cmd.rsplit('/').next().unwrap_or(cmd)
}
/// Best-effort path normalization without requiring the path to exist.
fn normalize_path(path: &Path) -> PathBuf {
// Try canonical first (resolves symlinks, requires path to exist)
if let Ok(canonical) = path.canonicalize() {
return canonical;
}
// Fall back to the path as-is but with components resolved
let mut result = PathBuf::new();
for component in path.components() {
match component {
std::path::Component::ParentDir => {
result.pop();
}
std::path::Component::CurDir => {}
_ => result.push(component),
}
}
result
}
#[cfg(test)]
#[path = "sandbox_tests.rs"]
mod tests;