worktrunk 0.35.2

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Security tests for shell script injection vulnerabilities
//!
//! # Attack Surface Analysis
//!
//! Worktrunk uses a file-based directive protocol for shell integration. When `WORKTRUNK_DIRECTIVE_FILE`
//! env var is set (pointing to a temp file), the wt binary:
//! - Streams all user-visible output (progress, errors, hints) to stderr in real-time
//! - Writes shell directives (cd commands, exec commands) to the directive file
//!
//! The shell wrapper sources the directive file after wt exits:
//! ```bash
//! directive_file="$(mktemp)"
//! WORKTRUNK_DIRECTIVE_FILE="$directive_file" wt ... || exit_code=$?
//! source "$directive_file"
//! ```
//!
//! ## Vulnerability: Shell Injection
//!
//! If external content (branch names, file paths, git output) can inject malicious shell
//! code into the directive file, the shell wrapper will execute it. This is analogous to SQL injection
//! or command injection vulnerabilities.
//!
//! ## Attack Vectors
//!
//! ### 1. Path Injection via Single Quote Escaping (HIGH RISK if not escaped)
//!
//! Paths are emitted in single quotes: `cd '/path/to/worktree'`
//! Single quotes prevent most shell metacharacter expansion, but embedded single quotes
//! could break out of the quoting if not properly escaped.
//!
//! **Example attack (if unescaped):**
//! ```bash
//! # Create directory with malicious name
//! mkdir "test'; rm -rf /; echo '"
//! WORKTRUNK_DIRECTIVE_FILE=/tmp/d wt switch branch  # If cd emits: cd 'test'; rm -rf /; echo ''
//! ```
//!
//! **Protection:** All paths are escaped using `replace('\'', "'\\''")` pattern,
//! which is the standard POSIX approach for embedding single quotes in single-quoted strings.
//!
//! ### 2. Execute Command Injection (LOW RISK - user-controlled)
//!
//! The `--execute` flag lets users specify shell commands to run. This is intentionally
//! user-controlled and not an injection vector (users can already run arbitrary commands).
//!
//! ### 3. Branch Name in Output (NO RISK)
//!
//! Branch names appear in stderr messages, not in the stdout shell script.
//! The shell wrapper only evals stdout, so stderr content cannot be executed.
//!
//! ## Current Protections
//!
//! **Shell script protocol with proper escaping:**
//!
//! 1. **Channel separation**: User messages go to stderr, shell directives go to a temp file
//!    - Shell wrapper only sources the directive file
//!    - Malicious content in stderr cannot be executed
//!
//! 2. **Path escaping**: All paths use single quotes with `'\''` escape pattern
//!    ```rust
//!    let escaped = path_str.replace('\'', "'\\''");
//!    writeln!(stdout, "cd '{}'", escaped)?;
//!    ```
//!    This handles all shell metacharacters: `$`, `` ` ``, `;`, `&`, `|`, spaces, etc.
//!
//! 3. **Git layer**: Git REJECTS invalid characters in ref names
//!
//! 4. **Filesystem layer**: OS enforces valid path characters
//!
//! ## Vulnerabilities We Test
//!
//! This test suite verifies that user-controlled content CANNOT inject shell commands:
//!
//! 1. ✅ Branch names with shell metacharacters
//! 2. ✅ Branch names with single quotes
//! 3. ✅ Paths with special characters
//! 4. ✅ Git output with shell commands
//!
//! ## Security Model
//!
//! The file-based directive protocol is secure:
//!
//! 1. **Simpler parsing**: Just source a file, no command substitution needed
//! 2. **Channel separation**: Messages on stderr, directives in temp file
//! 3. **Standard escaping**: Uses well-understood POSIX single-quote escaping
//! 4. **Smaller attack surface**: Only cd and exec commands in directive file
//!
//! ### Testing Limitations
//!
//! These tests verify that:
//! - Path escaping is correct for shell metacharacters
//! - Branch names with special characters don't break quoting
//!
//! However, they DON'T fully test shell execution security because:
//! - Tests run the Rust binary, not the shell wrapper
//! - Full end-to-end tests with malicious shell wrapper input are in `shell_wrapper.rs`
//!
//! For comprehensive security testing, see `tests/integration_tests/shell_wrapper.rs` which
//! tests the full shell integration pipeline.

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;

