1use crate::security::SecurityPolicy;
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use serde_json::json;
7use std::sync::Arc;
8
9pub struct FileEditTool {
16 security: Arc<SecurityPolicy>,
17}
18
19impl FileEditTool {
20 pub fn new(security: Arc<SecurityPolicy>) -> Self {
21 Self { security }
22 }
23}
24
25#[async_trait]
26impl Tool for FileEditTool {
27 fn category(&self) -> ToolCategory {
28 ToolCategory::Write
29 }
30
31 fn name(&self) -> &str {
32 "file_edit"
33 }
34
35 fn description(&self) -> &str {
36 "Edit a file by replacing an exact string match with new content"
37 }
38
39 fn parameters_schema(&self) -> serde_json::Value {
40 json!({
41 "type": "object",
42 "properties": {
43 "path": {
44 "type": "string",
45 "description": "Path to the file. Relative paths resolve from workspace; outside paths require policy allowlist."
46 },
47 "old_string": {
48 "type": "string",
49 "description": "The exact text to find and replace (must appear exactly once in the file)"
50 },
51 "new_string": {
52 "type": "string",
53 "description": "The replacement text (empty string to delete the matched text)"
54 }
55 },
56 "required": ["path", "old_string", "new_string"]
57 })
58 }
59
60 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
61 let path = args
63 .get("path")
64 .and_then(|v| v.as_str())
65 .ok_or_else(|| anyhow::anyhow!("Missing 'path' parameter"))?;
66
67 let old_string = args
68 .get("old_string")
69 .and_then(|v| v.as_str())
70 .ok_or_else(|| anyhow::anyhow!("Missing 'old_string' parameter"))?;
71
72 let new_string = args
73 .get("new_string")
74 .and_then(|v| v.as_str())
75 .ok_or_else(|| anyhow::anyhow!("Missing 'new_string' parameter"))?;
76
77 if old_string.is_empty() {
78 return Ok(ToolResult {
79 success: false,
80 output: String::new(),
81 error: Some("old_string must not be empty".into()),
82 });
83 }
84
85 if !self.security.can_act() {
87 return Ok(ToolResult {
88 success: false,
89 output: String::new(),
90 error: Some("Action blocked: autonomy is read-only".into()),
91 });
92 }
93
94 if self.security.is_rate_limited() {
96 return Ok(ToolResult {
97 success: false,
98 output: String::new(),
99 error: Some("Rate limit exceeded: too many actions in the last hour".into()),
100 });
101 }
102
103 if !self.security.is_path_allowed(path) {
105 return Ok(ToolResult {
106 success: false,
107 output: String::new(),
108 error: Some(format!("Path not allowed by security policy: {path}")),
109 });
110 }
111
112 let full_path = self.security.workspace_dir.join(path);
113
114 let Some(parent) = full_path.parent() else {
116 return Ok(ToolResult {
117 success: false,
118 output: String::new(),
119 error: Some("Invalid path: missing parent directory".into()),
120 });
121 };
122
123 let resolved_parent = match tokio::fs::canonicalize(parent).await {
124 Ok(p) => p,
125 Err(e) => {
126 return Ok(ToolResult {
127 success: false,
128 output: String::new(),
129 error: Some(format!("Failed to resolve file path: {e}")),
130 });
131 }
132 };
133
134 if !self.security.is_resolved_path_allowed(&resolved_parent) {
136 return Ok(ToolResult {
137 success: false,
138 output: String::new(),
139 error: Some(
140 self.security
141 .resolved_path_violation_message(&resolved_parent),
142 ),
143 });
144 }
145
146 let Some(file_name) = full_path.file_name() else {
147 return Ok(ToolResult {
148 success: false,
149 output: String::new(),
150 error: Some("Invalid path: missing file name".into()),
151 });
152 };
153
154 let resolved_target = resolved_parent.join(file_name);
155
156 if let Ok(meta) = tokio::fs::symlink_metadata(&resolved_target).await
158 && meta.file_type().is_symlink()
159 {
160 return Ok(ToolResult {
161 success: false,
162 output: String::new(),
163 error: Some(format!(
164 "Refusing to edit through symlink: {}",
165 resolved_target.display()
166 )),
167 });
168 }
169
170 if !self.security.record_action() {
172 return Ok(ToolResult {
173 success: false,
174 output: String::new(),
175 error: Some("Rate limit exceeded: action budget exhausted".into()),
176 });
177 }
178
179 let content = match tokio::fs::read_to_string(&resolved_target).await {
181 Ok(c) => c,
182 Err(e) => {
183 return Ok(ToolResult {
184 success: false,
185 output: String::new(),
186 error: Some(format!("Failed to read file: {e}")),
187 });
188 }
189 };
190
191 let match_count = content.matches(old_string).count();
192
193 if match_count == 0 {
194 return Ok(ToolResult {
195 success: false,
196 output: String::new(),
197 error: Some("old_string not found in file".into()),
198 });
199 }
200
201 if match_count > 1 {
202 return Ok(ToolResult {
203 success: false,
204 output: String::new(),
205 error: Some(format!(
206 "old_string matches {match_count} times; must match exactly once"
207 )),
208 });
209 }
210
211 let new_content = content.replacen(old_string, new_string, 1);
212
213 match tokio::fs::write(&resolved_target, &new_content).await {
214 Ok(()) => Ok(ToolResult {
215 success: true,
216 output: format!(
217 "Edited {path}: replaced 1 occurrence ({} bytes)",
218 new_content.len()
219 ),
220 error: None,
221 }),
222 Err(e) => Ok(ToolResult {
223 success: false,
224 output: String::new(),
225 error: Some(format!("Failed to write file: {e}")),
226 }),
227 }
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234 use crate::security::{AutonomyLevel, SecurityPolicy};
235
236 fn test_security(workspace: std::path::PathBuf) -> Arc<SecurityPolicy> {
237 Arc::new(SecurityPolicy {
238 autonomy: AutonomyLevel::Supervised,
239 workspace_dir: workspace,
240 ..SecurityPolicy::default()
241 })
242 }
243
244 fn test_security_with(
245 workspace: std::path::PathBuf,
246 autonomy: AutonomyLevel,
247 max_actions_per_hour: u32,
248 ) -> Arc<SecurityPolicy> {
249 Arc::new(SecurityPolicy {
250 autonomy,
251 workspace_dir: workspace,
252 max_actions_per_hour,
253 ..SecurityPolicy::default()
254 })
255 }
256
257 #[test]
258 fn file_edit_name() {
259 let tool = FileEditTool::new(test_security(std::env::temp_dir()));
260 assert_eq!(tool.name(), "file_edit");
261 }
262
263 #[test]
264 fn file_edit_schema_has_required_params() {
265 let tool = FileEditTool::new(test_security(std::env::temp_dir()));
266 let schema = tool.parameters_schema();
267 assert!(schema["properties"]["path"].is_object());
268 assert!(schema["properties"]["old_string"].is_object());
269 assert!(schema["properties"]["new_string"].is_object());
270 let required = schema["required"].as_array().unwrap();
271 assert!(required.contains(&json!("path")));
272 assert!(required.contains(&json!("old_string")));
273 assert!(required.contains(&json!("new_string")));
274 }
275
276 #[tokio::test]
277 async fn file_edit_replaces_single_match() {
278 let dir = std::env::temp_dir().join("nenjo_test_file_edit_single");
279 let _ = tokio::fs::remove_dir_all(&dir).await;
280 tokio::fs::create_dir_all(&dir).await.unwrap();
281 tokio::fs::write(dir.join("test.txt"), "hello world")
282 .await
283 .unwrap();
284
285 let tool = FileEditTool::new(test_security(dir.clone()));
286 let result = tool
287 .execute(json!({
288 "path": "test.txt",
289 "old_string": "hello",
290 "new_string": "goodbye"
291 }))
292 .await
293 .unwrap();
294
295 assert!(result.success, "edit should succeed: {:?}", result.error);
296 assert!(result.output.contains("replaced 1 occurrence"));
297
298 let content = tokio::fs::read_to_string(dir.join("test.txt"))
299 .await
300 .unwrap();
301 assert_eq!(content, "goodbye world");
302
303 let _ = tokio::fs::remove_dir_all(&dir).await;
304 }
305
306 #[tokio::test]
307 async fn file_edit_not_found() {
308 let dir = std::env::temp_dir().join("nenjo_test_file_edit_notfound");
309 let _ = tokio::fs::remove_dir_all(&dir).await;
310 tokio::fs::create_dir_all(&dir).await.unwrap();
311 tokio::fs::write(dir.join("test.txt"), "hello world")
312 .await
313 .unwrap();
314
315 let tool = FileEditTool::new(test_security(dir.clone()));
316 let result = tool
317 .execute(json!({
318 "path": "test.txt",
319 "old_string": "nonexistent",
320 "new_string": "replacement"
321 }))
322 .await
323 .unwrap();
324
325 assert!(!result.success);
326 assert!(result.error.as_deref().unwrap_or("").contains("not found"));
327
328 let content = tokio::fs::read_to_string(dir.join("test.txt"))
330 .await
331 .unwrap();
332 assert_eq!(content, "hello world");
333
334 let _ = tokio::fs::remove_dir_all(&dir).await;
335 }
336
337 #[tokio::test]
338 async fn file_edit_multiple_matches() {
339 let dir = std::env::temp_dir().join("nenjo_test_file_edit_multi");
340 let _ = tokio::fs::remove_dir_all(&dir).await;
341 tokio::fs::create_dir_all(&dir).await.unwrap();
342 tokio::fs::write(dir.join("test.txt"), "aaa bbb aaa")
343 .await
344 .unwrap();
345
346 let tool = FileEditTool::new(test_security(dir.clone()));
347 let result = tool
348 .execute(json!({
349 "path": "test.txt",
350 "old_string": "aaa",
351 "new_string": "ccc"
352 }))
353 .await
354 .unwrap();
355
356 assert!(!result.success);
357 assert!(
358 result
359 .error
360 .as_deref()
361 .unwrap_or("")
362 .contains("matches 2 times")
363 );
364
365 let content = tokio::fs::read_to_string(dir.join("test.txt"))
367 .await
368 .unwrap();
369 assert_eq!(content, "aaa bbb aaa");
370
371 let _ = tokio::fs::remove_dir_all(&dir).await;
372 }
373
374 #[tokio::test]
375 async fn file_edit_delete_via_empty_new_string() {
376 let dir = std::env::temp_dir().join("nenjo_test_file_edit_delete");
377 let _ = tokio::fs::remove_dir_all(&dir).await;
378 tokio::fs::create_dir_all(&dir).await.unwrap();
379 tokio::fs::write(dir.join("test.txt"), "keep remove keep")
380 .await
381 .unwrap();
382
383 let tool = FileEditTool::new(test_security(dir.clone()));
384 let result = tool
385 .execute(json!({
386 "path": "test.txt",
387 "old_string": " remove",
388 "new_string": ""
389 }))
390 .await
391 .unwrap();
392
393 assert!(
394 result.success,
395 "delete edit should succeed: {:?}",
396 result.error
397 );
398
399 let content = tokio::fs::read_to_string(dir.join("test.txt"))
400 .await
401 .unwrap();
402 assert_eq!(content, "keep keep");
403
404 let _ = tokio::fs::remove_dir_all(&dir).await;
405 }
406
407 #[tokio::test]
408 async fn file_edit_missing_path_param() {
409 let tool = FileEditTool::new(test_security(std::env::temp_dir()));
410 let result = tool
411 .execute(json!({"old_string": "a", "new_string": "b"}))
412 .await;
413 assert!(result.is_err());
414 }
415
416 #[tokio::test]
417 async fn file_edit_missing_old_string_param() {
418 let tool = FileEditTool::new(test_security(std::env::temp_dir()));
419 let result = tool
420 .execute(json!({"path": "f.txt", "new_string": "b"}))
421 .await;
422 assert!(result.is_err());
423 }
424
425 #[tokio::test]
426 async fn file_edit_missing_new_string_param() {
427 let tool = FileEditTool::new(test_security(std::env::temp_dir()));
428 let result = tool
429 .execute(json!({"path": "f.txt", "old_string": "a"}))
430 .await;
431 assert!(result.is_err());
432 }
433
434 #[tokio::test]
435 async fn file_edit_rejects_empty_old_string() {
436 let dir = std::env::temp_dir().join("nenjo_test_file_edit_empty_old_string");
437 let _ = tokio::fs::remove_dir_all(&dir).await;
438 tokio::fs::create_dir_all(&dir).await.unwrap();
439 tokio::fs::write(dir.join("test.txt"), "hello")
440 .await
441 .unwrap();
442
443 let tool = FileEditTool::new(test_security(dir.clone()));
444 let result = tool
445 .execute(json!({
446 "path": "test.txt",
447 "old_string": "",
448 "new_string": "x"
449 }))
450 .await
451 .unwrap();
452
453 assert!(!result.success);
454 assert!(
455 result
456 .error
457 .as_deref()
458 .unwrap_or("")
459 .contains("must not be empty")
460 );
461
462 let content = tokio::fs::read_to_string(dir.join("test.txt"))
463 .await
464 .unwrap();
465 assert_eq!(content, "hello");
466
467 let _ = tokio::fs::remove_dir_all(&dir).await;
468 }
469
470 #[tokio::test]
471 async fn file_edit_blocks_path_traversal() {
472 let dir = std::env::temp_dir().join("nenjo_test_file_edit_traversal");
473 let _ = tokio::fs::remove_dir_all(&dir).await;
474 tokio::fs::create_dir_all(&dir).await.unwrap();
475
476 let tool = FileEditTool::new(test_security(dir.clone()));
477 let result = tool
478 .execute(json!({
479 "path": "../../etc/passwd",
480 "old_string": "root",
481 "new_string": "hacked"
482 }))
483 .await
484 .unwrap();
485
486 assert!(!result.success);
487 assert!(result.error.as_ref().unwrap().contains("not allowed"));
488
489 let _ = tokio::fs::remove_dir_all(&dir).await;
490 }
491
492 #[tokio::test]
493 async fn file_edit_blocks_absolute_path() {
494 let tool = FileEditTool::new(test_security(std::env::temp_dir()));
495 let result = tool
496 .execute(json!({
497 "path": "/etc/passwd",
498 "old_string": "root",
499 "new_string": "hacked"
500 }))
501 .await
502 .unwrap();
503
504 assert!(!result.success);
505 assert!(result.error.as_ref().unwrap().contains("not allowed"));
506 }
507
508 #[cfg(unix)]
509 #[tokio::test]
510 async fn file_edit_blocks_symlink_escape() {
511 use std::os::unix::fs::symlink;
512
513 let root = std::env::temp_dir().join("nenjo_test_file_edit_symlink_escape");
514 let workspace = root.join("workspace");
515 let outside = root.join("outside");
516
517 let _ = tokio::fs::remove_dir_all(&root).await;
518 tokio::fs::create_dir_all(&workspace).await.unwrap();
519 tokio::fs::create_dir_all(&outside).await.unwrap();
520
521 symlink(&outside, workspace.join("escape_dir")).unwrap();
522
523 let tool = FileEditTool::new(test_security(workspace.clone()));
524 let result = tool
525 .execute(json!({
526 "path": "escape_dir/target.txt",
527 "old_string": "a",
528 "new_string": "b"
529 }))
530 .await
531 .unwrap();
532
533 assert!(!result.success);
534 assert!(
535 result
536 .error
537 .as_deref()
538 .unwrap_or("")
539 .contains("escapes workspace")
540 );
541
542 let _ = tokio::fs::remove_dir_all(&root).await;
543 }
544
545 #[cfg(unix)]
546 #[tokio::test]
547 async fn file_edit_blocks_symlink_target_file() {
548 use std::os::unix::fs::symlink;
549
550 let root = std::env::temp_dir().join("nenjo_test_file_edit_symlink_target");
551 let workspace = root.join("workspace");
552 let outside = root.join("outside");
553
554 let _ = tokio::fs::remove_dir_all(&root).await;
555 tokio::fs::create_dir_all(&workspace).await.unwrap();
556 tokio::fs::create_dir_all(&outside).await.unwrap();
557
558 tokio::fs::write(outside.join("target.txt"), "original")
559 .await
560 .unwrap();
561 symlink(outside.join("target.txt"), workspace.join("linked.txt")).unwrap();
562
563 let tool = FileEditTool::new(test_security(workspace.clone()));
564 let result = tool
565 .execute(json!({
566 "path": "linked.txt",
567 "old_string": "original",
568 "new_string": "hacked"
569 }))
570 .await
571 .unwrap();
572
573 assert!(!result.success, "editing through symlink must be blocked");
574 assert!(
575 result.error.as_deref().unwrap_or("").contains("symlink"),
576 "error should mention symlink"
577 );
578
579 let content = tokio::fs::read_to_string(outside.join("target.txt"))
580 .await
581 .unwrap();
582 assert_eq!(content, "original", "original file must not be modified");
583
584 let _ = tokio::fs::remove_dir_all(&root).await;
585 }
586
587 #[tokio::test]
588 async fn file_edit_blocks_readonly_mode() {
589 let dir = std::env::temp_dir().join("nenjo_test_file_edit_readonly");
590 let _ = tokio::fs::remove_dir_all(&dir).await;
591 tokio::fs::create_dir_all(&dir).await.unwrap();
592 tokio::fs::write(dir.join("test.txt"), "hello")
593 .await
594 .unwrap();
595
596 let tool = FileEditTool::new(test_security_with(dir.clone(), AutonomyLevel::ReadOnly, 20));
597 let result = tool
598 .execute(json!({
599 "path": "test.txt",
600 "old_string": "hello",
601 "new_string": "world"
602 }))
603 .await
604 .unwrap();
605
606 assert!(!result.success);
607 assert!(result.error.as_deref().unwrap_or("").contains("read-only"));
608
609 let content = tokio::fs::read_to_string(dir.join("test.txt"))
610 .await
611 .unwrap();
612 assert_eq!(content, "hello");
613
614 let _ = tokio::fs::remove_dir_all(&dir).await;
615 }
616
617 #[tokio::test]
618 async fn file_edit_blocks_when_rate_limited() {
619 let dir = std::env::temp_dir().join("nenjo_test_file_edit_rate_limited");
620 let _ = tokio::fs::remove_dir_all(&dir).await;
621 tokio::fs::create_dir_all(&dir).await.unwrap();
622 tokio::fs::write(dir.join("test.txt"), "hello")
623 .await
624 .unwrap();
625
626 let tool = FileEditTool::new(test_security_with(
627 dir.clone(),
628 AutonomyLevel::Supervised,
629 0,
630 ));
631 let result = tool
632 .execute(json!({
633 "path": "test.txt",
634 "old_string": "hello",
635 "new_string": "world"
636 }))
637 .await
638 .unwrap();
639
640 assert!(!result.success);
641 assert!(
642 result
643 .error
644 .as_deref()
645 .unwrap_or("")
646 .contains("Rate limit exceeded")
647 );
648
649 let content = tokio::fs::read_to_string(dir.join("test.txt"))
650 .await
651 .unwrap();
652 assert_eq!(content, "hello");
653
654 let _ = tokio::fs::remove_dir_all(&dir).await;
655 }
656
657 #[tokio::test]
658 async fn file_edit_nonexistent_file() {
659 let dir = std::env::temp_dir().join("nenjo_test_file_edit_nofile");
660 let _ = tokio::fs::remove_dir_all(&dir).await;
661 tokio::fs::create_dir_all(&dir).await.unwrap();
662
663 let tool = FileEditTool::new(test_security(dir.clone()));
664 let result = tool
665 .execute(json!({
666 "path": "missing.txt",
667 "old_string": "a",
668 "new_string": "b"
669 }))
670 .await
671 .unwrap();
672
673 assert!(!result.success);
674 assert!(
675 result
676 .error
677 .as_deref()
678 .unwrap_or("")
679 .contains("Failed to read file")
680 );
681
682 let _ = tokio::fs::remove_dir_all(&dir).await;
683 }
684
685 #[tokio::test]
686 async fn file_edit_blocks_null_byte_in_path() {
687 let dir = std::env::temp_dir().join("nenjo_test_file_edit_null_byte");
688 let _ = tokio::fs::remove_dir_all(&dir).await;
689 tokio::fs::create_dir_all(&dir).await.unwrap();
690
691 let tool = FileEditTool::new(test_security(dir.clone()));
692 let result = tool
693 .execute(json!({
694 "path": "test\0evil.txt",
695 "old_string": "old",
696 "new_string": "new"
697 }))
698 .await
699 .unwrap();
700 assert!(!result.success);
701 assert!(result.error.as_ref().unwrap().contains("not allowed"));
702
703 let _ = tokio::fs::remove_dir_all(&dir).await;
704 }
705}