openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(security): always canonicalize paths before policy check

Open M3gA-Mind opened this issue 6 months ago • 2 comments

Summary

  • Renamed is_path_allowed → is_path_string_allowed (string-only, no symlink resolution) and made the split intent explicit via a doc-comment warning.
  • Added validate_path() — async, canonicalizes via tokio::fs::canonicalize, checks workspace containment, and re-checks forbidden paths against the resolved path.
  • Added validate_parent_path() — same as above but canonicalizes the parent directory for write operations where the target file may not yet exist.
  • Migrated all 8 path-checking call sites (7 filesystem tools + image_info) to the unified API, removing the manual two-step pairing that callers could and did forget.
  • Fixed active exfiltration path: image_info.rs was calling is_path_allowed with no resolved check — an agent could read any file via a symlink inside the workspace.

Problem

is_path_allowed() validated path strings without resolving symlinks. A symlink created inside the allowed workspace pointing to /etc/shadow (or any forbidden file) passed all checks. A separate is_resolved_path_allowed() existed but had to be called manually — two callers (image_info.rs, cron/scheduler.rs) omitted it entirely, leaving active exfiltration paths open.

Solution

  • Unified API: validate_path() is the single entry point for any path used in file I/O. It fast-rejects at the string level, then calls canonicalize to resolve all symlinks, then checks workspace containment, then re-checks forbidden paths against the resolved canonical path. Returning Ok(PathBuf) on success gives callers the canonical path they need for I/O with no extra work.
  • Write-path variant: validate_parent_path() canonicalizes the parent directory for callers that write new files (the target may not exist yet).
  • Token-scanner preserved: is_path_string_allowed() (the renamed string-only check) is kept pub for cron/scheduler.rs::detect_forbidden_path_arguments, which scans shell command tokens without doing file I/O — the string-only check is intentionally correct there.
  • Forced audit: Removing the old is_path_allowed name produced compile errors at every call site, ensuring each was reviewed and migrated.
  • Design tradeoff: validate_path is async because tokio::fs::canonicalize is async. All existing callers already run in async contexts, so this is zero friction.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case)
  • [x] Diff coverage ≥ 80% — pnpm test:coverage + cargo test -p openhuman run locally; 6 new async tests cover all symlink attack vectors on changed lines
  • [x] Coverage matrix updated — N/A: security hardening of existing behaviour, no new feature rows
  • [x] All affected feature IDs from the matrix listed under ## Related — N/A: no new feature IDs
  • [x] No new external network dependencies introduced — N/A: pure in-process path validation
  • [x] Manual smoke checklist updated if this touches release-cut surfaces — N/A: internal security policy, no UI change
  • [x] Linked issue closed via Closes #NNN in ## Related

Impact

  • All platforms (desktop macOS/Windows/Linux): path validation now always resolves symlinks before policy checks.
  • Security: eliminates the symlink-bypass class of attacks on the agent filesystem tools and CEF image reader.
  • No user-visible change: the policy enforcement tightens but legitimate agent file access is unaffected.
  • Performance: one additional canonicalize syscall per file operation — negligible for agent tool use cadence.

Related

  • Closes #1927
  • Follow-up: consider O_NOFOLLOW / /proc/self/fd mitigations for TOCTOU (noted in implementation as out of scope for this issue)

AI Authored PR Metadata

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/symlink-bypass-path-validation
  • Commit SHA: 0f076cf9da1024d79de7236ef5365879da062e09

Validation Run

  • [x] pnpm --filter openhuman-app format:check — clean
  • [x] pnpm --filter openhuman-app compile — no errors
  • [x] Focused tests: cargo test -p openhuman -- policy — 6 new tests pass, all existing pass
  • [x] Rust fmt/check: cargo fmt --check + cargo clippy -p openhuman — clean
  • [x] Tauri fmt/check: N/A — no Tauri shell changes

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: symlinks are now resolved before path policy checks; previously a symlink inside the workspace to a forbidden file was allowed
  • User-visible effect: none under normal use; agents attempting to read forbidden files via symlinks will now receive an error

Parity Contract

  • Legacy behavior preserved: all string-level checks (.. traversal, null bytes, URL-encoded traversal, forbidden prefix matching) unchanged in is_path_string_allowed
  • Guard/fallback/dispatch parity checks: symlink_metadata guards in edit_file.rs and apply_patch.rs preserved — they enforce a stricter "no symlinks even within workspace" policy for those tools

Duplicate / Superseded PR Handling

  • Duplicate PR(s): N/A
  • Canonical PR: N/A
  • Resolution: N/A

