Skip to content

security(analysis): reject path traversal in diff parser (#2099) - #2174

Closed
EffortlessSteven wants to merge 8 commits into
mainfrom
codex/diff-parser-path-traversal-2099
Closed

EffortlessSteven wants to merge 8 commits into
mainfrom
codex/diff-parser-path-traversal-2099

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Problem

The diff parser's parse_new_path_marker accepted any path string from a +++ b/... marker without checking for directory traversal. A crafted diff like:

+++ b/../../../etc/passwd

would produce a ChangedFile.path pointing outside the workspace root. At the consumer site (probes/diff.rs:210), root.join(&changed.path) would then resolve to a path outside root, leaking into probes, SARIF output, and review comments.

Change

Add is_path_safe(path) guard in parse_new_path_marker that rejects paths containing Component::ParentDir (..) or Component::RootDir (/). The guard runs at the parser boundary so every downstream consumer (probes, pipeline, commands, agent support) inherits the protection.

fn is_path_safe(path: &Path) -> bool {
    !path.is_absolute()
        && !path.components().any(|c| {
            matches!(c, Component::ParentDir | Component::RootDir)
        })
}

Why both ParentDir and RootDir?

ParentDir catches ../../../etc/passwd. RootDir catches /etc/passwd — on Windows, Path::is_absolute() returns false for paths without a drive letter (e.g. /etc/passwd), but root.join("/etc/passwd") still replaces the base path on both platforms. The RootDir component check catches this cross-platform.

Tests

5 new tests in path.rs:

  • accepts normal relative path (b/src/lib.rs)
  • accepts nested subdirectory (b/src/nested/deep/file.rs)
  • rejects parent-dir traversal (b/../../../etc/passwd)
  • rejects single parent-dir (../secret)
  • rejects absolute path (/etc/passwd)

Evidence

cargo build -p ripr               PASS
cargo clippy -p ripr -D warnings  PASS
cargo test -p ripr --lib analysis::diff::path::tests  PASS (5)
cargo test -p ripr --lib analysis::diff  PASS (39)
cargo xtask goldens check         PASS

Scope

Single-file change to crates/ripr/src/analysis/diff/path.rs. No behavior change for any non-adversarial diff. Closes #2099.

Codex added 8 commits July 19, 2026 06:22
…ase audit (2026-07-19)

Add 9 entries to LEARNINGS.md covering:
- Gate blocking is non-functional (hardcoded seam_id None)
- Static receipts are advisory (fabrication is trivial)
- Every save re-runs the full pipeline (cache not wired in)
- continue-on-error on every CI step makes green meaningless
- Result<_, String> is the highest-leverage refactor target
- Cross-language consistency needs a shared vocabulary layer
- File-policy gate breaks main on new file types
- Duplicate run-status logic drifts
- The session's structural learnings document

Each entry follows the existing LEARNINGS.md format: date, title,
load-bearing lesson, and concrete evidence references.
The diff parser's parse_new_path_marker accepted any path string from
a +++ b/... marker without checking for directory traversal. A crafted
diff like:

  +++ b/../../../etc/passwd

would produce a ChangedFile.path pointing outside the workspace root.
At the consumer site (probes/diff.rs:210), root.join(&changed.path)
would then resolve to a path outside root, leaking into probes, SARIF
output, and review comments.

## Change

Add is_path_safe(path) guard in parse_new_path_marker that rejects
paths containing Component::ParentDir (..) or Component::RootDir (/).
The guard runs at the parser boundary so every downstream consumer
(probes, pipeline, commands, agent support) inherits the protection.

## Tests

5 new tests in path.rs:
- accepts normal relative path (b/src/lib.rs)
- accepts nested subdirectory (b/src/nested/deep/file.rs)
- rejects parent-dir traversal (b/../../../etc/passwd)
- rejects single parent-dir (../secret)
- rejects absolute path (/etc/passwd)

Verified:
  cargo build -p ripr               PASS
  cargo clippy -p ripr -D warnings  PASS
  cargo test -p ripr --lib analysis::diff::path::tests  PASS (5)
  cargo test -p ripr --lib analysis::diff  PASS (39)
  cargo xtask goldens check         PASS

Closes #2099.
@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

Summary by CodeRabbit

  • Bug Fixes
    • Improved safety when processing changed file paths.
    • Unsafe paths, including absolute paths and parent-directory traversal, are now rejected.
    • Normal relative paths and nested subdirectories continue to be accepted.

Walkthrough

Diff path parsing now rejects absolute and parent-directory paths before returning them, with tests covering safe relative paths and unsafe traversal inputs.

Changes

Diff path safety

Layer / File(s) Summary
Validate parsed diff paths
crates/ripr/src/analysis/diff/path.rs
parse_new_path_marker uses component-based validation to reject absolute, root, and parent-directory paths, with tests for accepted relative paths and rejected traversal paths.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Poem

A rabbit checks each diff with care,
No parent paths may hop from there.
Safe little folders pass the gate,
While roots and traversals meet their fate.
“Hop safely!” the bunny sings.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: rejecting diff path traversal in the parser.
Description check ✅ Passed The description covers the problem, fix, tests, evidence, and scope, though several template sections are omitted.
Linked Issues check ✅ Passed The change matches #2099 by rejecting parent-dir and root-dir paths at the diff parser boundary and adds tests for the cases.
Out of Scope Changes check ✅ Passed The PR stays within the stated single-file security fix and adds only related tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/diff-parser-path-traversal-2099
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch codex/diff-parser-path-traversal-2099

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

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/ripr/src/analysis/diff/path.rs`:
- Around line 42-46: Update is_path_safe to reject Component::Prefix(_)
alongside absolute, parent, and root components, preventing drive-prefix paths
such as C:outside from being accepted. Add a Windows-specific regression
covering the diff path +++ b/C:outside and verify it is rejected.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: fc258343-e526-40a7-9aa3-643eddb2915e

📥 Commits

Reviewing files that changed from the base of the PR and between 8292d97 and 2c5a74d.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • crates/ripr/src/analysis/diff/path.rs
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • EffortlessMetrics/ripr (auto-detected)
  • EffortlessMetrics/perl-lsp (auto-detected)
  • EffortlessMetrics/unsafe-review (auto-detected)
  • EffortlessMetrics/ub-review (auto-detected)

Comment on lines +42 to +46
fn is_path_safe(path: &Path) -> bool {
!path.is_absolute()
&& !path
.components()
.any(|c| matches!(c, Component::ParentDir | Component::RootDir))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

rustup run 1.95.0 cargo test -p ripr parse_new_path_marker_rejects_windows_drive_relative_path

Repository: EffortlessMetrics/ripr-swarm

Length of output: 285


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '== diff/path.rs ==\n'
cat -n crates/ripr/src/analysis/diff/path.rs | sed -n '1,220p'

printf '\n== parse.rs relevant slice ==\n'
cat -n crates/ripr/src/analysis/diff/parse.rs | sed -n '90,150p'

Repository: EffortlessMetrics/ripr-swarm

Length of output: 8182


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '== search for Prefix handling ==\n'
rg -n "Component::Prefix|is_path_safe|parse_new_path_marker|join\\(" crates/ripr/src -S

Repository: EffortlessMetrics/ripr-swarm

Length of output: 50385


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '== config.rs slice ==\n'
cat -n crates/ripr/src/config.rs | sed -n '620,650p'

printf '\n== lsp/gap_artifacts.rs slice ==\n'
cat -n crates/ripr/src/lsp/gap_artifacts.rs | sed -n '1200,1235p'

printf '\n== diff parser call sites ==\n'
rg -n "parse_new_path_marker\\(|parse_old_path_marker\\(" crates/ripr/src -S

Repository: EffortlessMetrics/ripr-swarm

Length of output: 3858


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import ntpath, posixpath

samples = ["C:outside", "C:/outside", r"C:\outside", r"\\server\share\file", "../secret", "src/lib.rs"]
for s in samples:
    print(s)
    print("  posix isabs:", posixpath.isabs(s), "normpath:", posixpath.normpath(s))
    print("  nt isabs   :", ntpath.isabs(s), "normpath:", ntpath.normpath(s))
    # simulate the current filter conceptually
    parts = [p for p in ntpath.normpath(s).split(ntpath.sep) if p]
    print()
PY

Repository: EffortlessMetrics/ripr-swarm

Length of output: 760


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import PureWindowsPath

samples = ["C:outside", "C:/outside", r"C:\outside", r"\\server\share\file", "../secret", "src/lib.rs"]
for s in samples:
    p = PureWindowsPath(s)
    print(s)
    print("  is_absolute:", p.is_absolute())
    print("  drive:", p.drive, "root:", p.root, "anchor:", p.anchor)
    print("  parts:", p.parts)
    print()
PY

Repository: EffortlessMetrics/ripr-swarm

Length of output: 749


🌐 Web query:

Rust std Path::join Windows prefix-only path C:outside behavior

💡 Result:

In Rust, when using the std::path::Path::join method on Windows, a path argument that consists of only a Windows drive prefix (e.g., "C:") is treated as an absolute path that replaces the base path entirely [1][2][3]. This behavior occurs because, under Windows path semantics, a path containing a prefix but no root (such as "C:outside") is technically considered to be an absolute path (or more specifically, a path that overrides the current working directory state of the specified drive) [2][4]. The Rust standard library's documentation for join and PathBuf::push explicitly states: "if path has a prefix but no root, self is ignored and path is returned" [1][5][3]. As a result, calling Path::new("C:\\existing").join("C:outside") will produce a PathBuf containing only "C:outside", effectively discarding the original base path [2]. This is a common point of confusion because such paths are often perceived as relative from a high-level perspective, but they are treated as "absolute" in the sense that they identify a complete location independently of the base path [6][2]. If you need to ensure the base path is preserved or correctly merged, you must either: 1. Ensure the join argument is a strictly relative path (e.g., by checking!path.is_absolute and verifying it does not start with a prefix) [2]. 2. Use absolute paths including the root (e.g., "C:\outside") if you intend to point to a specific root-based location, though this will still replace the base path [1][5]. 3. Manually handle the logic to concatenate components if the desired behavior is to append to the base path rather than replace it [4]. This behavior is standard across Rust's path handling on Windows and is documented to ensure consistency with how Windows APIs interpret these path formats [6][7][2].

Citations:


🌐 Web query:

Rust Path::join Windows prefix-only drive-relative path semantics

💡 Result:

In Rust, the behavior of Path::join on Windows is governed by whether the joined path is considered absolute [1][2]. For Windows, a path containing a prefix but no root (such as "C:foo") is treated as an absolute path by the join operation, causing it to replace the original path entirely rather than appending to it [1][2]. Specifically, the Rust documentation defines the following behavior for Path::join on Windows when joining self with path: 1. If path has a prefix but no root (e.g., "C:foo"), self is completely ignored and path is returned as the result [1][2]. 2. If path has a root but no prefix (e.g., "\windows"), it replaces everything except for the prefix (if any) of self [1][2]. 3. If path is otherwise considered absolute (having both a prefix and a root, e.g., "C:\windows"), it replaces the current path entirely [1][2]. This behavior stems from the fact that "drive-relative" paths (like "C:file") are interpreted by the Windows API as relative to the current directory of that specific drive [3][4]. Because Rust's Path::join is designed to replace the receiver when the argument is absolute, and drive-relative paths contain a prefix that makes them behave like absolute paths in this context, they trigger this replacement logic [5][6]. Users often find this counter-intuitive, as "C:foo" is technically a relative path, but it is treated as a "full" specification of a drive-relative path, leading to the replacement [5][7][8]. To avoid this replacement, ensure the path being joined does not contain a drive prefix (e.g., by stripping it) or use path components that are strictly relative [7]. There is no built-in "safe join" in the standard library that implicitly handles these Windows-specific drive-relative path semantics, so manual verification or path manipulation is often required when dealing with untrusted path inputs that may include drive letters [6][4].

Citations:


🏁 Script executed (no clone):

#!/bin/bash
set -euo pipefail
python3 - <<'PY'
import ntpath

base = r"C:\workspace"
samples = [r"C:outside", r"C:\outside", r"\outside", r"outside", r"\\server\share\file"]
for s in samples:
    print(f"join({base!r}, {s!r}) -> {ntpath.join(base, s)!r}")
PY

Length of output: 433


🌐 Web query:

site:doc.rust-lang.org std::path::Path::is_absolute Windows prefix no root C:outside

💡 Result:

On Windows, the method std::path::Path::is_absolute returns false for a path like C:outside because it lacks a root [1][2][3]. According to the official Rust documentation, a path on Windows is considered absolute only if it meets two criteria: it must have a prefix and it must start with the root [1][2]. While C:outside possesses a disk prefix (C:), it does not have a root component [1][3]. A path on Windows has a root if it satisfies any of the following conditions: - It has no prefix and begins with a separator (e.g., \windows) [1][2][3]. - It has a prefix followed by a separator (e.g., c:\windows) [1][2][3]. - It has any non-disk prefix (e.g., \server\share) [1][2][3]. Because C:outside does not have a separator following the disk prefix, it is considered relative to the current directory of the specified drive, and therefore is_absolute returns false [1][2].

Citations:


Path Traversal (CWE-22): Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Reachability: External

Reject Windows drive-prefix paths. Component::Prefix(_) still passes is_path_safe, so a diff path like C:outside can drop the workspace root when it’s joined later on Windows. Reject prefix components here and add a Windows regression for +++ b/C:outside.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/analysis/diff/path.rs` around lines 42 - 46, Update
is_path_safe to reject Component::Prefix(_) alongside absolute, parent, and root
components, preventing drive-prefix paths such as C:outside from being accepted.
Add a Windows-specific regression covering the diff path +++ b/C:outside and
verify it is rejected.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2c5a74dcb0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

!path.is_absolute()
&& !path
.components()
.any(|c| matches!(c, Component::ParentDir | Component::RootDir))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject Windows drive-prefix diff paths

Failure mode: on Windows, a crafted explicit diff path such as +++ b/C:secret.rs has a Component::Prefix but is not is_absolute() and has no RootDir, so this guard accepts it; downstream root.join(changed.path) then ignores the workspace root for prefix-only paths per the Path::join docs, leaving the traversal class still reachable for Windows users. Fix direction: reject Component::Prefix as unsafe and add a Windows-targeted regression for prefix-without-root paths; validate with cargo test -p ripr --lib analysis::diff. Confidence: High because the current predicate explicitly omits Prefix while this patch's safety claim depends on all joined paths staying under the workspace root.

Useful? React with 👍 / 👎.

Comment on lines +11 to +15
if is_path_safe(&parsed) {
Some(parsed)
} else {
None
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Skip unsafe file sections without reusing the prior path

Failure mode: when a plain unified diff has a valid file followed by an unsafe +++ marker, returning None here makes the boundary lookahead in parse.rs fail, so the parser stays in the previous hunk and consumes the second file's ---, +++, and hunk lines as changes to the prior safe path instead of dropping the unsafe section. Fix direction: distinguish “recognized but unsafe path marker” from “not a path marker”, close/skip that file section, and add a regression next to plain_diff_two_file_sections_while_in_hunk_recognized_as_boundary; validate with cargo test -p ripr --lib analysis::diff. Confidence: High based on the current state machine flow and the new None result for traversal paths.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Closing this stale duplicate after source reconciliation. Issue #2099 was already implemented and merged by PR #2139 (d160b516), and current main (a6e5f072) contains the stronger follow-up path parser: confine_to_relative_path rejects Component::Prefix, ParentDir, and RootDir, while is_new_path_marker keeps rejected +++ markers as file-section boundaries so unsafe hunks cannot be attributed to the prior safe path. PR #2174's branch is based on an older parser and conflicts with current main; repairing it would duplicate or risk regressing the landed fix.

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.

security(analysis): diff parser path traversal — +++ b/../../../etc/passwd escapes workspace root unconfined

1 participant