Skip to main content

nenjo_tools/
file_read.rs

1//! Read file contents with path sandboxing and symlink-escape protection.
2
3use crate::security::SecurityPolicy;
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use serde_json::json;
7use std::sync::Arc;
8
9const MAX_FILE_SIZE_BYTES: u64 = 10 * 1024 * 1024;
10
11/// Read file contents with path sandboxing
12pub struct FileReadTool {
13    security: Arc<SecurityPolicy>,
14}
15
16impl FileReadTool {
17    pub fn new(security: Arc<SecurityPolicy>) -> Self {
18        Self { security }
19    }
20}
21
22#[async_trait]
23impl Tool for FileReadTool {
24    fn category(&self) -> ToolCategory {
25        ToolCategory::Read
26    }
27
28    fn name(&self) -> &str {
29        "file_read"
30    }
31
32    fn description(&self) -> &str {
33        "Read the contents of a file in the workspace"
34    }
35
36    fn parameters_schema(&self) -> serde_json::Value {
37        json!({
38            "type": "object",
39            "properties": {
40                "path": {
41                    "type": "string",
42                    "description": "Relative path to the file within the workspace"
43                }
44            },
45            "required": ["path"]
46        })
47    }
48
49    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
50        let path = args
51            .get("path")
52            .and_then(|v| v.as_str())
53            .ok_or_else(|| anyhow::anyhow!("Missing 'path' parameter"))?;
54
55        if self.security.is_rate_limited() {
56            return Ok(ToolResult {
57                success: false,
58                output: String::new(),
59                error: Some("Rate limit exceeded: too many actions in the last hour".into()),
60            });
61        }
62
63        // Security check: validate path is within workspace
64        if !self.security.is_path_allowed(path) {
65            return Ok(ToolResult {
66                success: false,
67                output: String::new(),
68                error: Some(format!("Path not allowed by security policy: {path}")),
69            });
70        }
71
72        // Record action BEFORE canonicalization so that every non-trivially-rejected
73        // request consumes rate limit budget. This prevents attackers from probing
74        // path existence (via canonicalize errors) without rate limit cost.
75        if !self.security.record_action() {
76            return Ok(ToolResult {
77                success: false,
78                output: String::new(),
79                error: Some("Rate limit exceeded: action budget exhausted".into()),
80            });
81        }
82
83        let full_path = self.security.workspace_dir.join(path);
84
85        // Resolve path before reading to block symlink escapes.
86        let resolved_path = match tokio::fs::canonicalize(&full_path).await {
87            Ok(p) => p,
88            Err(e) => {
89                return Ok(ToolResult {
90                    success: false,
91                    output: String::new(),
92                    error: Some(format!("Failed to resolve file path: {e}")),
93                });
94            }
95        };
96
97        if !self.security.is_resolved_path_allowed(&resolved_path) {
98            return Ok(ToolResult {
99                success: false,
100                output: String::new(),
101                error: Some(format!(
102                    "Resolved path escapes workspace: {}",
103                    resolved_path.display()
104                )),
105            });
106        }
107
108        // Check file size AFTER canonicalization to prevent TOCTOU symlink bypass
109        match tokio::fs::metadata(&resolved_path).await {
110            Ok(meta) => {
111                if meta.len() > MAX_FILE_SIZE_BYTES {
112                    return Ok(ToolResult {
113                        success: false,
114                        output: String::new(),
115                        error: Some(format!(
116                            "File too large: {} bytes (limit: {MAX_FILE_SIZE_BYTES} bytes)",
117                            meta.len()
118                        )),
119                    });
120                }
121            }
122            Err(e) => {
123                return Ok(ToolResult {
124                    success: false,
125                    output: String::new(),
126                    error: Some(format!("Failed to read file metadata: {e}")),
127                });
128            }
129        }
130
131        match tokio::fs::read_to_string(&resolved_path).await {
132            Ok(contents) => Ok(ToolResult {
133                success: true,
134                output: contents,
135                error: None,
136            }),
137            Err(e) => Ok(ToolResult {
138                success: false,
139                output: String::new(),
140                error: Some(format!("Failed to read file: {e}")),
141            }),
142        }
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use crate::security::{AutonomyLevel, SecurityPolicy};
150
151    fn test_security(workspace: std::path::PathBuf) -> Arc<SecurityPolicy> {
152        Arc::new(SecurityPolicy {
153            autonomy: AutonomyLevel::Supervised,
154            workspace_dir: workspace,
155            ..SecurityPolicy::default()
156        })
157    }
158
159    fn test_security_with(
160        workspace: std::path::PathBuf,
161        autonomy: AutonomyLevel,
162        max_actions_per_hour: u32,
163    ) -> Arc<SecurityPolicy> {
164        Arc::new(SecurityPolicy {
165            autonomy,
166            workspace_dir: workspace,
167            max_actions_per_hour,
168            ..SecurityPolicy::default()
169        })
170    }
171
172    #[test]
173    fn file_read_name() {
174        let tool = FileReadTool::new(test_security(std::env::temp_dir()));
175        assert_eq!(tool.name(), "file_read");
176    }
177
178    #[test]
179    fn file_read_schema_has_path() {
180        let tool = FileReadTool::new(test_security(std::env::temp_dir()));
181        let schema = tool.parameters_schema();
182        assert!(schema["properties"]["path"].is_object());
183        assert!(
184            schema["required"]
185                .as_array()
186                .unwrap()
187                .contains(&json!("path"))
188        );
189    }
190
191    #[tokio::test]
192    async fn file_read_existing_file() {
193        let dir = std::env::temp_dir().join("nenjo_test_file_read");
194        let _ = tokio::fs::remove_dir_all(&dir).await;
195        tokio::fs::create_dir_all(&dir).await.unwrap();
196        tokio::fs::write(dir.join("test.txt"), "hello world")
197            .await
198            .unwrap();
199
200        let tool = FileReadTool::new(test_security(dir.clone()));
201        let result = tool.execute(json!({"path": "test.txt"})).await.unwrap();
202        assert!(result.success);
203        assert_eq!(result.output, "hello world");
204        assert!(result.error.is_none());
205
206        let _ = tokio::fs::remove_dir_all(&dir).await;
207    }
208
209    #[tokio::test]
210    async fn file_read_nonexistent_file() {
211        let dir = std::env::temp_dir().join("nenjo_test_file_read_missing");
212        let _ = tokio::fs::remove_dir_all(&dir).await;
213        tokio::fs::create_dir_all(&dir).await.unwrap();
214
215        let tool = FileReadTool::new(test_security(dir.clone()));
216        let result = tool.execute(json!({"path": "nope.txt"})).await.unwrap();
217        assert!(!result.success);
218        assert!(result.error.as_ref().unwrap().contains("Failed to resolve"));
219
220        let _ = tokio::fs::remove_dir_all(&dir).await;
221    }
222
223    #[tokio::test]
224    async fn file_read_blocks_path_traversal() {
225        let dir = std::env::temp_dir().join("nenjo_test_file_read_traversal");
226        let _ = tokio::fs::remove_dir_all(&dir).await;
227        tokio::fs::create_dir_all(&dir).await.unwrap();
228
229        let tool = FileReadTool::new(test_security(dir.clone()));
230        let result = tool
231            .execute(json!({"path": "../../../etc/passwd"}))
232            .await
233            .unwrap();
234        assert!(!result.success);
235        assert!(result.error.as_ref().unwrap().contains("not allowed"));
236
237        let _ = tokio::fs::remove_dir_all(&dir).await;
238    }
239
240    #[tokio::test]
241    async fn file_read_blocks_absolute_path() {
242        let tool = FileReadTool::new(test_security(std::env::temp_dir()));
243        let result = tool.execute(json!({"path": "/etc/passwd"})).await.unwrap();
244        assert!(!result.success);
245        assert!(result.error.as_ref().unwrap().contains("not allowed"));
246    }
247
248    #[tokio::test]
249    async fn file_read_blocks_when_rate_limited() {
250        let dir = std::env::temp_dir().join("nenjo_test_file_read_rate_limited");
251        let _ = tokio::fs::remove_dir_all(&dir).await;
252        tokio::fs::create_dir_all(&dir).await.unwrap();
253        tokio::fs::write(dir.join("test.txt"), "hello world")
254            .await
255            .unwrap();
256
257        let tool = FileReadTool::new(test_security_with(
258            dir.clone(),
259            AutonomyLevel::Supervised,
260            0,
261        ));
262        let result = tool.execute(json!({"path": "test.txt"})).await.unwrap();
263
264        assert!(!result.success);
265        assert!(
266            result
267                .error
268                .as_deref()
269                .unwrap_or("")
270                .contains("Rate limit exceeded")
271        );
272
273        let _ = tokio::fs::remove_dir_all(&dir).await;
274    }
275
276    #[tokio::test]
277    async fn file_read_allows_readonly_mode() {
278        let dir = std::env::temp_dir().join("nenjo_test_file_read_readonly");
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"), "readonly ok")
282            .await
283            .unwrap();
284
285        let tool = FileReadTool::new(test_security_with(dir.clone(), AutonomyLevel::ReadOnly, 20));
286        let result = tool.execute(json!({"path": "test.txt"})).await.unwrap();
287
288        assert!(result.success);
289        assert_eq!(result.output, "readonly ok");
290
291        let _ = tokio::fs::remove_dir_all(&dir).await;
292    }
293
294    #[tokio::test]
295    async fn file_read_missing_path_param() {
296        let tool = FileReadTool::new(test_security(std::env::temp_dir()));
297        let result = tool.execute(json!({})).await;
298        assert!(result.is_err());
299    }
300
301    #[tokio::test]
302    async fn file_read_empty_file() {
303        let dir = std::env::temp_dir().join("nenjo_test_file_read_empty");
304        let _ = tokio::fs::remove_dir_all(&dir).await;
305        tokio::fs::create_dir_all(&dir).await.unwrap();
306        tokio::fs::write(dir.join("empty.txt"), "").await.unwrap();
307
308        let tool = FileReadTool::new(test_security(dir.clone()));
309        let result = tool.execute(json!({"path": "empty.txt"})).await.unwrap();
310        assert!(result.success);
311        assert_eq!(result.output, "");
312
313        let _ = tokio::fs::remove_dir_all(&dir).await;
314    }
315
316    #[tokio::test]
317    async fn file_read_nested_path() {
318        let dir = std::env::temp_dir().join("nenjo_test_file_read_nested");
319        let _ = tokio::fs::remove_dir_all(&dir).await;
320        tokio::fs::create_dir_all(dir.join("sub/dir"))
321            .await
322            .unwrap();
323        tokio::fs::write(dir.join("sub/dir/deep.txt"), "deep content")
324            .await
325            .unwrap();
326
327        let tool = FileReadTool::new(test_security(dir.clone()));
328        let result = tool
329            .execute(json!({"path": "sub/dir/deep.txt"}))
330            .await
331            .unwrap();
332        assert!(result.success);
333        assert_eq!(result.output, "deep content");
334
335        let _ = tokio::fs::remove_dir_all(&dir).await;
336    }
337
338    #[cfg(unix)]
339    #[tokio::test]
340    async fn file_read_blocks_symlink_escape() {
341        use std::os::unix::fs::symlink;
342
343        let root = std::env::temp_dir().join("nenjo_test_file_read_symlink_escape");
344        let workspace = root.join("workspace");
345        let outside = root.join("outside");
346
347        let _ = tokio::fs::remove_dir_all(&root).await;
348        tokio::fs::create_dir_all(&workspace).await.unwrap();
349        tokio::fs::create_dir_all(&outside).await.unwrap();
350
351        tokio::fs::write(outside.join("secret.txt"), "outside workspace")
352            .await
353            .unwrap();
354
355        symlink(outside.join("secret.txt"), workspace.join("escape.txt")).unwrap();
356
357        let tool = FileReadTool::new(test_security(workspace.clone()));
358        let result = tool.execute(json!({"path": "escape.txt"})).await.unwrap();
359
360        assert!(!result.success);
361        assert!(
362            result
363                .error
364                .as_deref()
365                .unwrap_or("")
366                .contains("escapes workspace")
367        );
368
369        let _ = tokio::fs::remove_dir_all(&root).await;
370    }
371
372    #[tokio::test]
373    async fn file_read_nonexistent_consumes_rate_limit_budget() {
374        let dir = std::env::temp_dir().join("nenjo_test_file_read_probe");
375        let _ = tokio::fs::remove_dir_all(&dir).await;
376        tokio::fs::create_dir_all(&dir).await.unwrap();
377
378        // Allow only 2 actions total
379        let tool = FileReadTool::new(test_security_with(
380            dir.clone(),
381            AutonomyLevel::Supervised,
382            2,
383        ));
384
385        // Both reads fail (file doesn't exist) but should consume budget
386        let r1 = tool.execute(json!({"path": "nope1.txt"})).await.unwrap();
387        assert!(!r1.success);
388        assert!(r1.error.as_ref().unwrap().contains("Failed to resolve"));
389
390        let r2 = tool.execute(json!({"path": "nope2.txt"})).await.unwrap();
391        assert!(!r2.success);
392        assert!(r2.error.as_ref().unwrap().contains("Failed to resolve"));
393
394        // Third attempt should be rate limited even though file doesn't exist
395        let r3 = tool.execute(json!({"path": "nope3.txt"})).await.unwrap();
396        assert!(!r3.success);
397        assert!(
398            r3.error.as_ref().unwrap().contains("Rate limit"),
399            "Expected rate limit error, got: {:?}",
400            r3.error
401        );
402
403        let _ = tokio::fs::remove_dir_all(&dir).await;
404    }
405
406    #[tokio::test]
407    async fn file_read_rejects_oversized_file() {
408        let dir = std::env::temp_dir().join("nenjo_test_file_read_large");
409        let _ = tokio::fs::remove_dir_all(&dir).await;
410        tokio::fs::create_dir_all(&dir).await.unwrap();
411
412        // Create a file just over 10 MB
413        let big = vec![b'x'; 10 * 1024 * 1024 + 1];
414        tokio::fs::write(dir.join("huge.bin"), &big).await.unwrap();
415
416        let tool = FileReadTool::new(test_security(dir.clone()));
417        let result = tool.execute(json!({"path": "huge.bin"})).await.unwrap();
418        assert!(!result.success);
419        assert!(result.error.as_ref().unwrap().contains("File too large"));
420
421        let _ = tokio::fs::remove_dir_all(&dir).await;
422    }
423}