Skip to content

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

Fix copy-ignored symlink destination boundary (#2501)

Douglas Soares de Andradec33cb8c66508
diff --git a/benches/cow_copy.rs b/benches/cow_copy.rs
index 14a2588f8..53c63f3b7 100644
--- a/benches/cow_copy.rs
+++ b/benches/cow_copy.rs
@@ -148,7 +148,7 @@ fn bench_helper(
b.iter(|| {
let dest = temp.path().join(format!("copy_p_{}", iter));
iter += 1;
- copy_dir_recursive(src, &dest, false, &Progress::disabled()).unwrap();
+ copy_dir_recursive(src, &dest, None, false, &Progress::disabled()).unwrap();
std::fs::remove_dir_all(&dest).ok();
});
},
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 6315c76b9..347626427 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -820,10 +820,11 @@ pub fn step_copy_ignored(
let dest_entry = dest_path.join(relative);
if *is_dir {
- let (n, b) = copy_dir_recursive(src_entry, &dest_entry, force, &progress)
- .with_context(|| {
- format!("copying directory {}", format_path_for_display(relative))
- })?;
+ let (n, b) =
+ copy_dir_recursive(src_entry, &dest_entry, Some(&dest_path), force, &progress)
+ .with_context(|| {
+ format!("copying directory {}", format_path_for_display(relative))
+ })?;
copied_count += n;
copied_bytes += b;
} else {
@@ -835,7 +836,7 @@ pub fn step_copy_ignored(
)
})?;
}
- if let Some(bytes) = copy_leaf(src_entry, &dest_entry, force)? {
+ if let Some(bytes) = copy_leaf(src_entry, &dest_entry, Some(&dest_path), force)? {
copied_count += 1;
copied_bytes += bytes;
progress.record(bytes);
@@ -919,10 +920,10 @@ fn move_entry(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {
/// Copy then delete — fallback when `rename` fails with EXDEV (cross-device).
fn copy_and_remove(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {
if is_dir {
- copy_dir_recursive(src, dest, true, &Progress::disabled())?;
+ copy_dir_recursive(src, dest, None, true, &Progress::disabled())?;
fs::remove_dir_all(src).context(format!("removing source directory {}", src.display()))?;
} else {
- copy_leaf(src, dest, true)?;
+ copy_leaf(src, dest, None, true)?;
fs::remove_file(src).context(format!("removing source file {}", src.display()))?;
}
diff --git a/src/copy.rs b/src/copy.rs
index 2b8582507..dcf1770b2 100644
--- a/src/copy.rs
+++ b/src/copy.rs
@@ -25,6 +25,7 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use anyhow::Context;
use rayon::prelude::*;
+use crate::path::{canonicalize_with_parents, format_path_for_display};
use crate::progress::Progress;
/// Capped at 4 threads to avoid saturating the CPU — the global rayon pool is
@@ -42,7 +43,20 @@ static COPY_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
/// when the entry was copied (reporting the source's logical byte size), or
/// `None` if skipped because the destination already exists. When `force` is
/// true, existing entries are removed before copying.
-pub fn copy_leaf(src: &Path, dest: &Path, force: bool) -> anyhow::Result<Option<u64>> {
+///
+/// When `root` is `Some`, refuses destination paths whose parent resolves
+/// outside `root`. The check guards the parent chain, not the final leaf, so
+/// leaf-symlink behavior is preserved (without `force` the symlink is skipped;
+/// with `force` the symlink itself is replaced).
+pub fn copy_leaf(
+ src: &Path,
+ dest: &Path,
+ root: Option<&Path>,
+ force: bool,
+) -> anyhow::Result<Option<u64>> {
+ if let Some(root) = root {
+ ensure_path_within_root(dest.parent().unwrap_or(dest), root)?;
+ }
if force {
remove_if_exists(dest)?;
}
@@ -88,6 +102,20 @@ pub fn copy_leaf(src: &Path, dest: &Path, force: bool) -> anyhow::Result<Option<
Ok(Some(bytes))
}
+fn ensure_path_within_root(path: &Path, root: &Path) -> anyhow::Result<()> {
+ let canonical_root = canonicalize_with_parents(root);
+ let canonical_path = canonicalize_with_parents(path);
+
+ anyhow::ensure!(
+ canonical_path.starts_with(&canonical_root),
+ "refusing to copy outside destination worktree: {} resolves outside {}",
+ format_path_for_display(path),
+ format_path_for_display(root)
+ );
+
+ Ok(())
+}
+
/// A leaf item (file or symlink) collected during the directory walk.
struct CopyLeaf {
src: PathBuf,
@@ -105,10 +133,15 @@ struct CopyLeaf {
/// removed before copying. `progress` receives per-file callbacks; pass
/// [`Progress::disabled`] for a zero-overhead no-op.
///
+/// When `root` is `Some`, refuses destination directory ancestry that resolves
+/// outside `root`. Leaves inherit the guarantee because `entry.file_name()` is
+/// a single basename and cannot escape the validated parent directory.
+///
/// Returns `(files_copied, bytes_copied)` — counts exclude skipped entries.
pub fn copy_dir_recursive(
src: &Path,
dest: &Path,
+ root: Option<&Path>,
force: bool,
progress: &Progress,
) -> anyhow::Result<(usize, u64)> {
@@ -119,6 +152,9 @@ pub fn copy_dir_recursive(
let mut dirs_for_perms: Vec<(PathBuf, PathBuf)> = Vec::new();
while let Some((src_dir, dest_dir)) = dir_stack.pop() {
+ if let Some(root) = root {
+ ensure_path_within_root(&dest_dir, root)?;
+ }
fs::create_dir_all(&dest_dir)
.with_context(|| format!("creating directory {}", dest_dir.display()))?;
#[cfg(unix)]
@@ -150,7 +186,7 @@ pub fn copy_dir_recursive(
leaves
.par_iter()
.try_for_each(|leaf| -> anyhow::Result<()> {
- if let Some(bytes) = copy_leaf(&leaf.src, &leaf.dest, force)? {
+ if let Some(bytes) = copy_leaf(&leaf.src, &leaf.dest, None, force)? {
copied_files.fetch_add(1, Ordering::Relaxed);
copied_bytes.fetch_add(bytes, Ordering::Relaxed);
progress.record(bytes);
diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rs
index a8f642571..18ff98604 100644
--- a/tests/integration_tests/step_copy_ignored.rs
+++ b/tests/integration_tests/step_copy_ignored.rs
@@ -778,6 +778,88 @@ fn test_copy_ignored_force_directory(mut repo: TestRepo) {
);
}
+#[cfg(unix)]
+fn setup_copy_ignored_symlinked_dest_dir(repo: &mut TestRepo) -> (PathBuf, tempfile::TempDir) {
+ let feature_path = repo.add_worktree("feature");
+
+ let target_dir = repo.root_path().join("target");
+ fs::create_dir_all(target_dir.join("debug")).unwrap();
+ fs::write(target_dir.join("debug").join("output"), "copied content").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();
+ fs::write(repo.root_path().join(".worktreeinclude"), "target/\n").unwrap();
+
+ let outside = tempfile::tempdir().unwrap();
+ let outside_target = outside.path().join("target");
+ fs::create_dir_all(&outside_target).unwrap();
+ fs::write(outside_target.join("sentinel"), "keep me").unwrap();
+ std::os::unix::fs::symlink(&outside_target, feature_path.join("target")).unwrap();
+
+ (feature_path, outside)
+}
+
+#[cfg(unix)]
+fn assert_copy_ignored_rejects_symlinked_dest_dir(repo: &TestRepo, feature_path: &Path) {
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored"])
+ .current_dir(feature_path)
+ .output()
+ .unwrap();
+
+ assert!(!output.status.success(), "copy-ignored should fail");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("refusing to copy outside destination worktree"),
+ "expected outside-destination error, got: {stderr}",
+ );
+}
+
+#[cfg(unix)]
+fn assert_symlinked_dest_outside_unchanged(outside: &tempfile::TempDir) {
+ let outside_target = outside.path().join("target");
+ assert_eq!(
+ fs::read_to_string(outside_target.join("sentinel")).unwrap(),
+ "keep me",
+ "sentinel outside destination worktree should remain unchanged",
+ );
+ assert!(
+ !outside_target.join("debug").join("output").exists(),
+ "copy-ignored should not write through destination directory symlink",
+ );
+}
+
+/// Refuse to copy through destination directory symlinks.
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_rejects_symlinked_destination_directory(mut repo: TestRepo) {
+ let (feature_path, outside) = setup_copy_ignored_symlinked_dest_dir(&mut repo);
+
+ assert_copy_ignored_rejects_symlinked_dest_dir(&repo, &feature_path);
+ assert_symlinked_dest_outside_unchanged(&outside);
+}
+
+/// --force must not overwrite files through destination directory symlinks.
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_force_rejects_symlinked_destination_directory(mut repo: TestRepo) {
+ let (feature_path, outside) = setup_copy_ignored_symlinked_dest_dir(&mut repo);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored", "--force"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ assert!(!output.status.success(), "copy-ignored --force should fail");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("refusing to copy outside destination worktree"),
+ "expected outside-destination error, got: {stderr}",
+ );
+ assert_symlinked_dest_outside_unchanged(&outside);
+}
+
/// Test --verbose shows entries being copied (GitHub issue #1084)
#[rstest]
fn test_copy_ignored_verbose(mut repo: TestRepo) {