From 9d7aba95d3170f17d74a45538940dc950d8ed4b1 Mon Sep 17 00:00:00 2001 From: Daniel Kurzynski Date: Wed, 4 Nov 2026 17:42:23 +0100 Subject: [PATCH 1/3] Ask before the file tools read outside the project read_files, list_files, search_files, glob_files, view_images and view_documents refused any path leaving the project (absolute, `..`, or a symlink), whatever the permission tier. They now ask the user instead, once per call for all such paths: allow once, always for the session, or deny. A session grant covers all of these tools. Where no frontend can ask, the access is still rejected. Tools reach the session's ToolPermissions through ToolContext, and ToolContext::request_escalation asks for and remembers such grants. --- .../agent_core/src/runtime/tool_execution.rs | 3 + .../src/agent/sub_agent/tests.rs | 1 + crates/code_assistant_core/src/mocks.rs | 3 + .../src/session/permissions.rs | 33 +++ .../src/tests/format_on_save_tests.rs | 7 + .../src/tools/impls/glob_files.rs | 41 +++- .../src/tools/impls/list_files.rs | 47 +++- .../src/tools/impls/mod.rs | 1 + .../src/tools/impls/outside_project.rs | 232 ++++++++++++++++++ .../src/tools/impls/read_files.rs | 183 +++++++++++--- .../src/tools/impls/search_files.rs | 41 +++- .../src/tools/impls/view_documents.rs | 36 ++- .../src/tools/impls/view_images.rs | 43 +++- crates/fs_explorer/src/explorer.rs | 14 ++ crates/fs_explorer/src/lib.rs | 2 +- crates/mcp_client/src/tests.rs | 1 + crates/mcp_server/src/handler.rs | 1 + crates/tools_core/src/permissions.rs | 6 +- crates/tools_core/src/tool.rs | 46 +++- crates/ui_acp/src/permissions.rs | 12 + docs/permission-tiers.md | 10 + 21 files changed, 688 insertions(+), 75 deletions(-) create mode 100644 crates/code_assistant_core/src/tools/impls/outside_project.rs diff --git a/crates/agent_core/src/runtime/tool_execution.rs b/crates/agent_core/src/runtime/tool_execution.rs index f7ce7b01e..b7f53c990 100644 --- a/crates/agent_core/src/runtime/tool_execution.rs +++ b/crates/agent_core/src/runtime/tool_execution.rs @@ -12,6 +12,7 @@ struct Invocation { registry: Arc, command_executor: Arc, permission_handler: Option>, + permissions: ToolPermissions, cancellation: tools_core::RunCancellation, session_id: Option, services: Box, @@ -59,6 +60,7 @@ impl Invocation { tool_id: Some(self.request.id.clone()), session_id: self.session_id, permission_handler: self.permission_handler.as_deref(), + permissions: Some(&self.permissions), extensions: Some(self.services.as_mut()), }; // The registry is immutable for this run and was checked in prepare. @@ -320,6 +322,7 @@ impl AgentRuntime { }), tools_core::Clearance::Allowed => self.permission_handler.clone(), }, + permissions: self.permissions.clone(), cancellation: self.cancellation.clone(), session_id: self.session_id.clone(), services, diff --git a/crates/code_assistant_core/src/agent/sub_agent/tests.rs b/crates/code_assistant_core/src/agent/sub_agent/tests.rs index 089288e1c..a4459ab97 100644 --- a/crates/code_assistant_core/src/agent/sub_agent/tests.rs +++ b/crates/code_assistant_core/src/agent/sub_agent/tests.rs @@ -156,6 +156,7 @@ async fn sub_agent_tool_retains_structured_failure_output() { tool_id: Some("child".into()), session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; let mut input = SpawnAgentInput { diff --git a/crates/code_assistant_core/src/mocks.rs b/crates/code_assistant_core/src/mocks.rs index 6afbed848..b65838009 100644 --- a/crates/code_assistant_core/src/mocks.rs +++ b/crates/code_assistant_core/src/mocks.rs @@ -1089,6 +1089,7 @@ pub struct ToolTestFixture { tool_id: Option, session_id: Option, permission_handler: Option>, + permissions: tools_core::ToolPermissions, services: crate::tools::ToolServices, } @@ -1112,6 +1113,7 @@ impl ToolTestFixture { tool_id: None, session_id: None, permission_handler: None, + permissions: tools_core::ToolPermissions::default(), services, } } @@ -1322,6 +1324,7 @@ impl ToolTestFixture { tool_id: self.tool_id.clone(), session_id: self.session_id.clone(), permission_handler: self.permission_handler.as_deref(), + permissions: Some(&self.permissions), extensions: Some(&mut self.services), } } diff --git a/crates/code_assistant_core/src/session/permissions.rs b/crates/code_assistant_core/src/session/permissions.rs index bd9202b6c..9fd786a54 100644 --- a/crates/code_assistant_core/src/session/permissions.rs +++ b/crates/code_assistant_core/src/session/permissions.rs @@ -63,6 +63,23 @@ pub fn permission_options_for(reason: &PermissionRequestReason<'_>) -> Vec vec![ + PermissionOption::new( + PermissionDecision::GrantedOnce, + "Allow once", + "Read these files; ask again next time", + ), + PermissionOption::new( + PermissionDecision::GrantedSession, + "Always (session)", + "Let the agent read outside the project for the rest of this session", + ), + PermissionOption::new( + PermissionDecision::Denied, + "Deny", + "Reject the read; the agent is told not to retry", + ), + ], PermissionRequestReason::ExecuteCommand { .. } | PermissionRequestReason::ToolInvocation { .. } | PermissionRequestReason::AutoModeBlocked { .. } => vec![ @@ -158,6 +175,15 @@ impl PendingPermissionRequests { } } +/// Paths joined for a one-line summary. +fn display_paths(paths: &[std::path::PathBuf]) -> String { + paths + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join(", ") +} + /// [`PermissionMediator`] for sessions driven through [`SessionService`]: /// publishes the request on the event stream and awaits the decision from /// `respond_permission`. @@ -225,6 +251,13 @@ impl SessionPermissionMediator { "reason": reason, }), ), + PermissionRequestReason::ReadOutsideProject { paths } => ( + format!("Read outside the project: {}", display_paths(paths)), + serde_json::json!({ + "type": "read_outside_project", + "paths": paths.iter().map(|p| p.display().to_string()).collect::>(), + }), + ), PermissionRequestReason::TrustLocalMcp { project_dir, server_names, diff --git a/crates/code_assistant_core/src/tests/format_on_save_tests.rs b/crates/code_assistant_core/src/tests/format_on_save_tests.rs index cd7ef18a9..549d48433 100644 --- a/crates/code_assistant_core/src/tests/format_on_save_tests.rs +++ b/crates/code_assistant_core/src/tests/format_on_save_tests.rs @@ -194,6 +194,7 @@ async fn test_edit_tool_parameter_update_after_formatting() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -266,6 +267,7 @@ async fn test_write_file_with_format_on_save() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -335,6 +337,7 @@ async fn test_replace_in_file_with_format_on_save() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -411,6 +414,7 @@ async fn test_no_format_when_pattern_doesnt_match() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -481,6 +485,7 @@ async fn test_format_on_save_multiple_patterns() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -575,6 +580,7 @@ async fn test_format_on_save_glob_patterns() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -661,6 +667,7 @@ async fn test_format_on_save_with_conflicting_matches() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; diff --git a/crates/code_assistant_core/src/tools/impls/glob_files.rs b/crates/code_assistant_core/src/tools/impls/glob_files.rs index 845df317c..83acc6abc 100644 --- a/crates/code_assistant_core/src/tools/impls/glob_files.rs +++ b/crates/code_assistant_core/src/tools/impls/glob_files.rs @@ -84,7 +84,7 @@ impl Tool for GlobFilesTool { }, "pattern": { "type": "string", - "description": "Glob pattern to match files against. Examples: '*.rs', '**/*.json', 'src/**/*.ts'" + "description": "Glob pattern to match files against. Examples: '*.rs', '**/*.json', 'src/**/*.ts'. A pattern whose leading folders lie outside the project (absolute, or '../') matches there only after the user approves it." } }, "required": ["project", "pattern"] @@ -126,8 +126,26 @@ impl Tool for GlobFilesTool { // Get the root directory of the project let root_dir = explorer.root_dir(); + // A pattern whose leading directories leave the project (absolute, or + // `..`) matches below that folder, once the user approves it. + let (base, pattern) = split_literal_base(&input.pattern); + let (walk_root, pattern) = + match fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(&base)) { + Some(outside) => { + super::outside_project::approve_reads( + context, + "glob_files", + std::slice::from_ref(&outside), + ) + .await + .map_err(|denial| anyhow!(denial))?; + (outside, pattern) + } + None => (root_dir.clone(), input.pattern.clone()), + }; + // Find files matching the glob pattern - let files = find_files_matching_pattern(&root_dir, &input.pattern)?; + let files = find_files_matching_pattern(&walk_root, &pattern)?; // Convert absolute paths to relative paths for cleaner output let mut relative_files = Vec::new(); @@ -147,6 +165,25 @@ impl Tool for GlobFilesTool { } } +/// Split a glob pattern into its leading directories without wildcards and +/// the rest, e.g. `../other/src/**/*.rs` into `../other/src` and `**/*.rs`. +/// The last component always stays in the pattern. +fn split_literal_base(pattern: &str) -> (String, String) { + let components: Vec<&str> = pattern.split('/').collect(); + let literal = components + .iter() + .take(components.len().saturating_sub(1)) + .take_while(|c| !c.contains(['*', '?', '[', '{'])) + .count(); + let base = components[..literal].join("/"); + let base = if base.is_empty() && pattern.starts_with('/') { + "/".to_string() + } else { + base + }; + (base, components[literal..].join("/")) +} + // Helper function to find all files (text and binary) matching a glob pattern fn find_files_matching_pattern(root_dir: &std::path::Path, pattern: &str) -> Result> { use glob::{MatchOptions, Pattern}; diff --git a/crates/code_assistant_core/src/tools/impls/list_files.rs b/crates/code_assistant_core/src/tools/impls/list_files.rs index d1f1b20c7..ea060f4fc 100644 --- a/crates/code_assistant_core/src/tools/impls/list_files.rs +++ b/crates/code_assistant_core/src/tools/impls/list_files.rs @@ -104,7 +104,7 @@ impl Tool for ListFilesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Directory paths relative to project root", + "description": "Directory paths relative to project root. A path outside the project (absolute, or leading out with `..`) is listed only after the user approves it.", "items": { "type": "string" } @@ -172,20 +172,43 @@ impl Tool for ListFilesTool { // Convert max_depth from u64 to usize if present let max_depth = input.max_depth.map(|d| d as usize); + // Listing outside the project needs the user's approval, asked once + // for all such paths of this call. + let root_dir = explorer.root_dir(); + let outside_paths: Vec = input + .paths + .iter() + .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) + .collect(); + let outside_denial = + super::outside_project::approve_reads(context, "list_files", &outside_paths) + .await + .err(); + for path_str in input.paths.clone() { let path = PathBuf::from(&path_str); - // Check if path is absolute and handle it properly - if path.is_absolute() { - failed_paths.push(( - path.display().to_string(), - "Path must be relative to project root".to_string(), - )); - continue; - } - - let full_path = explorer.root_dir().join(&path); - match explorer.list_files(&full_path, max_depth).await { + let listing = match ( + fs_explorer::resolve_outside_root(&root_dir, &path), + &outside_denial, + ) { + (Some(_), Some(denial)) => { + failed_paths.push((path_str, denial.clone())); + continue; + } + // Approved: list through an explorer rooted at that folder. + (Some(outside), None) => { + let mut outside_explorer = fs_explorer::Explorer::new(outside.clone()); + fs_explorer::CodeExplorer::list_files( + &mut outside_explorer, + &outside, + max_depth, + ) + .await + } + (None, _) => explorer.list_files(&root_dir.join(&path), max_depth).await, + }; + match listing { Ok(tree_entry) => { expanded_paths.push((path, tree_entry)); } diff --git a/crates/code_assistant_core/src/tools/impls/mod.rs b/crates/code_assistant_core/src/tools/impls/mod.rs index ebb87523a..f53d4af03 100644 --- a/crates/code_assistant_core/src/tools/impls/mod.rs +++ b/crates/code_assistant_core/src/tools/impls/mod.rs @@ -12,6 +12,7 @@ pub mod list_skills; mod mcp_resources; pub mod monitor; pub mod name_session; +mod outside_project; pub mod perplexity_ask; pub mod read_files; pub mod read_skill; diff --git a/crates/code_assistant_core/src/tools/impls/outside_project.rs b/crates/code_assistant_core/src/tools/impls/outside_project.rs new file mode 100644 index 000000000..12f594247 --- /dev/null +++ b/crates/code_assistant_core/src/tools/impls/outside_project.rs @@ -0,0 +1,232 @@ +//! Reading files outside the project a file tool works in: allowed only +//! after the user approves it. + +use crate::tools::core::ToolContext; +use std::path::PathBuf; +use tools_core::PermissionRequestReason; + +/// Session grant key: an "always" answer lets every file tool read outside +/// the project for the rest of the session. +const READ_OUTSIDE_PROJECT_GRANT: &str = "read_outside_project"; + +/// Ask the user, once for all of `paths`, to let `tool_name` read them +/// outside the project. `Err` carries the message to report for each +/// refused path. +pub(crate) async fn approve_reads( + context: &mut ToolContext<'_>, + tool_name: &str, + paths: &[PathBuf], +) -> Result<(), String> { + if paths.is_empty() { + return Ok(()); + } + let mut paths = paths.to_vec(); + paths.sort(); + paths.dedup(); + match context + .request_escalation( + READ_OUTSIDE_PROJECT_GRANT, + tool_name, + PermissionRequestReason::ReadOutsideProject { paths: &paths }, + ) + .await + { + Ok(true) => Ok(()), + Ok(false) => Err( + "The user denied reading this file outside the project. Do not simply retry; \ + ask the user how to proceed." + .to_string(), + ), + Err(e) => Err(format!("Access outside project root is not allowed ({e})")), + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::mocks::ToolTestFixture; + use serde_json::json; + use std::sync::{Arc, Mutex}; + use tools_core::{PermissionDecision, PermissionMediator, PermissionRequest}; + + /// Answers every request with one decision and records the paths asked + /// about. + pub(crate) struct OutsideReadMediator { + decision: PermissionDecision, + pub(crate) asked: Mutex>>, + } + + impl OutsideReadMediator { + pub(crate) fn new(decision: PermissionDecision) -> Arc { + Arc::new(Self { + decision, + asked: Default::default(), + }) + } + } + + #[async_trait::async_trait] + impl PermissionMediator for OutsideReadMediator { + async fn request_permission( + &self, + request: PermissionRequest<'_>, + ) -> anyhow::Result { + let PermissionRequestReason::ReadOutsideProject { paths } = request.reason else { + panic!("unexpected permission request: {:?}", request.reason); + }; + self.asked.lock().unwrap().push(paths.to_vec()); + Ok(self.decision) + } + } + + /// The smallest PNG: one pixel. + const PIXEL_PNG: &[u8] = &[ + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 2, + 0, 0, 0, 144, 119, 83, 222, 0, 0, 0, 12, 73, 68, 65, 84, 120, 156, 99, 248, 207, 192, 0, 0, + 3, 1, 1, 0, 201, 254, 146, 239, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, + ]; + + /// A project folder `proj` with `inside.txt`, next to `outside.txt` and a + /// folder `other` holding `note.txt` and `pixel.png`. + pub(crate) fn outside_setup() -> (tempfile::TempDir, ToolTestFixture) { + let dir = tempfile::tempdir().unwrap(); + let project = dir.path().join("proj"); + std::fs::create_dir(&project).unwrap(); + std::fs::write(project.join("inside.txt"), "inside").unwrap(); + std::fs::write(dir.path().join("outside.txt"), "one\ntwo\nthree").unwrap(); + let other = dir.path().join("other"); + std::fs::create_dir(&other).unwrap(); + std::fs::write(other.join("note.txt"), "a needle here").unwrap(); + std::fs::write(other.join("pixel.png"), PIXEL_PNG).unwrap(); + let manager = crate::mocks::MockProjectManager::default().with_project_path( + "proj", + project.clone(), + Box::new(fs_explorer::Explorer::new(project)), + ); + (dir, ToolTestFixture::with_project_manager(manager)) + } + + /// One call per file tool, each reaching into `other`. + fn outside_calls() -> Vec<(&'static str, serde_json::Value, &'static str)> { + vec![ + ( + "read_files", + json!({"paths": ["../other/note.txt"]}), + "needle", + ), + ("list_files", json!({"paths": ["../other"]}), "note.txt"), + ( + "search_files", + json!({"regex": "needle", "paths": ["../other"]}), + "note.txt", + ), + ( + "glob_files", + json!({"pattern": "../other/*.txt"}), + "note.txt", + ), + ( + "view_images", + json!({"paths": ["../other/pixel.png"]}), + "pixel.png", + ), + ] + } + + async fn invoke( + fixture: &mut ToolTestFixture, + tool: &str, + mut params: serde_json::Value, + ) -> anyhow::Result { + params["project"] = json!("proj"); + let registry = crate::tools::test_registry(); + let result = registry + .get(tool) + .unwrap() + .invoke(&mut fixture.context(), &mut params) + .await?; + let output = result + .as_render() + .render(&mut tools_core::ResourcesTracker::new()); + anyhow::ensure!(result.is_success(), "{output}"); + Ok(output) + } + + #[tokio::test] + async fn every_file_tool_reads_outside_the_project_once_allowed() { + for (tool, params, expected) in outside_calls() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideReadMediator::new(PermissionDecision::GrantedOnce); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + let output = invoke(&mut fixture, tool, params).await.unwrap(); + + assert!(output.contains(expected), "{tool}: {output}"); + let asked = mediator.asked.lock().unwrap(); + assert_eq!(asked.len(), 1, "{tool} should ask once"); + let other = dir.path().join("other").canonicalize().unwrap(); + assert!(asked[0][0].starts_with(&other), "{tool}: {asked:?}"); + } + } + + #[tokio::test] + async fn every_file_tool_refuses_outside_the_project_when_denied() { + for (tool, params, _) in outside_calls() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideReadMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + let error = error.to_string(); + assert!(error.contains("denied"), "{tool}: {error}"); + assert!(!error.contains("needle"), "{tool}: {error}"); + } + } + + #[tokio::test] + async fn file_tools_refuse_outside_the_project_when_nobody_can_be_asked() { + for (tool, params, _) in outside_calls() { + let (_dir, mut fixture) = outside_setup(); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + assert!( + error.to_string().contains("outside project root"), + "{tool}: {error}" + ); + } + } + + #[tokio::test] + async fn a_session_grant_covers_every_file_tool() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideReadMediator::new(PermissionDecision::GrantedSession); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + for (tool, params, expected) in outside_calls() { + let output = invoke(&mut fixture, tool, params).await.unwrap(); + assert!(output.contains(expected), "{tool}: {output}"); + } + assert_eq!(mediator.asked.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn absolute_paths_inside_the_project_need_no_approval() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideReadMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + let inside = dir.path().join("proj/inside.txt"); + + let output = invoke( + &mut fixture, + "read_files", + json!({"paths": [inside.to_str().unwrap()]}), + ) + .await + .unwrap(); + + assert!(output.contains("inside")); + assert!(mediator.asked.lock().unwrap().is_empty()); + } +} diff --git a/crates/code_assistant_core/src/tools/impls/read_files.rs b/crates/code_assistant_core/src/tools/impls/read_files.rs index dc4a2f346..5468092e9 100644 --- a/crates/code_assistant_core/src/tools/impls/read_files.rs +++ b/crates/code_assistant_core/src/tools/impls/read_files.rs @@ -4,10 +4,11 @@ use crate::tools::core::{ }; use crate::tools::parse::PathWithLineRange; use anyhow::{Result, anyhow}; +use fs_explorer::CodeExplorer; use serde::{Deserialize, Serialize}; use serde_json::json; use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// Prefix each line of content with its line number. /// Format: " N | line content" where N is right-aligned based on max line number width. @@ -26,6 +27,21 @@ fn prefix_lines_with_numbers(content: &str, start_line: usize) -> String { .join("\n") } +/// Read a file, or only the requested lines of it. +async fn read_lines( + explorer: &dyn CodeExplorer, + full_path: &Path, + parsed: &PathWithLineRange, +) -> Result { + if parsed.start_line.is_some() || parsed.end_line.is_some() { + explorer + .read_file_range(full_path, parsed.start_line, parsed.end_line) + .await + } else { + explorer.read_file(full_path).await + } +} + /// Maximum file size in bytes before requiring explicit opt-in const MAX_FILE_SIZE: usize = 200 * 1024; // 200KB @@ -328,7 +344,7 @@ impl Tool for ReadFilesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to the files relative to the project root directory. Can include line ranges using 'file.txt:10-20' syntax.", + "description": "Paths to the files relative to the project root directory. Can include line ranges using 'file.txt:10-20' syntax. A path outside the project (absolute, or leading out with `..`) is read only after the user approves it.", "items": { "type": "string" } @@ -381,43 +397,51 @@ impl Tool for ReadFilesTool { let mut loaded_files = HashMap::new(); let mut failed_files = Vec::new(); - // Process each path + // Parse each path string to extract line range information, and note + // where the paths that leave the project really point. + let root = explorer.root_dir(); + let mut requests = Vec::new(); for path_str in input.paths.clone() { - // Parse the path string to extract line range information - let parsed_path = match PathWithLineRange::parse(&path_str) { - Ok(parsed) => parsed, - Err(e) => { - failed_files.push((PathBuf::from(path_str), e.to_string())); - continue; + match PathWithLineRange::parse(&path_str) { + Ok(parsed) => { + let outside = fs_explorer::resolve_outside_root(&root, &parsed.path); + requests.push((path_str, parsed, outside)); } - }; - - let path = &parsed_path.path; - - // Check for absolute paths - if path.is_absolute() { - failed_files.push((path.clone(), "Absolute paths are not allowed".to_string())); - continue; + Err(e) => failed_files.push((PathBuf::from(path_str), e.to_string())), } + } - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(path); + // Reading outside the project needs the user's approval, asked once + // for all such paths of this call. + let outside_paths: Vec = requests + .iter() + .filter_map(|(_, _, outside)| outside.clone()) + .collect(); + let outside_denial = + super::outside_project::approve_reads(context, "read_files", &outside_paths) + .await + .err(); + for (path_str, parsed_path, outside) in requests { // Determine the start line for line numbering // If a start_line is specified, use it; otherwise default to 1 let start_line = parsed_path.start_line.unwrap_or(1); - // Use either read_file_range or read_file based on whether we have line range info - let read_result = if parsed_path.start_line.is_some() || parsed_path.end_line.is_some() - { - // We have line range information, use read_file_range - explorer - .read_file_range(&full_path, parsed_path.start_line, parsed_path.end_line) - .await - } else { - // No line range specified, read the whole file - explorer.read_file(&full_path).await + let outside_explorer; + let (file_explorer, full_path) = match (&outside, &outside_denial) { + (Some(_), Some(denial)) => { + failed_files.push((PathBuf::from(&path_str), denial.clone())); + continue; + } + // Approved: read through an explorer rooted at the file's folder. + (Some(full_path), None) => { + let dir = full_path.parent().unwrap_or(full_path).to_path_buf(); + outside_explorer = fs_explorer::Explorer::new(dir); + (&outside_explorer as &dyn CodeExplorer, full_path.clone()) + } + (None, _) => (explorer.as_ref(), root.join(&parsed_path.path)), }; + let read_result = read_lines(file_explorer, &full_path, &parsed_path).await; match read_result { Ok(content) => { @@ -450,7 +474,7 @@ impl Tool for ReadFilesTool { // The agent saw the file now: a later change to it by // someone else makes its own next change fail. if has_line_range { - if let Ok(whole) = explorer.read_file(&full_path).await { + if let Ok(whole) = file_explorer.read_file(&full_path).await { context.seen_files().saw(&full_path, &whole); } } else { @@ -470,7 +494,7 @@ impl Tool for ReadFilesTool { } } - // Emit resource events for loaded files + // Emit resource events for loaded files inside the project if let Some(ui) = context.ui() { for path in loaded_files.keys() { // Get the base path without any line range information @@ -480,6 +504,9 @@ impl Tool for ReadFilesTool { } else { path.clone() }; + if fs_explorer::resolve_outside_root(&root, &base_path).is_some() { + continue; + } let _ = ui .send_event(crate::ui::UiEvent::ResourceLoaded { project: input.project.clone(), @@ -1169,4 +1196,98 @@ mod tests { Ok(()) } + + use super::super::outside_project::tests::{OutsideReadMediator, outside_setup}; + + fn read_input(paths: &[&str]) -> ReadFilesInput { + ReadFilesInput { + project: "proj".into(), + paths: paths.iter().map(|p| p.to_string()).collect(), + prefix_line_numbers: false, + ignore_size_limit: false, + } + } + + #[tokio::test] + async fn reading_outside_the_project_asks_once_and_reads_when_allowed() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideReadMediator::new(tools_core::PermissionDecision::GrantedOnce); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + let absolute = dir.path().join("outside.txt"); + let absolute = absolute.to_str().unwrap(); + let mut input = read_input(&["inside.txt", "../outside.txt:2", absolute]); + + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + + assert!(output.failed_files.is_empty(), "{:?}", output.failed_files); + assert_eq!( + output.loaded_files[&PathBuf::from("inside.txt")].content, + "inside" + ); + assert_eq!( + output.loaded_files[&PathBuf::from("../outside.txt:2")].content, + "two" + ); + assert_eq!( + output.loaded_files[&PathBuf::from(absolute)].content, + "one\ntwo\nthree" + ); + let canonical = dir.path().join("outside.txt").canonicalize().unwrap(); + assert_eq!(*mediator.asked.lock().unwrap(), vec![vec![canonical]]); + } + + #[tokio::test] + async fn denied_outside_read_fails_only_the_outside_paths() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideReadMediator::new(tools_core::PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator); + let mut input = read_input(&["inside.txt", "../outside.txt"]); + + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + + assert!( + output + .loaded_files + .contains_key(&PathBuf::from("inside.txt")) + ); + assert_eq!(output.failed_files.len(), 1); + assert!(output.failed_files[0].1.contains("denied")); + } + + #[tokio::test] + async fn outside_read_without_a_permission_handler_is_rejected() { + let (_dir, mut fixture) = outside_setup(); + let mut input = read_input(&["../outside.txt"]); + + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + + assert!(output.loaded_files.is_empty()); + assert!(output.failed_files[0].1.contains("outside project root")); + } + + #[tokio::test] + async fn session_grant_for_outside_reads_stops_asking() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideReadMediator::new(tools_core::PermissionDecision::GrantedSession); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + for _ in 0..2 { + let mut input = read_input(&["../outside.txt"]); + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + assert!(output.failed_files.is_empty(), "{:?}", output.failed_files); + } + assert_eq!(mediator.asked.lock().unwrap().len(), 1); + } } diff --git a/crates/code_assistant_core/src/tools/impls/search_files.rs b/crates/code_assistant_core/src/tools/impls/search_files.rs index 1617baefa..fe9d48f55 100644 --- a/crates/code_assistant_core/src/tools/impls/search_files.rs +++ b/crates/code_assistant_core/src/tools/impls/search_files.rs @@ -7,6 +7,7 @@ use fs_explorer::{DocumentMatchResult, SearchMode, SearchOptions, SearchResult}; use serde::{Deserialize, Serialize}; use serde_json::json; use std::collections::HashMap; +use std::path::PathBuf; // Input type for the search_files tool #[derive(Deserialize, Serialize)] @@ -413,7 +414,7 @@ impl Tool for SearchFilesTool { "items": { "type": "string" }, - "description": "Optional: Restrict search to specific paths within the project (e.g., ['src/', 'tests/']). Use with caution - only when you're certain the search should be limited to specific directories. Omitting this parameter searches the entire project, which is usually preferred to avoid missing relevant matches." + "description": "Optional: Restrict search to specific paths within the project (e.g., ['src/', 'tests/']). Use with caution - only when you're certain the search should be limited to specific directories. Omitting this parameter searches the entire project, which is usually preferred to avoid missing relevant matches. A path outside the project (absolute, or leading out with `..`) is searched only after the user approves it." } }, "required": ["project", "regex"] @@ -454,23 +455,35 @@ impl Tool for SearchFilesTool { let root_dir = explorer.root_dir(); - // Determine search paths + // Determine search paths, noting those that leave the project let search_paths = if let Some(paths) = &input.paths { // Validate and convert relative paths to absolute let mut absolute_paths = Vec::new(); for path in paths { let absolute_path = root_dir.join(path); if absolute_path.exists() { - absolute_paths.push(absolute_path); + let outside = + fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(path)); + absolute_paths.push((absolute_path, outside)); } else { return Err(anyhow!("Path not found: {path}")); } } absolute_paths } else { - vec![root_dir.clone()] + vec![(root_dir.clone(), None)] }; + // Searching outside the project needs the user's approval, asked + // once for all such paths of this call. + let outside_paths: Vec = search_paths + .iter() + .filter_map(|(_, outside)| outside.clone()) + .collect(); + super::outside_project::approve_reads(context, "search_files", &outside_paths) + .await + .map_err(|denial| anyhow!(denial))?; + // Set up search options with a reasonable initial limit let options = SearchOptions { query: input.regex.clone(), @@ -482,8 +495,24 @@ impl Tool for SearchFilesTool { // Perform searches across all specified paths let mut all_results = Vec::new(); - for search_path in search_paths { - let mut path_results = explorer.search(&search_path, options.clone()).await?; + for (search_path, outside) in search_paths { + let mut path_results = match outside { + // Approved: search through an explorer rooted at that path. + Some(outside) => { + let dir = if outside.is_dir() { + outside.clone() + } else { + outside.parent().unwrap_or(&outside).to_path_buf() + }; + fs_explorer::CodeExplorer::search( + &fs_explorer::Explorer::new(dir), + &outside, + options.clone(), + ) + .await? + } + None => explorer.search(&search_path, options.clone()).await?, + }; all_results.append(&mut path_results); } diff --git a/crates/code_assistant_core/src/tools/impls/view_documents.rs b/crates/code_assistant_core/src/tools/impls/view_documents.rs index 9c1fd4b4c..14e720520 100644 --- a/crates/code_assistant_core/src/tools/impls/view_documents.rs +++ b/crates/code_assistant_core/src/tools/impls/view_documents.rs @@ -32,10 +32,6 @@ fn document_format_for_extension(ext: &str) -> Option<&'static str> { /// Resolve a path relative to the project root and verify it stays within bounds. fn resolve_project_path(root_dir: &std::path::Path, rel_path: &std::path::Path) -> Result { - if rel_path.is_absolute() { - anyhow::bail!("Absolute paths are not allowed"); - } - let candidate = root_dir.join(rel_path); let canonical = candidate @@ -182,7 +178,7 @@ impl Tool for ViewDocumentsTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to document files relative to the project root directory", + "description": "Paths to document files relative to the project root directory. A path outside the project (absolute, or leading out with `..`) is read only after the user approves it.", "items": { "type": "string" } @@ -227,6 +223,18 @@ impl Tool for ViewDocumentsTool { let mut converted_documents = Vec::new(); let mut failed_documents = Vec::new(); let root_dir = explorer.root_dir(); + + // Reading outside the project needs the user's approval, asked once + // for all such paths of this call. + let outside_paths: Vec = input + .paths + .iter() + .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) + .collect(); + let outside_denial = + super::outside_project::approve_reads(context, "view_documents", &outside_paths) + .await + .err(); let mut total_output_chars: usize = 0; for path_str in &input.paths { @@ -258,12 +266,22 @@ impl Tool for ViewDocumentsTool { }; // Resolve and validate the path - let full_path = match resolve_project_path(&root_dir, &path) { - Ok(p) => p, - Err(e) => { - failed_documents.push((path_str.clone(), e.to_string())); + let full_path = match ( + fs_explorer::resolve_outside_root(&root_dir, &path), + &outside_denial, + ) { + (Some(_), Some(denial)) => { + failed_documents.push((path_str.clone(), denial.clone())); continue; } + (Some(outside), None) => outside, + (None, _) => match resolve_project_path(&root_dir, &path) { + Ok(p) => p, + Err(e) => { + failed_documents.push((path_str.clone(), e.to_string())); + continue; + } + }, }; // Check file size before reading diff --git a/crates/code_assistant_core/src/tools/impls/view_images.rs b/crates/code_assistant_core/src/tools/impls/view_images.rs index cdff65fdb..2cdf04e27 100644 --- a/crates/code_assistant_core/src/tools/impls/view_images.rs +++ b/crates/code_assistant_core/src/tools/impls/view_images.rs @@ -28,13 +28,10 @@ fn mime_type_for_extension(ext: &str) -> Option<&'static str> { } /// Resolve a path relative to the project root and verify it stays within bounds. -/// Returns the resolved absolute path. Rejects absolute paths, `..` traversals -/// that escape the root, and symlinks pointing outside the project. +/// Returns the resolved absolute path. Rejects `..` traversals +/// that escape the root, and symlinks pointing outside the project; those +/// are read only after the user approves them (see `outside_project`). fn resolve_project_path(root_dir: &std::path::Path, rel_path: &std::path::Path) -> Result { - if rel_path.is_absolute() { - anyhow::bail!("Absolute paths are not allowed"); - } - let candidate = root_dir.join(rel_path); // Canonicalize to resolve symlinks and .. components. @@ -197,7 +194,7 @@ impl Tool for ViewImagesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to image files relative to the project root directory", + "description": "Paths to image files relative to the project root directory. A path outside the project (absolute, or leading out with `..`) is read only after the user approves it.", "items": { "type": "string" } @@ -243,6 +240,18 @@ impl Tool for ViewImagesTool { let mut failed_images = Vec::new(); let root_dir = explorer.root_dir(); + // Reading outside the project needs the user's approval, asked once + // for all such paths of this call. + let outside_paths: Vec = input + .paths + .iter() + .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) + .collect(); + let outside_denial = + super::outside_project::approve_reads(context, "view_images", &outside_paths) + .await + .err(); + for path_str in &input.paths { let path = PathBuf::from(path_str); @@ -272,12 +281,22 @@ impl Tool for ViewImagesTool { }; // Resolve and validate the path stays within the project root - let full_path = match resolve_project_path(&root_dir, &path) { - Ok(p) => p, - Err(e) => { - failed_images.push((path_str.clone(), e.to_string())); + let full_path = match ( + fs_explorer::resolve_outside_root(&root_dir, &path), + &outside_denial, + ) { + (Some(_), Some(denial)) => { + failed_images.push((path_str.clone(), denial.clone())); continue; } + (Some(outside), None) => outside, + (None, _) => match resolve_project_path(&root_dir, &path) { + Ok(p) => p, + Err(e) => { + failed_images.push((path_str.clone(), e.to_string())); + continue; + } + }, }; // Read the raw bytes @@ -534,7 +553,7 @@ mod tests { let mut tracker = ResourcesTracker::new(); let output = result.as_render().render(&mut tracker); - assert!(output.contains("Absolute paths are not allowed")); + assert!(output.contains("Access outside project root is not allowed")); Ok(()) } diff --git a/crates/fs_explorer/src/explorer.rs b/crates/fs_explorer/src/explorer.rs index 82e60b1a2..206daf809 100644 --- a/crates/fs_explorer/src/explorer.rs +++ b/crates/fs_explorer/src/explorer.rs @@ -400,6 +400,20 @@ impl Explorer { } } +/// Where `path` (relative to `root`, or absolute) really points when that +/// lies outside `root`, following symlinks. `None` when it stays inside, or +/// when it cannot be resolved (reading it then fails as usual). +pub fn resolve_outside_root(root: &Path, path: &Path) -> Option { + let root = root.canonicalize().unwrap_or_else(|_| root.clean()); + let candidate = if path.is_absolute() { + path.to_path_buf() + } else { + root.join(path) + }; + let canonical = canonicalize_with_existing_parent(&candidate.clean()).ok()?; + (!canonical.starts_with(&root)).then_some(canonical) +} + fn canonicalize_with_existing_parent(path: &Path) -> std::io::Result { if path.exists() { return path.canonicalize(); diff --git a/crates/fs_explorer/src/lib.rs b/crates/fs_explorer/src/lib.rs index f6e5170ee..544335f8e 100644 --- a/crates/fs_explorer/src/lib.rs +++ b/crates/fs_explorer/src/lib.rs @@ -8,6 +8,6 @@ pub mod locks; pub mod types; pub mod watch; -pub use explorer::{Explorer, is_path_gitignored}; +pub use explorer::{Explorer, is_path_gitignored, resolve_outside_root}; pub use file_updater::*; pub use types::*; diff --git a/crates/mcp_client/src/tests.rs b/crates/mcp_client/src/tests.rs index 186828940..c47f23776 100644 --- a/crates/mcp_client/src/tests.rs +++ b/crates/mcp_client/src/tests.rs @@ -129,6 +129,7 @@ fn test_context() -> ToolContext<'static> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: None, } } diff --git a/crates/mcp_server/src/handler.rs b/crates/mcp_server/src/handler.rs index 94f47fe43..ef7cc52b8 100644 --- a/crates/mcp_server/src/handler.rs +++ b/crates/mcp_server/src/handler.rs @@ -273,6 +273,7 @@ impl MessageHandler { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; diff --git a/crates/tools_core/src/permissions.rs b/crates/tools_core/src/permissions.rs index 54053ba3c..7bd35c992 100644 --- a/crates/tools_core/src/permissions.rs +++ b/crates/tools_core/src/permissions.rs @@ -5,7 +5,7 @@ use anyhow::Result; use async_trait::async_trait; use serde::{Deserialize, Serialize}; use std::collections::HashSet; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; /// When to ask the user for permission before running a tool. @@ -251,6 +251,10 @@ pub enum PermissionRequestReason<'a> { params: &'a serde_json::Value, reason: &'a str, }, + /// A tool wants to read files outside the project it works in. Asked + /// independently of the tier, since the project root is the boundary + /// the file tools otherwise enforce. + ReadOutsideProject { paths: &'a [PathBuf] }, /// Approve loading a project's local `.mcp.json`, which launches the MCP /// servers it defines — i.e. runs project-supplied commands. Not tied to a /// tool invocation; raised before a project's registry is built. diff --git a/crates/tools_core/src/tool.rs b/crates/tools_core/src/tool.rs index a910778c6..d406afb7d 100644 --- a/crates/tools_core/src/tool.rs +++ b/crates/tools_core/src/tool.rs @@ -1,7 +1,10 @@ use super::render::Render; use super::result::ToolResult; use super::spec::ToolSpec; -use crate::permissions::PermissionMediator; +use crate::permissions::{ + PermissionDecision, PermissionMediator, PermissionRequest, PermissionRequestReason, + ToolPermissions, +}; use anyhow::{Result, anyhow}; use command_executor::CommandExecutor; use serde::{Deserialize, Serialize, de::DeserializeOwned}; @@ -22,6 +25,9 @@ pub struct ToolContext<'a> { pub session_id: Option, /// Optional permission handler for potentially sensitive operations pub permission_handler: Option<&'a dyn PermissionMediator>, + /// The session's permission state, for tools that ask for escalations + /// of their own and remember an "always (session)" answer. + pub permissions: Option<&'a ToolPermissions>, /// Application-specific services for tools that need more than the fields /// above. Tools downcast this to the concrete type they were registered /// with, keeping the context itself application-agnostic. @@ -42,6 +48,44 @@ impl<'a> ToolContext<'a> { .as_deref_mut() .and_then(|ext| ext.downcast_mut::()) } + + /// Ask the user for an escalation a tool needs regardless of the tier + /// (e.g. reading outside the project). An "always (session)" answer is + /// remembered under `grant_key`, so later requests pass without asking. + /// + /// Returns whether the escalation was granted, or an error when this + /// frontend cannot ask the user. `&mut` for `Send`: the context is not + /// `Sync`. + pub async fn request_escalation( + &mut self, + grant_key: &str, + tool_name: &str, + reason: PermissionRequestReason<'_>, + ) -> Result { + if self.permissions.is_some_and(|p| p.is_granted(grant_key)) { + return Ok(true); + } + let handler = self + .permission_handler + .ok_or_else(|| anyhow!("This frontend cannot ask the user for permission"))?; + let decision = handler + .request_permission(PermissionRequest { + tool_id: self.tool_id.as_deref(), + tool_name, + reason, + }) + .await?; + Ok(match decision { + PermissionDecision::Denied => false, + PermissionDecision::GrantedOnce => true, + PermissionDecision::GrantedSession | PermissionDecision::GrantedPersistent => { + if let Some(permissions) = self.permissions { + permissions.grant(grant_key); + } + true + } + }) + } } /// Core trait for tools, defining the execution interface diff --git a/crates/ui_acp/src/permissions.rs b/crates/ui_acp/src/permissions.rs index 63fd0a32f..099b6c474 100644 --- a/crates/ui_acp/src/permissions.rs +++ b/crates/ui_acp/src/permissions.rs @@ -107,6 +107,14 @@ impl AcpPermissionMediator { serde_json::to_string_pretty(params).unwrap_or_else(|_| params.to_string()) ) } + PermissionRequestReason::ReadOutsideProject { paths } => format!( + "Read files outside the project:\n{}", + paths + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join("\n") + ), PermissionRequestReason::TrustLocalMcp { project_dir, server_names, @@ -141,6 +149,10 @@ impl AcpPermissionMediator { "params": params, "reason": reason, }), + PermissionRequestReason::ReadOutsideProject { paths } => json!({ + "type": "read_outside_project", + "paths": paths.iter().map(|p| p.display().to_string()).collect::>(), + }), PermissionRequestReason::TrustLocalMcp { project_dir, server_names, diff --git a/docs/permission-tiers.md b/docs/permission-tiers.md index 186ce37da..c13f67bfc 100644 --- a/docs/permission-tiers.md +++ b/docs/permission-tiers.md @@ -96,6 +96,16 @@ parent gave them. `ask_user_approval` (sandbox bypass) keeps using the mediator directly, independent of the tier — except under `auto`, where a call the reviewer allowed gets its escalation granted (see above). +- **Reading outside the project**: the file tools (`read_files`, + `list_files`, `search_files`, `glob_files`, `view_images`, + `view_documents`) ask before reaching a path that leads out of the + project (absolute, `..`, or a symlink), in every tier including + `bypass-all` — one prompt per call for all such paths + (`PermissionRequestReason::ReadOutsideProject`, shared helper + `tools::impls::outside_project`). *Always (session)* covers all of these + tools and is remembered in the session's `ToolPermissions` (reached by + tools through `ToolContext::request_escalation`). Without a mediator the + access is rejected as before. Writing tools stay confined to the project. ## Frontend surfaces From f7c142770f5dec94047e23b56f5515d7bfd91205 Mon Sep 17 00:00:00 2001 From: Daniel Kurzynski Date: Wed, 4 Nov 2026 17:53:31 +0100 Subject: [PATCH 2/3] Ask before the file tools write outside the project write_file, edit, replace_in_file and delete_files refused any path leaving the project. Like the reading tools, they now ask the user instead. Reads and writes are asked and granted separately: the permission reason is now OutsideProject with a FileAccess of Read or Write, and a session grant for reads does not allow writes. Files written outside the project get no format-on-save (its command runs in the project) and no resource events. --- .../src/session/permissions.rs | 50 ++-- .../src/tools/impls/delete_files.rs | 55 +++-- .../src/tools/impls/edit.rs | 40 +-- .../src/tools/impls/glob_files.rs | 3 +- .../src/tools/impls/list_files.rs | 12 +- .../src/tools/impls/outside_project.rs | 229 ++++++++++++++++-- .../src/tools/impls/read_files.rs | 20 +- .../src/tools/impls/replace_in_file.rs | 42 ++-- .../src/tools/impls/search_files.rs | 11 +- .../src/tools/impls/view_documents.rs | 12 +- .../src/tools/impls/view_images.rs | 12 +- .../src/tools/impls/write_file.rs | 39 +-- crates/tools_core/src/lib.rs | 6 +- crates/tools_core/src/permissions.rs | 36 ++- crates/ui_acp/src/permissions.rs | 10 +- docs/permission-tiers.md | 23 +- 16 files changed, 443 insertions(+), 157 deletions(-) diff --git a/crates/code_assistant_core/src/session/permissions.rs b/crates/code_assistant_core/src/session/permissions.rs index 9fd786a54..f0637779e 100644 --- a/crates/code_assistant_core/src/session/permissions.rs +++ b/crates/code_assistant_core/src/session/permissions.rs @@ -63,23 +63,28 @@ pub fn permission_options_for(reason: &PermissionRequestReason<'_>) -> Vec vec![ - PermissionOption::new( - PermissionDecision::GrantedOnce, - "Allow once", - "Read these files; ask again next time", - ), - PermissionOption::new( - PermissionDecision::GrantedSession, - "Always (session)", - "Let the agent read outside the project for the rest of this session", - ), - PermissionOption::new( - PermissionDecision::Denied, - "Deny", - "Reject the read; the agent is told not to retry", - ), - ], + PermissionRequestReason::OutsideProject { access, .. } => { + let verb = access.verb(); + vec![ + PermissionOption::new( + PermissionDecision::GrantedOnce, + "Allow once", + &format!("Allow this {verb}; ask again next time"), + ), + PermissionOption::new( + PermissionDecision::GrantedSession, + "Always (session)", + &format!( + "Let the agent {verb} outside the project for the rest of this session" + ), + ), + PermissionOption::new( + PermissionDecision::Denied, + "Deny", + &format!("Reject the {verb}; the agent is told not to retry"), + ), + ] + } PermissionRequestReason::ExecuteCommand { .. } | PermissionRequestReason::ToolInvocation { .. } | PermissionRequestReason::AutoModeBlocked { .. } => vec![ @@ -251,10 +256,15 @@ impl SessionPermissionMediator { "reason": reason, }), ), - PermissionRequestReason::ReadOutsideProject { paths } => ( - format!("Read outside the project: {}", display_paths(paths)), + PermissionRequestReason::OutsideProject { access, paths } => ( + format!( + "{} outside the project: {}", + access.label(), + display_paths(paths) + ), serde_json::json!({ - "type": "read_outside_project", + "type": "outside_project", + "access": access.verb(), "paths": paths.iter().map(|p| p.display().to_string()).collect::>(), }), ), diff --git a/crates/code_assistant_core/src/tools/impls/delete_files.rs b/crates/code_assistant_core/src/tools/impls/delete_files.rs index 0fe6ae42c..d9e36b459 100644 --- a/crates/code_assistant_core/src/tools/impls/delete_files.rs +++ b/crates/code_assistant_core/src/tools/impls/delete_files.rs @@ -110,7 +110,7 @@ impl Tool for DeleteFilesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to the files relative to the project root directory", + "description": "Paths to the files relative to the project root directory. A path outside the project (absolute, or leading out with `..`) is deleted only after the user approves it.", "items": { "type": "string" } @@ -159,17 +159,39 @@ impl Tool for DeleteFilesTool { let mut deleted_contents = Vec::new(); // Process each path + // Deleting outside the project needs the user's approval, asked once + // for all such paths of this call. + let root_dir = explorer.root_dir(); + let outside_paths: Vec = input + .paths + .iter() + .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) + .collect(); + let outside_denial = super::outside_project::approve( + context, + "delete_files", + tools_core::FileAccess::Write, + &outside_paths, + ) + .await + .err(); + for path_str in input.paths.clone() { let path = PathBuf::from(&path_str); - // Check for absolute paths - if path.is_absolute() { - failed.push((path.clone(), "Absolute paths are not allowed".to_string())); - continue; - } - - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(&path); + let outside = fs_explorer::resolve_outside_root(&root_dir, &path); + let outside_explorer; + let (explorer, full_path) = match (&outside, &outside_denial) { + (Some(_), Some(denial)) => { + failed.push((path, denial.clone())); + continue; + } + (Some(outside), None) => { + outside_explorer = super::outside_project::explorer_for(outside); + (outside_explorer.as_ref(), outside.clone()) + } + (None, _) => (explorer.as_ref(), root_dir.join(&path)), + }; // Capture the content before deletion (best effort; binary or // unreadable files simply render without a diff) @@ -178,11 +200,7 @@ impl Tool for DeleteFilesTool { // Delete the file, unless it changed since this agent last saw it match context .seen_files() - .change( - explorer.as_ref(), - &full_path, - explorer.delete_file(&full_path), - ) + .change(explorer, &full_path, explorer.delete_file(&full_path)) .await { Ok(_) => { @@ -191,8 +209,8 @@ impl Tool for DeleteFilesTool { deleted_contents.push((path.clone(), content)); } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let Some(ui) = context.ui().filter(|_| outside.is_none()) { let _ = ui .send_event(crate::ui::UiEvent::ResourceDeleted { project: input.project.clone(), @@ -352,10 +370,11 @@ mod tests { .find(|(path, _)| path == &PathBuf::from("non-existing.txt")); assert!(non_existing.is_some()); - // One failure should be the absolute path + // One failure should be the path outside the project, since nobody + // can approve deleting it let absolute_path = result.failed.iter().find(|(path, error)| { path == &PathBuf::from("/absolute/path.txt") - && error.contains("Absolute paths are not allowed") + && error.contains("Access outside project root is not allowed") }); assert!(absolute_path.is_some()); diff --git a/crates/code_assistant_core/src/tools/impls/edit.rs b/crates/code_assistant_core/src/tools/impls/edit.rs index 974271b15..9d78d2c4f 100644 --- a/crates/code_assistant_core/src/tools/impls/edit.rs +++ b/crates/code_assistant_core/src/tools/impls/edit.rs @@ -114,7 +114,7 @@ impl Tool for EditTool { "path": { "examples": ["File path here"], "type": "string", - "description": "Path to the file to modify (relative to project root)" + "description": "Path to the file to modify (relative to project root). A path outside the project (absolute, or leading out with `..`) is written only after the user approves it." }, "old_text": { "type": "string", @@ -171,21 +171,22 @@ impl Tool for EditTool { .get_project(&input.project)? .ok_or_else(|| anyhow!("Project not found: {}", input.project))?; - // Check for absolute path + // A path outside the project is edited only once the user approves. let path = PathBuf::from(&input.path); - if path.is_absolute() { - return Ok(EditOutput { - project: input.project.clone(), - path, - error: Some(FileUpdaterError::Other( - "Absolute paths are not allowed".to_string(), - )), - match_start_lines: Vec::new(), - }); - } - - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(&path); + let target = + match super::outside_project::write_target(context, "edit", explorer, &path).await { + Ok(target) => target, + Err(error) => { + return Ok(EditOutput { + project: input.project.clone(), + path, + error: Some(FileUpdaterError::Other(error)), + match_start_lines: Vec::new(), + }); + } + }; + let explorer = target.explorer; + let full_path = target.full_path; // Create a FileReplacement from the input let replacements = [FileReplacement { @@ -204,7 +205,10 @@ impl Tool for EditTool { // Apply with or without formatting, based on project configuration, // unless the file changed since this agent last saw it. let apply = async { - if let Some(format_command) = project_config.format_command_for(&path) { + if let Some(format_command) = project_config + .format_command_for(&path) + .filter(|_| !target.outside) + { explorer .apply_replacements_with_formatting( &full_path, @@ -236,8 +240,8 @@ impl Tool for EditTool { input.replace_all = updated_replacement.replace_all; } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let Some(ui) = context.ui().filter(|_| !target.outside) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), diff --git a/crates/code_assistant_core/src/tools/impls/glob_files.rs b/crates/code_assistant_core/src/tools/impls/glob_files.rs index 83acc6abc..072dafcd7 100644 --- a/crates/code_assistant_core/src/tools/impls/glob_files.rs +++ b/crates/code_assistant_core/src/tools/impls/glob_files.rs @@ -132,9 +132,10 @@ impl Tool for GlobFilesTool { let (walk_root, pattern) = match fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(&base)) { Some(outside) => { - super::outside_project::approve_reads( + super::outside_project::approve( context, "glob_files", + tools_core::FileAccess::Read, std::slice::from_ref(&outside), ) .await diff --git a/crates/code_assistant_core/src/tools/impls/list_files.rs b/crates/code_assistant_core/src/tools/impls/list_files.rs index ea060f4fc..f24efe948 100644 --- a/crates/code_assistant_core/src/tools/impls/list_files.rs +++ b/crates/code_assistant_core/src/tools/impls/list_files.rs @@ -180,10 +180,14 @@ impl Tool for ListFilesTool { .iter() .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) .collect(); - let outside_denial = - super::outside_project::approve_reads(context, "list_files", &outside_paths) - .await - .err(); + let outside_denial = super::outside_project::approve( + context, + "list_files", + tools_core::FileAccess::Read, + &outside_paths, + ) + .await + .err(); for path_str in input.paths.clone() { let path = PathBuf::from(&path_str); diff --git a/crates/code_assistant_core/src/tools/impls/outside_project.rs b/crates/code_assistant_core/src/tools/impls/outside_project.rs index 12f594247..62fcc3eb3 100644 --- a/crates/code_assistant_core/src/tools/impls/outside_project.rs +++ b/crates/code_assistant_core/src/tools/impls/outside_project.rs @@ -1,20 +1,25 @@ -//! Reading files outside the project a file tool works in: allowed only +//! Files outside the project a file tool works in: read or written only //! after the user approves it. use crate::tools::core::ToolContext; -use std::path::PathBuf; -use tools_core::PermissionRequestReason; +use fs_explorer::CodeExplorer; +use std::path::{Path, PathBuf}; +use tools_core::{FileAccess, PermissionRequestReason}; -/// Session grant key: an "always" answer lets every file tool read outside -/// the project for the rest of the session. -const READ_OUTSIDE_PROJECT_GRANT: &str = "read_outside_project"; +/// Session grant key: an "always" answer lets every file tool read (or +/// write) outside the project for the rest of the session. Reads and writes +/// are granted separately. +fn grant_key(access: FileAccess) -> String { + format!("{}_outside_project", access.verb()) +} -/// Ask the user, once for all of `paths`, to let `tool_name` read them -/// outside the project. `Err` carries the message to report for each +/// Ask the user, once for all of `paths`, to let `tool_name` read or write +/// them outside the project. `Err` carries the message to report for each /// refused path. -pub(crate) async fn approve_reads( +pub(crate) async fn approve( context: &mut ToolContext<'_>, tool_name: &str, + access: FileAccess, paths: &[PathBuf], ) -> Result<(), String> { if paths.is_empty() { @@ -25,22 +30,75 @@ pub(crate) async fn approve_reads( paths.dedup(); match context .request_escalation( - READ_OUTSIDE_PROJECT_GRANT, + &grant_key(access), tool_name, - PermissionRequestReason::ReadOutsideProject { paths: &paths }, + PermissionRequestReason::OutsideProject { + access, + paths: &paths, + }, ) .await { Ok(true) => Ok(()), - Ok(false) => Err( - "The user denied reading this file outside the project. Do not simply retry; \ - ask the user how to proceed." - .to_string(), - ), + Ok(false) => Err(format!( + "The user denied the {} outside the project. Do not simply retry; \ + ask the user how to proceed.", + access.verb() + )), Err(e) => Err(format!("Access outside project root is not allowed ({e})")), } } +/// Where a file tool writes a file: inside the project, or outside it. +pub(crate) struct WriteTarget { + pub explorer: Box, + pub full_path: PathBuf, + /// Outside the project: no format-on-save, no resource events. + pub outside: bool, +} + +/// Where `tool_name` writes `path`: inside the project through `explorer`, +/// or — once the user approves — outside it through an explorer rooted at +/// the file's folder. `Err` carries the message for a refused path. +pub(crate) async fn write_target( + context: &mut ToolContext<'_>, + tool_name: &str, + explorer: Box, + path: &Path, +) -> Result { + let root = explorer.root_dir(); + let Some(outside) = fs_explorer::resolve_outside_root(&root, path) else { + return Ok(WriteTarget { + explorer, + full_path: root.join(path), + outside: false, + }); + }; + approve( + context, + tool_name, + FileAccess::Write, + std::slice::from_ref(&outside), + ) + .await?; + Ok(WriteTarget { + explorer: explorer_for(&outside), + full_path: outside, + outside: true, + }) +} + +/// An explorer for a path outside the project: rooted at the path itself +/// when it is a folder, else at its parent. +pub(crate) fn explorer_for(path: &Path) -> Box { + let dir = if path.is_dir() { + path + } else { + path.parent().unwrap_or(path) + }; + Box::new(fs_explorer::Explorer::new(dir.to_path_buf())) +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -51,30 +109,33 @@ pub(crate) mod tests { /// Answers every request with one decision and records the paths asked /// about. - pub(crate) struct OutsideReadMediator { + pub(crate) struct OutsideAccessMediator { decision: PermissionDecision, pub(crate) asked: Mutex>>, + pub(crate) accesses: Mutex>, } - impl OutsideReadMediator { + impl OutsideAccessMediator { pub(crate) fn new(decision: PermissionDecision) -> Arc { Arc::new(Self { decision, asked: Default::default(), + accesses: Default::default(), }) } } #[async_trait::async_trait] - impl PermissionMediator for OutsideReadMediator { + impl PermissionMediator for OutsideAccessMediator { async fn request_permission( &self, request: PermissionRequest<'_>, ) -> anyhow::Result { - let PermissionRequestReason::ReadOutsideProject { paths } = request.reason else { + let PermissionRequestReason::OutsideProject { access, paths } = request.reason else { panic!("unexpected permission request: {:?}", request.reason); }; self.asked.lock().unwrap().push(paths.to_vec()); + self.accesses.lock().unwrap().push(access); Ok(self.decision) } } @@ -156,7 +217,7 @@ pub(crate) mod tests { async fn every_file_tool_reads_outside_the_project_once_allowed() { for (tool, params, expected) in outside_calls() { let (dir, fixture) = outside_setup(); - let mediator = OutsideReadMediator::new(PermissionDecision::GrantedOnce); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedOnce); let mut fixture = fixture.with_permission_handler(mediator.clone()); let output = invoke(&mut fixture, tool, params).await.unwrap(); @@ -173,7 +234,7 @@ pub(crate) mod tests { async fn every_file_tool_refuses_outside_the_project_when_denied() { for (tool, params, _) in outside_calls() { let (_dir, fixture) = outside_setup(); - let mediator = OutsideReadMediator::new(PermissionDecision::Denied); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); let mut fixture = fixture.with_permission_handler(mediator); let error = invoke(&mut fixture, tool, params).await.unwrap_err(); @@ -201,7 +262,7 @@ pub(crate) mod tests { #[tokio::test] async fn a_session_grant_covers_every_file_tool() { let (_dir, fixture) = outside_setup(); - let mediator = OutsideReadMediator::new(PermissionDecision::GrantedSession); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedSession); let mut fixture = fixture.with_permission_handler(mediator.clone()); for (tool, params, expected) in outside_calls() { @@ -214,7 +275,7 @@ pub(crate) mod tests { #[tokio::test] async fn absolute_paths_inside_the_project_need_no_approval() { let (dir, fixture) = outside_setup(); - let mediator = OutsideReadMediator::new(PermissionDecision::Denied); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); let mut fixture = fixture.with_permission_handler(mediator.clone()); let inside = dir.path().join("proj/inside.txt"); @@ -229,4 +290,124 @@ pub(crate) mod tests { assert!(output.contains("inside")); assert!(mediator.asked.lock().unwrap().is_empty()); } + + /// One call per writing tool, each changing something in `other`, with + /// a check of the result on disk. + #[allow(clippy::type_complexity)] + fn outside_writes() -> Vec<(&'static str, serde_json::Value, fn(&Path) -> bool)> { + vec![ + ( + "write_file", + json!({"path": "../other/new.txt", "content": "written"}), + |other| { + std::fs::read_to_string(other.join("new.txt")) + .is_ok_and(|content| content.trim_end() == "written") + }, + ), + ( + "edit", + json!({"path": "../other/note.txt", "old_text": "needle", "new_text": "pin"}), + |other| { + std::fs::read_to_string(other.join("note.txt")) + .unwrap() + .trim_end() + == "a pin here" + }, + ), + ( + "replace_in_file", + json!({ + "path": "../other/note.txt", + "diff": "<<<<<<< SEARCH\nneedle\n=======\npin\n>>>>>>> REPLACE" + }), + |other| { + std::fs::read_to_string(other.join("note.txt")) + .unwrap() + .trim_end() + == "a pin here" + }, + ), + ( + "delete_files", + json!({"paths": ["../other/note.txt"]}), + |other| !other.join("note.txt").exists(), + ), + ] + } + + #[tokio::test] + async fn every_writing_tool_writes_outside_the_project_once_allowed() { + for (tool, params, written) in outside_writes() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedOnce); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + invoke(&mut fixture, tool, params).await.unwrap(); + + assert!(written(&dir.path().join("other")), "{tool} did not write"); + assert_eq!( + *mediator.accesses.lock().unwrap(), + vec![FileAccess::Write], + "{tool}" + ); + } + } + + #[tokio::test] + async fn every_writing_tool_leaves_outside_files_alone_when_denied() { + for (tool, params, written) in outside_writes() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + assert!(error.to_string().contains("denied"), "{tool}: {error}"); + assert!(!written(&dir.path().join("other")), "{tool} wrote anyway"); + assert_eq!( + std::fs::read_to_string(dir.path().join("other/note.txt")).unwrap(), + "a needle here" + ); + } + } + + #[tokio::test] + async fn writing_tools_refuse_outside_the_project_when_nobody_can_be_asked() { + for (tool, params, written) in outside_writes() { + let (dir, mut fixture) = outside_setup(); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + assert!( + error.to_string().contains("outside project root"), + "{tool}: {error}" + ); + assert!(!written(&dir.path().join("other")), "{tool} wrote anyway"); + } + } + + #[tokio::test] + async fn a_session_grant_for_reads_does_not_allow_writes() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedSession); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + let read = json!({"paths": ["../other/note.txt"]}); + invoke(&mut fixture, "read_files", read.clone()) + .await + .unwrap(); + let write = json!({"path": "../other/new.txt", "content": "written"}); + invoke(&mut fixture, "write_file", write.clone()) + .await + .unwrap(); + // Both grants are remembered now: neither asks again. + invoke(&mut fixture, "read_files", read).await.unwrap(); + invoke(&mut fixture, "write_file", write).await.unwrap(); + + assert_eq!( + *mediator.accesses.lock().unwrap(), + vec![FileAccess::Read, FileAccess::Write] + ); + assert!(dir.path().join("other/new.txt").exists()); + } } diff --git a/crates/code_assistant_core/src/tools/impls/read_files.rs b/crates/code_assistant_core/src/tools/impls/read_files.rs index 5468092e9..bfe439976 100644 --- a/crates/code_assistant_core/src/tools/impls/read_files.rs +++ b/crates/code_assistant_core/src/tools/impls/read_files.rs @@ -417,10 +417,14 @@ impl Tool for ReadFilesTool { .iter() .filter_map(|(_, _, outside)| outside.clone()) .collect(); - let outside_denial = - super::outside_project::approve_reads(context, "read_files", &outside_paths) - .await - .err(); + let outside_denial = super::outside_project::approve( + context, + "read_files", + tools_core::FileAccess::Read, + &outside_paths, + ) + .await + .err(); for (path_str, parsed_path, outside) in requests { // Determine the start line for line numbering @@ -1197,7 +1201,7 @@ mod tests { Ok(()) } - use super::super::outside_project::tests::{OutsideReadMediator, outside_setup}; + use super::super::outside_project::tests::{OutsideAccessMediator, outside_setup}; fn read_input(paths: &[&str]) -> ReadFilesInput { ReadFilesInput { @@ -1211,7 +1215,7 @@ mod tests { #[tokio::test] async fn reading_outside_the_project_asks_once_and_reads_when_allowed() { let (dir, fixture) = outside_setup(); - let mediator = OutsideReadMediator::new(tools_core::PermissionDecision::GrantedOnce); + let mediator = OutsideAccessMediator::new(tools_core::PermissionDecision::GrantedOnce); let mut fixture = fixture.with_permission_handler(mediator.clone()); let absolute = dir.path().join("outside.txt"); let absolute = absolute.to_str().unwrap(); @@ -1242,7 +1246,7 @@ mod tests { #[tokio::test] async fn denied_outside_read_fails_only_the_outside_paths() { let (_dir, fixture) = outside_setup(); - let mediator = OutsideReadMediator::new(tools_core::PermissionDecision::Denied); + let mediator = OutsideAccessMediator::new(tools_core::PermissionDecision::Denied); let mut fixture = fixture.with_permission_handler(mediator); let mut input = read_input(&["inside.txt", "../outside.txt"]); @@ -1277,7 +1281,7 @@ mod tests { #[tokio::test] async fn session_grant_for_outside_reads_stops_asking() { let (_dir, fixture) = outside_setup(); - let mediator = OutsideReadMediator::new(tools_core::PermissionDecision::GrantedSession); + let mediator = OutsideAccessMediator::new(tools_core::PermissionDecision::GrantedSession); let mut fixture = fixture.with_permission_handler(mediator.clone()); for _ in 0..2 { diff --git a/crates/code_assistant_core/src/tools/impls/replace_in_file.rs b/crates/code_assistant_core/src/tools/impls/replace_in_file.rs index 2cde3c73b..28071f86d 100644 --- a/crates/code_assistant_core/src/tools/impls/replace_in_file.rs +++ b/crates/code_assistant_core/src/tools/impls/replace_in_file.rs @@ -146,7 +146,7 @@ impl Tool for ReplaceInFileTool { "path": { "examples": ["File path here"], "type": "string", - "description": "Path to the file to modify (relative to project root)" + "description": "Path to the file to modify (relative to project root). A path outside the project (absolute, or leading out with `..`) is written only after the user approves it." }, "diff": { "type": "string", @@ -208,21 +208,24 @@ impl Tool for ReplaceInFileTool { } }; - // Check for absolute path + // A path outside the project is edited only once the user approves. let path = PathBuf::from(&input.path); - if path.is_absolute() { - return Ok(ReplaceInFileOutput { - project: input.project.clone(), - path, - error: Some(FileUpdaterError::Other( - "Absolute paths are not allowed".to_string(), - )), - match_start_lines: Vec::new(), - }); - } - - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(&path); + let target = + match super::outside_project::write_target(context, "replace_in_file", explorer, &path) + .await + { + Ok(target) => target, + Err(error) => { + return Ok(ReplaceInFileOutput { + project: input.project.clone(), + path, + error: Some(FileUpdaterError::Other(error)), + match_start_lines: Vec::new(), + }); + } + }; + let explorer = target.explorer; + let full_path = target.full_path; // Compute match start line numbers before applying (need the original content) let match_start_lines = if let Ok(content) = std::fs::read_to_string(&full_path) { @@ -234,7 +237,10 @@ impl Tool for ReplaceInFileTool { // If format-on-save applies, use format-aware path; nothing happens if // the file changed since this agent last saw it. let apply = async { - if let Some(command_line) = project_config.format_command_for(&path) { + if let Some(command_line) = project_config + .format_command_for(&path) + .filter(|_| !target.outside) + { explorer .apply_replacements_with_formatting( &full_path, @@ -262,8 +268,8 @@ impl Tool for ReplaceInFileTool { input.diff = render_diff_from_replacements(&updated); } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let Some(ui) = context.ui().filter(|_| !target.outside) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), diff --git a/crates/code_assistant_core/src/tools/impls/search_files.rs b/crates/code_assistant_core/src/tools/impls/search_files.rs index fe9d48f55..94190c4df 100644 --- a/crates/code_assistant_core/src/tools/impls/search_files.rs +++ b/crates/code_assistant_core/src/tools/impls/search_files.rs @@ -480,9 +480,14 @@ impl Tool for SearchFilesTool { .iter() .filter_map(|(_, outside)| outside.clone()) .collect(); - super::outside_project::approve_reads(context, "search_files", &outside_paths) - .await - .map_err(|denial| anyhow!(denial))?; + super::outside_project::approve( + context, + "search_files", + tools_core::FileAccess::Read, + &outside_paths, + ) + .await + .map_err(|denial| anyhow!(denial))?; // Set up search options with a reasonable initial limit let options = SearchOptions { diff --git a/crates/code_assistant_core/src/tools/impls/view_documents.rs b/crates/code_assistant_core/src/tools/impls/view_documents.rs index 14e720520..cc47f9e74 100644 --- a/crates/code_assistant_core/src/tools/impls/view_documents.rs +++ b/crates/code_assistant_core/src/tools/impls/view_documents.rs @@ -231,10 +231,14 @@ impl Tool for ViewDocumentsTool { .iter() .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) .collect(); - let outside_denial = - super::outside_project::approve_reads(context, "view_documents", &outside_paths) - .await - .err(); + let outside_denial = super::outside_project::approve( + context, + "view_documents", + tools_core::FileAccess::Read, + &outside_paths, + ) + .await + .err(); let mut total_output_chars: usize = 0; for path_str in &input.paths { diff --git a/crates/code_assistant_core/src/tools/impls/view_images.rs b/crates/code_assistant_core/src/tools/impls/view_images.rs index 2cdf04e27..943702a44 100644 --- a/crates/code_assistant_core/src/tools/impls/view_images.rs +++ b/crates/code_assistant_core/src/tools/impls/view_images.rs @@ -247,10 +247,14 @@ impl Tool for ViewImagesTool { .iter() .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) .collect(); - let outside_denial = - super::outside_project::approve_reads(context, "view_images", &outside_paths) - .await - .err(); + let outside_denial = super::outside_project::approve( + context, + "view_images", + tools_core::FileAccess::Read, + &outside_paths, + ) + .await + .err(); for path_str in &input.paths { let path = PathBuf::from(path_str); diff --git a/crates/code_assistant_core/src/tools/impls/write_file.rs b/crates/code_assistant_core/src/tools/impls/write_file.rs index 2c84123e5..65ebac4ca 100644 --- a/crates/code_assistant_core/src/tools/impls/write_file.rs +++ b/crates/code_assistant_core/src/tools/impls/write_file.rs @@ -99,7 +99,7 @@ impl Tool for WriteFileTool { "path": { "examples": ["File path here"], "type": "string", - "description": "Path to create or overwrite (relative to project root)" + "description": "Path to create or overwrite (relative to project root). A path outside the project (absolute, or leading out with `..`) is written only after the user approves it." }, "content": { "type": "string", @@ -179,19 +179,29 @@ impl Tool for WriteFileTool { // Check for absolute path let path = PathBuf::from(&input.path); - if path.is_absolute() { - return Ok(WriteFileOutput { - path, - content: String::new(), - error: Some("Absolute paths are not allowed".to_string()), - original_content: None, - }); - } - let project_root = explorer.root_dir(); - // Join with root_dir to get full path - let full_path = project_root.join(&path); + // A path outside the project is written only once the user approves. + let target = match super::outside_project::write_target( + context, + "write_file", + explorer, + &path, + ) + .await + { + Ok(target) => target, + Err(error) => { + return Ok(WriteFileOutput { + path, + content: String::new(), + error: Some(error), + original_content: None, + }); + } + }; + let explorer = target.explorer; + let full_path = target.full_path; // Read the original content before writing (if the file exists and we're not appending). // This allows the UI to show a proper diff for overwrites. @@ -205,6 +215,7 @@ impl Tool for WriteFileTool { // one change, so the formatted content counts as seen. let format_command = project_config .as_ref() + .filter(|_| !target.outside) .and_then(|config| config.format_command_for(&path)); let write = async { explorer @@ -234,8 +245,8 @@ impl Tool for WriteFileTool { input.content = updated; } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let Some(ui) = context.ui().filter(|_| !target.outside) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), diff --git a/crates/tools_core/src/lib.rs b/crates/tools_core/src/lib.rs index 02f54ab62..3ff54b9e0 100644 --- a/crates/tools_core/src/lib.rs +++ b/crates/tools_core/src/lib.rs @@ -25,9 +25,9 @@ pub mod tool; pub use dyn_tool::{AnyOutput, DynTool}; pub use image::{MAX_IMAGE_EDGE, cap_base64_image, cap_image_data, svg_to_png}; pub use permissions::{ - Clearance, PermissionDecision, PermissionMediator, PermissionRequest, PermissionRequestReason, - PermissionTier, ReviewVerdict, ReviewedCallMediator, ToolCallReview, ToolCallReviewer, - ToolPermissions, + Clearance, FileAccess, PermissionDecision, PermissionMediator, PermissionRequest, + PermissionRequestReason, PermissionTier, ReviewVerdict, ReviewedCallMediator, ToolCallReview, + ToolCallReviewer, ToolPermissions, }; pub use registry::ToolRegistry; pub use render::{ImageData, Render, ResourcesTracker}; diff --git a/crates/tools_core/src/permissions.rs b/crates/tools_core/src/permissions.rs index 7bd35c992..9d40fa56f 100644 --- a/crates/tools_core/src/permissions.rs +++ b/crates/tools_core/src/permissions.rs @@ -251,10 +251,13 @@ pub enum PermissionRequestReason<'a> { params: &'a serde_json::Value, reason: &'a str, }, - /// A tool wants to read files outside the project it works in. Asked - /// independently of the tier, since the project root is the boundary - /// the file tools otherwise enforce. - ReadOutsideProject { paths: &'a [PathBuf] }, + /// A tool wants to read or write files outside the project it works in. + /// Asked independently of the tier, since the project root is the + /// boundary the file tools otherwise enforce. + OutsideProject { + access: FileAccess, + paths: &'a [PathBuf], + }, /// Approve loading a project's local `.mcp.json`, which launches the MCP /// servers it defines — i.e. runs project-supplied commands. Not tied to a /// tool invocation; raised before a project's registry is built. @@ -264,6 +267,31 @@ pub enum PermissionRequestReason<'a> { }, } +/// What a tool wants to do with files outside its project. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FileAccess { + Read, + Write, +} + +impl FileAccess { + /// `"read"` or `"write"`, for prompts and request metadata. + pub fn verb(self) -> &'static str { + match self { + FileAccess::Read => "read", + FileAccess::Write => "write", + } + } + + /// `"Read"` or `"Write"`, to start a prompt with. + pub fn label(self) -> &'static str { + match self { + FileAccess::Read => "Read", + FileAccess::Write => "Write", + } + } +} + /// Request payload passed to a [`PermissionMediator`]. #[derive(Debug)] pub struct PermissionRequest<'a> { diff --git a/crates/ui_acp/src/permissions.rs b/crates/ui_acp/src/permissions.rs index 099b6c474..1cd6d30a7 100644 --- a/crates/ui_acp/src/permissions.rs +++ b/crates/ui_acp/src/permissions.rs @@ -107,8 +107,9 @@ impl AcpPermissionMediator { serde_json::to_string_pretty(params).unwrap_or_else(|_| params.to_string()) ) } - PermissionRequestReason::ReadOutsideProject { paths } => format!( - "Read files outside the project:\n{}", + PermissionRequestReason::OutsideProject { access, paths } => format!( + "{} files outside the project:\n{}", + access.label(), paths .iter() .map(|p| p.display().to_string()) @@ -149,8 +150,9 @@ impl AcpPermissionMediator { "params": params, "reason": reason, }), - PermissionRequestReason::ReadOutsideProject { paths } => json!({ - "type": "read_outside_project", + PermissionRequestReason::OutsideProject { access, paths } => json!({ + "type": "outside_project", + "access": access.verb(), "paths": paths.iter().map(|p| p.display().to_string()).collect::>(), }), PermissionRequestReason::TrustLocalMcp { diff --git a/docs/permission-tiers.md b/docs/permission-tiers.md index c13f67bfc..fb0d35d65 100644 --- a/docs/permission-tiers.md +++ b/docs/permission-tiers.md @@ -96,16 +96,19 @@ parent gave them. `ask_user_approval` (sandbox bypass) keeps using the mediator directly, independent of the tier — except under `auto`, where a call the reviewer allowed gets its escalation granted (see above). -- **Reading outside the project**: the file tools (`read_files`, - `list_files`, `search_files`, `glob_files`, `view_images`, - `view_documents`) ask before reaching a path that leads out of the - project (absolute, `..`, or a symlink), in every tier including - `bypass-all` — one prompt per call for all such paths - (`PermissionRequestReason::ReadOutsideProject`, shared helper - `tools::impls::outside_project`). *Always (session)* covers all of these - tools and is remembered in the session's `ToolPermissions` (reached by - tools through `ToolContext::request_escalation`). Without a mediator the - access is rejected as before. Writing tools stay confined to the project. +- **Files outside the project**: the file tools ask before reaching a + path that leads out of the project (absolute, `..`, or a symlink), in + every tier including `bypass-all` — one prompt per call for all such + paths (`PermissionRequestReason::OutsideProject`, shared helper + `tools::impls::outside_project`). Reading (`read_files`, `list_files`, + `search_files`, `glob_files`, `view_images`, `view_documents`) and + writing (`write_file`, `edit`, `replace_in_file`, `delete_files`) are + asked and granted separately (`FileAccess`). *Always (session)* covers + every tool of that kind and is remembered in the session's + `ToolPermissions` (reached by tools through + `ToolContext::request_escalation`). Files written outside get no + format-on-save and no resource events. Without a mediator the access is + rejected as before. ## Frontend surfaces From c009218442b469e7062edb79c0611578c54d6b41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stephan=20A=C3=9Fmus?= Date: Tue, 17 Nov 2026 10:17:25 +0100 Subject: [PATCH 3/3] Resolve outside paths once and ask one question at a time Address review findings on the outside-project permission: - Tools use the path resolved before the question, so a symlink changed while it is open cannot redirect the access (resolve_and_approve) - search_files asks before it says whether an outside path exists - Absolute glob patterns inside the project match; the literal base is split by path components, so Windows separators work - Absolute paths inside the project are made relative for format-on-save and resource events - Outside explorers come from explorer_for everywhere; read_files no longer resolves paths again for its resource events - Parallel calls ask one after another, so an "always" answer covers the calls waiting behind it --- .../src/tools/impls/delete_files.rs | 34 ++-- .../src/tools/impls/edit.rs | 11 +- .../src/tools/impls/glob_files.rs | 102 +++++++--- .../src/tools/impls/list_files.rs | 39 ++-- .../src/tools/impls/outside_project.rs | 191 +++++++++++++++++- .../src/tools/impls/read_files.rs | 57 ++---- .../src/tools/impls/replace_in_file.rs | 11 +- .../src/tools/impls/search_files.rs | 70 +++---- .../src/tools/impls/view_documents.rs | 29 +-- .../src/tools/impls/view_images.rs | 29 +-- .../src/tools/impls/write_file.rs | 9 +- crates/tools_core/src/permissions.rs | 11 + crates/tools_core/src/tool.rs | 65 ++++++ docs/permission-tiers.md | 5 +- 14 files changed, 454 insertions(+), 209 deletions(-) diff --git a/crates/code_assistant_core/src/tools/impls/delete_files.rs b/crates/code_assistant_core/src/tools/impls/delete_files.rs index d9e36b459..d447ba501 100644 --- a/crates/code_assistant_core/src/tools/impls/delete_files.rs +++ b/crates/code_assistant_core/src/tools/impls/delete_files.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -158,39 +159,32 @@ impl Tool for DeleteFilesTool { let mut failed = Vec::new(); let mut deleted_contents = Vec::new(); - // Process each path // Deleting outside the project needs the user's approval, asked once // for all such paths of this call. let root_dir = explorer.root_dir(); - let outside_paths: Vec = input - .paths - .iter() - .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) - .collect(); - let outside_denial = super::outside_project::approve( + let resolved = super::outside_project::resolve_and_approve( context, "delete_files", tools_core::FileAccess::Write, - &outside_paths, + &root_dir, + input.paths.iter().map(std::path::Path::new), ) - .await - .err(); + .await; - for path_str in input.paths.clone() { + for (path_str, resolved) in input.paths.clone().into_iter().zip(resolved) { let path = PathBuf::from(&path_str); - let outside = fs_explorer::resolve_outside_root(&root_dir, &path); let outside_explorer; - let (explorer, full_path) = match (&outside, &outside_denial) { - (Some(_), Some(denial)) => { - failed.push((path, denial.clone())); + let (explorer, full_path, inside) = match resolved { + Resolved::Refused(denial) => { + failed.push((path, denial)); continue; } - (Some(outside), None) => { - outside_explorer = super::outside_project::explorer_for(outside); - (outside_explorer.as_ref(), outside.clone()) + Resolved::Outside(outside) => { + outside_explorer = super::outside_project::explorer_for(&outside); + (outside_explorer.as_ref(), outside, false) } - (None, _) => (explorer.as_ref(), root_dir.join(&path)), + Resolved::Inside => (explorer.as_ref(), root_dir.join(&path), true), }; // Capture the content before deletion (best effort; binary or @@ -210,7 +204,7 @@ impl Tool for DeleteFilesTool { } // Emit resource event (files outside the project are no resource of it) - if let Some(ui) = context.ui().filter(|_| outside.is_none()) { + if let Some(ui) = context.ui().filter(|_| inside) { let _ = ui .send_event(crate::ui::UiEvent::ResourceDeleted { project: input.project.clone(), diff --git a/crates/code_assistant_core/src/tools/impls/edit.rs b/crates/code_assistant_core/src/tools/impls/edit.rs index 9d78d2c4f..206708767 100644 --- a/crates/code_assistant_core/src/tools/impls/edit.rs +++ b/crates/code_assistant_core/src/tools/impls/edit.rs @@ -205,9 +205,10 @@ impl Tool for EditTool { // Apply with or without formatting, based on project configuration, // unless the file changed since this agent last saw it. let apply = async { - if let Some(format_command) = project_config - .format_command_for(&path) - .filter(|_| !target.outside) + if let Some(format_command) = target + .project_path + .as_deref() + .and_then(|project_path| project_config.format_command_for(project_path)) { explorer .apply_replacements_with_formatting( @@ -241,11 +242,11 @@ impl Tool for EditTool { } // Emit resource event (files outside the project are no resource of it) - if let Some(ui) = context.ui().filter(|_| !target.outside) { + if let (Some(ui), Some(project_path)) = (context.ui(), &target.project_path) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), - path: path.clone(), + path: project_path.clone(), }) .await; } diff --git a/crates/code_assistant_core/src/tools/impls/glob_files.rs b/crates/code_assistant_core/src/tools/impls/glob_files.rs index 072dafcd7..fe7ac3dcc 100644 --- a/crates/code_assistant_core/src/tools/impls/glob_files.rs +++ b/crates/code_assistant_core/src/tools/impls/glob_files.rs @@ -5,7 +5,7 @@ use crate::tools::core::{ use anyhow::{Result, anyhow}; use serde::{Deserialize, Serialize}; use serde_json::json; -use std::path::PathBuf; +use std::path::{Component, Path, PathBuf}; // Input type for the glob_files tool #[derive(Deserialize, Serialize)] @@ -127,23 +127,27 @@ impl Tool for GlobFilesTool { let root_dir = explorer.root_dir(); // A pattern whose leading directories leave the project (absolute, or - // `..`) matches below that folder, once the user approves it. - let (base, pattern) = split_literal_base(&input.pattern); - let (walk_root, pattern) = - match fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(&base)) { - Some(outside) => { - super::outside_project::approve( - context, - "glob_files", - tools_core::FileAccess::Read, - std::slice::from_ref(&outside), - ) - .await - .map_err(|denial| anyhow!(denial))?; - (outside, pattern) - } - None => (root_dir.clone(), input.pattern.clone()), - }; + // `..`) matches below that folder, once the user approves it. An + // absolute pattern inside the project matches like its relative form. + let (base, rest) = split_literal_base(&input.pattern); + let (walk_root, pattern) = match fs_explorer::resolve_outside_root(&root_dir, &base) { + Some(outside) => { + super::outside_project::approve( + context, + "glob_files", + tools_core::FileAccess::Read, + std::slice::from_ref(&outside), + ) + .await + .map_err(|denial| anyhow!(denial))?; + (outside, rest) + } + None if base.is_absolute() => { + let base = super::outside_project::relative_to_root(&root_dir, &base); + (root_dir.clone(), join_pattern(&base, &rest)) + } + None => (root_dir.clone(), input.pattern.clone()), + }; // Find files matching the glob pattern let files = find_files_matching_pattern(&walk_root, &pattern)?; @@ -168,25 +172,38 @@ impl Tool for GlobFilesTool { /// Split a glob pattern into its leading directories without wildcards and /// the rest, e.g. `../other/src/**/*.rs` into `../other/src` and `**/*.rs`. -/// The last component always stays in the pattern. -fn split_literal_base(pattern: &str) -> (String, String) { - let components: Vec<&str> = pattern.split('/').collect(); +/// The last component always stays in the pattern. Splits at the platform's +/// separators, so `..\\other\\*.rs` works on Windows too. +fn split_literal_base(pattern: &str) -> (PathBuf, String) { + let components: Vec = Path::new(pattern).components().collect(); let literal = components .iter() .take(components.len().saturating_sub(1)) - .take_while(|c| !c.contains(['*', '?', '[', '{'])) + .take_while(|c| { + !c.as_os_str() + .to_string_lossy() + .contains(['*', '?', '[', '{']) + }) .count(); - let base = components[..literal].join("/"); - let base = if base.is_empty() && pattern.starts_with('/') { - "/".to_string() - } else { - base - }; - (base, components[literal..].join("/")) + let rest: PathBuf = components[literal..].iter().collect(); + (components[..literal].iter().collect(), glob_string(&rest)) +} + +/// `rest` below the folder `base`, as a glob pattern. +fn join_pattern(base: &Path, rest: &str) -> String { + glob_string(&base.join(rest)) +} + +/// A relative path as a glob pattern: components joined with `/`. +fn glob_string(path: &Path) -> String { + path.components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/") } // Helper function to find all files (text and binary) matching a glob pattern -fn find_files_matching_pattern(root_dir: &std::path::Path, pattern: &str) -> Result> { +fn find_files_matching_pattern(root_dir: &Path, pattern: &str) -> Result> { use glob::{MatchOptions, Pattern}; use ignore::WalkBuilder; @@ -437,4 +454,29 @@ mod tests { Ok(()) } + + #[test] + fn splits_a_pattern_at_its_first_wildcard_folder() { + let split = |pattern| { + let (base, rest) = split_literal_base(pattern); + (base.to_string_lossy().into_owned(), rest) + }; + assert_eq!( + split("../other/src/**/*.rs"), + ("../other/src".into(), "**/*.rs".into()) + ); + assert_eq!(split("*.rs"), ("".into(), "*.rs".into())); + assert_eq!(split("src/*.rs"), ("src".into(), "*.rs".into())); + assert_eq!(split("/abs/dir/*.rs"), ("/abs/dir".into(), "*.rs".into())); + assert_eq!(split("../note.txt"), ("..".into(), "note.txt".into())); + assert_eq!(split("src/{a,b}/*.rs"), ("src".into(), "{a,b}/*.rs".into())); + } + + #[cfg(windows)] + #[test] + fn splits_a_windows_pattern() { + let (base, rest) = split_literal_base(r"..\other\*.rs"); + assert_eq!(base, std::path::Path::new(r"..\other")); + assert_eq!(rest, "*.rs"); + } } diff --git a/crates/code_assistant_core/src/tools/impls/list_files.rs b/crates/code_assistant_core/src/tools/impls/list_files.rs index f24efe948..e0baa941c 100644 --- a/crates/code_assistant_core/src/tools/impls/list_files.rs +++ b/crates/code_assistant_core/src/tools/impls/list_files.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -175,42 +176,30 @@ impl Tool for ListFilesTool { // Listing outside the project needs the user's approval, asked once // for all such paths of this call. let root_dir = explorer.root_dir(); - let outside_paths: Vec = input - .paths - .iter() - .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) - .collect(); - let outside_denial = super::outside_project::approve( + let resolved = super::outside_project::resolve_and_approve( context, "list_files", tools_core::FileAccess::Read, - &outside_paths, + &root_dir, + input.paths.iter().map(std::path::Path::new), ) - .await - .err(); + .await; - for path_str in input.paths.clone() { + for (path_str, resolved) in input.paths.clone().into_iter().zip(resolved) { let path = PathBuf::from(&path_str); - let listing = match ( - fs_explorer::resolve_outside_root(&root_dir, &path), - &outside_denial, - ) { - (Some(_), Some(denial)) => { - failed_paths.push((path_str, denial.clone())); + let listing = match resolved { + Resolved::Refused(denial) => { + failed_paths.push((path_str, denial)); continue; } // Approved: list through an explorer rooted at that folder. - (Some(outside), None) => { - let mut outside_explorer = fs_explorer::Explorer::new(outside.clone()); - fs_explorer::CodeExplorer::list_files( - &mut outside_explorer, - &outside, - max_depth, - ) - .await + Resolved::Outside(outside) => { + super::outside_project::explorer_for(&outside) + .list_files(&outside, max_depth) + .await } - (None, _) => explorer.list_files(&root_dir.join(&path), max_depth).await, + Resolved::Inside => explorer.list_files(&root_dir.join(&path), max_depth).await, }; match listing { Ok(tree_entry) => { diff --git a/crates/code_assistant_core/src/tools/impls/outside_project.rs b/crates/code_assistant_core/src/tools/impls/outside_project.rs index 62fcc3eb3..b617367fe 100644 --- a/crates/code_assistant_core/src/tools/impls/outside_project.rs +++ b/crates/code_assistant_core/src/tools/impls/outside_project.rs @@ -49,12 +49,52 @@ pub(crate) async fn approve( } } +/// Where a path a file tool was given leads. +#[derive(Debug)] +pub(crate) enum Resolved { + /// Inside the project: the tool resolves it as usual. + Inside, + /// Outside the project, and the user allowed it: where it really points. + Outside(PathBuf), + /// Outside the project, and refused: the message to report for it. + Refused(String), +} + +/// Resolve each of `paths` (relative to `root`, or absolute) and ask the +/// user, once for all that leave the project, to let `tool_name` reach them. +/// The result is in the order of `paths`. Each path is resolved only here, +/// so a tool touches exactly what the user approved, even if a symlink +/// changes while the question is open. +pub(crate) async fn resolve_and_approve<'p>( + context: &mut ToolContext<'_>, + tool_name: &str, + access: FileAccess, + root: &Path, + paths: impl IntoIterator, +) -> Vec { + let outside: Vec> = paths + .into_iter() + .map(|path| fs_explorer::resolve_outside_root(root, path)) + .collect(); + let asked: Vec = outside.iter().flatten().cloned().collect(); + let denial = approve(context, tool_name, access, &asked).await.err(); + outside + .into_iter() + .map(|outside| match (outside, &denial) { + (None, _) => Resolved::Inside, + (Some(_), Some(denial)) => Resolved::Refused(denial.clone()), + (Some(path), None) => Resolved::Outside(path), + }) + .collect() +} + /// Where a file tool writes a file: inside the project, or outside it. pub(crate) struct WriteTarget { pub explorer: Box, pub full_path: PathBuf, - /// Outside the project: no format-on-save, no resource events. - pub outside: bool, + /// The path relative to the project root, for format-on-save and + /// resource events; `None` outside the project, which gets neither. + pub project_path: Option, } /// Where `tool_name` writes `path`: inside the project through `explorer`, @@ -68,10 +108,11 @@ pub(crate) async fn write_target( ) -> Result { let root = explorer.root_dir(); let Some(outside) = fs_explorer::resolve_outside_root(&root, path) else { + let project_path = relative_to_root(&root, path); return Ok(WriteTarget { explorer, - full_path: root.join(path), - outside: false, + full_path: root.join(&project_path), + project_path: Some(project_path), }); }; approve( @@ -84,10 +125,33 @@ pub(crate) async fn write_target( Ok(WriteTarget { explorer: explorer_for(&outside), full_path: outside, - outside: true, + project_path: None, }) } +/// `path`, known to lie inside `root`, relative to it: an absolute path +/// loses the root (also when it reaches the root through a symlink, such as +/// macOS's `/tmp`). Falls back to `path` itself when that fails. +pub(crate) fn relative_to_root(root: &Path, path: &Path) -> PathBuf { + if !path.is_absolute() { + return path.to_path_buf(); + } + let canonical = || { + path.canonicalize().ok().or_else(|| { + let parent = path.parent()?.canonicalize().ok()?; + Some(parent.join(path.file_name()?)) + }) + }; + path.strip_prefix(root) + .ok() + .map(Path::to_path_buf) + .or_else(|| { + canonical() + .and_then(|canonical| canonical.strip_prefix(root).ok().map(Path::to_path_buf)) + }) + .unwrap_or_else(|| path.to_path_buf()) +} + /// An explorer for a path outside the project: rooted at the path itself /// when it is a folder, else at its parent. pub(crate) fn explorer_for(path: &Path) -> Box { @@ -113,6 +177,8 @@ pub(crate) mod tests { decision: PermissionDecision, pub(crate) asked: Mutex>>, pub(crate) accesses: Mutex>, + /// Runs while the question is open, before the answer. + while_asking: Option>, } impl OutsideAccessMediator { @@ -121,6 +187,20 @@ pub(crate) mod tests { decision, asked: Default::default(), accesses: Default::default(), + while_asking: None, + }) + } + + /// Like [`Self::new`], running `while_asking` before each answer. + pub(crate) fn while_asking( + decision: PermissionDecision, + while_asking: impl Fn() + Send + Sync + 'static, + ) -> Arc { + Arc::new(Self { + decision, + asked: Default::default(), + accesses: Default::default(), + while_asking: Some(Box::new(while_asking)), }) } } @@ -136,6 +216,9 @@ pub(crate) mod tests { }; self.asked.lock().unwrap().push(paths.to_vec()); self.accesses.lock().unwrap().push(access); + if let Some(while_asking) = &self.while_asking { + while_asking(); + } Ok(self.decision) } } @@ -410,4 +493,102 @@ pub(crate) mod tests { ); assert!(dir.path().join("other/new.txt").exists()); } + + #[cfg(unix)] + #[tokio::test] + async fn a_tool_uses_the_path_the_user_approved_even_if_a_symlink_changes_meanwhile() { + let (dir, fixture) = outside_setup(); + let first = dir.path().join("first"); + let second = dir.path().join("second"); + for folder in [&first, &second] { + std::fs::create_dir(folder).unwrap(); + std::fs::write(folder.join("x.txt"), "x").unwrap(); + } + let link = dir.path().join("proj/link"); + std::os::unix::fs::symlink(&first, &link).unwrap(); + let mediator = { + let (link, second) = (link.clone(), second.clone()); + OutsideAccessMediator::while_asking(PermissionDecision::GrantedOnce, move || { + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&second, &link).unwrap(); + }) + }; + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + invoke( + &mut fixture, + "delete_files", + json!({"paths": ["link/x.txt"]}), + ) + .await + .unwrap(); + + assert!( + !first.join("x.txt").exists(), + "the approved file is deleted" + ); + assert!(second.join("x.txt").exists(), "the other file is not"); + } + + #[tokio::test] + async fn search_files_says_nothing_about_an_outside_path_before_it_is_approved() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + let error = invoke( + &mut fixture, + "search_files", + json!({"regex": "x", "paths": ["../missing"]}), + ) + .await + .unwrap_err() + .to_string(); + + assert!(error.contains("denied"), "{error}"); + assert!(!error.contains("not found"), "{error}"); + assert_eq!(mediator.asked.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn an_absolute_glob_inside_the_project_matches_without_asking() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + let pattern = dir.path().join("proj").join("*.txt"); + + let output = invoke( + &mut fixture, + "glob_files", + json!({"pattern": pattern.to_str().unwrap()}), + ) + .await + .unwrap(); + + assert!(output.contains("inside.txt"), "{output}"); + assert!(mediator.asked.lock().unwrap().is_empty()); + } + + #[test] + fn absolute_paths_inside_the_root_become_relative() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("src")).unwrap(); + std::fs::write(dir.path().join("src/lib.rs"), "").unwrap(); + // The explorer's root is canonical; on macOS the temp dir is not. + let root = dir.path().canonicalize().unwrap(); + + for path in [ + dir.path().join("src/lib.rs"), + root.join("src/lib.rs"), + dir.path().join("src/new.rs"), + ] { + let relative = relative_to_root(&root, &path); + assert!(relative.is_relative(), "{}", path.display()); + assert!(relative.starts_with("src"), "{}", relative.display()); + } + assert_eq!( + relative_to_root(&root, Path::new("src/lib.rs")), + Path::new("src/lib.rs") + ); + } } diff --git a/crates/code_assistant_core/src/tools/impls/read_files.rs b/crates/code_assistant_core/src/tools/impls/read_files.rs index bfe439976..1df52daea 100644 --- a/crates/code_assistant_core/src/tools/impls/read_files.rs +++ b/crates/code_assistant_core/src/tools/impls/read_files.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -397,53 +398,46 @@ impl Tool for ReadFilesTool { let mut loaded_files = HashMap::new(); let mut failed_files = Vec::new(); - // Parse each path string to extract line range information, and note - // where the paths that leave the project really point. + // Parse each path string to extract line range information let root = explorer.root_dir(); let mut requests = Vec::new(); for path_str in input.paths.clone() { match PathWithLineRange::parse(&path_str) { - Ok(parsed) => { - let outside = fs_explorer::resolve_outside_root(&root, &parsed.path); - requests.push((path_str, parsed, outside)); - } + Ok(parsed) => requests.push((path_str, parsed)), Err(e) => failed_files.push((PathBuf::from(path_str), e.to_string())), } } // Reading outside the project needs the user's approval, asked once // for all such paths of this call. - let outside_paths: Vec = requests - .iter() - .filter_map(|(_, _, outside)| outside.clone()) - .collect(); - let outside_denial = super::outside_project::approve( + let resolved = super::outside_project::resolve_and_approve( context, "read_files", tools_core::FileAccess::Read, - &outside_paths, + &root, + requests.iter().map(|(_, parsed)| parsed.path.as_path()), ) - .await - .err(); + .await; - for (path_str, parsed_path, outside) in requests { + // Files inside the project, announced to the UI as resources + let mut project_files = Vec::new(); + for ((path_str, parsed_path), resolved) in requests.into_iter().zip(resolved) { // Determine the start line for line numbering // If a start_line is specified, use it; otherwise default to 1 let start_line = parsed_path.start_line.unwrap_or(1); let outside_explorer; - let (file_explorer, full_path) = match (&outside, &outside_denial) { - (Some(_), Some(denial)) => { - failed_files.push((PathBuf::from(&path_str), denial.clone())); + let (file_explorer, full_path, inside) = match resolved { + Resolved::Refused(denial) => { + failed_files.push((PathBuf::from(&path_str), denial)); continue; } // Approved: read through an explorer rooted at the file's folder. - (Some(full_path), None) => { - let dir = full_path.parent().unwrap_or(full_path).to_path_buf(); - outside_explorer = fs_explorer::Explorer::new(dir); - (&outside_explorer as &dyn CodeExplorer, full_path.clone()) + Resolved::Outside(full_path) => { + outside_explorer = super::outside_project::explorer_for(&full_path); + (outside_explorer.as_ref(), full_path, false) } - (None, _) => (explorer.as_ref(), root.join(&parsed_path.path)), + Resolved::Inside => (explorer.as_ref(), root.join(&parsed_path.path), true), }; let read_result = read_lines(file_explorer, &full_path, &parsed_path).await; @@ -491,6 +485,9 @@ impl Tool for ReadFilesTool { start_line, }, ); + if inside { + project_files.push(parsed_path.path); + } } Err(e) => { failed_files.push((PathBuf::from(&path_str), e.to_string())); @@ -500,21 +497,11 @@ impl Tool for ReadFilesTool { // Emit resource events for loaded files inside the project if let Some(ui) = context.ui() { - for path in loaded_files.keys() { - // Get the base path without any line range information - let base_path = - if let Ok(parsed) = PathWithLineRange::parse(path.to_str().unwrap_or("")) { - parsed.path.clone() - } else { - path.clone() - }; - if fs_explorer::resolve_outside_root(&root, &base_path).is_some() { - continue; - } + for path in project_files { let _ = ui .send_event(crate::ui::UiEvent::ResourceLoaded { project: input.project.clone(), - path: base_path, + path, }) .await; } diff --git a/crates/code_assistant_core/src/tools/impls/replace_in_file.rs b/crates/code_assistant_core/src/tools/impls/replace_in_file.rs index 28071f86d..00cb8c0b2 100644 --- a/crates/code_assistant_core/src/tools/impls/replace_in_file.rs +++ b/crates/code_assistant_core/src/tools/impls/replace_in_file.rs @@ -237,9 +237,10 @@ impl Tool for ReplaceInFileTool { // If format-on-save applies, use format-aware path; nothing happens if // the file changed since this agent last saw it. let apply = async { - if let Some(command_line) = project_config - .format_command_for(&path) - .filter(|_| !target.outside) + if let Some(command_line) = target + .project_path + .as_deref() + .and_then(|project_path| project_config.format_command_for(project_path)) { explorer .apply_replacements_with_formatting( @@ -269,11 +270,11 @@ impl Tool for ReplaceInFileTool { } // Emit resource event (files outside the project are no resource of it) - if let Some(ui) = context.ui().filter(|_| !target.outside) { + if let (Some(ui), Some(project_path)) = (context.ui(), &target.project_path) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), - path: path.clone(), + path: project_path.clone(), }) .await; } diff --git a/crates/code_assistant_core/src/tools/impls/search_files.rs b/crates/code_assistant_core/src/tools/impls/search_files.rs index 94190c4df..185882e2b 100644 --- a/crates/code_assistant_core/src/tools/impls/search_files.rs +++ b/crates/code_assistant_core/src/tools/impls/search_files.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -7,7 +8,6 @@ use fs_explorer::{DocumentMatchResult, SearchMode, SearchOptions, SearchResult}; use serde::{Deserialize, Serialize}; use serde_json::json; use std::collections::HashMap; -use std::path::PathBuf; // Input type for the search_files tool #[derive(Deserialize, Serialize)] @@ -455,40 +455,35 @@ impl Tool for SearchFilesTool { let root_dir = explorer.root_dir(); - // Determine search paths, noting those that leave the project + // Determine search paths. Those that leave the project need the + // user's approval (asked once for all of them) before anything about + // them reaches the agent, not even whether they exist. let search_paths = if let Some(paths) = &input.paths { - // Validate and convert relative paths to absolute - let mut absolute_paths = Vec::new(); - for path in paths { - let absolute_path = root_dir.join(path); - if absolute_path.exists() { - let outside = - fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(path)); - absolute_paths.push((absolute_path, outside)); - } else { + let resolved = super::outside_project::resolve_and_approve( + context, + "search_files", + tools_core::FileAccess::Read, + &root_dir, + paths.iter().map(std::path::Path::new), + ) + .await; + let mut search_paths = Vec::new(); + for (path, resolved) in paths.iter().zip(resolved) { + let (search_path, outside) = match resolved { + Resolved::Refused(denial) => return Err(anyhow!(denial)), + Resolved::Outside(outside) => (outside, true), + Resolved::Inside => (root_dir.join(path), false), + }; + if !search_path.exists() { return Err(anyhow!("Path not found: {path}")); } + search_paths.push((search_path, outside)); } - absolute_paths + search_paths } else { - vec![(root_dir.clone(), None)] + vec![(root_dir.clone(), false)] }; - // Searching outside the project needs the user's approval, asked - // once for all such paths of this call. - let outside_paths: Vec = search_paths - .iter() - .filter_map(|(_, outside)| outside.clone()) - .collect(); - super::outside_project::approve( - context, - "search_files", - tools_core::FileAccess::Read, - &outside_paths, - ) - .await - .map_err(|denial| anyhow!(denial))?; - // Set up search options with a reasonable initial limit let options = SearchOptions { query: input.regex.clone(), @@ -501,22 +496,13 @@ impl Tool for SearchFilesTool { // Perform searches across all specified paths let mut all_results = Vec::new(); for (search_path, outside) in search_paths { - let mut path_results = match outside { + let mut path_results = if outside { // Approved: search through an explorer rooted at that path. - Some(outside) => { - let dir = if outside.is_dir() { - outside.clone() - } else { - outside.parent().unwrap_or(&outside).to_path_buf() - }; - fs_explorer::CodeExplorer::search( - &fs_explorer::Explorer::new(dir), - &outside, - options.clone(), - ) + super::outside_project::explorer_for(&search_path) + .search(&search_path, options.clone()) .await? - } - None => explorer.search(&search_path, options.clone()).await?, + } else { + explorer.search(&search_path, options.clone()).await? }; all_results.append(&mut path_results); } diff --git a/crates/code_assistant_core/src/tools/impls/view_documents.rs b/crates/code_assistant_core/src/tools/impls/view_documents.rs index cc47f9e74..22698df32 100644 --- a/crates/code_assistant_core/src/tools/impls/view_documents.rs +++ b/crates/code_assistant_core/src/tools/impls/view_documents.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -226,22 +227,17 @@ impl Tool for ViewDocumentsTool { // Reading outside the project needs the user's approval, asked once // for all such paths of this call. - let outside_paths: Vec = input - .paths - .iter() - .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) - .collect(); - let outside_denial = super::outside_project::approve( + let resolved = super::outside_project::resolve_and_approve( context, "view_documents", tools_core::FileAccess::Read, - &outside_paths, + &root_dir, + input.paths.iter().map(std::path::Path::new), ) - .await - .err(); + .await; let mut total_output_chars: usize = 0; - for path_str in &input.paths { + for (path_str, resolved) in input.paths.iter().zip(resolved) { let path = PathBuf::from(path_str); // Check extension @@ -270,16 +266,13 @@ impl Tool for ViewDocumentsTool { }; // Resolve and validate the path - let full_path = match ( - fs_explorer::resolve_outside_root(&root_dir, &path), - &outside_denial, - ) { - (Some(_), Some(denial)) => { - failed_documents.push((path_str.clone(), denial.clone())); + let full_path = match resolved { + Resolved::Refused(denial) => { + failed_documents.push((path_str.clone(), denial)); continue; } - (Some(outside), None) => outside, - (None, _) => match resolve_project_path(&root_dir, &path) { + Resolved::Outside(outside) => outside, + Resolved::Inside => match resolve_project_path(&root_dir, &path) { Ok(p) => p, Err(e) => { failed_documents.push((path_str.clone(), e.to_string())); diff --git a/crates/code_assistant_core/src/tools/impls/view_images.rs b/crates/code_assistant_core/src/tools/impls/view_images.rs index 943702a44..21d21d6f0 100644 --- a/crates/code_assistant_core/src/tools/impls/view_images.rs +++ b/crates/code_assistant_core/src/tools/impls/view_images.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ ImageData, MAX_IMAGE_EDGE, Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, @@ -242,21 +243,16 @@ impl Tool for ViewImagesTool { // Reading outside the project needs the user's approval, asked once // for all such paths of this call. - let outside_paths: Vec = input - .paths - .iter() - .filter_map(|p| fs_explorer::resolve_outside_root(&root_dir, std::path::Path::new(p))) - .collect(); - let outside_denial = super::outside_project::approve( + let resolved = super::outside_project::resolve_and_approve( context, "view_images", tools_core::FileAccess::Read, - &outside_paths, + &root_dir, + input.paths.iter().map(std::path::Path::new), ) - .await - .err(); + .await; - for path_str in &input.paths { + for (path_str, resolved) in input.paths.iter().zip(resolved) { let path = PathBuf::from(path_str); // Check extension @@ -285,16 +281,13 @@ impl Tool for ViewImagesTool { }; // Resolve and validate the path stays within the project root - let full_path = match ( - fs_explorer::resolve_outside_root(&root_dir, &path), - &outside_denial, - ) { - (Some(_), Some(denial)) => { - failed_images.push((path_str.clone(), denial.clone())); + let full_path = match resolved { + Resolved::Refused(denial) => { + failed_images.push((path_str.clone(), denial)); continue; } - (Some(outside), None) => outside, - (None, _) => match resolve_project_path(&root_dir, &path) { + Resolved::Outside(outside) => outside, + Resolved::Inside => match resolve_project_path(&root_dir, &path) { Ok(p) => p, Err(e) => { failed_images.push((path_str.clone(), e.to_string())); diff --git a/crates/code_assistant_core/src/tools/impls/write_file.rs b/crates/code_assistant_core/src/tools/impls/write_file.rs index 65ebac4ca..42642dcb8 100644 --- a/crates/code_assistant_core/src/tools/impls/write_file.rs +++ b/crates/code_assistant_core/src/tools/impls/write_file.rs @@ -177,7 +177,6 @@ impl Tool for WriteFileTool { // entry (and thus no format-on-save). let project_config = context.project_manager().get_project(&input.project)?; - // Check for absolute path let path = PathBuf::from(&input.path); let project_root = explorer.root_dir(); @@ -215,8 +214,8 @@ impl Tool for WriteFileTool { // one change, so the formatted content counts as seen. let format_command = project_config .as_ref() - .filter(|_| !target.outside) - .and_then(|config| config.format_command_for(&path)); + .zip(target.project_path.as_deref()) + .and_then(|(config, project_path)| config.format_command_for(project_path)); let write = async { explorer .write_file(&full_path, &input.content, input.append) @@ -246,11 +245,11 @@ impl Tool for WriteFileTool { } // Emit resource event (files outside the project are no resource of it) - if let Some(ui) = context.ui().filter(|_| !target.outside) { + if let (Some(ui), Some(project_path)) = (context.ui(), &target.project_path) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), - path: path.clone(), + path: project_path.clone(), }) .await; } diff --git a/crates/tools_core/src/permissions.rs b/crates/tools_core/src/permissions.rs index 9d40fa56f..04616e568 100644 --- a/crates/tools_core/src/permissions.rs +++ b/crates/tools_core/src/permissions.rs @@ -129,6 +129,9 @@ pub struct ToolPermissions { /// asks the user about every call it would have reviewed. pub reviewer: Option>, granted_tools: Arc>>, + /// Held while a tool asks for an escalation of its own, see + /// [`ToolPermissions::escalation_turn`]. + escalations: Arc>, } impl ToolPermissions { @@ -137,9 +140,17 @@ impl ToolPermissions { tier, reviewer: None, granted_tools: Arc::default(), + escalations: Arc::default(), } } + /// Wait until no other tool call of the session is asking the user for + /// an escalation. Parallel calls so ask one after another, and a call + /// waiting behind an "always (session)" answer passes without asking. + pub async fn escalation_turn(&self) -> tokio::sync::OwnedMutexGuard<()> { + self.escalations.clone().lock_owned().await + } + pub fn is_granted(&self, tool_name: &str) -> bool { self.granted_tools.lock().unwrap().contains(tool_name) } diff --git a/crates/tools_core/src/tool.rs b/crates/tools_core/src/tool.rs index d406afb7d..473106679 100644 --- a/crates/tools_core/src/tool.rs +++ b/crates/tools_core/src/tool.rs @@ -62,6 +62,12 @@ impl<'a> ToolContext<'a> { tool_name: &str, reason: PermissionRequestReason<'_>, ) -> Result { + // One question at a time per session; the grant is checked after + // waiting, since the question before may have granted it. + let _turn = match self.permissions { + Some(permissions) => Some(permissions.escalation_turn().await), + None => None, + }; if self.permissions.is_some_and(|p| p.is_granted(grant_key)) { return Ok(true); } @@ -113,3 +119,62 @@ pub trait Tool: Send + Sync + 'static { serde_json::from_value(json).map_err(|e| anyhow!("Failed to deserialize output: {e}")) } } + +#[cfg(test)] +mod escalation_tests { + use super::*; + use crate::permissions::FileAccess; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Answers "always (session)" after giving other tasks a chance to run, + /// counting the questions. + struct SlowSessionGrant { + asked: AtomicUsize, + } + + #[async_trait::async_trait] + impl PermissionMediator for SlowSessionGrant { + async fn request_permission( + &self, + _request: PermissionRequest<'_>, + ) -> Result { + self.asked.fetch_add(1, Ordering::SeqCst); + for _ in 0..10 { + tokio::task::yield_now().await; + } + Ok(PermissionDecision::GrantedSession) + } + } + + #[tokio::test] + async fn parallel_escalations_ask_once_when_the_first_answer_grants_the_session() { + let executor = command_executor::DefaultCommandExecutor; + let mediator = SlowSessionGrant { + asked: AtomicUsize::new(0), + }; + let permissions = ToolPermissions::default(); + let paths = [PathBuf::from("/elsewhere")]; + let context = || ToolContext { + command_executor: &executor, + tool_id: None, + session_id: None, + permission_handler: Some(&mediator), + permissions: Some(&permissions), + extensions: None, + }; + let reason = || PermissionRequestReason::OutsideProject { + access: FileAccess::Read, + paths: &paths, + }; + let (mut first, mut second) = (context(), context()); + + let (a, b) = tokio::join!( + first.request_escalation("key", "tool", reason()), + second.request_escalation("key", "tool", reason()), + ); + + assert!(a.unwrap() && b.unwrap()); + assert_eq!(mediator.asked.load(Ordering::SeqCst), 1); + } +} diff --git a/docs/permission-tiers.md b/docs/permission-tiers.md index fb0d35d65..65cd569a5 100644 --- a/docs/permission-tiers.md +++ b/docs/permission-tiers.md @@ -108,7 +108,10 @@ parent gave them. `ToolPermissions` (reached by tools through `ToolContext::request_escalation`). Files written outside get no format-on-save and no resource events. Without a mediator the access is - rejected as before. + rejected as before. Each path is resolved once, before the question, and + the tool uses exactly that path. Parallel calls ask one after another + (`ToolPermissions::escalation_turn`), so a call behind an *always* answer + does not ask again. ## Frontend surfaces