From d68ff210f0eada05d10824d6ebb0dd2924e6b40d Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 4 Mar 2026 16:42:52 -0600 Subject: [PATCH 1/7] feat(guard): add file path sandboxing via AGENT_ALLOWED_PATHS When AGENT_ALLOWED_PATHS is set (colon-separated directory prefixes), Edit/Write/Read/NotebookEdit tools are restricted to those paths. This prevents dispatched agents from escaping their worktree. - Parses AGENT_ALLOWED_PATHS env var into allowed directory prefixes - Validates file_path/notebook_path against allowed prefixes - Denies with clear message showing the blocked path and allowed dirs - Only active when env var is set (no-op in interactive mode) - Bash tool continues using existing destructive command detection Co-Authored-By: Claude Opus 4.6 --- src/guard.rs | 241 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 235 insertions(+), 6 deletions(-) diff --git a/src/guard.rs b/src/guard.rs index 08c3c22..f580bd2 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -1,8 +1,14 @@ -//! Deterministic destructive command detection for Claude Code PreToolUse hooks. +//! Deterministic destructive command detection and file path sandboxing for +//! Claude Code PreToolUse hooks. //! -//! Reads hook JSON from stdin, evaluates the Bash command for destructive patterns, -//! and returns structured JSON to block or allow execution. No LLM evaluation — -//! pure pattern matching in Rust. +//! Reads hook JSON from stdin, evaluates the tool input, and returns structured +//! JSON to block or allow execution. No LLM evaluation — pure pattern matching +//! in Rust. +//! +//! Two modes: +//! - **Bash guard**: Evaluates Bash commands for destructive patterns (always active). +//! - **File path sandbox**: When `AGENT_ALLOWED_PATHS` is set, restricts Edit/Write/Read/ +//! NotebookEdit tools to allowed directory prefixes. Inactive in interactive mode. //! //! Configuration is loaded from `.claude/agent-guard.toml` (project-level) or //! `~/.claude/agent-guard.toml` (user-level), with embedded defaults as fallback. @@ -286,12 +292,48 @@ impl GuardConfig { /// Entry point for `meta agent guard`. /// -/// Reads PreToolUse hook JSON from stdin, evaluates the command, -/// prints denial JSON to stdout if destructive, exits silently if safe. +/// Reads PreToolUse hook JSON from stdin, evaluates the tool input, +/// prints denial JSON to stdout if blocked, exits silently if safe. +/// +/// For Bash tools: checks command against destructive patterns. +/// For Edit/Write/Read/NotebookEdit: validates file_path against `AGENT_ALLOWED_PATHS`. pub fn handle_guard() -> Result<()> { let mut input = String::new(); std::io::stdin().read_to_string(&mut input)?; + let trimmed = input.trim(); + if trimmed.is_empty() { + return Ok(()); + } + + let hook_input: HookInput = match serde_json::from_str(trimmed) { + Ok(hi) => hi, + Err(_) => return Ok(()), // Malformed input — allow + }; + + let tool_name = hook_input.tool_name.as_deref().unwrap_or(""); + + // File-path tools: validate path against allowed directories + if matches!(tool_name, "Edit" | "Write" | "Read" | "NotebookEdit") { + if let Some(ref ti) = hook_input.tool_input { + let path = ti.file_path.as_ref().or(ti.notebook_path.as_ref()); + if let Some(fp) = path { + if let Some(denial) = evaluate_file_path(tool_name, fp) { + let output = HookOutput { + hook_specific_output: HookSpecificOutput { + hook_event_name: "PreToolUse".to_string(), + permission_decision: "deny".to_string(), + permission_decision_reason: denial.reason, + }, + }; + println!("{}", serde_json::to_string(&output)?); + } + } + } + return Ok(()); + } + + // Bash tool: check command for destructive patterns let command = match parse_command(&input) { Some(cmd) => cmd, None => return Ok(()), // No command to evaluate — allow @@ -315,12 +357,15 @@ pub fn handle_guard() -> Result<()> { #[derive(Deserialize)] struct HookInput { + tool_name: Option, tool_input: Option, } #[derive(Deserialize)] struct ToolInput { command: Option, + file_path: Option, + notebook_path: Option, } #[derive(Serialize)] @@ -345,6 +390,75 @@ pub struct DenyReason { pub reason: String, } +// ── File Path Sandboxing ──────────────────────────────── + +/// Validate a file path against `AGENT_ALLOWED_PATHS` (colon-separated prefixes). +/// +/// When the env var is unset or empty, all paths are allowed (interactive mode). +/// When set, the resolved path must start with at least one allowed prefix. +/// Resolves symlinks and `..` components to prevent path traversal escapes. +pub fn evaluate_file_path(tool_name: &str, file_path: &str) -> Option { + let allowed = match std::env::var("AGENT_ALLOWED_PATHS") { + Ok(v) if !v.is_empty() => v, + _ => return None, // No restriction in interactive mode + }; + + // Resolve the path to catch traversal (../../..) and symlink escapes. + // For files that don't exist yet (Write creating new file), resolve the parent. + let resolved = resolve_path(file_path); + + // Debug logging + if std::env::var("META_DEBUG_GUARD").is_ok() { + eprintln!( + "[agent-guard] File path check: tool={}, path={}, resolved={}", + tool_name, file_path, resolved + ); + } + + for prefix in allowed.split(':') { + let prefix = prefix.trim(); + if prefix.is_empty() { + continue; + } + if resolved.starts_with(prefix) { + return None; // Path is within an allowed prefix + } + } + + Some(DenyReason { + reason: format!( + "{} blocked: '{}' is outside the allowed workspace. Stay within your worktree.", + tool_name, file_path + ), + }) +} + +/// Resolve a file path to an absolute, canonical form. +/// Handles symlinks and `..` components. Falls back to the raw path if resolution fails. +fn resolve_path(path: &str) -> String { + let p = Path::new(path); + + // Try full canonicalize first (file exists) + if let Ok(canonical) = p.canonicalize() { + return canonical.to_string_lossy().to_string(); + } + + // File doesn't exist — canonicalize parent, append filename + if let Some(parent) = p.parent() { + if let Ok(canonical_parent) = parent.canonicalize() { + if let Some(name) = p.file_name() { + return canonical_parent + .join(name) + .to_string_lossy() + .to_string(); + } + } + } + + // Last resort: return as-is (already absolute from Claude Code) + path.to_string() +} + // ── Input Parsing ─────────────────────────────────────── /// Extract the command string from hook JSON input. @@ -1228,4 +1342,119 @@ message = "medium priority" assert_eq!(patterns[1].priority, 100); assert_eq!(patterns[2].priority, 50); } + + // ── File path sandboxing ──────────────────────────── + + #[test] + fn file_path_allows_when_env_unset() { + std::env::remove_var("AGENT_ALLOWED_PATHS"); + assert!(evaluate_file_path("Edit", "/some/random/path").is_none()); + assert!(evaluate_file_path("Write", "/etc/passwd").is_none()); + } + + #[test] + fn file_path_allows_when_env_empty() { + std::env::set_var("AGENT_ALLOWED_PATHS", ""); + assert!(evaluate_file_path("Read", "/any/path").is_none()); + std::env::remove_var("AGENT_ALLOWED_PATHS"); + } + + #[test] + fn file_path_allows_within_prefix() { + std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/worktrees/test:/tmp"); + assert!(evaluate_file_path("Edit", "/tmp/worktrees/test/src/main.rs").is_none()); + assert!(evaluate_file_path("Write", "/tmp/somefile.txt").is_none()); + std::env::remove_var("AGENT_ALLOWED_PATHS"); + } + + #[test] + fn file_path_denies_outside_prefix() { + std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/worktrees/test"); + let result = evaluate_file_path("Edit", "/Users/matt/real-repo/src/main.rs"); + assert!(result.is_some()); + assert!(result.unwrap().reason.contains("outside the allowed workspace")); + std::env::remove_var("AGENT_ALLOWED_PATHS"); + } + + #[test] + fn file_path_denies_read_outside() { + std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/worktrees/test"); + let result = evaluate_file_path("Read", "/Users/matt/real-repo/secrets.env"); + assert!(result.is_some()); + std::env::remove_var("AGENT_ALLOWED_PATHS"); + } + + #[test] + fn file_path_multiple_prefixes() { + std::env::set_var( + "AGENT_ALLOWED_PATHS", + "/tmp/worktrees/test:/home/user/.kb:/tmp", + ); + assert!(evaluate_file_path("Write", "/home/user/.kb/workspace/task.md").is_none()); + assert!(evaluate_file_path("Edit", "/tmp/worktrees/test/code.rs").is_none()); + let result = evaluate_file_path("Edit", "/home/user/real-code/main.rs"); + assert!(result.is_some()); + std::env::remove_var("AGENT_ALLOWED_PATHS"); + } + + #[test] + fn file_path_denial_includes_tool_name() { + std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/allowed"); + let result = evaluate_file_path("NotebookEdit", "/forbidden/notebook.ipynb").unwrap(); + assert!(result.reason.contains("NotebookEdit")); + std::env::remove_var("AGENT_ALLOWED_PATHS"); + } + + // ── handle_guard with tool_name ───────────────────── + + #[test] + fn parse_hook_input_with_tool_name() { + let input = r#"{"tool_name":"Edit","tool_input":{"file_path":"/tmp/test.rs"}}"#; + let hi: HookInput = serde_json::from_str(input).unwrap(); + assert_eq!(hi.tool_name.as_deref(), Some("Edit")); + assert_eq!( + hi.tool_input.as_ref().unwrap().file_path.as_deref(), + Some("/tmp/test.rs") + ); + } + + #[test] + fn parse_hook_input_with_notebook_path() { + let input = + r#"{"tool_name":"NotebookEdit","tool_input":{"notebook_path":"/tmp/nb.ipynb"}}"#; + let hi: HookInput = serde_json::from_str(input).unwrap(); + assert_eq!(hi.tool_name.as_deref(), Some("NotebookEdit")); + assert_eq!( + hi.tool_input.as_ref().unwrap().notebook_path.as_deref(), + Some("/tmp/nb.ipynb") + ); + } + + #[test] + fn parse_hook_input_bash_still_works() { + let input = r#"{"tool_name":"Bash","tool_input":{"command":"git status"}}"#; + let hi: HookInput = serde_json::from_str(input).unwrap(); + assert_eq!(hi.tool_name.as_deref(), Some("Bash")); + assert_eq!( + hi.tool_input.as_ref().unwrap().command.as_deref(), + Some("git status") + ); + assert!(hi.tool_input.as_ref().unwrap().file_path.is_none()); + } + + #[test] + fn resolve_path_handles_existing_paths() { + // /tmp should exist on all platforms + let resolved = resolve_path("/tmp"); + assert!(resolved.starts_with('/')); + // On macOS, /tmp -> /private/tmp + assert!(resolved == "/tmp" || resolved == "/private/tmp"); + } + + #[test] + fn resolve_path_handles_nonexistent_files() { + let resolved = resolve_path("/tmp/nonexistent_guard_test_file.rs"); + // Should resolve parent (/tmp or /private/tmp) + filename + assert!(resolved.ends_with("nonexistent_guard_test_file.rs")); + } } From a3e44f5a5d17b50564eaf100bfa75d554b15b6f6 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 4 Mar 2026 16:52:01 -0600 Subject: [PATCH 2/7] fix: resolve CI test failures for file path sandboxing Three fixes: 1. Resolve allowed prefixes through symlinks too (macOS /tmp -> /private/tmp) 2. Walk up path tree for canonicalization instead of single parent level, ensuring consistent resolution when intermediate dirs exist as symlinks 3. Refactor tests to use evaluate_file_path_with_allowed() instead of env vars, eliminating parallel test race conditions 4. Gate resolve_path Unix-specific tests behind #[cfg(not(windows))] Co-Authored-By: Claude Opus 4.6 --- src/guard.rs | 126 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 80 insertions(+), 46 deletions(-) diff --git a/src/guard.rs b/src/guard.rs index f580bd2..c02a92d 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -403,6 +403,15 @@ pub fn evaluate_file_path(tool_name: &str, file_path: &str) -> Option return None, // No restriction in interactive mode }; + evaluate_file_path_with_allowed(tool_name, file_path, &allowed) +} + +/// Inner implementation that accepts allowed paths explicitly (testable without env vars). +fn evaluate_file_path_with_allowed( + tool_name: &str, + file_path: &str, + allowed: &str, +) -> Option { // Resolve the path to catch traversal (../../..) and symlink escapes. // For files that don't exist yet (Write creating new file), resolve the parent. let resolved = resolve_path(file_path); @@ -420,7 +429,9 @@ pub fn evaluate_file_path(tool_name: &str, file_path: &str) -> Option /private/tmp on macOS) + let resolved_prefix = resolve_path(prefix); + if resolved.starts_with(&resolved_prefix) { return None; // Path is within an allowed prefix } } @@ -435,23 +446,43 @@ pub fn evaluate_file_path(tool_name: &str, file_path: &str) -> Option String { let p = Path::new(path); - // Try full canonicalize first (file exists) + // Try full canonicalize first (entire path exists) if let Ok(canonical) = p.canonicalize() { return canonical.to_string_lossy().to_string(); } - // File doesn't exist — canonicalize parent, append filename - if let Some(parent) = p.parent() { - if let Ok(canonical_parent) = parent.canonicalize() { - if let Some(name) = p.file_name() { - return canonical_parent - .join(name) - .to_string_lossy() - .to_string(); + // Walk up the path tree to find the deepest existing ancestor, + // then rebuild with remaining components. + let mut to_append = Vec::new(); + let mut current = p.to_path_buf(); + + loop { + if let Some(name) = current.file_name() { + to_append.push(name.to_os_string()); + } else { + break; + } + + match current.parent() { + Some(parent) => { + if let Ok(canonical) = parent.canonicalize() { + let mut result = canonical; + for component in to_append.iter().rev() { + result = result.join(component); + } + return result.to_string_lossy().to_string(); + } + current = parent.to_path_buf(); } + None => break, } } @@ -1344,65 +1375,67 @@ message = "medium priority" } // ── File path sandboxing ──────────────────────────── - - #[test] - fn file_path_allows_when_env_unset() { - std::env::remove_var("AGENT_ALLOWED_PATHS"); - assert!(evaluate_file_path("Edit", "/some/random/path").is_none()); - assert!(evaluate_file_path("Write", "/etc/passwd").is_none()); - } - - #[test] - fn file_path_allows_when_env_empty() { - std::env::set_var("AGENT_ALLOWED_PATHS", ""); - assert!(evaluate_file_path("Read", "/any/path").is_none()); - std::env::remove_var("AGENT_ALLOWED_PATHS"); - } + // + // Tests use evaluate_file_path_with_allowed() to avoid env var races + // when tests run in parallel. #[test] fn file_path_allows_within_prefix() { - std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/worktrees/test:/tmp"); - assert!(evaluate_file_path("Edit", "/tmp/worktrees/test/src/main.rs").is_none()); - assert!(evaluate_file_path("Write", "/tmp/somefile.txt").is_none()); - std::env::remove_var("AGENT_ALLOWED_PATHS"); + let allowed = "/tmp/worktrees/test:/tmp"; + assert!(evaluate_file_path_with_allowed( + "Edit", + "/tmp/worktrees/test/src/main.rs", + allowed + ) + .is_none()); + assert!(evaluate_file_path_with_allowed("Write", "/tmp/somefile.txt", allowed).is_none()); } #[test] fn file_path_denies_outside_prefix() { - std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/worktrees/test"); - let result = evaluate_file_path("Edit", "/Users/matt/real-repo/src/main.rs"); + let allowed = "/tmp/worktrees/test"; + let result = + evaluate_file_path_with_allowed("Edit", "/Users/matt/real-repo/src/main.rs", allowed); assert!(result.is_some()); - assert!(result.unwrap().reason.contains("outside the allowed workspace")); - std::env::remove_var("AGENT_ALLOWED_PATHS"); + assert!(result + .unwrap() + .reason + .contains("outside the allowed workspace")); } #[test] fn file_path_denies_read_outside() { - std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/worktrees/test"); - let result = evaluate_file_path("Read", "/Users/matt/real-repo/secrets.env"); + let allowed = "/tmp/worktrees/test"; + let result = + evaluate_file_path_with_allowed("Read", "/Users/matt/real-repo/secrets.env", allowed); assert!(result.is_some()); - std::env::remove_var("AGENT_ALLOWED_PATHS"); } #[test] fn file_path_multiple_prefixes() { - std::env::set_var( - "AGENT_ALLOWED_PATHS", - "/tmp/worktrees/test:/home/user/.kb:/tmp", + let allowed = "/tmp/worktrees/test:/home/user/.kb:/tmp"; + assert!(evaluate_file_path_with_allowed( + "Write", + "/home/user/.kb/workspace/task.md", + allowed, + ) + .is_none()); + assert!( + evaluate_file_path_with_allowed("Edit", "/tmp/worktrees/test/code.rs", allowed) + .is_none() ); - assert!(evaluate_file_path("Write", "/home/user/.kb/workspace/task.md").is_none()); - assert!(evaluate_file_path("Edit", "/tmp/worktrees/test/code.rs").is_none()); - let result = evaluate_file_path("Edit", "/home/user/real-code/main.rs"); + let result = + evaluate_file_path_with_allowed("Edit", "/home/user/real-code/main.rs", allowed); assert!(result.is_some()); - std::env::remove_var("AGENT_ALLOWED_PATHS"); } #[test] fn file_path_denial_includes_tool_name() { - std::env::set_var("AGENT_ALLOWED_PATHS", "/tmp/allowed"); - let result = evaluate_file_path("NotebookEdit", "/forbidden/notebook.ipynb").unwrap(); + let allowed = "/tmp/allowed"; + let result = + evaluate_file_path_with_allowed("NotebookEdit", "/forbidden/notebook.ipynb", allowed) + .unwrap(); assert!(result.reason.contains("NotebookEdit")); - std::env::remove_var("AGENT_ALLOWED_PATHS"); } // ── handle_guard with tool_name ───────────────────── @@ -1442,15 +1475,16 @@ message = "medium priority" assert!(hi.tool_input.as_ref().unwrap().file_path.is_none()); } + #[cfg(not(windows))] #[test] fn resolve_path_handles_existing_paths() { - // /tmp should exist on all platforms let resolved = resolve_path("/tmp"); assert!(resolved.starts_with('/')); // On macOS, /tmp -> /private/tmp assert!(resolved == "/tmp" || resolved == "/private/tmp"); } + #[cfg(not(windows))] #[test] fn resolve_path_handles_nonexistent_files() { let resolved = resolve_path("/tmp/nonexistent_guard_test_file.rs"); From 169844b93b9bbc358cf8f2c8871f8c63b8134176 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 4 Mar 2026 17:02:29 -0600 Subject: [PATCH 3/7] fix: satisfy clippy while_let_loop lint Co-Authored-By: Claude Opus 4.6 --- src/guard.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/src/guard.rs b/src/guard.rs index c02a92d..3126f8e 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -464,26 +464,21 @@ fn resolve_path(path: &str) -> String { let mut to_append = Vec::new(); let mut current = p.to_path_buf(); - loop { - if let Some(name) = current.file_name() { - to_append.push(name.to_os_string()); - } else { + while let Some(name) = current.file_name() { + to_append.push(name.to_os_string()); + + let Some(parent) = current.parent() else { break; - } + }; - match current.parent() { - Some(parent) => { - if let Ok(canonical) = parent.canonicalize() { - let mut result = canonical; - for component in to_append.iter().rev() { - result = result.join(component); - } - return result.to_string_lossy().to_string(); - } - current = parent.to_path_buf(); + if let Ok(canonical) = parent.canonicalize() { + let mut result = canonical; + for component in to_append.iter().rev() { + result = result.join(component); } - None => break, + return result.to_string_lossy().to_string(); } + current = parent.to_path_buf(); } // Last resort: return as-is (already absolute from Claude Code) From 587ac939e4459f57f123fea03b19cb2cf66a796d Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 4 Mar 2026 17:14:19 -0600 Subject: [PATCH 4/7] fix: use OS-native path list parsing for AGENT_ALLOWED_PATHS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use std::env::split_paths instead of splitting on ':' so Windows drive-letter paths (C:\...) aren't broken by the colon delimiter. Unix uses ':', Windows uses ';' — split_paths handles both. Co-Authored-By: Claude Opus 4.6 --- src/guard.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/guard.rs b/src/guard.rs index 3126f8e..90c33c3 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -392,7 +392,7 @@ pub struct DenyReason { // ── File Path Sandboxing ──────────────────────────────── -/// Validate a file path against `AGENT_ALLOWED_PATHS` (colon-separated prefixes). +/// Validate a file path against `AGENT_ALLOWED_PATHS` (OS-native path list: `:` on Unix, `;` on Windows). /// /// When the env var is unset or empty, all paths are allowed (interactive mode). /// When set, the resolved path must start with at least one allowed prefix. @@ -424,13 +424,13 @@ fn evaluate_file_path_with_allowed( ); } - for prefix in allowed.split(':') { - let prefix = prefix.trim(); - if prefix.is_empty() { + // Use split_paths for OS-native parsing (`:` on Unix, `;` on Windows) + for prefix in std::env::split_paths(std::ffi::OsStr::new(allowed)) { + if prefix.as_os_str().is_empty() { continue; } // Resolve the prefix too, so symlinks match (e.g., /tmp -> /private/tmp on macOS) - let resolved_prefix = resolve_path(prefix); + let resolved_prefix = resolve_path(&prefix.to_string_lossy()); if resolved.starts_with(&resolved_prefix) { return None; // Path is within an allowed prefix } From c60c435c5e65864f389da05605ebd23cfd139186 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 4 Mar 2026 17:30:03 -0600 Subject: [PATCH 5/7] fix(guard): harden file path sandboxing against traversal and bypass attacks - Normalize `..` components in resolve_path to prevent traversal via non-existent intermediate paths (e.g., /allowed/nonexistent/../../etc/passwd) - Use Path::starts_with instead of str::starts_with for component-aware prefix matching, preventing /tmp/safe from matching /tmp/safevil - Deny file-path tools with missing path when sandboxing is active, closing fail-open bypass via malformed payloads - Guard Bash destructive-pattern check to only apply to Bash tool - Use std::env::join_paths in tests for cross-platform path separators - Add tests for traversal via .. and partial directory name bypass Co-Authored-By: Claude Opus 4.6 --- src/guard.rs | 105 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 95 insertions(+), 10 deletions(-) diff --git a/src/guard.rs b/src/guard.rs index 90c33c3..26e9f59 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -315,9 +315,13 @@ pub fn handle_guard() -> Result<()> { // File-path tools: validate path against allowed directories if matches!(tool_name, "Edit" | "Write" | "Read" | "NotebookEdit") { - if let Some(ref ti) = hook_input.tool_input { - let path = ti.file_path.as_ref().or(ti.notebook_path.as_ref()); - if let Some(fp) = path { + let path = hook_input + .tool_input + .as_ref() + .and_then(|ti| ti.file_path.as_ref().or(ti.notebook_path.as_ref())); + + match path { + Some(fp) => { if let Some(denial) = evaluate_file_path(tool_name, fp) { let output = HookOutput { hook_specific_output: HookSpecificOutput { @@ -329,11 +333,32 @@ pub fn handle_guard() -> Result<()> { println!("{}", serde_json::to_string(&output)?); } } + None => { + // When sandboxing is active, deny file-path tools with no path + // to prevent bypass via malformed payloads + if std::env::var("AGENT_ALLOWED_PATHS").map_or(false, |v| !v.is_empty()) { + let output = HookOutput { + hook_specific_output: HookSpecificOutput { + hook_event_name: "PreToolUse".to_string(), + permission_decision: "deny".to_string(), + permission_decision_reason: format!( + "{} blocked: no file path provided for sandboxed tool.", + tool_name + ), + }, + }; + println!("{}", serde_json::to_string(&output)?); + } + } } return Ok(()); } - // Bash tool: check command for destructive patterns + // Only evaluate Bash tool for destructive command patterns + if !matches!(tool_name, "" | "Bash") { + return Ok(()); + } + let command = match parse_command(&input) { Some(cmd) => cmd, None => return Ok(()), // No command to evaluate — allow @@ -431,7 +456,9 @@ fn evaluate_file_path_with_allowed( } // Resolve the prefix too, so symlinks match (e.g., /tmp -> /private/tmp on macOS) let resolved_prefix = resolve_path(&prefix.to_string_lossy()); - if resolved.starts_with(&resolved_prefix) { + // Use Path::starts_with for component-aware comparison, preventing + // prefix bypass (e.g., /tmp/safe matching /tmp/safevil) + if Path::new(&resolved).starts_with(Path::new(&resolved_prefix)) { return None; // Path is within an allowed prefix } } @@ -476,13 +503,33 @@ fn resolve_path(path: &str) -> String { for component in to_append.iter().rev() { result = result.join(component); } - return result.to_string_lossy().to_string(); + // Normalize away any remaining `..` components to prevent traversal + return normalize_path(&result).to_string_lossy().to_string(); } current = parent.to_path_buf(); } - // Last resort: return as-is (already absolute from Claude Code) - path.to_string() + // Last resort: normalize and return (already absolute from Claude Code) + normalize_path(Path::new(path)).to_string_lossy().to_string() +} + +/// Normalize a path by collapsing `.` and `..` components logically. +/// Unlike `canonicalize`, this does not require the path to exist. +fn normalize_path(path: &Path) -> std::path::PathBuf { + use std::path::Component; + let mut normalized = std::path::PathBuf::new(); + for component in path.components() { + match component { + Component::ParentDir => { + normalized.pop(); + } + Component::CurDir => {} + _ => { + normalized.push(component); + } + } + } + normalized } // ── Input Parsing ─────────────────────────────────────── @@ -1376,7 +1423,11 @@ message = "medium priority" #[test] fn file_path_allows_within_prefix() { - let allowed = "/tmp/worktrees/test:/tmp"; + let allowed = std::env::join_paths(["/tmp/worktrees/test", "/tmp"]) + .unwrap() + .to_string_lossy() + .to_string(); + let allowed = allowed.as_str(); assert!(evaluate_file_path_with_allowed( "Edit", "/tmp/worktrees/test/src/main.rs", @@ -1408,7 +1459,11 @@ message = "medium priority" #[test] fn file_path_multiple_prefixes() { - let allowed = "/tmp/worktrees/test:/home/user/.kb:/tmp"; + let allowed = std::env::join_paths(["/tmp/worktrees/test", "/home/user/.kb", "/tmp"]) + .unwrap() + .to_string_lossy() + .to_string(); + let allowed = allowed.as_str(); assert!(evaluate_file_path_with_allowed( "Write", "/home/user/.kb/workspace/task.md", @@ -1433,6 +1488,36 @@ message = "medium priority" assert!(result.reason.contains("NotebookEdit")); } + #[test] + fn file_path_denies_traversal_via_dotdot() { + let allowed = "/tmp/worktrees/test"; + // Attempt to escape via .. in a non-existent path + let result = evaluate_file_path_with_allowed( + "Write", + "/tmp/worktrees/test/nonexistent/../../etc/passwd", + allowed, + ); + assert!( + result.is_some(), + "path traversal via .. should be denied" + ); + } + + #[test] + fn file_path_denies_prefix_partial_match() { + let allowed = "/tmp/safe"; + // /tmp/safevil should NOT match /tmp/safe + let result = evaluate_file_path_with_allowed( + "Edit", + "/tmp/safevil/malicious.sh", + allowed, + ); + assert!( + result.is_some(), + "partial directory name match should be denied" + ); + } + // ── handle_guard with tool_name ───────────────────── #[test] From b1dec7bfc01106eb86ac483f2b9533f793cf4004 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 4 Mar 2026 18:10:22 -0600 Subject: [PATCH 6/7] =?UTF-8?q?fix(guard):=20harden=20path=20validation=20?= =?UTF-8?q?=E2=80=94=20validate=20all=20fields,=20reject=20non-absolute,?= =?UTF-8?q?=20use=20var=5Fos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Validate ALL path fields (file_path + notebook_path) in tool payloads, preventing sandbox bypass via a smuggled second path field - Reject empty, whitespace-only, and relative paths early with clear error - Switch to var_os for AGENT_ALLOWED_PATHS to prevent non-UTF8 fail-open bypass - Use tool-specific path selection (notebook_path for NotebookEdit, file_path for others) - Extract emit_denial() helper to reduce HookOutput construction duplication - Add tests for empty, whitespace, and relative path edge cases (126 total) Co-Authored-By: Claude Opus 4.6 --- src/guard.rs | 136 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 85 insertions(+), 51 deletions(-) diff --git a/src/guard.rs b/src/guard.rs index 26e9f59..4e28ad3 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -313,41 +313,39 @@ pub fn handle_guard() -> Result<()> { let tool_name = hook_input.tool_name.as_deref().unwrap_or(""); - // File-path tools: validate path against allowed directories + // File-path tools: validate ALL path fields against allowed directories. + // Both file_path and notebook_path are checked when present, preventing + // bypass via a payload that smuggles a second path field. if matches!(tool_name, "Edit" | "Write" | "Read" | "NotebookEdit") { - let path = hook_input + let paths: Vec<&String> = hook_input .tool_input .as_ref() - .and_then(|ti| ti.file_path.as_ref().or(ti.notebook_path.as_ref())); - - match path { - Some(fp) => { - if let Some(denial) = evaluate_file_path(tool_name, fp) { - let output = HookOutput { - hook_specific_output: HookSpecificOutput { - hook_event_name: "PreToolUse".to_string(), - permission_decision: "deny".to_string(), - permission_decision_reason: denial.reason, - }, - }; - println!("{}", serde_json::to_string(&output)?); + .map(|ti| { + let mut v = Vec::new(); + if let Some(fp) = ti.file_path.as_ref() { + v.push(fp); + } + if let Some(np) = ti.notebook_path.as_ref() { + v.push(np); } + v + }) + .unwrap_or_default(); + + if paths.is_empty() { + // When sandboxing is active, deny file-path tools with no path + // to prevent bypass via malformed payloads + if std::env::var_os("AGENT_ALLOWED_PATHS").is_some_and(|v| !v.is_empty()) { + emit_denial(format!( + "{} blocked: no file path provided for sandboxed tool.", + tool_name + ))?; } - None => { - // When sandboxing is active, deny file-path tools with no path - // to prevent bypass via malformed payloads - if std::env::var("AGENT_ALLOWED_PATHS").map_or(false, |v| !v.is_empty()) { - let output = HookOutput { - hook_specific_output: HookSpecificOutput { - hook_event_name: "PreToolUse".to_string(), - permission_decision: "deny".to_string(), - permission_decision_reason: format!( - "{} blocked: no file path provided for sandboxed tool.", - tool_name - ), - }, - }; - println!("{}", serde_json::to_string(&output)?); + } else { + for fp in &paths { + if let Some(denial) = evaluate_file_path(tool_name, fp) { + emit_denial(denial.reason)?; + break; } } } @@ -365,14 +363,7 @@ pub fn handle_guard() -> Result<()> { }; if let Some(denial) = evaluate_command(&command) { - let output = HookOutput { - hook_specific_output: HookSpecificOutput { - hook_event_name: "PreToolUse".to_string(), - permission_decision: "deny".to_string(), - permission_decision_reason: denial.reason, - }, - }; - println!("{}", serde_json::to_string(&output)?); + emit_denial(denial.reason)?; } Ok(()) @@ -415,6 +406,19 @@ pub struct DenyReason { pub reason: String, } +/// Emit a denial JSON response to stdout. +fn emit_denial(reason: String) -> Result<()> { + let output = HookOutput { + hook_specific_output: HookSpecificOutput { + hook_event_name: "PreToolUse".to_string(), + permission_decision: "deny".to_string(), + permission_decision_reason: reason, + }, + }; + println!("{}", serde_json::to_string(&output)?); + Ok(()) +} + // ── File Path Sandboxing ──────────────────────────────── /// Validate a file path against `AGENT_ALLOWED_PATHS` (OS-native path list: `:` on Unix, `;` on Windows). @@ -423,8 +427,8 @@ pub struct DenyReason { /// When set, the resolved path must start with at least one allowed prefix. /// Resolves symlinks and `..` components to prevent path traversal escapes. pub fn evaluate_file_path(tool_name: &str, file_path: &str) -> Option { - let allowed = match std::env::var("AGENT_ALLOWED_PATHS") { - Ok(v) if !v.is_empty() => v, + let allowed = match std::env::var_os("AGENT_ALLOWED_PATHS") { + Some(v) if !v.is_empty() => v.to_string_lossy().to_string(), _ => return None, // No restriction in interactive mode }; @@ -437,9 +441,21 @@ fn evaluate_file_path_with_allowed( file_path: &str, allowed: &str, ) -> Option { + // Reject empty and relative paths early — Claude Code should always send absolute paths, + // so anything else is suspicious. This prevents CWD-dependent canonicalization surprises. + let trimmed_path = file_path.trim(); + if trimmed_path.is_empty() || !Path::new(trimmed_path).is_absolute() { + return Some(DenyReason { + reason: format!( + "{} blocked: path must be absolute, got '{}'.", + tool_name, file_path + ), + }); + } + // Resolve the path to catch traversal (../../..) and symlink escapes. // For files that don't exist yet (Write creating new file), resolve the parent. - let resolved = resolve_path(file_path); + let resolved = resolve_path(trimmed_path); // Debug logging if std::env::var("META_DEBUG_GUARD").is_ok() { @@ -510,7 +526,9 @@ fn resolve_path(path: &str) -> String { } // Last resort: normalize and return (already absolute from Claude Code) - normalize_path(Path::new(path)).to_string_lossy().to_string() + normalize_path(Path::new(path)) + .to_string_lossy() + .to_string() } /// Normalize a path by collapsing `.` and `..` components logically. @@ -1497,27 +1515,43 @@ message = "medium priority" "/tmp/worktrees/test/nonexistent/../../etc/passwd", allowed, ); - assert!( - result.is_some(), - "path traversal via .. should be denied" - ); + assert!(result.is_some(), "path traversal via .. should be denied"); } #[test] fn file_path_denies_prefix_partial_match() { let allowed = "/tmp/safe"; // /tmp/safevil should NOT match /tmp/safe - let result = evaluate_file_path_with_allowed( - "Edit", - "/tmp/safevil/malicious.sh", - allowed, - ); + let result = evaluate_file_path_with_allowed("Edit", "/tmp/safevil/malicious.sh", allowed); assert!( result.is_some(), "partial directory name match should be denied" ); } + #[test] + fn file_path_denies_empty_path() { + let allowed = "/tmp/worktrees/test"; + let result = evaluate_file_path_with_allowed("Edit", "", allowed); + assert!(result.is_some(), "empty path should be denied"); + assert!(result.unwrap().reason.contains("must be absolute")); + } + + #[test] + fn file_path_denies_whitespace_only_path() { + let allowed = "/tmp/worktrees/test"; + let result = evaluate_file_path_with_allowed("Write", " ", allowed); + assert!(result.is_some(), "whitespace-only path should be denied"); + } + + #[test] + fn file_path_denies_relative_path() { + let allowed = "/tmp/worktrees/test"; + let result = evaluate_file_path_with_allowed("Write", "../../etc/passwd", allowed); + assert!(result.is_some(), "relative path should be denied"); + assert!(result.unwrap().reason.contains("must be absolute")); + } + // ── handle_guard with tool_name ───────────────────── #[test] From b04891b25f5f2bcd6d6c5dd6a11c0895828222ec Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 4 Mar 2026 18:13:25 -0600 Subject: [PATCH 7/7] fix(guard): gate file path sandbox tests with cfg(not(windows)) Unix-style paths like /tmp/... are not absolute on Windows, causing test failures after adding the is_absolute() early rejection check. All file path sandbox tests now skip on Windows, matching the existing pattern used by resolve_path tests. Co-Authored-By: Claude Opus 4.6 --- src/guard.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/guard.rs b/src/guard.rs index 4e28ad3..44d79cc 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -1437,8 +1437,10 @@ message = "medium priority" // ── File path sandboxing ──────────────────────────── // // Tests use evaluate_file_path_with_allowed() to avoid env var races - // when tests run in parallel. + // when tests run in parallel. Tests use Unix-style paths and are + // skipped on Windows where `/tmp/...` is not considered absolute. + #[cfg(not(windows))] #[test] fn file_path_allows_within_prefix() { let allowed = std::env::join_paths(["/tmp/worktrees/test", "/tmp"]) @@ -1455,6 +1457,7 @@ message = "medium priority" assert!(evaluate_file_path_with_allowed("Write", "/tmp/somefile.txt", allowed).is_none()); } + #[cfg(not(windows))] #[test] fn file_path_denies_outside_prefix() { let allowed = "/tmp/worktrees/test"; @@ -1467,6 +1470,7 @@ message = "medium priority" .contains("outside the allowed workspace")); } + #[cfg(not(windows))] #[test] fn file_path_denies_read_outside() { let allowed = "/tmp/worktrees/test"; @@ -1475,6 +1479,7 @@ message = "medium priority" assert!(result.is_some()); } + #[cfg(not(windows))] #[test] fn file_path_multiple_prefixes() { let allowed = std::env::join_paths(["/tmp/worktrees/test", "/home/user/.kb", "/tmp"]) @@ -1497,6 +1502,7 @@ message = "medium priority" assert!(result.is_some()); } + #[cfg(not(windows))] #[test] fn file_path_denial_includes_tool_name() { let allowed = "/tmp/allowed"; @@ -1506,6 +1512,7 @@ message = "medium priority" assert!(result.reason.contains("NotebookEdit")); } + #[cfg(not(windows))] #[test] fn file_path_denies_traversal_via_dotdot() { let allowed = "/tmp/worktrees/test"; @@ -1518,6 +1525,7 @@ message = "medium priority" assert!(result.is_some(), "path traversal via .. should be denied"); } + #[cfg(not(windows))] #[test] fn file_path_denies_prefix_partial_match() { let allowed = "/tmp/safe"; @@ -1529,6 +1537,7 @@ message = "medium priority" ); } + #[cfg(not(windows))] #[test] fn file_path_denies_empty_path() { let allowed = "/tmp/worktrees/test"; @@ -1537,6 +1546,7 @@ message = "medium priority" assert!(result.unwrap().reason.contains("must be absolute")); } + #[cfg(not(windows))] #[test] fn file_path_denies_whitespace_only_path() { let allowed = "/tmp/worktrees/test"; @@ -1544,6 +1554,7 @@ message = "medium priority" assert!(result.is_some(), "whitespace-only path should be denied"); } + #[cfg(not(windows))] #[test] fn file_path_denies_relative_path() { let allowed = "/tmp/worktrees/test";