///
/// Git provides the first line of defense by refusing to create commits
/// with NUL bytes in the message.
#[rstest]
fn test_git_rejects_nul_in_commit_messages(repo: TestRepo) {
    use std::process::Stdio;

    // Try to create a commit with NUL in the message
    // We can't use Command::arg() because Rust rejects NUL bytes,
    // so we use printf piped to git commit -F -
    let malicious_message = "Fix bug\0__WORKTRUNK_EXEC__echo PWNED";

    // Create a file to commit
    std::fs::write(repo.root_path().join("test.txt"), "content").unwrap();
    repo.run_git(&["add", "."]);

    // Try to commit with NUL in message using shell redirection
    let shell_cmd = format!(
        "printf '{}' | git commit -F -",
        malicious_message.replace('\0', "\\0")
    );

    let mut cmd = Command::new("sh");
    repo.configure_git_cmd(&mut cmd);
    cmd.arg("-c")
        .arg(&shell_cmd)
        .current_dir(repo.root_path())
        .stdout(Stdio::null())
        .stderr(Stdio::piped());

    let output = cmd.output().unwrap();

    // Git should reject this
    assert!(
        !output.status.success(),
        "Expected git to reject NUL bytes in commit message"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("NUL byte") || stderr.contains("nul byte"),
        "Expected git to complain about NUL bytes, got: {}",
        stderr
    );
}

///
/// This verifies that the OS/Rust provides protection against NUL injection.
/// Rust's Command API uses C strings internally, which reject NUL bytes.
#[rstest]
fn test_rust_prevents_nul_bytes_in_args(repo: TestRepo) {
    // Rust's Command API should reject NUL bytes in arguments
    let malicious_branch = "feature\0__WORKTRUNK_EXEC__echo PWNED";

    // Cmd::run() should fail with InvalidInput error (NUL bytes rejected by Command API)
    let result = repo.git_command().args(["branch", malicious_branch]).run();

    match result {
        Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => {
            // Good! Rust prevented the NUL byte injection
        }
        Ok(output) => {
            panic!(
                "Expected Rust to reject NUL bytes in args, but command succeeded: {:?}",
                output
            );
        }
        Err(e) => {
            panic!(
                "Expected InvalidInput error for NUL bytes, got different error: {:?}",
                e
            );
        }
    }
}

///
/// This tests the case where the entire branch name is a directive
#[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();

    if !result.status.success() {
        // Git rejected the malicious branch name
        return;
    }

    let mut settings = Settings::clone_current();
    settings.set_snapshot_path("../snapshots");

    settings.bind(|| {
        let (directive_path, _guard) = directive_file();
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        configure_directive_file(&mut cmd, &directive_path);
        cmd.arg("switch")
            .arg("--create")
            .arg(malicious_branch)
            .current_dir(repo.root_path());

        assert_cmd_snapshot!(cmd);
    });

    // Verify the malicious file was NOT created
    assert!(
        !std::path::Path::new("/tmp/hacked2").exists(),
        "Malicious code was executed! File /tmp/hacked2 should not exist"
    );
}

#[rstest]
fn test_branch_name_with_newline_directive_not_executed(repo: TestRepo) {
    let malicious_branch = "feature\n__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked3";

    let result = repo
        .git_command()
        .args(["branch", malicious_branch])
        .run()
        .unwrap();

    if !result.status.success() {
        return;
    }

    let mut settings = Settings::clone_current();
    settings.set_snapshot_path("../snapshots");

    settings.bind(|| {
        let (directive_path, _guard) = directive_file();
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        configure_directive_file(&mut cmd, &directive_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!"
    );
}

///
/// This tests if commit messages shown in output (e.g., wt list, logs) could inject directives
#[rstest]
fn test_commit_message_with_directive_not_executed(mut repo: TestRepo) {
    // Create commit with malicious message (no NUL - Rust prevents those)
    let malicious_message = "Fix bug\n__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked4";
    repo.commit_with_message(malicious_message);

    // Create a worktree
    let _feature_wt = repo.add_worktree("feature");

    let mut settings = setup_snapshot_settings(&repo);
    // Filter SHAs because commit_with_message creates non-deterministic hashes
    settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA]");

    // Run 'wt list' which might show commit messages
    settings.bind(|| {
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(repo.root_path());

        // Verify output - commit message should be escaped/sanitized
        assert_cmd_snapshot!(cmd);
    });

    // Verify the malicious file was NOT created
    assert!(
        !std::path::Path::new("/tmp/hacked4").exists(),
        "Malicious code was executed from commit message!"
    );
}

///
/// This tests if file paths shown in output could inject directives
#[cfg(unix)]
#[rstest]
fn test_path_with_directive_not_executed(repo: TestRepo) {
    // Create a directory with a malicious name
    let malicious_dir = repo
        .root_path()
        .join("__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked5");
    std::fs::create_dir_all(&malicious_dir).unwrap();

    let settings = setup_snapshot_settings(&repo);

    // Run a command that might display this path
    settings.bind(|| {
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(repo.root_path());

        assert_cmd_snapshot!(cmd);
    });

    assert!(
        !std::path::Path::new("/tmp/hacked5").exists(),
        "Malicious code was executed from path display!"
    );
}

///
/// Similar to EXEC injection, but for CD directives
#[rstest]
fn test_branch_name_with_cd_directive_not_executed(repo: TestRepo) {
    // Branch name that IS a CD directive (no NUL - git allows this)
    let malicious_branch = "__WORKTRUNK_CD__/tmp";

    let result = repo
        .git_command()
        .args(["branch", malicious_branch])
        .run()
        .unwrap();

    if !result.status.success() {
        // Git rejected it - that's fine, nothing to test
        return;
    }

    let settings = setup_snapshot_settings(&repo);

    settings.bind(|| {
        let (directive_path, _guard) = directive_file();
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        configure_directive_file(&mut cmd, &directive_path);
        cmd.arg("switch")
            .arg("--create")
            .arg(malicious_branch)
            .current_dir(repo.root_path());

        // Branch name should appear in success message, but not as a separate directive
        assert_cmd_snapshot!(cmd);
    });
}

///
/// This tests if error messages (e.g., from git) could inject directives
#[rstest]
fn test_error_message_with_directive_not_executed(repo: TestRepo) {
    // Try to switch to a non-existent branch with a name that looks like a directive
    let malicious_branch = "__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6";

    let settings = setup_snapshot_settings(&repo);

    settings.bind(|| {
        let (directive_path, _guard) = directive_file();
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        configure_directive_file(&mut cmd, &directive_path);
        cmd.arg("switch")
            .arg(malicious_branch)
            .current_dir(repo.root_path());

        // Should fail with error, but not execute directive
        assert_cmd_snapshot!(cmd);
    });

    assert!(
        !std::path::Path::new("/tmp/hacked6").exists(),
        "Malicious code was executed from error message!"
    );
}

///
/// The -x flag is SUPPOSED to execute commands, so this tests that:
/// 1. Commands from -x are written to the directive file
/// 2. User content in branch names that looks like old directives doesn't cause injection
#[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";

    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");

    settings.bind(|| {
        let (directive_path, _guard) = directive_file();
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        configure_directive_file(&mut cmd, &directive_path);
        cmd.arg("switch")
            .arg("--create")
            .arg(malicious_branch)
            .arg("-x")
            .arg("echo legitimate command")
            .current_dir(repo.root_path());

        // The -x command should be written to directive file
        // The branch name should NOT inject additional commands
        assert_cmd_snapshot!(cmd);
    });

    // The legitimate command would execute (we're not actually running the shell wrapper),
    // but the injected command should NOT
    assert!(
        !std::path::Path::new("/tmp/hacked7").exists(),
        "Malicious code was executed alongside legitimate -x command!"
    );
}

