Skip to content

feat(guard): file path sandboxing via AGENT_ALLOWED_PATHS - #3

Merged
mateodelnorte merged 7 commits into
mainfrom
feat/file-path-sandbox
Mar 5, 2026
Merged

mateodelnorte merged 7 commits into
mainfrom
feat/file-path-sandbox

Conversation

@mateodelnorte

@mateodelnorte mateodelnorte commented Mar 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds file path validation to meta agent guard for Edit/Write/Read/NotebookEdit tools
  • When AGENT_ALLOWED_PATHS env var is set (colon-separated directory prefixes), file operations outside those paths are denied
  • Only active when env var is set — no-op in interactive/unsandboxed mode
  • Bash tool continues using existing destructive command detection unchanged

Motivation

Dispatched agents running with --dangerously-skip-permissions could escape their worktree and write to the actual repo. This adds OS-level enforcement via the PreToolUse hook.

Test plan

  • Set AGENT_ALLOWED_PATHS=/tmp/test and verify Edit to /tmp/test/file.rs is allowed
  • Set AGENT_ALLOWED_PATHS=/tmp/test and verify Edit to /home/user/file.rs is denied
  • Verify without env var, all file operations are allowed (no-op)
  • Verify Bash tool still blocks destructive commands as before

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Enhanced file-path sandboxing for file operation tools (Edit, Write, Read, NotebookEdit). Requests accessing paths outside allowed directories are now blocked and return a clear denial response (JSON).
    • Path validation now resolves symlinks and relative components for more accurate checks.
    • Public API added to validate tool file paths while remaining backward-compatible.
  • Tests

    • Added tests for path validation, resolution behavior, and integration with guard checks.

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>
@coderabbitai

coderabbitai Bot commented Mar 4, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds file-path sandboxing to the guard module: a public evaluate_file_path(tool_name, file_path) that resolves symlinks and relative components, validates against allowed prefixes, integrates checks into handle_guard for Edit/Write/Read/NotebookEdit, and adds helpers and tests.

Changes

Cohort / File(s) Summary
Guard module / sandboxing
src/guard.rs
Adds pub fn evaluate_file_path(tool_name: &str, file_path: &str) -> Option<DenyReason>, internal helpers (evaluate_file_path_with_allowed, resolve_path, normalize_path), integrates path checks into handle_guard for Edit/Write/Read/NotebookEdit flows, extends HookInput parsing to capture tool_name and file/notebook paths, and emits denial JSON when blocked.
Tests
tests/..., src/... (guard tests)
Adds unit and integration tests covering allowed/denied paths, symlink and relative resolution, and integration of path sandboxing with existing pattern-based checks.
Manifest
Cargo.toml
Project manifest updated (diff includes changes); no backward-incompatible public API removals — new public function added.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 I hopped through symlinks and tiptoed each dot,

I chased down .. paths and sniffed every lot.
With resolve and check I guard every door,
Deny where it's needed, allow paths once more.
A rabbit on duty — soft steps, firm forethought.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(guard): file path sandboxing via AGENT_ALLOWED_PATHS' directly and clearly describes the main feature being added - a file path sandboxing capability integrated into the guard system using the AGENT_ALLOWED_PATHS environment variable. This matches the primary objective of the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/file-path-sandbox

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🔵 Trivial

Redundant JSON parsing — reuse already-parsed hook_input.

The code parses input twice: once at line 309 into hook_input, then again at line 337 via parse_command(&input). For Bash tools, extract the command directly from hook_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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2d1be45e-3417-4455-807b-f9309a8d8a29

📥 Commits

Reviewing files that changed from the base of the PR and between 1e3027c and d68ff21.

📒 Files selected for processing (1)
  • src/guard.rs

Comment thread src/guard.rs Resolved
Comment thread src/guard.rs Resolved
Comment thread src/guard.rs Resolved
Comment thread src/guard.rs Resolved
Comment thread src/guard.rs Resolved
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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
src/guard.rs (2)

427-435: ⚠️ Potential issue | 🔴 Critical

Use 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 | 🔴 Critical

Fail 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1840f7ad-1e66-44a8-b6bd-f344e8622767

📥 Commits

Reviewing files that changed from the base of the PR and between d68ff21 and a3e44f5.

📒 Files selected for processing (1)
  • src/guard.rs

