Skip to content
Closed
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 59 additions & 2 deletions crates/ripr/src/analysis/diff/path.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::{Component, Path, PathBuf};

pub(super) fn parse_new_path_marker(raw: &str) -> Option<PathBuf> {
let marker = raw.strip_prefix("+++ ")?;
Expand All @@ -7,7 +7,12 @@ pub(super) fn parse_new_path_marker(raw: &str) -> Option<PathBuf> {
return None;
}
let path = path.strip_prefix("b/").unwrap_or(&path);
Some(PathBuf::from(path))
let parsed = PathBuf::from(path);
if is_path_safe(&parsed) {
Some(parsed)
} else {
None
}
Comment on lines +11 to +15

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 👍 / 👎.

}

pub(super) fn parse_old_path_marker(raw: &str) -> bool {
Expand All @@ -28,6 +33,19 @@ fn is_plausible_unquoted_diff_path(path: &str) -> bool {
!path.is_empty() && !path.chars().any(char::is_whitespace)
}

/// Reject paths that traverse outside the workspace root or are absolute.
/// A git diff path like `b/../../../etc/passwd` would otherwise be joined
/// to the workspace root at the consumer site (`root.join(changed.path)`),
/// producing a path outside root. This guard stops the traversal at the
/// parser boundary so every downstream consumer inherits the protection.
/// See #2099.
fn is_path_safe(path: &Path) -> bool {
!path.is_absolute()
&& !path
.components()
.any(|c| matches!(c, Component::ParentDir | Component::RootDir))
Comment on lines +42 to +46

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.

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 👍 / 👎.

}

fn parse_diff_path_token(raw: &str) -> Option<String> {
let raw = raw.trim_end_matches('\r');
if let Some(quoted) = raw.strip_prefix('"') {
Expand Down Expand Up @@ -91,3 +109,42 @@ where

char::from_u32(value).unwrap_or('\u{FFFD}')
}

#[cfg(test)]
mod tests {
use super::parse_new_path_marker;
use std::path::PathBuf;

#[test]
fn parse_new_path_marker_accepts_normal_relative_path() -> Result<(), String> {
let path = parse_new_path_marker("+++ b/src/lib.rs")
.ok_or_else(|| "expected Some for normal relative path".to_string())?;
assert_eq!(path, PathBuf::from("src/lib.rs"));
Ok(())
}

#[test]
fn parse_new_path_marker_rejects_parent_dir_traversal() {
// `+++ b/../../../etc/passwd` must be rejected — the path would
// escape the workspace root when joined at the consumer site.
assert_eq!(parse_new_path_marker("+++ b/../../../etc/passwd"), None);
}

#[test]
fn parse_new_path_marker_rejects_single_parent_dir() {
assert_eq!(parse_new_path_marker("+++ ../secret"), None);
}

#[test]
fn parse_new_path_marker_rejects_absolute_path() {
assert_eq!(parse_new_path_marker("+++ /etc/passwd"), None);
}

#[test]
fn parse_new_path_marker_accepts_nested_subdirectory() -> Result<(), String> {
let path = parse_new_path_marker("+++ b/src/nested/deep/file.rs")
.ok_or_else(|| "expected Some for nested path".to_string())?;
assert_eq!(path, PathBuf::from("src/nested/deep/file.rs"));
Ok(())
}
}