Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix: fence user-controlled refs against git flag injection (#3317)

Maximilian Roosf25282d7b2cb
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 9b981a33d..bc1211076 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -194,6 +194,9 @@ pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> a
stat_width_arg = format!("--stat-width={stat_width}");
args.push(&stat_width_arg);
}
+ // Fence the range positional so a target branch named like a flag
+ // (`-x..HEAD`) can't be misparsed as an option.
+ args.push("--end-of-options");
args.push(range);
let diff_stat = repo.run_command(&args)?.trim_end().to_string();
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 07c381e8d..cea16f60d 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -282,29 +282,44 @@ impl SkimItem for HeaderSkimItem {
}
/// Common diff rendering: check stat, show stat + full diff if non-empty.
+/// Render a `git diff` preview (stat header, then the colored diff). `prefix`
+/// is the command through the `diff` subcommand (e.g. `["diff"]` or
+/// `["-C", path, "diff"]`); `revs` are the positional revisions.
+///
+/// The diff options precede an `--end-of-options` sentinel, which fences the
+/// positional `revs` so a ref that looks like a flag (a branch literally named
+/// `-x` or `--foo`) can't be misparsed as an option. Today's callers pass
+/// resolved SHAs and `HEAD`, but the fence keeps the helper safe for any future
+/// caller that passes a raw name.
fn compute_diff_preview(
repo: &Repository,
- args: &[&str],
+ prefix: &[&str],
+ revs: &[&str],
no_changes_msg: &str,
width: usize,
) -> String {
let mut output = String::new();
-
- // Check stat output first
- let mut stat_args = args.to_vec();
- stat_args.push("--stat");
- stat_args.push("--color=always");
- let stat_width_arg = format!("--stat-width={}", width);
- stat_args.push(&stat_width_arg);
+ let stat_width_arg = format!("--stat-width={width}");
+
+ // Check stat output first.
+ let mut stat_args = prefix.to_vec();
+ stat_args.extend([
+ "--stat",
+ "--color=always",
+ stat_width_arg.as_str(),
+ "--end-of-options",
+ ]);
+ stat_args.extend_from_slice(revs);
if let Ok(stat) = repo.run_command(&stat_args)
&& !stat.trim().is_empty()
{
output.push_str(&stat);
- // Build diff args with color
- let mut diff_args = args.to_vec();
- diff_args.push("--color=always");
+ // Build diff args with color.
+ let mut diff_args = prefix.to_vec();
+ diff_args.extend(["--color=always", "--end-of-options"]);
+ diff_args.extend_from_slice(revs);
if let Ok(diff) = repo.run_command(&diff_args) {
output.push_str(&diff);
@@ -1269,7 +1284,8 @@ impl PickerRow {
let reset = Reset;
compute_diff_preview(
repo,
- &["-C", &path, "diff", "HEAD"],
+ &["-C", &path, "diff"],
+ &["HEAD"],
&cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no uncommitted changes"),
width,
)
@@ -1303,12 +1319,12 @@ impl PickerRow {
return cached;
}
- let mut diff_args = vec!["diff"];
- diff_args.extend(spec.revs.iter().map(String::as_str));
+ let revs: Vec<&str> = spec.revs.iter().map(String::as_str).collect();
let base_name = &spec.base_name;
let result = compute_diff_preview(
repo,
- &diff_args,
+ &["diff"],
+ &revs,
&cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no file changes vs <bold>{base_name}</>{reset}"
),
@@ -1380,7 +1396,8 @@ impl PickerRow {
let range = format!("{upstream_sha}...{}", item.head());
compute_diff_preview(
repo,
- &["diff", &range],
+ &["diff"],
+ &[&range],
&cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has diverged (⇡{ahead} ⇣{behind}) but no unique file changes"
),
@@ -1390,7 +1407,8 @@ impl PickerRow {
let range = format!("{upstream_sha}...{}", item.head());
compute_diff_preview(
repo,
- &["diff", &range],
+ &["diff"],
+ &[&range],
&cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no unpushed file changes"
),
@@ -1400,7 +1418,8 @@ impl PickerRow {
let range = format!("{}...{upstream_sha}", item.head());
compute_diff_preview(
repo,
- &["diff", &range],
+ &["diff"],
+ &[&range],
&cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} is behind upstream (⇣{behind}) but no file changes"
),
@@ -2710,6 +2729,31 @@ mod tests {
);
}
+ #[test]
+ fn diff_preview_fences_flag_like_refs() {
+ // A ref whose name starts with `-` must reach git as a positional, not
+ // an option. Without the `--end-of-options` fence, `git diff <sha>
+ // -weird` misparses `-weird` as a flag and errors out; the fence lets
+ // it resolve as a ref. `git branch` rejects leading-dash names, so the
+ // ref is created via `update-ref`.
+ let (t, repo) = repo_with_main();
+ std::fs::write(t.path().join("fenced.txt"), "fenced\n").unwrap();
+ repo.run_command(&["add", "fenced.txt"]).unwrap();
+ repo.run_command(&["commit", "-m", "fenced commit"])
+ .unwrap();
+ let head = repo.run_command(&["rev-parse", "HEAD"]).unwrap();
+ let root = repo.run_command(&["rev-parse", "HEAD~1"]).unwrap();
+ repo.run_command(&["update-ref", "refs/heads/-weird", head.trim()])
+ .unwrap();
+
+ let out =
+ compute_diff_preview(&repo, &["diff"], &[root.trim(), "-weird"], "NO CHANGES", 80);
+ assert!(
+ out.contains("fenced.txt"),
+ "the --end-of-options fence must let `-weird` resolve as a ref; got: {out:?}"
+ );
+ }
+
#[test]
fn branch_diff_cache_short_circuits_recompute() {
// Pre-populate the disk cache with a sentinel value, then call
diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rs
index 96a50323c..b6a6a23de 100644
--- a/src/commands/worktree/push.rs
+++ b/src/commands/worktree/push.rs
@@ -127,7 +127,12 @@ impl MergeContext {
let commit_count = repo.count_commits(&target_branch, "HEAD")?;
let stats_summary = if commit_count > 0 {
- repo.diff_stats_summary(&["diff", "--shortstat", &format!("{}..HEAD", target_branch)])
+ repo.diff_stats_summary(&[
+ "diff",
+ "--shortstat",
+ "--end-of-options",
+ &format!("{}..HEAD", target_branch),
+ ])
} else {
Vec::new()
};
@@ -183,6 +188,7 @@ impl MergeContext {
"--color=always",
"--graph",
"--oneline",
+ "--end-of-options",
&format!("{}..HEAD", self.target_branch),
])?;
eprintln!("{}", format_with_gutter(&log_output, None));
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 181a09227..ca33810bc 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -407,7 +407,7 @@ pub fn delete_branch_if_safe(
// Force-delete: skip integration check entirely (matches compute_integration_reason
// behavior for the Worktree path). The user explicitly chose -D.
if force_delete {
- repo.run_command(&["branch", "-D", branch_name])?;
+ repo.run_command(&["branch", "-D", "--", branch_name])?;
return Ok(BranchDeletionResult {
outcome: BranchDeletionOutcome::ForceDeleted,
integration_target: target.to_string(),
@@ -436,7 +436,7 @@ pub fn delete_branch_if_safe(
// pre-CAS behavior in a corner case rather than introducing a
// new error class.
None => {
- repo.run_command(&["branch", "-D", branch_name])?;
+ repo.run_command(&["branch", "-D", "--", branch_name])?;
BranchDeletionOutcome::Integrated(r)
}
}
@@ -582,6 +582,30 @@ mod tests {
assert!(!exit.success(), "branch should have been deleted");
}
+ /// A branch whose name starts with `-` must still force-delete: the
+ /// `git branch -D -- <name>` separator stops git from parsing `-x` as an
+ /// option. Created via `update-ref` since `git branch` rejects leading-dash
+ /// names.
+ #[test]
+ fn force_delete_handles_flag_like_branch_name() {
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+ let head = repo.run_command(&["rev-parse", "HEAD"]).unwrap();
+ test.run_git(&["update-ref", "refs/heads/-x", head.trim()]);
+
+ let snapshot = repo.capture_refs().unwrap();
+ let result = delete_branch_if_safe(&repo, &snapshot, "-x", "main", true).unwrap();
+ assert!(
+ matches!(result.outcome, BranchDeletionOutcome::ForceDeleted),
+ "expected ForceDeleted, got a different outcome"
+ );
+ assert!(
+ repo.run_command(&["rev-parse", "--verify", "--quiet", "refs/heads/-x"])
+ .is_err(),
+ "flag-like branch should have been force-deleted"
+ );
+ }
+
/// When the branch ref vanishes between snapshot capture and the CAS
/// delete, `git update-ref -d` fails *and* the ref is already absent, so
/// the outcome is a real error (propagated) — distinct from the
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 205138307..0dc64c0a8 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1126,7 +1126,7 @@ fn handle_branch_only_output(
handle_branch_deletion_result(result, branch_name)?
} else if deletion_mode.is_force() {
let repo = worktrunk::git::Repository::current()?;
- let result = repo.run_command(&["branch", "-D", branch_name]);
+ let result = repo.run_command(&["branch", "-D", "--", branch_name]);
handle_branch_deletion_result(
result.map(|_| BranchDeletionResult {
outcome: BranchDeletionOutcome::ForceDeleted,