1use crate::runtime::RuntimeAdapter;
4use crate::security::SecurityPolicy;
5use crate::{Tool, ToolCategory, ToolResult};
6use async_trait::async_trait;
7use serde_json::json;
8use std::sync::Arc;
9use std::time::Duration;
10
11const SHELL_TIMEOUT_SECS: u64 = 60;
13const MAX_OUTPUT_BYTES: usize = 1_048_576;
15const SAFE_ENV_VARS: &[&str] = &[
18 "PATH", "HOME", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "USER", "SHELL", "TMPDIR",
19];
20
21pub struct ShellTool {
23 security: Arc<SecurityPolicy>,
24 runtime: Arc<dyn RuntimeAdapter>,
25 description: String,
26}
27
28impl ShellTool {
29 pub fn new(security: Arc<SecurityPolicy>, runtime: Arc<dyn RuntimeAdapter>) -> Self {
30 let description = build_shell_description();
31 Self {
32 security,
33 runtime,
34 description,
35 }
36 }
37}
38
39fn build_shell_description() -> String {
41 let os_label = std::process::Command::new("uname")
44 .arg("-sr")
45 .output()
46 .ok()
47 .and_then(|o| String::from_utf8(o.stdout).ok())
48 .map(|s| s.trim().to_string())
49 .filter(|s| !s.is_empty())
50 .unwrap_or_else(|| std::env::consts::OS.to_string());
51
52 let sed_note = if std::env::consts::OS == "macos" {
54 "sed in-place edits require an empty-string extension on macOS: \
55 `sed -i '' 's/old/new/' file` (GNU Linux syntax `sed -i` will fail). "
56 } else {
57 "sed in-place edits use the standard syntax: `sed -i 's/old/new/' file`. "
58 };
59
60 format!(
61 "Execute a shell command in the workspace directory. \
62 Environment: {os_label}. \
63 {sed_note}\
64 Output redirections (> and >>) are blocked by policy — use file_write to create or \
65 replace files instead. Prefer file_read + file_write over sed/awk for file edits."
66 )
67}
68
69#[async_trait]
70impl Tool for ShellTool {
71 fn category(&self) -> ToolCategory {
72 ToolCategory::ReadWrite
73 }
74
75 fn name(&self) -> &str {
76 "shell"
77 }
78
79 fn description(&self) -> &str {
80 &self.description
81 }
82
83 fn parameters_schema(&self) -> serde_json::Value {
84 json!({
85 "type": "object",
86 "properties": {
87 "command": {
88 "type": "string",
89 "description": "The shell command to execute"
90 },
91 "approved": {
92 "type": "boolean",
93 "description": "Set true to explicitly approve medium/high-risk commands in supervised mode",
94 "default": false
95 }
96 },
97 "required": ["command"]
98 })
99 }
100
101 #[allow(clippy::incompatible_msrv)]
102 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
103 let command = args
104 .get("command")
105 .and_then(|v| v.as_str())
106 .ok_or_else(|| anyhow::anyhow!("Missing 'command' parameter"))?;
107 let approved = args
108 .get("approved")
109 .and_then(|v| v.as_bool())
110 .unwrap_or(false);
111
112 if self.security.is_rate_limited() {
113 return Ok(ToolResult {
114 success: false,
115 output: String::new(),
116 error: Some("Rate limit exceeded: too many actions in the last hour".into()),
117 });
118 }
119
120 match self.security.validate_command_execution(command, approved) {
121 Ok(_) => {}
122 Err(reason) => {
123 return Ok(ToolResult {
124 success: false,
125 output: String::new(),
126 error: Some(reason),
127 });
128 }
129 }
130
131 if !self.security.record_action() {
132 return Ok(ToolResult {
133 success: false,
134 output: String::new(),
135 error: Some("Rate limit exceeded: action budget exhausted".into()),
136 });
137 }
138
139 let mut cmd = match self
143 .runtime
144 .build_shell_command(command, &self.security.workspace_dir)
145 {
146 Ok(cmd) => cmd,
147 Err(e) => {
148 return Ok(ToolResult {
149 success: false,
150 output: String::new(),
151 error: Some(format!("Failed to build runtime command: {e}")),
152 });
153 }
154 };
155 cmd.env_clear();
156
157 for var in SAFE_ENV_VARS {
158 if let Ok(val) = std::env::var(var) {
159 cmd.env(var, val);
160 }
161 }
162
163 for (key, val) in &self.security.forwarded_env {
165 cmd.env(key, val);
166 }
167
168 let result =
169 tokio::time::timeout(Duration::from_secs(SHELL_TIMEOUT_SECS), cmd.output()).await;
170
171 match result {
172 Ok(Ok(output)) => {
173 let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();
174 let mut stderr = String::from_utf8_lossy(&output.stderr).to_string();
175
176 if stdout.len() > MAX_OUTPUT_BYTES {
178 stdout.truncate(stdout.floor_char_boundary(MAX_OUTPUT_BYTES));
179 stdout.push_str("\n... [output truncated at 1MB]");
180 }
181 if stderr.len() > MAX_OUTPUT_BYTES {
182 stderr.truncate(stderr.floor_char_boundary(MAX_OUTPUT_BYTES));
183 stderr.push_str("\n... [stderr truncated at 1MB]");
184 }
185
186 Ok(ToolResult {
187 success: output.status.success(),
188 output: stdout,
189 error: if stderr.is_empty() {
190 None
191 } else {
192 Some(stderr)
193 },
194 })
195 }
196 Ok(Err(e)) => Ok(ToolResult {
197 success: false,
198 output: String::new(),
199 error: Some(format!("Failed to execute command: {e}")),
200 }),
201 Err(_) => Ok(ToolResult {
202 success: false,
203 output: String::new(),
204 error: Some(format!(
205 "Command timed out after {SHELL_TIMEOUT_SECS}s and was killed"
206 )),
207 }),
208 }
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215 use crate::runtime::RuntimeAdapter;
216 use crate::security::{AutonomyLevel, SecurityPolicy};
217
218 fn test_security(autonomy: AutonomyLevel) -> Arc<SecurityPolicy> {
219 Arc::new(SecurityPolicy {
220 autonomy,
221 workspace_dir: std::env::temp_dir(),
222 ..SecurityPolicy::default()
223 })
224 }
225
226 struct TestNativeRuntime;
228
229 impl RuntimeAdapter for TestNativeRuntime {
230 fn name(&self) -> &str {
231 "test-native"
232 }
233 fn has_shell_access(&self) -> bool {
234 true
235 }
236 fn has_filesystem_access(&self) -> bool {
237 true
238 }
239 fn storage_path(&self) -> std::path::PathBuf {
240 std::env::temp_dir()
241 }
242 fn supports_long_running(&self) -> bool {
243 true
244 }
245 fn build_shell_command(
246 &self,
247 command: &str,
248 workspace_dir: &std::path::Path,
249 ) -> anyhow::Result<tokio::process::Command> {
250 let mut cmd = tokio::process::Command::new("sh");
251 cmd.arg("-c").arg(command).current_dir(workspace_dir);
252 Ok(cmd)
253 }
254 }
255
256 fn test_runtime() -> Arc<dyn RuntimeAdapter> {
257 Arc::new(TestNativeRuntime)
258 }
259
260 #[test]
261 fn shell_tool_name() {
262 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
263 assert_eq!(tool.name(), "shell");
264 }
265
266 #[test]
267 fn shell_tool_description() {
268 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
269 assert!(!tool.description().is_empty());
270 }
271
272 #[test]
273 fn shell_tool_schema_has_command() {
274 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
275 let schema = tool.parameters_schema();
276 assert!(schema["properties"]["command"].is_object());
277 assert!(
278 schema["required"]
279 .as_array()
280 .unwrap()
281 .contains(&json!("command"))
282 );
283 assert!(schema["properties"]["approved"].is_object());
284 }
285
286 #[tokio::test]
287 async fn shell_executes_allowed_command() {
288 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
289 let result = tool
290 .execute(json!({"command": "echo hello"}))
291 .await
292 .unwrap();
293 assert!(result.success);
294 assert!(result.output.trim().contains("hello"));
295 assert!(result.error.is_none());
296 }
297
298 #[tokio::test]
299 async fn shell_blocks_disallowed_command() {
300 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
301 let result = tool.execute(json!({"command": "rm -rf /"})).await.unwrap();
302 assert!(!result.success);
303 let error = result.error.as_deref().unwrap_or("");
304 assert!(error.contains("not allowed") || error.contains("high-risk"));
305 }
306
307 #[tokio::test]
308 async fn shell_blocks_readonly() {
309 let tool = ShellTool::new(test_security(AutonomyLevel::ReadOnly), test_runtime());
310 let result = tool.execute(json!({"command": "ls"})).await.unwrap();
311 assert!(!result.success);
312 assert!(result.error.as_ref().unwrap().contains("not allowed"));
313 }
314
315 #[tokio::test]
316 async fn shell_missing_command_param() {
317 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
318 let result = tool.execute(json!({})).await;
319 assert!(result.is_err());
320 assert!(result.unwrap_err().to_string().contains("command"));
321 }
322
323 #[tokio::test]
324 async fn shell_wrong_type_param() {
325 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
326 let result = tool.execute(json!({"command": 123})).await;
327 assert!(result.is_err());
328 }
329
330 #[tokio::test]
331 async fn shell_captures_exit_code() {
332 let tool = ShellTool::new(test_security(AutonomyLevel::Supervised), test_runtime());
333 let result = tool
334 .execute(json!({"command": "ls /nonexistent_dir_xyz"}))
335 .await
336 .unwrap();
337 assert!(!result.success);
338 }
339
340 fn test_security_with_env_cmd() -> Arc<SecurityPolicy> {
341 Arc::new(SecurityPolicy {
342 autonomy: AutonomyLevel::Supervised,
343 workspace_dir: std::env::temp_dir(),
344 blocked_commands: vec![],
345 ..SecurityPolicy::default()
346 })
347 }
348
349 struct EnvGuard {
352 key: &'static str,
353 original: Option<String>,
354 }
355
356 impl EnvGuard {
357 fn set(key: &'static str, value: &str) -> Self {
358 let original = std::env::var(key).ok();
359 unsafe {
360 std::env::set_var(key, value);
361 }
362 Self { key, original }
363 }
364 }
365
366 impl Drop for EnvGuard {
367 fn drop(&mut self) {
368 match &self.original {
369 Some(val) => unsafe { std::env::set_var(self.key, val) },
370 None => unsafe { std::env::remove_var(self.key) },
371 }
372 }
373 }
374
375 #[tokio::test(flavor = "current_thread")]
376 async fn shell_does_not_leak_api_key() {
377 let _g1 = EnvGuard::set("API_KEY", "sk-test-secret-12345");
378 let _g2 = EnvGuard::set("ZEROCLAW_API_KEY", "sk-test-secret-67890");
379
380 let tool = ShellTool::new(test_security_with_env_cmd(), test_runtime());
381 let result = tool.execute(json!({"command": "env"})).await.unwrap();
382 assert!(result.success);
383 assert!(
384 !result.output.contains("sk-test-secret-12345"),
385 "API_KEY leaked to shell command output"
386 );
387 assert!(
388 !result.output.contains("sk-test-secret-67890"),
389 "ZEROCLAW_API_KEY leaked to shell command output"
390 );
391 }
392
393 #[tokio::test]
394 async fn shell_preserves_path_and_home() {
395 let tool = ShellTool::new(test_security_with_env_cmd(), test_runtime());
396
397 let result = tool
398 .execute(json!({"command": "echo $HOME"}))
399 .await
400 .unwrap();
401 assert!(result.success);
402 assert!(
403 !result.output.trim().is_empty(),
404 "HOME should be available in shell"
405 );
406
407 let result = tool
408 .execute(json!({"command": "echo $PATH"}))
409 .await
410 .unwrap();
411 assert!(result.success);
412 assert!(
413 !result.output.trim().is_empty(),
414 "PATH should be available in shell"
415 );
416 }
417
418 #[tokio::test]
419 async fn shell_forwards_env_from_security_policy() {
420 let security = Arc::new(SecurityPolicy {
421 autonomy: AutonomyLevel::Supervised,
422 blocked_commands: vec![],
423 workspace_dir: std::env::temp_dir(),
424 forwarded_env: vec![
425 ("GH_TOKEN".into(), "test-gh-token-xyz".into()),
426 ("GITHUB_TOKEN".into(), "test-github-token-xyz".into()),
427 ],
428 ..SecurityPolicy::default()
429 });
430
431 let tool = ShellTool::new(security, test_runtime());
432 let result = tool.execute(json!({"command": "env"})).await.unwrap();
433 assert!(result.success);
434 assert!(
435 result.output.contains("GH_TOKEN=test-gh-token-xyz"),
436 "GH_TOKEN should be forwarded to shell subprocess"
437 );
438 assert!(
439 result.output.contains("GITHUB_TOKEN=test-github-token-xyz"),
440 "GITHUB_TOKEN should be forwarded to shell subprocess"
441 );
442 }
443
444 #[tokio::test]
445 async fn shell_requires_approval_for_medium_risk_command() {
446 let security = Arc::new(SecurityPolicy {
447 autonomy: AutonomyLevel::Supervised,
448 blocked_commands: vec![],
449 workspace_dir: std::env::temp_dir(),
450 ..SecurityPolicy::default()
451 });
452
453 let tool = ShellTool::new(security.clone(), test_runtime());
454 let denied = tool
455 .execute(json!({"command": "touch nenjo_shell_approval_test"}))
456 .await
457 .unwrap();
458 assert!(!denied.success);
459 assert!(
460 denied
461 .error
462 .as_deref()
463 .unwrap_or("")
464 .contains("explicit approval")
465 );
466
467 let allowed = tool
468 .execute(json!({
469 "command": "touch nenjo_shell_approval_test",
470 "approved": true
471 }))
472 .await
473 .unwrap();
474 assert!(allowed.success);
475
476 let _ = std::fs::remove_file(std::env::temp_dir().join("nenjo_shell_approval_test"));
477 }
478}