Skip to content

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

test(security): give the directive-injection tests branch names git accepts (#4194)

Worktrunk Botd3bbda2485bd
diff --git a/tests/integration_tests/security.rs b/tests/integration_tests/security.rs
index 6508d1217..78f51dbdb 100644
--- a/tests/integration_tests/security.rs
+++ b/tests/integration_tests/security.rs
@@ -33,14 +33,28 @@
//! the direct execution input is safe, but they don't test the wrapper. Full
//! end-to-end tests with the shell wrapper
//! are in `tests/integration_tests/shell_wrapper.rs`.
+//!
+//! ## Writing a payload git will accept
+//!
+//! A branch-name payload has to survive git's ref-name rules (git-check-ref-format(1)
+//! rule 4), which reject a space and every ASCII control character — so
+//! `echo PWNED > /tmp/…` and anything carrying a newline can never become a
+//! branch, and a test built on one exercises nothing. Word-split the payload
+//! with `$IFS` instead: `touch$IFS/tmp/hacked2` is a legal ref name and still
+//! creates the canary if a shell ever evaluates it. A payload that reaches a
+//! worktree path must also be a legal filename on Windows, which rules out
+//! `< > : " | ? *` — `sanitize_branch_name` only rewrites `/` and `\`.
+//!
+//! Where git's own rules are the defense, assert the refusal rather than
+//! returning early from it: a skip reads as a pass on every platform.
use crate::common::{
TestRepo, configure_directive_file, directive_file, repo, setup_snapshot_settings, wt_command,
};
-use insta::Settings;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::process::Command;
+use worktrunk::config::sanitize_branch_name;
///
/// Git provides the first line of defense by refusing to create commits
@@ -118,26 +132,26 @@ fn test_rust_prevents_nul_bytes_in_args(repo: TestRepo) {
}
}
+/// A branch name that is entirely an EXEC directive must not be executed.
///
-/// This tests the case where the entire branch name is a directive
+/// The payload carries no space: git's ref-name rule 4 rejects a space outright
+/// (as it does control characters), so a name built around `echo PWNED >
+/// /tmp/…` can never be created and everything below it would be skipped.
+/// `touch$IFS/tmp/hacked2` is the space-free equivalent — a valid ref name, a
+/// legal path component on every platform `wt` builds a worktree on, and a
+/// shell command that still creates the canary through `$IFS` word splitting
+/// if anything ever evaluates it.
+///
+/// `wt switch --create` creates the branch itself, so this covers the success
+/// path: the snapshot shows the directive-shaped name reaching the worktree
+/// path and the success message verbatim, and the canary assertion shows
+/// nothing evaluated it on the way.
#[rstest]
fn test_branch_name_is_directive_not_executed(repo: TestRepo) {
- let malicious_branch = "__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked2";
-
- // Try to create this branch
- let result = repo
- .git_command()
- .args(["branch", malicious_branch])
- .run()
- .unwrap();
+ let malicious_branch = "__WORKTRUNK_EXEC__touch$IFS/tmp/hacked2";
+ let expected_worktree = expected_worktree_path(&repo, malicious_branch);
- if !result.status.success() {
- // Git rejected the malicious branch name
- return;
- }
-
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
+ let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let (cd_path, _guard) = directive_file();
@@ -150,6 +164,8 @@ fn test_branch_name_is_directive_not_executed(repo: TestRepo) {
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
+
+ assert_cd_file_holds_worktree_path(&cd_path, &expected_worktree);
});
// Verify the malicious file was NOT created
@@ -159,9 +175,79 @@ fn test_branch_name_is_directive_not_executed(repo: TestRepo) {
);
}
+/// The worktree path `wt switch --create <branch>` produces under the default
+/// layout: a sibling of the repo named `<repo>.<branch>`, with `/` and `\`
+/// dashed out by `sanitize_branch_name` and nothing else rewritten.
+fn expected_worktree_path(repo: &TestRepo, branch: &str) -> std::path::PathBuf {
+ let root = repo.root_path();
+ let repo_name = root.file_name().expect("repo root has a name");
+ root.parent().expect("repo root has a parent").join(format!(
+ "{}.{}",
+ repo_name.to_string_lossy(),
+ sanitize_branch_name(branch)
+ ))
+}
+
+/// Assert the CD directive file holds what `wt` promises a wrapper it holds:
+/// one line, and that line is the worktree `wt` just created.
+///
+/// This is the assertion that carries the directive tests. `wt` writes the CD
+/// file itself (`src/output/global.rs`), so a branch name that smuggled a
+/// second line or a different destination past the display layer would show up
+/// here — whereas the `/tmp/hackedN` canaries in the callers can only ever
+/// pass: these tests run the binary directly, and no shell evaluates the
+/// file's contents.
+///
+/// It compares against `expected` rather than asking whether the line names
+/// *a* directory, because the directive these tests model
+/// (`__WORKTRUNK_CD__/tmp`) smuggles a path that exists — a verifier that only
+/// checked `is_dir()` would pass on the leak it is named for. Both sides are
+/// canonicalized: `wt` writes the logical, symlink-preserved path, which is
+/// not textually the tempdir path on macOS.
+fn assert_cd_file_holds_worktree_path(cd_path: &std::path::Path, expected: &std::path::Path) {
+ let cd_content = std::fs::read_to_string(cd_path).unwrap_or_default();
+ assert_eq!(
+ cd_content.lines().count(),
+ 1,
+ "the CD file must hold a single line, got {cd_content:?}"
+ );
+ let written = std::fs::canonicalize(cd_content.trim()).unwrap_or_else(|e| {
+ panic!("the CD file must hold an existing path, got {cd_content:?}: {e}")
+ });
+ let expected = std::fs::canonicalize(expected)
+ .unwrap_or_else(|e| panic!("the new worktree {} should exist: {e}", expected.display()));
+ assert_eq!(
+ written, expected,
+ "the CD file must hold the new worktree's path, got {cd_content:?}"
+ );
+}
+
+/// Assert `wt` left the CD directive file untouched.
+///
+/// The counterpart to [`assert_cd_file_holds_worktree_path`] for the tests
+/// whose `wt switch` fails: no switch happened, so nothing may move the user's
+/// shell. `directive_file()` hands over an empty file, and `wt` only writes one
+/// after a successful switch (`handle_switch_output`), so any content here is a
+/// destination that came from somewhere other than a completed switch.
+fn assert_cd_file_unwritten(cd_path: &std::path::Path) {
+ let cd_content = std::fs::read_to_string(cd_path).unwrap_or_default();
+ assert!(
+ cd_content.is_empty(),
+ "a failed switch must not write a cd directive, got {cd_content:?}"
+ );
+}
+
+/// A directive smuggled onto a second line never reaches `wt` at all.
+///
+/// Git's ref-name validation is the layer that stops this one (defense layer 3
+/// above): a newline is a control character, so `git branch` refuses the name
+/// on every platform and no such branch can exist for `wt` to read. Assert that
+/// refusal rather than skipping past it — the earlier form of this test tried
+/// to create the branch and returned early when git said no, so its body never
+/// ran and it passed without exercising anything.
#[rstest]
-fn test_branch_name_with_newline_directive_not_executed(repo: TestRepo) {
- let malicious_branch = "feature\n__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked3";
+fn test_git_rejects_newline_directive_in_branch_name(repo: TestRepo) {
+ let malicious_branch = "feature\n__WORKTRUNK_EXEC__touch$IFS/tmp/hacked3";
let result = repo
.git_command()
@@ -169,29 +255,9 @@ fn test_branch_name_with_newline_directive_not_executed(repo: TestRepo) {
.run()
.unwrap();
- if !result.status.success() {
- return;
- }
-
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
-
- settings.bind(|| {
- let (cd_path, _guard) = directive_file();
- let mut cmd = wt_command();
- repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &cd_path);
- cmd.arg("switch")
- .arg("--create")
- .arg(malicious_branch)
- .current_dir(repo.root_path());
-
- assert_cmd_snapshot!(cmd);
- });
-
assert!(
- !std::path::Path::new("/tmp/hacked3").exists(),
- "Malicious code was executed!"
+ !result.status.success(),
+ "git should reject a branch name containing a newline"
);
}
@@ -240,10 +306,11 @@ fn test_branch_name_with_cd_directive_not_executed(repo: TestRepo) {
.run()
.unwrap();
- if !result.status.success() {
- // Git rejected it - that's fine, nothing to test
- return;
- }
+ assert!(
+ result.status.success(),
+ "git should accept {malicious_branch} as a branch name; \
+ without the branch there is nothing for this test to exercise"
+ );
let settings = setup_snapshot_settings(&repo);
@@ -257,8 +324,13 @@ fn test_branch_name_with_cd_directive_not_executed(repo: TestRepo) {
.arg(malicious_branch)
.current_dir(repo.root_path());
- // Branch name should appear in success message, but not as a separate directive
+ // The branch is pre-created above, so `--create` fails: this snapshots
+ // how a directive-shaped name renders in an error message.
assert_cmd_snapshot!(cmd);
+
+ // The payload names `/tmp`, which exists: the proof that nothing
+ // honored it is that the failed switch wrote no destination at all.
+ assert_cd_file_unwritten(&cd_path);
});
}
@@ -282,6 +354,8 @@ fn test_error_message_with_directive_not_executed(repo: TestRepo) {
// Should fail with error, but not execute directive
assert_cmd_snapshot!(cmd);
+
+ assert_cd_file_unwritten(&cd_path);
});
assert!(
@@ -295,22 +369,14 @@ fn test_error_message_with_directive_not_executed(repo: TestRepo) {
/// part of the explicitly requested command.
#[rstest]
fn test_execute_flag_with_directive_like_branch_name(repo: TestRepo) {
- // Branch name that looks like a directive
- let malicious_branch = "__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked7";
+ // Branch name that looks like a directive. Space-free for the same reason
+ // as `test_branch_name_is_directive_not_executed`: git rejects a ref-name
+ // containing a space, so the old payload could never be created and the
+ // branch it needs never existed.
+ let malicious_branch = "__WORKTRUNK_EXEC__touch$IFS/tmp/hacked7";
+ let expected_worktree = expected_worktree_path(&repo, malicious_branch);
- let result = repo
- .git_command()
- .args(["branch", malicious_branch])
- .run()
- .unwrap();
-
- if !result.status.success() {
- // Git rejected the branch name
- return;
- }
-
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
+ let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let (cd_path, _guard) = directive_file();
@@ -326,6 +392,8 @@ fn test_execute_flag_with_directive_like_branch_name(repo: TestRepo) {
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
+
+ assert_cd_file_holds_worktree_path(&cd_path, &expected_worktree);
});
assert!(
@@ -389,20 +457,24 @@ fn test_git_rejects_ansi_escape_in_branch_names(repo: TestRepo) {
fn test_literal_escape_like_branch_names_displayed_safely(repo: TestRepo) {
let branch_name = "fix-backslash-x1b-test";
- let result = repo.git_command().args(["branch", branch_name]).run();
-
- if let Ok(output) = result
- && output.status.success()
- {
- let mut settings = setup_snapshot_settings(&repo);
- settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA]");
-
- settings.bind(|| {
- let mut cmd = wt_command();
- repo.configure_wt_cmd(&mut cmd);
- cmd.args(["list", "--branches"])
- .current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd);
- });
- }
+ let output = repo
+ .git_command()
+ .args(["branch", branch_name])
+ .run()
+ .expect("git branch should run");
+ assert!(
+ output.status.success(),
+ "git should accept {branch_name} as a branch name"
+ );
+
+ let mut settings = setup_snapshot_settings(&repo);
+ settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA]");
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.args(["list", "--branches"])
+ .current_dir(repo.root_path());
+ assert_cmd_snapshot!(cmd);
+ });
}
diff --git a/tests/snapshots/integration__integration_tests__security__branch_name_is_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__branch_name_is_directive_not_executed.snap
new file mode 100644
index 000000000..08071187f
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__security__branch_name_is_directive_not_executed.snap
@@ -0,0 +1,66 @@
+---
+source: tests/integration_tests/security.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - __WORKTRUNK_EXEC__touch$IFS/tmp/hacked2
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch __WORKTRUNK_EXEC__touch$IFS/tmp/hacked2 from main and worktree @ '_REPO_.__WORKTRUNK_EXEC__touch$IFS-tmp-hacked2'
+↳ To customize worktree locations, run wt config create
+
diff --git a/tests/snapshots/integration__integration_tests__security__execute_flag_with_directive_like_branch_name.snap b/tests/snapshots/integration__integration_tests__security__execute_flag_with_directive_like_branch_name.snap
new file mode 100644
index 000000000..7dde0cd2c
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__security__execute_flag_with_directive_like_branch_name.snap
@@ -0,0 +1,73 @@
+---
+source: tests/integration_tests/security.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - __WORKTRUNK_EXEC__touch$IFS/tmp/hacked7
+ - "-x"
+ - echo
+ - "--"
+ - legitimate command
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+legitimate command
+
+----- stderr -----
+✓ Created branch __WORKTRUNK_EXEC__touch$IFS/tmp/hacked7 from main and worktree @ '_REPO_.__WORKTRUNK_EXEC__touch$IFS-tmp-hacked7'
+↳ To customize worktree locations, run wt config create
+◎ Executing (--execute):
+  echo 'legitimate command'
+