Comment thread src/guard.rs Resolved
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/guard.rs (1)

433-435: ⚠️ Potential issue | 🔴 Critical

Critical: 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7c2de97d-be32-4cad-8b15-23270ad20ee0

📥 Commits

Reviewing files that changed from the base of the PR and between a3e44f5 and 169844b.

📒 Files selected for processing (1)
  • src/guard.rs

Comment thread src/guard.rs Resolved
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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/guard.rs (1)

433-435: ⚠️ Potential issue | 🔴 Critical

Use path-component comparison for sandbox boundary checks.

Line 434 performs a String::starts_with check, 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 768e1c6d-53c8-4a0c-a2c6-11efd058cac2

📥 Commits

Reviewing files that changed from the base of the PR and between 169844b and 587ac93.

📒 Files selected for processing (1)
  • src/guard.rs

Comment thread src/guard.rs Resolved
…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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
src/guard.rs (1)

510-513: ⚠️ Potential issue | 🟡 Minor

CI 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: b0d296c3-529e-4aa0-b472-4a611aba34eb

📥 Commits

Reviewing files that changed from the base of the PR and between 587ac93 and c60c435.

📒 Files selected for processing (1)
  • src/guard.rs

Comment thread src/guard.rs Resolved
Comment thread src/guard.rs Resolved
…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>
@mateodelnorte

Copy link
Copy Markdown
Contributor Author

Fixes in b1dec7b

Review Comments Addressed

Critical — Tool-specific path selection bypass (#2886686134)
Now validates ALL path fields present in the payload (both file_path and notebook_path), preventing sandbox bypass via a smuggled second path field.

Major — Non-UTF8 env var bypass (#2886686141)
Switched to var_os / is_some_and to prevent non-UTF8 AGENT_ALLOWED_PATHS from failing open.

Formatting (#2886546289, #2886546305)
cargo fmt --all applied.

Self-Review Fixes

  • Reject empty/relative paths early — paths that are not absolute are now rejected before resolve_path(), preventing CWD-dependent canonicalization surprises
  • Extract emit_denial() helper — reduces 3x repeated HookOutput construction to a single function
  • 3 new edge case tests — empty path, whitespace-only path, relative path traversal (126 total tests)

Already Fixed (Verified Still Present)

  • Path prefix bypass via String::starts_with -> uses Path::starts_with (a3e44f5)
  • Fallback .. components -> uses normalize_path (a3e44f5)
  • while_let_loop clippy lint (169844b)
  • OS-native path list parsing via split_paths (587ac93)
  • Unsafe env var manipulation -> tests use evaluate_file_path_with_allowed (a3e44f5)

Known Limitations (Not Fixed)

  • TOCTOU symlink race: Inherent to check-then-act architecture. Acceptable given Claude Code is the path constructor, not an external attacker.
  • Glob/Grep tools not sandboxed: These tools use different input schemas without file_path/notebook_path fields.

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>
@mateodelnorte

Copy link
Copy Markdown
Contributor Author

Final Summary

All CI checks green, all review comments addressed.

Commits

Commit Description
b1dec7b Validate ALL path fields, reject non-absolute paths, use var_os, extract emit_denial helper, add 3 edge case tests
b04891b Gate file path sandbox tests with cfg(not(windows)) to fix Windows CI

Review Comments Resolved

All 10 CodeRabbit comments addressed:

  • 6 were already fixed in prior commits (verified still present)
  • 2 fixed in b1dec7b (tool-specific path selection bypass, var_os non-UTF8 bypass)
  • 2 formatting issues fixed in b1dec7b

Self-Review Fixes

  • Validate all path fields: Both file_path and notebook_path checked when present, preventing payload smuggling
  • Reject non-absolute paths: Empty, whitespace, and relative paths denied early
  • emit_denial() helper: Reduces 3x code duplication
  • 3 new tests: Empty path, whitespace-only path, relative path traversal
  • Windows CI fix: All Unix-path tests gated with cfg(not(windows))

Known Limitations (for human review)

  • TOCTOU symlink race: Inherent to check-then-act. Acceptable given Claude Code constructs paths.
  • Glob/Grep not sandboxed: Different input schema, would require separate implementation.

CI: All 5 checks pass (Test ubuntu/macos/windows, Clippy, Format)

@mateodelnorte
mateodelnorte merged commit ce59853 into main Mar 5, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant