Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
457 changes: 457 additions & 0 deletions rust/crates/core/src/tests/git_colon_paths.rs

Large diffs are not rendered by default.

12 changes: 8 additions & 4 deletions rust/crates/core/src/tests/git_untracked_directories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,13 @@ fn summarized_directory_supports_diff_stage_and_discard_as_a_unit() {
// `:` cannot appear in a Windows file name.
#[cfg(not(windows))]
#[test]
fn summarized_directory_diff_fails_instead_of_dropping_a_file_it_cannot_export() {
fn summarized_directory_diff_preserves_colon_named_files() {
let repository = Repository::new("untracked-unexportable");
repository.write("generated/a.txt", "alpha\n");
repository.write("generated/bad:name.txt", "kept\n");

// Shelve would save the patch and then clean `generated/`, so a patch
// without `bad:name.txt` would delete that file without a copy.
// Shelve saves the patch before cleaning `generated/`. A colon is a
// supported Unix filename, so both files must be captured in that patch.
let response: Value = serde_json::from_str(&execute_json(
&json!({
"command": "git.diff",
Expand All @@ -263,7 +263,11 @@ fn summarized_directory_diff_fails_instead_of_dropping_a_file_it_cannot_export()
.to_string(),
))
.unwrap();
assert_eq!(response["ok"], false, "{response}");
assert_eq!(response["ok"], true, "{response}");
let patch = response["data"]["patch"].as_str().unwrap();
assert!(patch.contains("+alpha"), "{patch}");
assert!(patch.contains("b/generated/bad:name.txt"), "{patch}");
assert!(patch.contains("+kept"), "{patch}");
assert!(repository.0.join("generated/bad:name.txt").exists());
}

Expand Down
2 changes: 2 additions & 0 deletions rust/crates/core/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ mod git;
mod git_branch_delete;
mod git_change_targets;
mod git_changed_file_groups;
#[cfg(unix)]
mod git_colon_paths;
mod git_diff_blocks;
mod git_fetch;
mod git_fetch_plan;
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/git/src/branches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ pub(crate) fn local_branch_name(reference: &str) -> Result<String, CoreError> {
"Only local branches support this Git operation",
)
})?;
if !is_safe_pathspec(branch) {
if !is_safe_refspec_name(branch) {
return Err(CoreError::new(
ErrorCode::InvalidRequest,
"Invalid Git branch name",
Expand Down
9 changes: 7 additions & 2 deletions rust/crates/git/src/commits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,12 +391,14 @@ pub(crate) fn commit_selected_paths(
"--pathspec-from-file=-".to_string(),
"--pathspec-file-nul".to_string(),
];
let mut stage_environment = environment.clone();
stage_environment.push(("GIT_LITERAL_PATHSPECS".to_string(), "1".to_string()));
let staged = execute_git_with_environment(
root,
&stage_arguments,
Some(pathspec_input.clone()),
false,
&environment,
&stage_environment,
)?;
if staged.exit_code != 0 {
return Ok(staged);
Expand Down Expand Up @@ -498,7 +500,8 @@ pub(crate) fn commit_selected_paths(

// Reconcile only committed paths in the real index. Unrelated staging that
// another Git process created while hooks ran remains intact.
let mut reconciled = execute_git(
let literal = [("GIT_LITERAL_PATHSPECS".to_string(), "1".to_string())];
let mut reconciled = execute_git_with_environment(
root,
&[
"reset".to_string(),
Expand All @@ -508,6 +511,8 @@ pub(crate) fn commit_selected_paths(
"--pathspec-file-nul".to_string(),
],
Some(pathspec_input),
false,
&literal,
)?;
if reconciled.exit_code != 0 {
reconciled.warnings.push(GitOperationWarning::new(
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/git/src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ pub(crate) fn diff_impl(request: GitDiffRequest) -> Result<GitDiffResponse, Core
if request.include_file_sections {
configure_structured_diff(&mut arguments);
}
// A selected filename such as `:(glob)*.txt` must not expand to other files.
arguments.insert(0, "--literal-pathspecs".into());
let root = validate_root(&request.root)?;
let mut output = if expands_untracked_directories {
GitProcessOutput {
Expand Down Expand Up @@ -226,6 +228,7 @@ pub(crate) fn diff_impl(request: GitDiffRequest) -> Result<GitDiffResponse, Core
let untracked_paths = readonly_command(GitCommandRequest {
root: root.clone(),
arguments: vec![
"--literal-pathspecs".into(),
"ls-files".into(),
"--others".into(),
"--exclude-standard".into(),
Expand Down Expand Up @@ -353,6 +356,7 @@ fn worktree_snapshot_diff(
if request.include_file_sections {
configure_structured_diff(&mut arguments);
}
arguments.insert(0, "--literal-pathspecs".into());
let mut output = capture_git_with_environment(root, &arguments, None, true, &environment)?;
if output.exit_code != 0 {
return Err(
Expand All @@ -378,6 +382,7 @@ fn worktree_snapshot_diff(
};
let mut section_bytes = sections.as_ref().map(structured_file_bytes).unwrap_or(0);
let untracked_arguments = vec![
"--literal-pathspecs".into(),
"ls-files".into(),
"--others".into(),
"--exclude-standard".into(),
Expand Down
6 changes: 4 additions & 2 deletions rust/crates/git/src/line_history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ fn line_history_merge_ranges(
let listing = readonly_command(GitCommandRequest {
root: root.to_string(),
arguments: vec![
"--literal-pathspecs".to_string(),
"log".to_string(),
"--first-parent".to_string(),
"--format=%H".to_string(),
Expand Down Expand Up @@ -633,8 +634,9 @@ pub fn line_history(request: GitLineHistoryRequest) -> Result<GitLineHistoryResp
}

// One process traces every interval; `-L` emits only hunks intersecting
// the traced lines, and `--first-parent` pins the merge semantics.
let mut arguments = vec!["log".to_string()];
// the traced lines, and `--first-parent` pins the merge semantics. Even
// -L's filename can activate pathspec magic unless Git is in literal mode.
let mut arguments = vec!["--literal-pathspecs".to_string(), "log".to_string()];
for (start, end) in &intervals {
arguments.push(format!("-L{start},{end}:{}", request.path));
}
Expand Down
6 changes: 3 additions & 3 deletions rust/crates/git/src/mutations.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Shared Git mutation helpers kept outside the command facade.

use super::{capture_git_with_options, is_safe_pathspec};
use super::{capture_git_with_options, is_safe_refspec_name};
use lithe_protocol::{CoreError, ErrorCode};

use super::{
Expand Down Expand Up @@ -94,8 +94,8 @@ pub(super) fn remote_branch_components(
if branch.is_empty()
|| remote.starts_with('-')
|| branch.starts_with('-')
|| !is_safe_pathspec(remote)
|| !is_safe_pathspec(branch)
|| !is_safe_refspec_name(remote)
|| !is_safe_refspec_name(branch)
{
return Err(CoreError::new(
ErrorCode::InvalidRequest,
Expand Down
10 changes: 10 additions & 0 deletions rust/crates/git/src/references.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

use super::*;

/// Guards names combined into refspecs independently of filesystem path rules.
/// Git forbids colons and backslashes in ref names on every platform; complete
/// reference syntax is still checked by the existing `check-ref-format` calls.
pub(crate) fn is_safe_refspec_name(name: &str) -> bool {
!name.is_empty()
&& !name.starts_with('/')
&& !name.split('/').any(|component| component == "..")
&& !name.contains([':', '\\', '\0'])
}

#[derive(Clone)]
pub(crate) struct ValidatedGitReference {
pub(crate) full_name: String,
Expand Down
14 changes: 8 additions & 6 deletions rust/crates/git/src/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use super::*;
use lithe_platform::names::is_reserved_device_name;
use lithe_platform::paths::{slash_separated, slash_separated_path};
use lithe_platform::paths::{invalid_native_relative_path, slash_separated, slash_separated_path};
use lithe_platform::Platform;

/// Discovers Git repositories for an opened workspace using shared traversal rules.
Expand Down Expand Up @@ -456,12 +456,14 @@ pub(crate) fn empty_tree_oid(root: &str) -> Result<String, CoreError> {
Ok(oid.to_string())
}

/// Workspace paths follow the host's filename rules, independently of Git refs.
/// Callers passing these paths as pathspecs must keep Git's matching literal.
pub(crate) fn is_safe_pathspec(path: &str) -> bool {
let normalized = slash_separated(path, Platform::HOST);
!normalized.is_empty()
&& !normalized.starts_with('/')
&& !normalized.split('/').any(|component| component == "..")
&& !normalized.contains(':')
is_safe_pathspec_for(path, Platform::HOST)
}

pub(crate) fn is_safe_pathspec_for(path: &str, platform: Platform) -> bool {
!invalid_native_relative_path(path, platform)
}

pub(crate) fn null_device() -> &'static str {
Expand Down
58 changes: 58 additions & 0 deletions rust/crates/git/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,64 @@ use lithe_protocol::{CoreError, ErrorCode};
use serde_json::Value;
use std::path::PathBuf;

#[test]
fn local_branch_names_reject_colon_refspecs_on_every_platform() {
assert_eq!(
super::local_branch_name("refs/heads/topic/nested").unwrap(),
"topic/nested"
);
for name in ["topic:main", ":main", "topic:refs/heads/main"] {
let error = super::local_branch_name(&format!("refs/heads/{name}")).unwrap_err();
assert!(
matches!(error.code, ErrorCode::InvalidRequest),
"{name}: {error:?}"
);
}
}

#[test]
fn remote_and_branch_refspec_components_do_not_follow_unix_filename_rules() {
for name in ["origin", "origin/team", "topic/nested", "@"] {
assert!(super::is_safe_refspec_name(name), "{name}");
}
for name in [
"",
"/topic",
"../topic",
"topic/../main",
"origin:topic",
":main",
"topic:refs/heads/main",
"topic\\main",
"topic\0main",
] {
assert!(!super::is_safe_refspec_name(name), "{name:?}");
}
}

#[test]
fn workspace_pathspecs_follow_platform_filename_rules() {
for path in ["a:b.txt", ":(glob)*.txt", ":(exclude)*.txt", r"D:\logs"] {
assert!(
super::is_safe_pathspec_for(path, lithe_platform::Platform::Unix),
"{path}"
);
assert!(
!super::is_safe_pathspec_for(path, lithe_platform::Platform::Windows),
"{path}"
);
}
for platform in lithe_platform::Platform::ALL {
assert!(super::is_safe_pathspec_for("src/main.rs", platform));
for invalid in ["", "/etc", "../secret", "a/../b", "a\0b"] {
assert!(
!super::is_safe_pathspec_for(invalid, platform),
"{invalid:?} on {platform:?}"
);
}
}
}

/// Only an exact `Name <email>` names an author; the options keep Git's order.
#[test]
fn commit_identity_requires_an_exact_author() {
Expand Down
9 changes: 8 additions & 1 deletion rust/crates/git/src/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,14 @@ fn write_with_trace(request: GitWriteRequest) -> Result<GitCommandResponse, Core
"--pathspec-from-file=-".into(),
"--pathspec-file-nul".into(),
]);
return execute_git(&root, &arguments, Some(nul_pathspec_input(&paths)));
let literal = [("GIT_LITERAL_PATHSPECS".to_string(), "1".to_string())];
return execute_git_with_environment(
&root,
&arguments,
Some(nul_pathspec_input(&paths)),
false,
&literal,
);
}
}
"operationContinue" | "operationAbort" | "operationSkip" => {
Expand Down
Loading