Repository navigation
feat(guard): file path sandboxing via AGENT_ALLOWED_PATHS - #3
Conversation
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 <noreply@anthropic.com>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds file-path sandboxing to the guard module: a public Changes
Sequence DiagramsequenceDiagram
participant Tool as File Operation Tool
participant Guard as Guard Module
participant Resolver as Path Resolver
participant Allowed as Allowed Paths Checker
participant Response as Response Handler
Tool->>Guard: handle_guard(tool_name, hook_input)
Guard->>Resolver: resolve_path(hook_input.file_path / notebook_path)
Resolver-->>Guard: canonicalized_path
Guard->>Allowed: evaluate_file_path(tool_name, canonicalized_path)
Allowed-->>Guard: None or Some(DenyReason)
alt Path Allowed
Guard->>Response: allow execution / continue flow
else Path Denied
Guard->>Response: emit denial JSON (DenyReason)
end
Response-->>Tool: decision/result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/guard.rs (1)
336-340: 🧹 Nitpick | 🔵 TrivialRedundant JSON parsing — reuse already-parsed
hook_input.The code parses
inputtwice: once at line 309 intohook_input, then again at line 337 viaparse_command(&input). For Bash tools, extract the command directly fromhook_input.tool_input.♻️ Proposed fix to reuse parsed input
- // Bash tool: check command for destructive patterns - let command = match parse_command(&input) { - Some(cmd) => cmd, - None => return Ok(()), // No command to evaluate — allow - }; + // Bash tool: check command for destructive patterns + let command = match hook_input.tool_input.and_then(|ti| ti.command) { + Some(cmd) if !cmd.trim().is_empty() => cmd, + _ => return Ok(()), // No command to evaluate — allow + };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/guard.rs` around lines 336 - 340, The code currently reparses `input` with parse_command(&input) even though JSON was already deserialized into `hook_input` earlier; modify the Bash tool command extraction to read from `hook_input.tool_input` (or its appropriate field) instead of calling parse_command(&input) again, and pass that string into the existing command parsing logic (or directly parse it) so you reuse the already-parsed structure (`hook_input`) and remove the redundant parse_command(&input) branch while preserving the same None => return Ok(()) behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/guard.rs`:
- Around line 1370-1377: The test function file_path_denies_outside_prefix in
src/guard.rs has formatting issues flagged by CI; run rustfmt (cargo fmt --all)
or reformat the file so the test and surrounding code match the project's Rust
formatting style, then re-run tests; ensure evaluate_file_path usage and the
set/remove env var lines are formatted correctly and commit the formatted
changes.
- Around line 446-456: The CI failure is due to formatting issues in the block
handling missing files (the branch that uses p.parent(), parent.canonicalize(),
p.file_name(), and canonical_parent.join(name).to_string_lossy()); fix it by
running `cargo fmt --all` (or applying rustfmt) to reformat src/guard.rs so the
indentation and spacing around that if-let chain matches project style, then
re-run CI; no logic changes required—only formatting for the p.parent() /
canonical_parent.join(name).to_string_lossy() block.
- Around line 458-460: The fallback that returns path.to_string() may leave
unresolved ".." components; update the fallback in src/guard.rs (where
canonicalize() is used and currently falls back to returning path.to_string())
to either (A) normalize the path components manually by iterating
Path::components() and resolving '.' and '..' (rejecting/returning an error if
'..' would climb above the allowed root) before returning the normalized string,
or (B) outright reject/unable-to-resolve paths instead of returning the raw
string; ensure you operate on the same "path" variable and preserve the
subsequent prefix check semantics so no ".." can bypass the prefix.
- Around line 1348-1359: These tests manipulate the AGENT_ALLOWED_PATHS env var
unsafely and must be serialized; add the serial_test crate as a dev-dependency
and annotate each affected test function (file_path_allows_when_env_unset,
file_path_allows_when_env_empty, file_path_allows_within_prefix,
file_path_denies_outside_prefix, file_path_denies_read_outside,
file_path_multiple_prefixes, file_path_denial_includes_tool_name) with the
#[serial] attribute (or alternatively guard env access with a shared Mutex
helper) so std::env::set_var/remove_var no longer run concurrently and cause
flakiness. Ensure you import #[serial] in the test module and run cargo test
normally afterward.
- Around line 418-426: The loop uses character-based String::starts_with and can
be bypassed by names like "/tmp/testevil"; change to path-component comparison
by converting prefix into a Path (e.g., Path::new(prefix)) and use
resolved_path.starts_with(prefix_path) instead of resolved.starts_with(prefix),
ensuring you operate on the canonicalized resolved path (the variable named
resolved or its Path/PathBuf form) and continue to trim/skip empty prefixes;
this replaces the vulnerable string prefix check with Path::starts_with to
correctly compare path components.
---
Outside diff comments:
In `@src/guard.rs`:
- Around line 336-340: The code currently reparses `input` with
parse_command(&input) even though JSON was already deserialized into
`hook_input` earlier; modify the Bash tool command extraction to read from
`hook_input.tool_input` (or its appropriate field) instead of calling
parse_command(&input) again, and pass that string into the existing command
parsing logic (or directly parse it) so you reuse the already-parsed structure
(`hook_input`) and remove the redundant parse_command(&input) branch while
preserving the same None => return Ok(()) behavior.
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 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/guard.rs (2)
427-435:⚠️ Potential issue | 🔴 CriticalUse path-component containment, not string-prefix matching.
At Line 434,
resolved.starts_with(&resolved_prefix)is byte-prefix matching and can allow boundary bypasses like/tmp/testevil/...for allowed/tmp/test.🔒 Proposed fix
- let resolved_prefix = resolve_path(prefix); - if resolved.starts_with(&resolved_prefix) { + let resolved_prefix = resolve_path(prefix); + if Path::new(&resolved).starts_with(Path::new(&resolved_prefix)) { return None; // Path is within an allowed prefix }#!/bin/bash # Verify current implementation still uses string-prefix comparison rg -n 'resolved\.starts_with\(&resolved_prefix\)' src/guard.rs -C 2🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/guard.rs` around lines 427 - 435, The code currently uses byte-prefix matching via resolved.starts_with(&resolved_prefix), which permits boundary bypasses; change to component-aware path containment by converting both resolved and resolved_prefix to std::path::Path and using Path::starts_with (or comparing components/ancestors) so only true path-component prefixes match; update the block around resolve_path, the loop over allowed.split(':') and the resolved.starts_with check to use Path::new(&resolved).starts_with(Path::new(&resolved_prefix)) (or an equivalent components-based comparison) and ensure both paths are canonical/resolved before comparison.
489-490:⚠️ Potential issue | 🔴 CriticalFail closed when fallback resolution cannot eliminate traversal components.
At Line 490, returning raw
path.to_string()can preserve unresolved..segments, weakening containment checks for partially non-existent paths.🛡️ Proposed hardening
- // Last resort: return as-is (already absolute from Claude Code) - path.to_string() + // Last resort: lexical normalization (no filesystem access) to collapse `.` / `..`. + // Fail closed if traversal cannot be resolved safely. + let mut normalized = std::path::PathBuf::new(); + for component in p.components() { + match component { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + if !normalized.pop() { + return String::new(); // forces deny in prefix checks + } + } + _ => normalized.push(component.as_os_str()), + } + } + normalized.to_string_lossy().to_string()#!/bin/bash # Verify fallback currently returns raw path sed -n '485,492p' src/guard.rs🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/guard.rs` around lines 489 - 490, The fallback branch that currently returns path.to_string() can preserve unresolved traversal components (e.g., "..") and weaken containment checks; instead, update the fallback in the resolver/sanitizer function that contains path.to_string() so it fails closed: attempt a final canonicalization (e.g., std::fs::canonicalize or equivalent) and if canonicalization fails or yields a path outside the expected root, return an error (Result::Err) with a clear InvalidPathTraversal/InvalidPath error rather than returning the raw string, ensuring unresolved "../" are never accepted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/guard.rs`:
- Around line 467-487: Refactor the manual loop that pulls file_name and walks
up parents into a while-let: replace the outer loop and the initial if-let on
current.file_name() with a while let Some(name) = current.file_name() {
to_append.push(name.to_os_string()); 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, } } so the code still uses current, to_append, parent.canonicalize(),
and result but uses idiomatic while-let to satisfy clippy.
---
Duplicate comments:
In `@src/guard.rs`:
- Around line 427-435: The code currently uses byte-prefix matching via
resolved.starts_with(&resolved_prefix), which permits boundary bypasses; change
to component-aware path containment by converting both resolved and
resolved_prefix to std::path::Path and using Path::starts_with (or comparing
components/ancestors) so only true path-component prefixes match; update the
block around resolve_path, the loop over allowed.split(':') and the
resolved.starts_with check to use
Path::new(&resolved).starts_with(Path::new(&resolved_prefix)) (or an equivalent
components-based comparison) and ensure both paths are canonical/resolved before
comparison.
- Around line 489-490: The fallback branch that currently returns
path.to_string() can preserve unresolved traversal components (e.g., "..") and
weaken containment checks; instead, update the fallback in the
resolver/sanitizer function that contains path.to_string() so it fails closed:
attempt a final canonicalization (e.g., std::fs::canonicalize or equivalent) and
if canonicalization fails or yields a path outside the expected root, return an
error (Result::Err) with a clear InvalidPathTraversal/InvalidPath error rather
than returning the raw string, ensuring unresolved "../" are never accepted.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/guard.rs (1)
433-435:⚠️ Potential issue | 🔴 CriticalCritical: sandbox escape remains possible in prefix check and unresolved traversal handling.
Line 434 uses byte-prefix matching, so
/tmp/testevil/...matches allowed/tmp/test. Also, Lines 474-485 can return/rebuild paths that still contain.., which can bypass workspace intent for non-existent targets.🔒 Suggested hardening (component-aware + lexical normalization)
-use std::path::Path; +use std::path::{Component, Path, PathBuf}; @@ - let resolved_prefix = resolve_path(prefix); - if resolved.starts_with(&resolved_prefix) { + let resolved_prefix = resolve_path(prefix); + let resolved_path = normalize_lexical(Path::new(&resolved)); + let prefix_path = normalize_lexical(Path::new(&resolved_prefix)); + if resolved_path.starts_with(&prefix_path) { return None; // Path is within an allowed prefix } @@ - // Last resort: return as-is (already absolute from Claude Code) - path.to_string() + // Last resort: normalize lexically to remove "." and ".." components. + normalize_lexical(p).to_string_lossy().to_string() } + +fn normalize_lexical(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for c in path.components() { + match c { + Component::CurDir => {} + Component::ParentDir => { + let _ = out.pop(); + } + Component::Prefix(_) | Component::RootDir | Component::Normal(_) => { + out.push(c.as_os_str()); + } + } + } + out +}Also applies to: 474-485
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/guard.rs` around lines 433 - 435, The current prefix check uses byte-prefix matching on resolved and resolved_prefix (resolved.starts_with(&resolved_prefix)) and the path-rebuilding code later can return paths still containing "..", allowing sandbox escape; fix by making resolve_path produce a lexical-normalized Path with all "."/".." resolved (no ParentDir components) and then perform a component-aware prefix check: compare prefix and candidate by iterating Path::components and ensuring the candidate's first N components exactly equal the prefix components (or append a separator boundary check) rather than starts_with on bytes; additionally, after any path rebuild (the code that currently may return/rebuild paths with "..") validate that no Component::ParentDir remains and reject or return None if normalization fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/guard.rs`:
- Line 427: The code currently parses AGENT_ALLOWED_PATHS by splitting the
string on ':' (the loop at "for prefix in allowed.split(':')"), which breaks on
Windows paths; change it to use std::env::split_paths to parse the environment
variable into platform-native PathBufs, then iterate those paths (e.g., replace
the split and the "prefix" string usage with the iterator returned by
split_paths and use Path/PathBuf comparisons accordingly) so AGENT_ALLOWED_PATHS
is handled correctly on Windows and Unix.
---
Duplicate comments:
In `@src/guard.rs`:
- Around line 433-435: The current prefix check uses byte-prefix matching on
resolved and resolved_prefix (resolved.starts_with(&resolved_prefix)) and the
path-rebuilding code later can return paths still containing "..", allowing
sandbox escape; fix by making resolve_path produce a lexical-normalized Path
with all "."/".." resolved (no ParentDir components) and then perform a
component-aware prefix check: compare prefix and candidate by iterating
Path::components and ensuring the candidate's first N components exactly equal
the prefix components (or append a separator boundary check) rather than
starts_with on bytes; additionally, after any path rebuild (the code that
currently may return/rebuild paths with "..") validate that no
Component::ParentDir remains and reject or return None if normalization fails.
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 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/guard.rs (1)
433-435:⚠️ Potential issue | 🔴 CriticalUse path-component comparison for sandbox boundary checks.
Line 434 performs a
String::starts_withcheck, which is bypassable (/tmp/testevil/...matches allowed/tmp/test). This weakens the sandbox boundary.🔒 Proposed fix
- let resolved_prefix = resolve_path(&prefix.to_string_lossy()); - if resolved.starts_with(&resolved_prefix) { + let resolved_prefix = resolve_path(&prefix.to_string_lossy()); + let resolved_path = Path::new(&resolved); + let prefix_path = Path::new(&resolved_prefix); + if resolved_path.starts_with(prefix_path) { return None; // Path is within an allowed prefix }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/guard.rs` around lines 433 - 435, The sandbox check currently computes resolved_prefix via resolve_path(&prefix.to_string_lossy()) and then uses resolved.starts_with(&resolved_prefix), which can be bypassed by path strings; change the logic to perform path-component comparison instead: canonicalize/normalize both resolved and resolved_prefix into Path (or use resolve_path to return a PathBuf), then check that resolved == resolved_prefix or that resolved has resolved_prefix as a parent (e.g., iterate ancestors or use Path::starts_with on Path values) so only true directory boundaries are accepted; update the check around the variables resolved, resolved_prefix, prefix, and the function resolve_path to operate on Path/PathBuf component-aware comparisons rather than String::starts_with.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/guard.rs`:
- Around line 1379-1383: The tests hard-code ":" as the path-separator when
constructing the allowed-path string, which breaks on Windows; replace those
literals by building the allowed string using std::env::join_paths (or PathBufs
collected into an iterator) so separators are OS-native, e.g., construct a
Vec<PathBuf> of the prefixes used in the tests and call std::env::join_paths to
produce the allowed string passed to evaluate_file_path_with_allowed (update the
instances around evaluate_file_path_with_allowed calls such as the one
referencing "/tmp/worktrees/test:/tmp" and the other at line ~1411).
---
Duplicate comments:
In `@src/guard.rs`:
- Around line 433-435: The sandbox check currently computes resolved_prefix via
resolve_path(&prefix.to_string_lossy()) and then uses
resolved.starts_with(&resolved_prefix), which can be bypassed by path strings;
change the logic to perform path-component comparison instead:
canonicalize/normalize both resolved and resolved_prefix into Path (or use
resolve_path to return a PathBuf), then check that resolved == resolved_prefix
or that resolved has resolved_prefix as a parent (e.g., iterate ancestors or use
Path::starts_with on Path values) so only true directory boundaries are
accepted; update the check around the variables resolved, resolved_prefix,
prefix, and the function resolve_path to operate on Path/PathBuf component-aware
comparisons rather than String::starts_with.
…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 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/guard.rs (1)
510-513:⚠️ Potential issue | 🟡 MinorCI is still failing rustfmt on the new path-sandbox code/tests.
Please run
cargo fmt --all; pipeline is reporting formatting mismatches in this block (including Line 510 and the traversal/prefix tests).Also applies to: 1492-1518
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/guard.rs` around lines 510 - 513, CI reports rustfmt mismatches around the path-sandbox changes; run `cargo fmt --all` to reformat the codebase, then commit the formatted files—specifically reformat the block using normalize_path(Path::new(path)).to_string_lossy().to_string() and nearby tests (including traversal/prefix tests and the region around lines referenced by function normalize_path) so rustfmt no longer flags differences.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/guard.rs`:
- Around line 317-322: The current selection of path in src/guard.rs (uses
hook_input.tool_input -> file_path.or(notebook_path)) is ambiguous and can
validate file_path for a NotebookEdit; change the logic so the chosen field is
tool-specific: when tool_name == "NotebookEdit" pick ti.notebook_path only
(validate notebook_path and reject if missing), and for "Edit" | "Write" |
"Read" pick ti.file_path only (validate file_path and reject if missing). Update
the code that builds `path` from `hook_input.tool_input` (references:
hook_input, tool_input, file_path, notebook_path, and the tool_name match) to
use an explicit match on tool_name and validate the correct field to prevent
sandbox bypass.
- Line 339: Replace uses of std::env::var("AGENT_ALLOWED_PATHS") with
std::env::var_os("AGENT_ALLOWED_PATHS") in the guard logic (both places
currently referencing AGENT_ALLOWED_PATHS) so non-UTF8 env values are preserved;
update the option handling closures to accept OsString/OsStr (e.g.,
map_or(false, |v: OsString| !v.is_empty())) and ensure subsequent calls that
parse paths use std::env::split_paths on the OsStr/OsString (the existing
split_paths calls already accept OsStr), avoiding the fail-open behavior on
non-UTF8 values.
---
Duplicate comments:
In `@src/guard.rs`:
- Around line 510-513: CI reports rustfmt mismatches around the path-sandbox
changes; run `cargo fmt --all` to reformat the codebase, then commit the
formatted files—specifically reformat the block using
normalize_path(Path::new(path)).to_string_lossy().to_string() and nearby tests
(including traversal/prefix tests and the region around lines referenced by
function normalize_path) so rustfmt no longer flags differences.
…absolute, use var_os - 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 <noreply@anthropic.com>
Fixes in b1dec7bReview Comments AddressedCritical — Tool-specific path selection bypass (#2886686134) Major — Non-UTF8 env var bypass (#2886686141) Formatting (#2886546289, #2886546305) Self-Review Fixes
Already Fixed (Verified Still Present)
Known Limitations (Not Fixed)
CI: clippy, fmt, 126 tests all pass locally. |
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 <noreply@anthropic.com>
Final SummaryAll CI checks green, all review comments addressed. Commits
Review Comments ResolvedAll 10 CodeRabbit comments addressed:
Self-Review Fixes
Known Limitations (for human review)
CI: All 5 checks pass (Test ubuntu/macos/windows, Clippy, Format) |
Summary
meta agent guardfor Edit/Write/Read/NotebookEdit toolsAGENT_ALLOWED_PATHSenv var is set (colon-separated directory prefixes), file operations outside those paths are deniedMotivation
Dispatched agents running with
--dangerously-skip-permissionscould escape their worktree and write to the actual repo. This adds OS-level enforcement via the PreToolUse hook.Test plan
AGENT_ALLOWED_PATHS=/tmp/testand verify Edit to/tmp/test/file.rsis allowedAGENT_ALLOWED_PATHS=/tmp/testand verify Edit to/home/user/file.rsis denied🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests