Skip to content

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

test: stop the suite reaching the network (#3596)

Maximilian Roosae363c2b4cdf
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 40141bb04..a4f00df29 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -978,16 +978,7 @@ fn build_worktree_config_bare_layout() -> (tempfile::TempDir, std::path::PathBuf
"[init]\n\tdefaultBranch = main\n[user]\n\tname = test\n\temail = test@test\n",
)
.unwrap();
- let git = || {
- Cmd::new("git")
- .env("GIT_CONFIG_GLOBAL", &gitconfig)
- .env("GIT_CONFIG_SYSTEM", "/dev/null")
- .env("GIT_TERMINAL_PROMPT", "0")
- .env("LC_ALL", "C")
- .env("LANG", "C")
- .env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z")
- .env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z")
- };
+ let git = || crate::testing::configure_git_env(Cmd::new("git"), &gitconfig);
let path_str = |p: &std::path::Path| p.to_str().unwrap().to_owned();
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index b93e8ff1c..bda14b806 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -243,6 +243,34 @@ pub const TEST_EPOCH: u64 = 1735776000;
/// Generous to avoid flakiness under CI load; exponential backoff means fast tests when things work.
const BG_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
+/// Value for `GIT_ALLOW_PROTOCOL` on every git process a test spawns, whether
+/// directly or as a child of `wt`: local paths and `file://` only, so the
+/// suite cannot reach the wire.
+///
+/// Tests point remotes at real hosts (`https://github.com/test-owner/…`) to
+/// drive forge detection, and `Repository::default_branch()` is allowed to
+/// fall through to `git ls-remote` when neither the worktrunk cache nor
+/// `origin/HEAD` resolves. So a test that never meant to do network work
+/// makes an unbounded connect to whatever host the URL names. Nothing in that
+/// path has a timeout: an unanswered SYN costs ~127 s per address on Linux
+/// (`tcp_syn_retries=6`) and a host with several A/AAAA records is tried in
+/// turn, which is how a 2-second test reaches nextest's 180 s limit.
+///
+/// Denying the transport turns that into an immediate `transport 'https' not
+/// allowed`; detection then falls back to local inference, leaving output
+/// unchanged. The adjacent `GIT_TERMINAL_PROMPT=0` doesn't subsume this: it
+/// only suppresses the credential prompt the host's 401 triggers, so the
+/// request has already gone out by the time it applies.
+const GIT_ALLOWED_PROTOCOLS: &str = "file";
+
+/// Restore git's default protocol set on a command built by
+/// [`configure_git_cmd`], for a caller whose job is to fetch a fixture from
+/// upstream — the real-repo benchmark clone. Grep for this to enumerate
+/// everything that may reach the wire; tests are not among them.
+pub fn allow_network_transports(cmd: &mut Command) {
+ cmd.env_remove("GIT_ALLOW_PROTOCOL");
+}
+
/// Static environment variables shared by all test isolation helpers.
///
/// These are used by both `configure_cli_command()` (for Command-based tests)
@@ -253,6 +281,10 @@ const BG_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
/// are NOT included here because they depend on the TestRepo instance.
pub const STATIC_TEST_ENV_VARS: &[(&str, &str)] = &[
("CLICOLOR_FORCE", "1"),
+ // Deny network git transports (see GIT_ALLOWED_PROTOCOLS). Host-independent,
+ // so it belongs here rather than in each builder's path-dependent block —
+ // which is what reaches the hand-rolled PTY env builders too.
+ ("GIT_ALLOW_PROTOCOL", GIT_ALLOWED_PROTOCOLS),
// Terminal width for PTY tests. configure_cli_command() overrides to 500 for longer paths.
("COLUMNS", "150"),
// Deterministic locale settings
@@ -590,6 +622,7 @@ pub fn configure_cli_command(cmd: &mut Command) {
/// - Deterministic commit timestamps
/// - Consistent locale settings
/// - No terminal prompts
+/// - No network transports (`GIT_ALLOWED_PROTOCOLS`)
///
/// # Arguments
/// * `cmd` - The git Command to configure
@@ -608,6 +641,7 @@ pub fn configure_git_cmd(cmd: &mut Command, git_config_path: &Path) {
cmd.env("LANG", "C");
cmd.env("WORKTRUNK_TEST_EPOCH", TEST_EPOCH.to_string());
cmd.env("GIT_TERMINAL_PROMPT", "0");
+ cmd.env("GIT_ALLOW_PROTOCOL", GIT_ALLOWED_PROTOCOLS);
}
/// Configure a `Cmd`-based git command with isolated environment for testing.
@@ -627,6 +661,7 @@ pub fn configure_git_env(cmd: Cmd, git_config_path: &Path) -> Cmd {
.env("LANG", "C")
.env("WORKTRUNK_TEST_EPOCH", TEST_EPOCH.to_string())
.env("GIT_TERMINAL_PROMPT", "0")
+ .env("GIT_ALLOW_PROTOCOL", GIT_ALLOWED_PROTOCOLS)
}
/// Shared interface for test repository fixtures.
@@ -3078,6 +3113,46 @@ fn is_leap_year(year: i64) -> bool {
mod tests {
use super::*;
+ /// A harness-built `git` reaches local paths and nothing else, so no test
+ /// can make an unbounded connect to whatever host a fixture URL names
+ /// (see [`GIT_ALLOWED_PROTOCOLS`]).
+ #[test]
+ fn test_harness_git_allows_local_paths_only() {
+ let repo = TestRepo::with_initial_commit();
+ let ls_remote = |url: &str| {
+ repo.git_command()
+ .args(["ls-remote", "--symref", url, "HEAD"])
+ .run()
+ .unwrap()
+ };
+
+ let local = ls_remote(&path_slash::PathExt::to_slash_lossy(repo.root_path()));
+ let local_stderr = String::from_utf8_lossy(&local.stderr);
+ assert!(
+ local.status.success(),
+ "local-path remote must still resolve: {local_stderr}"
+ );
+
+ let remote = ls_remote("https://github.com/test-owner/test-repo.git");
+ let stderr = String::from_utf8_lossy(&remote.stderr);
+ assert!(
+ stderr.contains("transport 'https' not allowed"),
+ "https transport must be refused, got: {stderr}"
+ );
+
+ // The opt-out has to clear the var, not narrow it: a value that still
+ // named a protocol list would silently keep the fixture clone offline,
+ // and the daily benchmark run is the only thing that would notice.
+ let mut opted_out = Command::new("git");
+ configure_git_cmd(&mut opted_out, Path::new(NULL_DEVICE));
+ allow_network_transports(&mut opted_out);
+ assert!(
+ opted_out
+ .get_envs()
+ .any(|(k, v)| k == "GIT_ALLOW_PROTOCOL" && v.is_none())
+ );
+ }
+
#[test]
fn test_unix_to_iso8601() {
// 2025-01-01T00:00:00Z
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index a6f56fdfc..45b5894a8 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -47,6 +47,7 @@ be isolated from the host environment to prevent:
- **Directive leakage**: Test commands writing to the user's shell directive file
- **Config pollution**: Tests reading/writing the user's real config
- **Git interference**: Host GIT_* environment variables affecting test behavior
+- **Network access**: a fixture's `https://` remote URL becoming a real connect, with no timeout bounding it (`GIT_ALLOWED_PROTOCOLS` in `src/testing/mod.rs`)
### With a TestRepo fixture (most tests)
diff --git a/tests/helpers/wt-perf/src/lib.rs b/tests/helpers/wt-perf/src/lib.rs
index 751d247f5..d615196b8 100644
--- a/tests/helpers/wt-perf/src/lib.rs
+++ b/tests/helpers/wt-perf/src/lib.rs
@@ -28,7 +28,7 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use tempfile::TempDir;
-use worktrunk::testing::{NULL_DEVICE, configure_git_cmd};
+use worktrunk::testing::{NULL_DEVICE, allow_network_transports, configure_git_cmd};
/// Lazy-initialized rust repo path.
static RUST_REPO: OnceLock<PathBuf> = OnceLock::new();
@@ -156,7 +156,8 @@ pub fn parse_pair(config: &str, prefix: &str) -> Option<(usize, usize)> {
/// redirected to `NULL_DEVICE`. Thin call-site wrapper around
/// [`configure_git_cmd`] — every git invocation in this crate goes
/// through here. Doesn't set `current_dir`; callers do that explicitly
-/// when they have a target.
+/// when they have a target. Network transports are denied; the upstream
+/// fixture clone re-permits them via [`allow_network_transports`].
fn git_command() -> Command {
let mut cmd = Command::new("git");
configure_git_cmd(&mut cmd, Path::new(NULL_DEVICE));
@@ -709,7 +710,9 @@ fn ensure_rust_repo() -> PathBuf {
std::fs::create_dir_all(&cache_dir).unwrap();
eprintln!("Cloning rust-lang/rust (this will take several minutes)...");
- let clone_output = git_command()
+ let mut clone = git_command();
+ allow_network_transports(&mut clone);
+ let clone_output = clone
.args([
"clone",
"https://github.com/rust-lang/rust.git",
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_self_hosted_tea_authed.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_self_hosted_tea_authed.snap
index 875ef2cc4..8873e1e3e 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_self_hosted_tea_authed.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_self_hosted_tea_authed.snap
@@ -7,8 +7,10 @@ info:
- "pr:101"
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_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
@@ -35,6 +37,7 @@ info:
WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
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_SKIP_URL_HEALTH_CHECK: "1"
@@ -51,4 +54,4 @@ exit_code: 1
  by @alice · open · feature-auth · https://forge.selfhosted.test/owner/test-repo/pulls/101
◎ Fetching feature-auth from origin...
✗ Failed to fetch branch feature-auth from origin
-  fatal: unable to access 'https://forge.selfhosted.test/owner/test-repo.git/': Could not resolve host: forge.selfhosted.test
+  fatal: transport 'https' not allowed