// =============================================================================
// ANSI escape sequence handling in branch names
// =============================================================================

/// Test that git rejects branch names containing ANSI escape sequences.
///
/// ANSI escape sequences could theoretically corrupt terminal output if they
/// appeared in branch names displayed by `wt list`. However, git blocks this
/// at the ref validation level: control characters (bytes < 0x20 or 0x7F)
/// are rejected by git check-ref-format rule 4.
///
/// The escape character (`\x1b` = 27) is a control character, so git rejects it.
///
/// Note: Git for Windows with MSYS2 bash behaves differently and may accept
/// these branch names, so this test is Unix-only.
#[rstest]
#[cfg(unix)]
fn test_git_rejects_ansi_escape_in_branch_names(repo: TestRepo) {
    let shell_cmd = r#"git branch $'feature-\x1b[31mRED\x1b[0m-test'"#;

    let output = Command::new("bash")
        .args(["-c", shell_cmd])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "Expected git to reject ANSI escape sequences in branch name"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("not a valid branch name") || stderr.contains("invalid"),
        "Expected git to complain about invalid branch name, got: {}",
        stderr
    );
}

/// Test that manually created refs with ANSI escapes are ignored by git.
///
/// Even if an attacker bypasses git's normal validation and creates a ref file
/// directly in .git/refs/heads/ with ANSI codes in the filename, git ignores it.
#[rstest]
#[cfg(unix)]
fn test_git_ignores_malformed_refs_with_ansi(repo: TestRepo) {
    let shell_cmd = r#"
        commit_sha=$(git rev-parse HEAD)
        printf "$commit_sha" > '.git/refs/heads/feature-'$'\x1b''[31mRED'$'\x1b''[0m-test'
        "#;

    let create_result = Command::new("bash")
        .args(["-c", shell_cmd])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    assert!(
        create_result.status.success(),
        "Failed to create malformed ref file: {}",
        String::from_utf8_lossy(&create_result.stderr)
    );

    // Git should ignore the malformed ref
    let branch_output = repo.git_output(&["branch", "-a"]);
    assert!(
        !branch_output.contains("RED"),
        "Malformed ref with ANSI escape should not appear in branch list"
    );

    // wt list should also not show it
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(repo.root_path());
        assert_cmd_snapshot!(cmd);
    });
}

/// Test that literal escape-like text in branch names displays safely.
///
/// Branch names like "fix-backslash-x1b-test" contain literal characters
/// (not actual escape codes). Git allows this and they should display literally.
#[rstest]
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);
        });
    }
}