Skip to main content

nenjo_tools/
file_write.rs

1//! Write file contents with path sandboxing and auto-created parent directories.
2
3use crate::security::SecurityPolicy;
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use serde_json::json;
7use std::sync::Arc;
8
9/// Write file contents with path sandboxing
10pub struct FileWriteTool {
11    security: Arc<SecurityPolicy>,
12}
13
14impl FileWriteTool {
15    pub fn new(security: Arc<SecurityPolicy>) -> Self {
16        Self { security }
17    }
18}
19
20#[async_trait]
21impl Tool for FileWriteTool {
22    fn category(&self) -> ToolCategory {
23        ToolCategory::Write
24    }
25
26    fn name(&self) -> &str {
27        "file_write"
28    }
29
30    fn description(&self) -> &str {
31        "Write contents to a file in the workspace. \
32        IMPORTANT: this completely replaces the entire file with the provided content. \
33        To edit an existing file, first read it with file_read, make your changes to the \
34        full content, then write the entire modified content back with file_write. \
35        Never write only the changed lines — always supply the complete file."
36    }
37
38    fn parameters_schema(&self) -> serde_json::Value {
39        json!({
40            "type": "object",
41            "properties": {
42                "path": {
43                    "type": "string",
44                    "description": "Relative path to the file within the workspace"
45                },
46                "content": {
47                    "type": "string",
48                    "description": "Content to write to the file"
49                }
50            },
51            "required": ["path", "content"]
52        })
53    }
54
55    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
56        let path = args
57            .get("path")
58            .and_then(|v| v.as_str())
59            .ok_or_else(|| anyhow::anyhow!("Missing 'path' parameter"))?;
60
61        let content = args
62            .get("content")
63            .and_then(|v| v.as_str())
64            .ok_or_else(|| anyhow::anyhow!("Missing 'content' parameter"))?;
65
66        if !self.security.can_act() {
67            return Ok(ToolResult {
68                success: false,
69                output: String::new(),
70                error: Some("Action blocked: autonomy is read-only".into()),
71            });
72        }
73
74        if self.security.is_rate_limited() {
75            return Ok(ToolResult {
76                success: false,
77                output: String::new(),
78                error: Some("Rate limit exceeded: too many actions in the last hour".into()),
79            });
80        }
81
82        // Security check: validate path is within workspace
83        if !self.security.is_path_allowed(path) {
84            return Ok(ToolResult {
85                success: false,
86                output: String::new(),
87                error: Some(format!("Path not allowed by security policy: {path}")),
88            });
89        }
90
91        let full_path = self.security.workspace_dir.join(path);
92
93        let Some(parent) = full_path.parent() else {
94            return Ok(ToolResult {
95                success: false,
96                output: String::new(),
97                error: Some("Invalid path: missing parent directory".into()),
98            });
99        };
100
101        // Ensure parent directory exists
102        tokio::fs::create_dir_all(parent).await?;
103
104        // Resolve parent AFTER creation to block symlink escapes.
105        let resolved_parent = match tokio::fs::canonicalize(parent).await {
106            Ok(p) => p,
107            Err(e) => {
108                return Ok(ToolResult {
109                    success: false,
110                    output: String::new(),
111                    error: Some(format!("Failed to resolve file path: {e}")),
112                });
113            }
114        };
115
116        if !self.security.is_resolved_path_allowed(&resolved_parent) {
117            return Ok(ToolResult {
118                success: false,
119                output: String::new(),
120                error: Some(format!(
121                    "Resolved path escapes workspace: {}",
122                    resolved_parent.display()
123                )),
124            });
125        }
126
127        let Some(file_name) = full_path.file_name() else {
128            return Ok(ToolResult {
129                success: false,
130                output: String::new(),
131                error: Some("Invalid path: missing file name".into()),
132            });
133        };
134
135        let resolved_target = resolved_parent.join(file_name);
136
137        // If the target already exists and is a symlink, refuse to follow it
138        if let Ok(meta) = tokio::fs::symlink_metadata(&resolved_target).await
139            && meta.file_type().is_symlink()
140        {
141            return Ok(ToolResult {
142                success: false,
143                output: String::new(),
144                error: Some(format!(
145                    "Refusing to write through symlink: {}",
146                    resolved_target.display()
147                )),
148            });
149        }
150
151        if !self.security.record_action() {
152            return Ok(ToolResult {
153                success: false,
154                output: String::new(),
155                error: Some("Rate limit exceeded: action budget exhausted".into()),
156            });
157        }
158
159        match tokio::fs::write(&resolved_target, content).await {
160            Ok(()) => Ok(ToolResult {
161                success: true,
162                output: format!("Written {} bytes to {path}", content.len()),
163                error: None,
164            }),
165            Err(e) => Ok(ToolResult {
166                success: false,
167                output: String::new(),
168                error: Some(format!("Failed to write file: {e}")),
169            }),
170        }
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use crate::security::{AutonomyLevel, SecurityPolicy};
178
179    fn test_security(workspace: std::path::PathBuf) -> Arc<SecurityPolicy> {
180        Arc::new(SecurityPolicy {
181            autonomy: AutonomyLevel::Supervised,
182            workspace_dir: workspace,
183            ..SecurityPolicy::default()
184        })
185    }
186
187    fn test_security_with(
188        workspace: std::path::PathBuf,
189        autonomy: AutonomyLevel,
190        max_actions_per_hour: u32,
191    ) -> Arc<SecurityPolicy> {
192        Arc::new(SecurityPolicy {
193            autonomy,
194            workspace_dir: workspace,
195            max_actions_per_hour,
196            ..SecurityPolicy::default()
197        })
198    }
199
200    #[test]
201    fn file_write_name() {
202        let tool = FileWriteTool::new(test_security(std::env::temp_dir()));
203        assert_eq!(tool.name(), "file_write");
204    }
205
206    #[test]
207    fn file_write_schema_has_path_and_content() {
208        let tool = FileWriteTool::new(test_security(std::env::temp_dir()));
209        let schema = tool.parameters_schema();
210        assert!(schema["properties"]["path"].is_object());
211        assert!(schema["properties"]["content"].is_object());
212        let required = schema["required"].as_array().unwrap();
213        assert!(required.contains(&json!("path")));
214        assert!(required.contains(&json!("content")));
215    }
216
217    #[tokio::test]
218    async fn file_write_creates_file() {
219        let dir = std::env::temp_dir().join("nenjo_test_file_write");
220        let _ = tokio::fs::remove_dir_all(&dir).await;
221        tokio::fs::create_dir_all(&dir).await.unwrap();
222
223        let tool = FileWriteTool::new(test_security(dir.clone()));
224        let result = tool
225            .execute(json!({"path": "out.txt", "content": "written!"}))
226            .await
227            .unwrap();
228        assert!(result.success);
229        assert!(result.output.contains("8 bytes"));
230
231        let content = tokio::fs::read_to_string(dir.join("out.txt"))
232            .await
233            .unwrap();
234        assert_eq!(content, "written!");
235
236        let _ = tokio::fs::remove_dir_all(&dir).await;
237    }
238
239    #[tokio::test]
240    async fn file_write_creates_parent_dirs() {
241        let dir = std::env::temp_dir().join("nenjo_test_file_write_nested");
242        let _ = tokio::fs::remove_dir_all(&dir).await;
243        tokio::fs::create_dir_all(&dir).await.unwrap();
244
245        let tool = FileWriteTool::new(test_security(dir.clone()));
246        let result = tool
247            .execute(json!({"path": "a/b/c/deep.txt", "content": "deep"}))
248            .await
249            .unwrap();
250        assert!(result.success);
251
252        let content = tokio::fs::read_to_string(dir.join("a/b/c/deep.txt"))
253            .await
254            .unwrap();
255        assert_eq!(content, "deep");
256
257        let _ = tokio::fs::remove_dir_all(&dir).await;
258    }
259
260    #[tokio::test]
261    async fn file_write_overwrites_existing() {
262        let dir = std::env::temp_dir().join("nenjo_test_file_write_overwrite");
263        let _ = tokio::fs::remove_dir_all(&dir).await;
264        tokio::fs::create_dir_all(&dir).await.unwrap();
265        tokio::fs::write(dir.join("exist.txt"), "old")
266            .await
267            .unwrap();
268
269        let tool = FileWriteTool::new(test_security(dir.clone()));
270        let result = tool
271            .execute(json!({"path": "exist.txt", "content": "new"}))
272            .await
273            .unwrap();
274        assert!(result.success);
275
276        let content = tokio::fs::read_to_string(dir.join("exist.txt"))
277            .await
278            .unwrap();
279        assert_eq!(content, "new");
280
281        let _ = tokio::fs::remove_dir_all(&dir).await;
282    }
283
284    #[tokio::test]
285    async fn file_write_blocks_path_traversal() {
286        let dir = std::env::temp_dir().join("nenjo_test_file_write_traversal");
287        let _ = tokio::fs::remove_dir_all(&dir).await;
288        tokio::fs::create_dir_all(&dir).await.unwrap();
289
290        let tool = FileWriteTool::new(test_security(dir.clone()));
291        let result = tool
292            .execute(json!({"path": "../../etc/evil", "content": "bad"}))
293            .await
294            .unwrap();
295        assert!(!result.success);
296        assert!(result.error.as_ref().unwrap().contains("not allowed"));
297
298        let _ = tokio::fs::remove_dir_all(&dir).await;
299    }
300
301    #[tokio::test]
302    async fn file_write_blocks_absolute_path() {
303        let tool = FileWriteTool::new(test_security(std::env::temp_dir()));
304        let result = tool
305            .execute(json!({"path": "/etc/evil", "content": "bad"}))
306            .await
307            .unwrap();
308        assert!(!result.success);
309        assert!(result.error.as_ref().unwrap().contains("not allowed"));
310    }
311
312    #[tokio::test]
313    async fn file_write_missing_path_param() {
314        let tool = FileWriteTool::new(test_security(std::env::temp_dir()));
315        let result = tool.execute(json!({"content": "data"})).await;
316        assert!(result.is_err());
317    }
318
319    #[tokio::test]
320    async fn file_write_missing_content_param() {
321        let tool = FileWriteTool::new(test_security(std::env::temp_dir()));
322        let result = tool.execute(json!({"path": "file.txt"})).await;
323        assert!(result.is_err());
324    }
325
326    #[tokio::test]
327    async fn file_write_empty_content() {
328        let dir = std::env::temp_dir().join("nenjo_test_file_write_empty");
329        let _ = tokio::fs::remove_dir_all(&dir).await;
330        tokio::fs::create_dir_all(&dir).await.unwrap();
331
332        let tool = FileWriteTool::new(test_security(dir.clone()));
333        let result = tool
334            .execute(json!({"path": "empty.txt", "content": ""}))
335            .await
336            .unwrap();
337        assert!(result.success);
338        assert!(result.output.contains("0 bytes"));
339
340        let _ = tokio::fs::remove_dir_all(&dir).await;
341    }
342
343    #[cfg(unix)]
344    #[tokio::test]
345    async fn file_write_blocks_symlink_escape() {
346        use std::os::unix::fs::symlink;
347
348        let root = std::env::temp_dir().join("nenjo_test_file_write_symlink_escape");
349        let workspace = root.join("workspace");
350        let outside = root.join("outside");
351
352        let _ = tokio::fs::remove_dir_all(&root).await;
353        tokio::fs::create_dir_all(&workspace).await.unwrap();
354        tokio::fs::create_dir_all(&outside).await.unwrap();
355
356        symlink(&outside, workspace.join("escape_dir")).unwrap();
357
358        let tool = FileWriteTool::new(test_security(workspace.clone()));
359        let result = tool
360            .execute(json!({"path": "escape_dir/hijack.txt", "content": "bad"}))
361            .await
362            .unwrap();
363
364        assert!(!result.success);
365        assert!(
366            result
367                .error
368                .as_deref()
369                .unwrap_or("")
370                .contains("escapes workspace")
371        );
372        assert!(!outside.join("hijack.txt").exists());
373
374        let _ = tokio::fs::remove_dir_all(&root).await;
375    }
376
377    #[tokio::test]
378    async fn file_write_blocks_readonly_mode() {
379        let dir = std::env::temp_dir().join("nenjo_test_file_write_readonly");
380        let _ = tokio::fs::remove_dir_all(&dir).await;
381        tokio::fs::create_dir_all(&dir).await.unwrap();
382
383        let tool = FileWriteTool::new(test_security_with(dir.clone(), AutonomyLevel::ReadOnly, 20));
384        let result = tool
385            .execute(json!({"path": "out.txt", "content": "should-block"}))
386            .await
387            .unwrap();
388
389        assert!(!result.success);
390        assert!(result.error.as_deref().unwrap_or("").contains("read-only"));
391        assert!(!dir.join("out.txt").exists());
392
393        let _ = tokio::fs::remove_dir_all(&dir).await;
394    }
395
396    #[tokio::test]
397    async fn file_write_blocks_when_rate_limited() {
398        let dir = std::env::temp_dir().join("nenjo_test_file_write_rate_limited");
399        let _ = tokio::fs::remove_dir_all(&dir).await;
400        tokio::fs::create_dir_all(&dir).await.unwrap();
401
402        let tool = FileWriteTool::new(test_security_with(
403            dir.clone(),
404            AutonomyLevel::Supervised,
405            0,
406        ));
407        let result = tool
408            .execute(json!({"path": "out.txt", "content": "should-block"}))
409            .await
410            .unwrap();
411
412        assert!(!result.success);
413        assert!(
414            result
415                .error
416                .as_deref()
417                .unwrap_or("")
418                .contains("Rate limit exceeded")
419        );
420        assert!(!dir.join("out.txt").exists());
421
422        let _ = tokio::fs::remove_dir_all(&dir).await;
423    }
424}