Summary by CodeRabbit

  • New Features

    • Added async path- and parent-path validation APIs to resolve and validate targets before file ops.
  • Bug Fixes

    • Stronger path validation preventing symlink escapes, traversal, null-byte and encoded-traversal attacks.
    • Tilde (~) expansion and forbidden-directory checks enforced consistently; writes into forbidden locations blocked.
  • Refactor

    • Centralized, string-based path checks used across file tools; parent-path validation now runs before directory creation.
  • Tests

    • Expanded coverage for resolved-path/parent-path validation and edge cases.

Review Change Stack

M3gA-Mind avatar May 18 '26 13:05 M3gA-Mind

[!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

Walkthrough

SecurityPolicy now separates string checks (is_path_string_allowed) from resolved-path validation and adds async APIs validate_path and validate_parent_path that canonicalize targets, enforce workspace containment, and reject forbidden directories; filesystem tools and tests were updated to use these APIs.

Changes

Security Refactor: Unified Path Validation with Symlink Resolution

Layer / File(s) Summary
Security Policy Core Refactoring
src/openhuman/security/policy.rs
Adds expand_tilde; renames is_path_allowed → is_path_string_allowed; adds validate_path and validate_parent_path which canonicalize, check workspace containment, and match against forbidden directories.
Security Policy Test Coverage
src/openhuman/security/policy_tests.rs
Updates synchronous tests to use is_path_string_allowed and adds async Unix tests for validate_path and validate_parent_path, covering symlink resolution and forbidden-path cases.
Cron Scheduler Integration
src/openhuman/cron/scheduler.rs
Uses is_path_string_allowed for forbidden path-argument checks.
Filesystem Read & Scan Tools
src/openhuman/tools/impl/browser/image_info.rs, src/openhuman/tools/impl/filesystem/file_read.rs, src/openhuman/tools/impl/filesystem/list_files.rs, src/openhuman/tools/impl/filesystem/grep.rs
Tools now call validate_path(path).await (rate-limit recording moved before validation where applied) and use returned resolved PathBufs for metadata/read/scan operations.
Filesystem Write-Path Tools
src/openhuman/tools/impl/filesystem/file_write.rs, src/openhuman/tools/impl/filesystem/csv_export.rs
Tools now call validate_parent_path(path).await to obtain a resolved target before creating directories and writing files.
Filesystem Modify-Path Tools
src/openhuman/tools/impl/filesystem/apply_patch.rs, src/openhuman/tools/impl/filesystem/edit_file.rs
Apply Patch and Edit File now use is_path_string_allowed for string checks and validate_path(...).await for resolved-path validation, returning early on validation failures.

Sequence Diagram(s)

sequenceDiagram
  participant Tool as FileTool (e.g. ImageInfoTool)
  participant Policy as SecurityPolicy
  participant FS as Filesystem
  Tool->>Policy: validate_path(path).await / validate_parent_path(path).await
  Policy->>FS: canonicalize / read deepest existing ancestor
  FS-->>Policy: resolved PathBuf or error
  Policy->>Policy: is_resolved_path_allowed + forbidden checks
  Policy-->>Tool: Ok(resolved PathBuf) or Err(message)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • senamakel

Poem

A rabbit hops along the trail,
Expands the tilde without fail,
Canonical paths it traces neat,
Symlinks halted where they meet,
Safe gardens kept beneath its feet—🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: centralizing path canonicalization into the security policy layer before policy checks to fix a symlink bypass vulnerability.
Linked Issues check ✅ Passed The PR fully addresses #1927's coding objectives: canonicalization is enforced before policy checks, the fragmented API is unified, symlink validation is added across all call sites, and forbidden-path checks now operate on resolved paths.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the symlink bypass vulnerability: renaming is_path_allowed to is_path_string_allowed, adding validate_path and validate_parent_path async APIs, migrating 8 call sites, and adding regression tests.
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.


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

coderabbitai[bot] avatar May 18 '26 13:05 coderabbitai[bot]

Addressed the two actionable items from the self-review in commit 61343cff:

  • image_info.rs: Removed the redundant "Path not allowed: " prefix on the validate_path error — validate_path already returns a complete user-facing message, so the outer wrapper was producing doubled text like "Path not allowed: Path not allowed by security policy: …".
  • policy_tests.rs: Added validate_path_blocks_symlink_to_relative_forbidden_entry — a regression test for the be296695 fix where relative forbidden entries (e.g. "secrets") were not resolved against the workspace root. The test asserts that both a direct path (secrets/token.txt) and a symlink pointing into the forbidden directory (link/token.txt) are correctly blocked.

(The workspace_dir.canonicalize() loop note from the review was incorrect — it was already computed outside the loop; no change needed there.)

M3gA-Mind avatar May 19 '26 09:05 M3gA-Mind