diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 88601e9384..3be76a3711 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3137,6 +3137,7 @@ dependencies = [ "once_cell", "pretty_assertions", "regex", + "same-file", "schemars 0.8.22", "serde", "similar", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 34097b56aa..736f0b04b2 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -381,6 +381,7 @@ rustls = { version = "0.23", default-features = false, features = [ ] } rustls-native-certs = "0.8.3" rustls-pki-types = "1.14.0" +same-file = "1.0.6" schemars = "0.8.22" seccompiler = "0.5.0" semver = "1.0" diff --git a/codex-rs/core/src/turn_metadata.rs b/codex-rs/core/src/turn_metadata.rs index e110aa0b9d..9e0587c6a9 100644 --- a/codex-rs/core/src/turn_metadata.rs +++ b/codex-rs/core/src/turn_metadata.rs @@ -319,7 +319,7 @@ impl TurnMetadataState { let (head_commit_hash, associated_remote_urls, has_changes_result) = tokio::join!( get_head_commit_hash(&self.cwd), get_git_remote_urls_assume_git_repo(&self.cwd), - try_get_has_changes(&self.cwd), + Box::pin(try_get_has_changes(&self.cwd)), ); let latest_git_commit_hash = head_commit_hash.map(|sha| sha.0); let (has_changes, has_changes_unavailable_reason) = split_has_changes(has_changes_result); @@ -338,7 +338,7 @@ async fn memory_workspaces(cwd: &AbsolutePathBuf) -> BTreeMap io::Result { let git = GitRunner::for_cwd_io(&req.cwd)?; let mut cfg_parts = configured_git_config_parts(); + ensure_no_worktree_config_sources(&git, &req.cwd, &cfg_parts)?; + let requested_cwd = std::fs::canonicalize(&req.cwd)?; let git_root = resolve_git_root(&git, &req.cwd, &cfg_parts)?; + if git_root != requested_cwd { + ensure_no_worktree_config_sources(&git, &git_root, &cfg_parts)?; + } // Write unified diff into a temporary file let (tmpdir, patch_path) = write_temp_patch(&req.diff)?; // Keep tmpdir alive until function end to ensure the file exists let _guard = tmpdir; - let patch_path_inventory = extract_patch_path_inventory(&git, &patch_path, req.revert)?; + let patch_path_inventory = + extract_patch_path_inventory(&git, &git_root, &patch_path, req.revert, &cfg_parts)?; let patch_paths = &patch_path_inventory.effective_paths; let filter_guard = ensure_no_selected_executable_git_filters(&git, &git_root, patch_paths, &cfg_parts)?; @@ -160,12 +167,11 @@ fn resolve_git_root( git_config_args: &[String], ) -> io::Result { let requested_cwd = std::fs::canonicalize(cwd)?; - let mut command = git.command(); + let mut command = git.command_for_cwd(&requested_cwd)?; command .args(git_config_args) .arg("rev-parse") - .arg("--show-toplevel") - .current_dir(&requested_cwd); + .arg("--show-toplevel"); let out = git.output(command)?; let code = out.status.code().unwrap_or(-1); if code != 0 { @@ -203,7 +209,7 @@ fn resolve_git_root( Ok(root) } -fn configured_git_config_parts() -> Vec { +pub(crate) fn configured_git_config_parts() -> Vec { let mut cfg_parts = Vec::new(); if let Ok(cfg) = std::env::var("CODEX_APPLY_GIT_CFG") { for pair in cfg.split(',') { @@ -231,14 +237,13 @@ pub(crate) fn run_git( git_cfg: &[String], args: &[String], ) -> io::Result<(i32, String, String)> { - let mut cmd = git.command(); + let mut cmd = git.command_for_cwd(cwd)?; for p in git_cfg { cmd.arg(p); } for a in args { cmd.arg(a); } - cmd.current_dir(cwd); let out = git.output(cmd)?; let code = out.status.code().unwrap_or(-1); let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); @@ -848,4 +853,31 @@ diff --git a/ghost.txt b/ghost.txt\n--- a/ghost.txt\n+++ b/ghost.txt\n@@ -1,1 +1 assert!(error.to_string().contains("instead of expected worktree")); } } + + #[cfg(unix)] + #[test] + fn apply_propagates_unsafe_repository_metadata_before_git_launch() { + use std::os::unix::fs::symlink; + + let repo = init_repo(); + let root = repo.path(); + let external = tempfile::tempdir().expect("external metadata parent"); + let admin = external.path().join("admin"); + std::fs::rename(root.join(".git"), &admin).expect("move metadata external"); + symlink(&admin, root.join("switch")).expect("worktree metadata switch"); + std::fs::write(root.join(".git"), "gitdir: switch\n").expect("write gitdir marker"); + let (code, _, stderr) = run(root, &["git", "rev-parse", "--absolute-git-dir"]); + assert_eq!(code, 0, "native Git fixture: {stderr}"); + + let request = ApplyGitRequest { + cwd: root.to_path_buf(), + diff: String::new(), + revert: false, + preflight: true, + }; + let error = apply_git_patch(&request).expect_err("unsafe metadata route"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("Git metadata route crosses")); + assert!(!error.to_string().contains("PATH")); + } } diff --git a/codex-rs/git-utils/src/apply_filter_tests.rs b/codex-rs/git-utils/src/apply_filter_tests.rs index 8536f9617c..12da828fa6 100644 --- a/codex-rs/git-utils/src/apply_filter_tests.rs +++ b/codex-rs/git-utils/src/apply_filter_tests.rs @@ -4,6 +4,9 @@ use std::ffi::OsStr; use std::fs::File; use std::fs::FileTimes; use std::path::Path; +use std::thread; +use std::time::Duration; +use std::time::Instant; use std::time::UNIX_EPOCH; const PATCH: &str = @@ -46,6 +49,7 @@ fn init_repo() -> tempfile::TempDir { run_success(root, &["init"]); run_success(root, &["config", "user.email", "codex@example.com"]); run_success(root, &["config", "user.name", "Codex"]); + run_success(root, &["config", "core.autocrlf", "false"]); std::fs::write(root.join("file.txt"), "orig\n").expect("write file"); run_success(root, &["add", "file.txt"]); run_success(root, &["commit", "-m", "seed"]); @@ -200,6 +204,21 @@ fn run_isolated_test(test_name: &str, env: &[(&str, &OsStr)]) { ); } +fn wait_for_config_source_probe(trace: &Path) -> bool { + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + let contents = std::fs::read_to_string(trace).unwrap_or_default(); + if contents + .find("^include") + .is_some_and(|offset| contents[offset..].contains("\"event\":\"exit\"")) + { + return true; + } + thread::yield_now(); + } + false +} + #[test] fn reverse_staging_uses_command_scoped_filter_override() { if std::env::var_os("CODEX_GIT_UTILS_APPLY_FILTER_ENV_CHILD").is_none() { @@ -235,6 +254,127 @@ fn reverse_staging_uses_command_scoped_filter_override() { ); } +#[cfg(unix)] +#[test] +fn apply_rejects_worktree_primary_config_fifo_before_any_git_launch() { + use std::io::Write as _; + + const TEST_NAME: &str = + "apply::filter_tests::apply_rejects_worktree_primary_config_fifo_before_any_git_launch"; + if std::env::var_os("CODEX_GIT_UTILS_APPLY_FILTER_ENV_CHILD").is_none() { + let repo = init_repo(); + let primary_config = repo.path().join("worktree-global.fifo"); + let status = std::process::Command::new("mkfifo") + .arg(&primary_config) + .status() + .expect("run mkfifo"); + assert!(status.success(), "mkfifo failed: {status}"); + let trace = tempfile::NamedTempFile::new().expect("trace file"); + run_isolated_test( + TEST_NAME, + &[ + ("CODEX_APPLY_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_GLOBAL", primary_config.as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ("GIT_TRACE2_EVENT", trace.path().as_os_str()), + ], + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_APPLY_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + let trace = PathBuf::from(std::env::var_os("GIT_TRACE2_EVENT").expect("trace path")); + let primary_config = + PathBuf::from(std::env::var_os("GIT_CONFIG_GLOBAL").expect("worktree primary config FIFO")); + // Keep the FIFO readable and prefill a valid config so a regression starts + // and finishes instead of hanging the test process while opening it. + let mut fifo_guard = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(primary_config) + .expect("open worktree primary config FIFO"); + fifo_guard + .write_all(b"[user]\n\tname = worktree-controlled\n") + .expect("prefill worktree primary config FIFO"); + let release_fifo = thread::spawn(move || { + thread::sleep(Duration::from_secs(1)); + drop(fifo_guard); + }); + let error = apply_git_patch(&request( + &root, /*revert*/ false, /*preflight*/ true, + )) + .expect_err("reject worktree-controlled primary config"); + release_fifo.join().expect("release config FIFO"); + + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("worktree-controlled"), "{error}"); + assert_eq!( + std::fs::read_to_string(trace).expect("read Git trace"), + "", + "config authorization must reject before rev-parse or numstat starts Git", + ); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")).expect("read worktree file"), + "orig\n" + ); +} + +#[test] +fn apply_rejects_unseen_driver_added_through_worktree_include_after_source_probe() { + const TEST_NAME: &str = "apply::filter_tests::apply_rejects_unseen_driver_added_through_worktree_include_after_source_probe"; + if std::env::var_os("CODEX_GIT_UTILS_APPLY_FILTER_ENV_CHILD").is_none() { + let trace = tempfile::NamedTempFile::new().expect("trace file"); + run_isolated_test(TEST_NAME, &[("GIT_TRACE2_EVENT", trace.path().as_os_str())]); + return; + } + + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt filter=fresh\n") + .expect("write filter attributes"); + run_success(root, &["add", ".gitattributes"]); + run_success(root, &["commit", "-m", "filter target"]); + let included = root.join("driver-config"); + std::fs::write(&included, "").expect("write initially empty included config"); + run_success(root, &["config", "include.path", "../driver-config"]); + + let trace = PathBuf::from(std::env::var_os("GIT_TRACE2_EVENT").expect("trace path")); + std::fs::write(&trace, "").expect("clear fixture trace"); + let watcher_trace = trace.clone(); + let watcher = thread::spawn(move || { + let observed = wait_for_config_source_probe(&watcher_trace); + if observed { + std::fs::write( + included, + format!("[filter \"fresh\"]\n\tclean = {FILTER_COMMAND}\n\trequired = true\n"), + ) + .expect("add previously unseen filter driver"); + } + observed + }); + + let error = apply_git_patch(&request( + root, /*revert*/ false, /*preflight*/ false, + )) + .expect_err("reject worktree config source before final apply"); + assert!(watcher.join().expect("config watcher")); + + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(!configured_filter_ran(root)); + assert_eq!(index_contents(root, "file.txt"), "orig\n"); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")).expect("read worktree file"), + "orig\n" + ); + assert!( + !std::fs::read_to_string(trace) + .expect("read completed trace") + .contains("--3way") + ); +} + #[test] fn apply_treats_empty_name_filter_as_selected_only() { for command in ["clean", "smudge", "process"] { diff --git a/codex-rs/git-utils/src/errors.rs b/codex-rs/git-utils/src/errors.rs index 4494c7e897..0c22fc424a 100644 --- a/codex-rs/git-utils/src/errors.rs +++ b/codex-rs/git-utils/src/errors.rs @@ -46,8 +46,28 @@ pub enum GitToolingError { rename_all_fields = "camelCase" )] pub enum GitReadError { - #[error("no trusted Git executable is available")] + #[error( + "no trusted native Git executable is available; script-based and non-native Git wrappers are skipped, so install a native Git binary outside the repository and place its directory on PATH" + )] NoTrustedGit, + #[error( + "refusing non-bare linked worktree because its primary worktree cannot be proven from Git metadata: {common_dir}; run the operation from the primary worktree, or use a standard linked-worktree or plain bare-backed layout" + )] + UnprovenPrimaryAuthority { common_dir: String }, + #[error("unsafe Git repository metadata at {path:?}: {reason}")] + UnsafeRepositoryMetadata { + #[serde(with = "lossy_path")] + path: PathBuf, + #[serde(rename = "details")] + reason: String, + }, + #[error("invalid or unsupported Git repository metadata at {path:?}: {reason}")] + InvalidRepositoryMetadata { + #[serde(with = "lossy_path")] + path: PathBuf, + #[serde(rename = "details")] + reason: String, + }, #[error("{path:?} is not a Git repository")] NotRepository { #[serde(with = "lossy_path")] @@ -69,6 +89,10 @@ pub enum GitReadError { }, #[error("Git operation {operation:?} returned invalid output")] InvalidOutput { operation: String }, + #[error("repository authority refused Git operation {operation:?}")] + AuthorityRefused { operation: String }, + #[error("Git filter attribute selection exceeded its {max_probes}-probe limit")] + FilterSelectionProbeLimitExceeded { max_probes: usize }, #[error("executable filter {driver:?} is selected for {path:?}")] SelectedExecutableFilter { driver: String, path: String }, } @@ -98,3 +122,26 @@ mod lossy_path { String::deserialize(deserializer).map(PathBuf::from) } } + +impl GitReadError { + pub(crate) fn io_kind(&self) -> std::io::ErrorKind { + match self { + Self::NoTrustedGit | Self::NotRepository { .. } => std::io::ErrorKind::NotFound, + Self::UnprovenPrimaryAuthority { .. } + | Self::UnsafeRepositoryMetadata { .. } + | Self::RepositoryRootMismatch { .. } + | Self::AuthorityRefused { .. } + | Self::FilterSelectionProbeLimitExceeded { .. } + | Self::SelectedExecutableFilter { .. } => std::io::ErrorKind::PermissionDenied, + Self::InvalidRepositoryMetadata { .. } | Self::InvalidOutput { .. } => { + std::io::ErrorKind::InvalidData + } + Self::CommandTimedOut { .. } => std::io::ErrorKind::TimedOut, + Self::CommandFailed { .. } => std::io::ErrorKind::Other, + } + } + + pub(crate) fn into_io_error(self) -> std::io::Error { + std::io::Error::new(self.io_kind(), self) + } +} diff --git a/codex-rs/git-utils/src/exact_index_policy.rs b/codex-rs/git-utils/src/exact_index_policy.rs index 11677730d2..dd04aa455a 100644 --- a/codex-rs/git-utils/src/exact_index_policy.rs +++ b/codex-rs/git-utils/src/exact_index_policy.rs @@ -174,12 +174,11 @@ pub(crate) fn resolve_exact_index_policy( fn read_index(git: &GitRunner, git_root: &Path, git_config_args: &[String]) -> io::Result> { // One full, byte-oriented scan avoids invoking Git once per patch path and // lets one parse enforce aliases, directory prefixes, and flags together. - let mut command = git.command(); + let mut command = git.command_for_cwd(git_root)?; command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) - .args(["ls-files", "--cached", "-v", "-z"]) - .current_dir(git_root); + .args(["ls-files", "--cached", "-v", "-z"]); let output = git.output(command)?; if !output.status.success() { return Err(io::Error::other(format!( @@ -430,12 +429,11 @@ pub(crate) fn effective_git_bool( git_config_args: &[String], key: &str, ) -> io::Result> { - let mut command = git.command(); + let mut command = git.command_for_cwd(git_root)?; command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) - .args(["config", "--type=bool", "--get", key]) - .current_dir(git_root); + .args(["config", "--type=bool", "--get", key]); let output = git.output(command)?; if output.status.code() == Some(1) && output.stdout.is_empty() && output.stderr.is_empty() { return Ok(None); diff --git a/codex-rs/git-utils/src/exact_staging.rs b/codex-rs/git-utils/src/exact_staging.rs index 26ac6f41c8..1ae755363a 100644 --- a/codex-rs/git-utils/src/exact_staging.rs +++ b/codex-rs/git-utils/src/exact_staging.rs @@ -12,6 +12,7 @@ use crate::exact_index_policy::ExactIndexPolicy; use crate::exact_index_policy::effective_git_bool; use crate::exact_index_policy::resolve_exact_index_policy; use crate::git_command::GitRunner; +use crate::git_config_sources::ensure_no_worktree_config_sources; use crate::patch_paths::validate_patch_path; use crate::safe_git::ensure_no_selected_git_add_filters; @@ -67,6 +68,8 @@ pub(crate) fn update_index_exact_paths( )); } + ensure_no_worktree_config_sources(git, git_root, git_config_args)?; + let (paths, content_filter_paths) = match resolve_exact_index_policy( git, git_root, @@ -135,14 +138,13 @@ fn ignored_untracked_paths( .map(|path| format!("./{path}")) .collect::>(); let input = nul_path_input(&probe_paths)?; - let mut command = git.command(); + let mut command = git.command_for_cwd(git_root)?; command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) // `check-ignore --stdin` consumes pathnames rather than pathspecs and // rejects the global literal-pathspec mode as unsupported magic. .args(["check-ignore", "--stdin", "-z"]) - .current_dir(git_root) .stdin(Stdio::from(input)); let output = git.output(command)?; match output.status.code() { @@ -183,12 +185,11 @@ fn sparse_checkout_policy( // `git-sparse-checkout` helper. Repository-controlled PATH entries are // outside the trusted executable boundary. `--list-cmds=builtins` is a // main-program capability query and cannot dispatch an external command. - let mut builtins_command = git.command(); + let mut builtins_command = git.command_for_cwd(git_root)?; builtins_command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) - .arg("--list-cmds=builtins") - .current_dir(git_root); + .arg("--list-cmds=builtins"); let builtins = git.output(builtins_command)?; let sparse_checkout_is_builtin = builtins.status.success() && std::str::from_utf8(&builtins.stdout) @@ -202,12 +203,11 @@ fn sparse_checkout_policy( } let input = nul_path_input(paths)?; - let mut command = git.command(); + let mut command = git.command_for_cwd(git_root)?; command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) .args(["sparse-checkout", "check-rules", "-z"]) - .current_dir(git_root) .stdin(Stdio::from(input)); let output = git.output(command)?; if !output.status.success() { diff --git a/codex-rs/git-utils/src/filter_sentinel.rs b/codex-rs/git-utils/src/filter_sentinel.rs new file mode 100644 index 0000000000..a38ebc6f0e --- /dev/null +++ b/codex-rs/git-utils/src/filter_sentinel.rs @@ -0,0 +1,70 @@ +use std::io; + +const MAX_SENTINEL_FILTER_CHILD_PROBES: usize = 16; + +#[derive(Debug, Default)] +pub(crate) struct SentinelFilterProbeBudget { + completed_child_probes: usize, +} + +impl SentinelFilterProbeBudget { + pub(crate) const fn max_probes() -> usize { + MAX_SENTINEL_FILTER_CHILD_PROBES + } + + pub(crate) fn ensure_probe_available(&self) -> io::Result<()> { + if self.completed_child_probes >= MAX_SENTINEL_FILTER_CHILD_PROBES { + return Err(io::Error::other(format!( + "refusing to continue Git filter sentinel disambiguation after {} child probes (hard limit: {})", + self.completed_child_probes, MAX_SENTINEL_FILTER_CHILD_PROBES + ))); + } + Ok(()) + } + + pub(crate) fn record_completed_probe(&mut self) { + debug_assert!(self.completed_child_probes < MAX_SENTINEL_FILTER_CHILD_PROBES); + self.completed_child_probes += 1; + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SentinelFilterProbeResolution { + SpecialAttributeState, + NeedsOptionalProbe, + LiteralDriver, + ProbeFailure, +} + +pub(crate) fn classify_sentinel_filter_probes( + required_succeeded: bool, + optional_succeeded: Option, +) -> SentinelFilterProbeResolution { + if required_succeeded { + SentinelFilterProbeResolution::SpecialAttributeState + } else { + match optional_succeeded { + None => SentinelFilterProbeResolution::NeedsOptionalProbe, + Some(true) => SentinelFilterProbeResolution::LiteralDriver, + Some(false) => SentinelFilterProbeResolution::ProbeFailure, + } + } +} + +pub(crate) fn sentinel_filter_probe_config_args( + neutralization_args: &[String], + driver: &str, + required: bool, +) -> io::Result> { + if !matches!(driver, "set" | "unset" | "unspecified") { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Git filter sentinel probe requested for a non-sentinel driver", + )); + } + let mut args = Vec::with_capacity(neutralization_args.len() + 2); + args.extend_from_slice(neutralization_args); + args.push("-c".to_string()); + args.push(format!("filter.{driver}.required={required}")); + Ok(args) +} diff --git a/codex-rs/git-utils/src/git_command.rs b/codex-rs/git-utils/src/git_command.rs index 49bbb747f5..d80045625b 100644 --- a/codex-rs/git-utils/src/git_command.rs +++ b/codex-rs/git-utils/src/git_command.rs @@ -1,389 +1,314 @@ use std::ffi::OsStr; use std::io; -#[cfg(windows)] -use std::path::Component; use std::path::Path; use std::path::PathBuf; -#[cfg(windows)] -use std::path::Prefix; use std::process::Command; +use std::process::Stdio; + +use tokio::io::AsyncRead; +use tokio::io::AsyncReadExt; use crate::errors::GitReadError; -use crate::git_config::path_is_within; +#[cfg(test)] +use crate::git_executable::git_executable_name; +use crate::git_executable::harden_git_launch_environment; +#[cfg(test)] +use crate::git_executable::path_is_untrusted; +#[cfg(test)] +use crate::git_executable::search_directory_is_untrusted; +use crate::git_executable::select_git_executable; +#[cfg(all(test, windows))] +use crate::git_executable::windows_path_requires_fail_closed; +use crate::repository_authority::RepositoryAuthority; +#[cfg(test)] +use crate::repository_authority::parse_marker_path as parse_git_marker_path; use crate::safe_git::isolate_git_command_environment; -use crate::safe_git::isolate_tokio_git_command_environment; + +pub(crate) const MAX_INTERNAL_GIT_OUTPUT_BYTES: usize = 16 * 1024 * 1024; /// A Git executable outside the repository-controlled roots for one operation. -#[derive(Clone, Debug)] +#[derive(Debug)] pub(crate) struct GitRunner { + /// Canonical executable target pinned at selection time. Never execute the + /// mutable PATH spelling after validation. executable: PathBuf, + #[cfg(any(unix, test))] + argv0: PathBuf, + safe_path: std::ffi::OsString, + authority: RepositoryAuthority, } -struct UntrustedGitLocations { - roots: Vec, - common_dirs: Vec, +/// A Git command that can only be spawned through [`GitRunner::output`], +/// keeping metadata revalidation and launch hardening at one choke point. +pub(crate) struct GitCommand { + inner: Command, +} + +/// A Tokio Git command that retains the same authority and launch-hardening +/// choke point as [`GitCommand`]. Callers can configure arguments and stdin, +/// but cannot replace the authorized process cwd. +pub(crate) struct GitAsyncCommand { + inner: tokio::process::Command, + stdin_configured: bool, +} + +impl GitCommand { + pub(crate) fn arg(&mut self, arg: impl AsRef) -> &mut Self { + self.inner.arg(arg); + self + } + + pub(crate) fn args(&mut self, args: I) -> &mut Self + where + I: IntoIterator, + S: AsRef, + { + self.inner.args(args); + self + } + + pub(crate) fn env(&mut self, key: impl AsRef, value: impl AsRef) -> &mut Self { + self.inner.env(key, value); + self + } + + pub(crate) fn env_remove(&mut self, key: impl AsRef) -> &mut Self { + self.inner.env_remove(key); + self + } + + pub(crate) fn stdin(&mut self, config: impl Into) -> &mut Self { + self.inner.stdin(config); + self + } +} + +impl GitAsyncCommand { + pub(crate) fn arg(&mut self, arg: impl AsRef) -> &mut Self { + self.inner.arg(arg); + self + } + + pub(crate) fn args(&mut self, args: I) -> &mut Self + where + I: IntoIterator, + S: AsRef, + { + self.inner.args(args); + self + } + + pub(crate) fn env(&mut self, key: impl AsRef, value: impl AsRef) -> &mut Self { + self.inner.env(key, value); + self + } + + pub(crate) fn env_remove(&mut self, key: impl AsRef) -> &mut Self { + self.inner.env_remove(key); + self + } + + pub(crate) fn stdin(&mut self, config: impl Into) -> &mut Self { + self.inner.stdin(config); + self.stdin_configured = true; + self + } } impl GitRunner { pub(crate) fn for_cwd(cwd: &Path) -> Result { - let locations = untrusted_git_locations_for_cwd(cwd)?; + let authority = repository_authority_for_cwd(cwd)?; let search_path = std::env::var_os("PATH").ok_or(GitReadError::NoTrustedGit)?; - Self::from_search_path(&locations, &search_path) + Self::from_search_path(authority, &search_path) } pub(crate) fn for_cwd_io(cwd: &Path) -> io::Result { - Self::for_cwd(cwd).map_err(|error| io::Error::new(io::ErrorKind::NotFound, error)) + Self::for_cwd(cwd).map_err(GitReadError::into_io_error) } - pub(crate) fn command(&self) -> Command { - Command::new(&self.executable) + pub(crate) fn command(&self) -> GitCommand { + let mut command = Command::new(&self.executable); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + + command.arg0(&self.argv0); + } + if let Some(parent) = self.executable.parent() { + command.current_dir(parent); + } + harden_git_launch_environment(&mut command, &self.safe_path); + GitCommand { inner: command } } - pub(crate) fn tokio_command(&self) -> tokio::process::Command { - tokio::process::Command::new(&self.executable) + pub(crate) fn command_for_cwd(&self, cwd: &Path) -> io::Result { + let cwd = self.canonical_command_cwd(cwd)?; + let mut command = self.command(); + command.arg("-C").arg(cwd); + Ok(command) } - pub(crate) fn output(&self, mut command: Command) -> io::Result { - isolate_git_command_environment(&mut command); + pub(crate) fn async_command_for_cwd(&self, cwd: &Path) -> io::Result { + let cwd = self.canonical_command_cwd(cwd)?; + let mut command = tokio::process::Command::from(self.command().inner); + command.arg("-C").arg(cwd); + Ok(GitAsyncCommand { + inner: command, + stdin_configured: false, + }) + } + + fn canonical_command_cwd(&self, cwd: &Path) -> io::Result { + let cwd = if cwd.is_absolute() { + cwd.to_path_buf() + } else { + std::env::current_dir()?.join(cwd) + }; + self.authority.canonical_command_cwd(&cwd) + } + + pub(crate) fn ensure_config_source_is_not_worktree_controlled( + &self, + path: &Path, + description: &str, + ) -> io::Result<()> { + self.authority + .ensure_config_source_is_not_worktree_controlled(path, description) + } + + pub(crate) fn active_worktree_root(&self) -> Option<&Path> { + self.authority.active_worktree_root() + } + + pub(crate) fn output(&self, mut command: GitCommand) -> io::Result { + self.prepare_command_for_launch(&mut command.inner)?; + command.inner.output() + } + + fn revalidate_active_repository_metadata(&self) -> io::Result<()> { + self.authority.revalidate_active_repository_metadata() + } + + fn prepare_command_for_launch(&self, command: &mut Command) -> io::Result<()> { + self.revalidate_active_repository_metadata()?; + isolate_git_command_environment(command); command.envs(crate::local_only_git_env()); - command.output() + harden_git_launch_environment(command, &self.safe_path); + Ok(()) } /// Spawn a configured Tokio command after applying the final /// repository-selector environment lock. - pub(crate) async fn output_tokio( + #[cfg(test)] + pub(crate) async fn output_async( &self, - mut command: tokio::process::Command, + mut command: GitAsyncCommand, ) -> io::Result { - isolate_tokio_git_command_environment(&mut command); - command.envs(crate::local_only_git_env()); - command.output().await + self.prepare_command_for_launch(command.inner.as_std_mut())?; + command.inner.kill_on_drop(true); + command.inner.output().await + } + + pub(crate) async fn output_async_bounded( + &self, + mut command: GitAsyncCommand, + max_bytes_per_stream: usize, + ) -> io::Result { + self.prepare_command_for_launch(command.inner.as_std_mut())?; + command.inner.kill_on_drop(true); + if !command.stdin_configured { + command.inner.stdin(Stdio::null()); + } + command.inner.stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child = command.inner.spawn()?; + // No caller can obtain the pipe writer through this opaque command. + // Close it immediately so a child configured with `Stdio::piped()` + // observes EOF instead of waiting forever for unreachable input. + drop(child.stdin.take()); + let stdout = child + .stdout + .take() + .ok_or_else(|| io::Error::other("missing bounded Git stdout pipe"))?; + let stderr = child + .stderr + .take() + .ok_or_else(|| io::Error::other("missing bounded Git stderr pipe"))?; + let output = tokio::try_join!( + read_bounded_output(stdout, max_bytes_per_stream), + read_bounded_output(stderr, max_bytes_per_stream) + ); + let (stdout, stderr) = match output { + Ok(output) => output, + Err(error) => { + let _ = child.kill().await; + let _ = child.wait().await; + return Err(error); + } + }; + let status = child.wait().await?; + Ok(std::process::Output { + status, + stdout, + stderr, + }) } fn from_search_path( - untrusted: &UntrustedGitLocations, + authority: RepositoryAuthority, search_path: &OsStr, ) -> Result { - for directory in std::env::split_paths(search_path) { - if !directory.is_absolute() { - continue; - } - // Check the PATH spelling before appending `git`. On Windows, - // PathBuf::push resolves `..` when its base uses a verbatim prefix, - // which would otherwise erase repository traversal before the - // first containment check. - if search_directory_is_untrusted(&directory, untrusted) { - continue; - } - let candidate = directory.join(git_executable_name()); - if path_is_untrusted(&candidate, untrusted) { - continue; - } - let Ok(canonical_parent) = std::fs::canonicalize(&directory) else { - continue; - }; - if path_is_untrusted(&canonical_parent, untrusted) { - continue; - } - let Ok(canonical_candidate) = std::fs::canonicalize(&candidate) else { - continue; - }; - if path_is_untrusted(&canonical_candidate, untrusted) - || !is_native_executable_file(&canonical_candidate) - { - continue; - } - return Ok(Self { - // Preserve multicall spelling because argv[0] may select mode. - executable: candidate, - }); - } - Err(GitReadError::NoTrustedGit) + authority.ensure_primary_authority()?; + let selected = select_git_executable(&authority, search_path)?; + Ok(Self { + executable: selected.executable, + #[cfg(any(unix, test))] + argv0: selected.argv0, + safe_path: selected.safe_path, + authority, + }) } #[cfg(all(test, unix))] - pub(crate) fn from_executable_for_test(executable: PathBuf) -> Self { - Self { executable } + pub(crate) fn from_executable_for_test( + cwd: &Path, + executable: PathBuf, + ) -> Result { + let authority = repository_authority_for_cwd(cwd)?; + let safe_path = std::env::var_os("PATH").ok_or(GitReadError::NoTrustedGit)?; + Ok(Self { + argv0: executable.clone(), + executable, + safe_path, + authority, + }) } } -fn untrusted_git_locations_for_cwd(cwd: &Path) -> Result { - let lexical_cwd = if cwd.is_absolute() { - cwd.to_path_buf() - } else { - std::env::current_dir() - .map_err(|_| GitReadError::NotRepository { - path: cwd.to_path_buf(), - })? - .join(cwd) - }; - let canonical_cwd = std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository { - path: cwd.to_path_buf(), - })?; - let worktree_root = crate::get_git_repo_root(&canonical_cwd) - .and_then(|root| std::fs::canonicalize(root).ok()) - .unwrap_or_else(|| canonical_cwd.clone()); - let mut locations = UntrustedGitLocations { - roots: Vec::new(), - common_dirs: Vec::new(), - }; - record_repository_ancestry(&worktree_root, &mut locations)?; - - // Canonicalization can erase a repository-controlled symlink prefix. Walk - // the requested spelling too, deliberately retaining symlink and `..` - // components so every lexical enclosing checkout remains untrusted. - let lexical_base = if lexical_cwd.is_dir() { - lexical_cwd - } else { - lexical_cwd - .parent() - .ok_or_else(|| GitReadError::NotRepository { - path: cwd.to_path_buf(), - })? - .to_path_buf() - }; - record_repository_ancestry(&lexical_base, &mut locations)?; - - // Callers commonly obtain their default cwd from `current_dir()`, which - // can already have erased a symlink spelling. Recover the standard logical - // process cwd only when it is absolute and resolves to both the requested - // cwd and the process cwd. Treating extra roots as untrusted cannot widen - // executable selection. - if let Some(logical_cwd) = validated_logical_process_cwd(&canonical_cwd) { - record_repository_ancestry(&logical_cwd, &mut locations)?; - } - Ok(locations) -} - -fn validated_logical_process_cwd(canonical_cwd: &Path) -> Option { - let process_cwd = std::fs::canonicalize(std::env::current_dir().ok()?).ok()?; - if !paths_equal(&process_cwd, canonical_cwd) { - return None; - } - let logical_cwd = PathBuf::from(std::env::var_os("PWD")?); - if !logical_cwd.is_absolute() { - return None; - } - let canonical_logical_cwd = std::fs::canonicalize(&logical_cwd).ok()?; - paths_equal(&canonical_logical_cwd, canonical_cwd).then_some(logical_cwd) -} - -fn record_repository_ancestry( - start: &Path, - locations: &mut UntrustedGitLocations, -) -> Result<(), GitReadError> { - push_unique(&mut locations.roots, start.to_path_buf()); - record_repository_marker(start, locations)?; - for ancestor in start.parent().into_iter().flat_map(Path::ancestors) { - let dot_git = ancestor.join(".git"); - match std::fs::symlink_metadata(&dot_git) { - Ok(_) => { - push_unique(&mut locations.roots, ancestor.to_path_buf()); - let canonical_root = - std::fs::canonicalize(ancestor).map_err(|_| GitReadError::NoTrustedGit)?; - push_unique(&mut locations.roots, canonical_root.clone()); - record_repository_marker(ancestor, locations)?; - } - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(_) => return Err(GitReadError::NoTrustedGit), +async fn read_bounded_output( + mut reader: impl AsyncRead + Unpin, + max_bytes: usize, +) -> io::Result> { + let mut output = Vec::new(); + let mut chunk = [0_u8; 8192]; + loop { + let read = reader.read(&mut chunk).await?; + if read == 0 { + return Ok(output); } - } - Ok(()) -} - -fn record_repository_marker( - worktree_root: &Path, - locations: &mut UntrustedGitLocations, -) -> Result<(), GitReadError> { - let dot_git = worktree_root.join(".git"); - let common_dir = match std::fs::symlink_metadata(&dot_git) { - Ok(_) => resolve_common_git_dir(&dot_git).map_err(|()| GitReadError::NoTrustedGit)?, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(_) => return Err(GitReadError::NoTrustedGit), - }; - if !path_is_within(&common_dir, worktree_root) { - push_unique(&mut locations.roots, common_dir.clone()); - } - push_unique(&mut locations.common_dirs, common_dir); - Ok(()) -} - -fn push_unique(paths: &mut Vec, path: PathBuf) { - if !paths.iter().any(|existing| paths_equal(existing, &path)) { - paths.push(path); - } -} - -fn path_is_untrusted(path: &Path, locations: &UntrustedGitLocations) -> bool { - if locations - .roots - .iter() - .any(|root| path_is_within(path, root)) - { - return true; - } - locations - .common_dirs - .iter() - .any(|common_dir| path_is_in_worktree_for_common_dir(path, common_dir)) -} - -fn search_directory_is_untrusted(directory: &Path, locations: &UntrustedGitLocations) -> bool { - #[cfg(windows)] - if windows_path_requires_fail_closed(directory) - || windows_path_has_untrusted_canonical_ancestor(directory, locations) - { - return true; - } - path_is_untrusted(directory, locations) -} - -#[cfg(windows)] -fn windows_path_requires_fail_closed(path: &Path) -> bool { - let mut components = path.components(); - let supported_namespace = match components.next() { - Some(Component::Prefix(prefix)) => match prefix.kind() { - Prefix::Disk(_) - | Prefix::VerbatimDisk(_) - | Prefix::UNC(_, _) - | Prefix::VerbatimUNC(_, _) => true, - Prefix::DeviceNS(device) => windows_device_namespace_is_filesystem(device), - Prefix::Verbatim(namespace) => namespace - .to_str() - .is_some_and(|namespace| namespace.eq_ignore_ascii_case("UNC")), - }, - _ => false, - }; - !supported_namespace || components.any(|component| matches!(component, Component::ParentDir)) -} - -#[cfg(windows)] -fn windows_device_namespace_is_filesystem(device: &OsStr) -> bool { - let bytes = device.as_encoded_bytes(); - bytes.eq_ignore_ascii_case(b"UNC") - || matches!(bytes, [drive, b':'] if drive.is_ascii_alphabetic()) -} - -#[cfg(windows)] -fn windows_path_has_untrusted_canonical_ancestor( - path: &Path, - locations: &UntrustedGitLocations, -) -> bool { - let Ok(canonical_path) = std::fs::canonicalize(path) else { - return true; - }; - if path_is_untrusted(&canonical_path, locations) { - return true; - } - for ancestor in path.ancestors().skip(1) { - let canonical_ancestor = match std::fs::canonicalize(ancestor) { - Ok(canonical_ancestor) => canonical_ancestor, - Err(error) - if matches!( - error.kind(), - io::ErrorKind::NotFound | io::ErrorKind::InvalidInput - ) => - { - continue; - } - Err(_) => return true, - }; - if path_is_untrusted(&canonical_ancestor, locations) { - return true; + if output.len().saturating_add(read) > max_bytes { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Git output exceeded the {max_bytes}-byte stream limit"), + )); } + output.extend_from_slice(&chunk[..read]); } - false } -fn path_is_in_worktree_for_common_dir(path: &Path, expected_common_dir: &Path) -> bool { - let path = if path.is_dir() { - path - } else { - path.parent().unwrap_or(path) - }; - for ancestor in path.ancestors() { - let dot_git = ancestor.join(".git"); - match std::fs::symlink_metadata(&dot_git) { - Ok(_) => match resolve_common_git_dir(&dot_git) { - Ok(common_dir) if paths_equal(&common_dir, expected_common_dir) => return true, - Ok(_) => {} - Err(()) => return true, - }, - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(_) => return true, - } - } - false -} - -fn paths_equal(left: &Path, right: &Path) -> bool { - path_is_within(left, right) && path_is_within(right, left) -} - -fn resolve_common_git_dir(dot_git: &Path) -> Result { - if dot_git.is_dir() { - return std::fs::canonicalize(dot_git).map_err(|_| ()); - } - let contents = std::fs::read_to_string(dot_git).map_err(|_| ())?; - let git_dir = contents - .trim() - .strip_prefix("gitdir:") - .map(str::trim) - .filter(|path| !path.is_empty()) - .ok_or(())?; - let git_dir = canonicalize_from(dot_git.parent().ok_or(())?, git_dir)?; - let commondir = git_dir.join("commondir"); - if commondir.is_file() { - let common_dir = std::fs::read_to_string(commondir).map_err(|_| ())?; - let common_dir = common_dir.trim(); - if common_dir.is_empty() { - return Err(()); - } - return canonicalize_from(&git_dir, common_dir); - } - if git_dir - .parent() - .is_some_and(|parent| parent.file_name() == Some(OsStr::new("worktrees"))) - { - return std::fs::canonicalize(git_dir.parent().and_then(Path::parent).ok_or(())?) - .map_err(|_| ()); - } - Ok(git_dir) -} - -fn canonicalize_from(base: &Path, path: &str) -> Result { - std::fs::canonicalize(base.join(path)).map_err(|_| ()) -} - -#[cfg(windows)] -fn git_executable_name() -> &'static str { - "git.exe" -} - -#[cfg(not(windows))] -fn git_executable_name() -> &'static str { - "git" -} - -#[cfg(unix)] -fn is_native_executable_file(path: &Path) -> bool { - use std::os::unix::fs::PermissionsExt; - - std::fs::metadata(path) - .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0) -} - -#[cfg(windows)] -fn is_native_executable_file(path: &Path) -> bool { - path.extension() - .and_then(OsStr::to_str) - .is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) - && std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) -} - -#[cfg(not(any(unix, windows)))] -fn is_native_executable_file(path: &Path) -> bool { - std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) +pub(crate) fn repository_authority_for_cwd( + cwd: &Path, +) -> Result { + RepositoryAuthority::discover(cwd) } #[cfg(test)] diff --git a/codex-rs/git-utils/src/git_command_tests.rs b/codex-rs/git-utils/src/git_command_tests.rs index 5ea99191d6..67106efaa9 100644 --- a/codex-rs/git-utils/src/git_command_tests.rs +++ b/codex-rs/git-utils/src/git_command_tests.rs @@ -33,6 +33,67 @@ fn run_git(cwd: &Path, args: &[&str]) { assert!(status.success(), "git {args:?} failed"); } +#[tokio::test] +async fn bounded_async_output_rejects_the_first_byte_over_limit() { + use tokio::io::AsyncWriteExt; + + let (mut writer, reader) = tokio::io::duplex(16); + let write = tokio::spawn(async move { + writer.write_all(b"12345").await.expect("write fixture"); + }); + let error = read_bounded_output(reader, 4) + .await + .expect_err("fifth byte must exceed limit"); + write.await.expect("join fixture writer"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); +} + +#[cfg(unix)] +#[tokio::test] +async fn bounded_async_output_closes_an_unowned_piped_stdin() { + let fixture = tempfile::tempdir().expect("fixture"); + let repo = fixture.path().join("repo"); + std::fs::create_dir_all(&repo).expect("create repository"); + run_git(&repo, &["init", "-q"]); + let fake_git = fixture.path().join("git"); + write_executable(&fake_git, "#!/bin/sh\nexec /bin/cat\n"); + let git = GitRunner::from_executable_for_test(&repo, fake_git).expect("test Git runner"); + let mut command = git + .async_command_for_cwd(&repo) + .expect("authorized async command"); + command.stdin(std::process::Stdio::piped()); + + let output = tokio::time::timeout( + std::time::Duration::from_secs(1), + git.output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES), + ) + .await + .expect("unowned pipe must close before the child waits for EOF") + .expect("run fake Git"); + + assert!(output.status.success()); + assert!(output.stdout.is_empty()); +} + +fn run_git_stdout(cwd: &Path, args: &[&str]) -> String { + let mut command = Command::new("git"); + isolate_git_command_environment(&mut command); + let output = command + .args(args) + .current_dir(cwd) + .output() + .expect("run real Git"); + assert!( + output.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout) + .expect("UTF-8 Git output") + .trim() + .to_string() +} + fn commit_all(cwd: &Path, message: &str) { run_git( cwd, @@ -53,16 +114,63 @@ fn commit_all(cwd: &Path, message: &str) { fn write_git_candidate(directory: &Path) { std::fs::create_dir_all(directory).expect("create candidate directory"); let candidate = directory.join(git_executable_name()); - #[cfg(unix)] - write_executable(&candidate, "#!/bin/sh\nexit 0\n"); #[cfg(windows)] - std::fs::write(candidate, b"MZ").expect("write native executable fixture"); - #[cfg(not(any(unix, windows)))] - std::fs::write(candidate, b"git fixture").expect("write executable fixture"); + { + let mut pe = [0_u8; 68]; + pe[..2].copy_from_slice(b"MZ"); + pe[60..64].copy_from_slice(&64_u32.to_le_bytes()); + pe[64..].copy_from_slice(b"PE\0\0"); + std::fs::write(candidate, pe).expect("write native PE fixture"); + } + #[cfg(not(windows))] + std::fs::copy(native_git_fixture(), candidate).expect("copy native Git fixture"); +} + +fn write_runnable_git_candidate(directory: &Path) { + #[cfg(windows)] + { + std::fs::create_dir_all(directory.parent().expect("candidate parent")) + .expect("create candidate parent"); + create_junction(directory, &native_git_search_directory()); + } + #[cfg(not(windows))] + write_git_candidate(directory); +} + +#[cfg(windows)] +fn native_git_search_directory() -> PathBuf { + let path = std::env::var_os("PATH").expect("PATH"); + for directory in std::env::split_paths(&path) { + let candidate = directory.join(git_executable_name()); + if let Ok(candidate) = std::fs::canonicalize(candidate) + && crate::git_executable::is_native_executable_file(&candidate) + { + return directory; + } + } + panic!("no native Git directory in PATH") +} + +fn native_git_fixture() -> PathBuf { + let path = std::env::var_os("PATH").expect("PATH"); + for directory in std::env::split_paths(&path) { + let candidate = directory.join(git_executable_name()); + if let Ok(candidate) = std::fs::canonicalize(candidate) + && crate::git_executable::is_native_executable_file(&candidate) + { + return candidate; + } + } + panic!("no native Git fixture in PATH") } #[cfg(windows)] fn create_junction(path: &Path, target: &Path) { + // Bazel's GNU Windows runner can surface temporary paths with `/` + // separators. `mklink` treats those separators as option prefixes, so + // pass native separators to the cmd.exe built-in. + let path = path.as_os_str().to_string_lossy().replace('/', "\\"); + let target = target.as_os_str().to_string_lossy().replace('/', "\\"); let output = Command::new("cmd.exe") .args(["/D", "/C", "mklink", "/J"]) .arg(path) @@ -77,16 +185,24 @@ fn create_junction(path: &Path, target: &Path) { ); } -fn locations_for_root(root: &Path) -> UntrustedGitLocations { +fn locations_for_root(root: &Path) -> RepositoryAuthority { let mut roots = vec![root.to_path_buf()]; - push_unique( - &mut roots, - std::fs::canonicalize(root).expect("canonical root"), - ); - UntrustedGitLocations { - roots, - common_dirs: Vec::new(), + let canonical = std::fs::canonicalize(root).expect("canonical root"); + if !roots.contains(&canonical) { + roots.push(canonical); } + RepositoryAuthority::from_test_locations(roots.clone(), roots, Vec::new()) + .expect("test repository authority") +} + +fn config_authority_for_root(root: &Path) -> RepositoryAuthority { + let mut roots = vec![root.to_path_buf()]; + let canonical = std::fs::canonicalize(root).expect("canonical root"); + if !roots.contains(&canonical) { + roots.push(canonical); + } + RepositoryAuthority::from_test_locations(roots.clone(), roots, vec![root.join(".git")]) + .expect("config repository authority") } fn raw_parent_traversal(root: &Path, sibling: &str) -> PathBuf { @@ -103,11 +219,446 @@ fn path_text(path: &Path) -> &str { path.to_str().expect("UTF-8 fixture path") } -fn selected_git(locations: &UntrustedGitLocations, directories: &[&Path]) -> PathBuf { +fn tempdir_for_native_git() -> tempfile::TempDir { + #[cfg(windows)] + { + // Git for Windows rejects the `\\?\` spelling returned when the + // process temp directory is canonicalized. + tempfile::tempdir().expect("fixture") + } + #[cfg(not(windows))] + { + let temp_base = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp dir"); + tempfile::tempdir_in(temp_base).expect("fixture") + } +} + +fn git_config_path(path: &Path) -> String { + let path = path.to_string_lossy(); + #[cfg(windows)] + let path = path.replace('\\', "/"); + #[cfg(not(windows))] + let path = path.into_owned(); + format!("\"{}\"", path.replace('\\', "\\\\").replace('"', "\\\"")) +} + +struct OverlappingRegisteredRoute { + main: PathBuf, + nested: PathBuf, + linked: PathBuf, + #[cfg(unix)] + nested_admin: PathBuf, + linked_admin: PathBuf, + registry_marker: PathBuf, + raw_marker: PathBuf, +} + +fn overlapping_registered_route(fixture: &Path) -> OverlappingRegisteredRoute { + let main = fixture.join("main"); + let nested = main.join("nested"); + let linked = main.join("linked"); + std::fs::create_dir_all(&main).expect("create main worktree"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&nested)]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&linked)]); + #[cfg(unix)] + let nested_admin = PathBuf::from(run_git_stdout( + &nested, + &["rev-parse", "--absolute-git-dir"], + )); + let linked_admin = PathBuf::from(run_git_stdout( + &linked, + &["rev-parse", "--absolute-git-dir"], + )); + let registry_marker = linked_admin.join("gitdir"); + let raw_marker = nested.join("..").join("linked/.git"); + std::fs::write(®istry_marker, format!("{}\n", raw_marker.display())) + .expect("write overlapping registry route"); + OverlappingRegisteredRoute { + main, + nested, + linked, + #[cfg(unix)] + nested_admin, + linked_admin, + registry_marker, + raw_marker, + } +} + +struct MetadataAliasRegisteredRoute { + main: PathBuf, + linked: PathBuf, + linked_admin: PathBuf, + pivot: PathBuf, + registry_marker: PathBuf, + #[cfg(unix)] + raw_marker: PathBuf, +} + +fn metadata_alias_registered_route( + fixture: &Path, + main_name: &str, + route_main_name: &str, +) -> MetadataAliasRegisteredRoute { + let main = fixture.join(main_name); + let linked = main.join("linked"); + std::fs::create_dir_all(&main).expect("create main worktree"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&linked)]); + let linked_admin = PathBuf::from(run_git_stdout( + &linked, + &["rev-parse", "--absolute-git-dir"], + )); + let pivot = main.join("pivot"); + let registry_marker = linked_admin.join("gitdir"); + let raw_marker = fixture + .join(route_main_name) + .join("pivot") + .join("..") + .join("linked/.git"); + std::fs::write(®istry_marker, format!("{}\n", raw_marker.display())) + .expect("write metadata-alias registry route"); + MetadataAliasRegisteredRoute { + main, + linked, + linked_admin, + pivot, + registry_marker, + #[cfg(unix)] + raw_marker, + } +} + +#[test] +fn git_metadata_marker_parser_preserves_leading_path_space() { + assert_eq!( + parse_git_marker_path(b"gitdir: relative/path \r\n", b"gitdir: ") + .expect("parse .git marker"), + PathBuf::from(" relative/path") + ); + assert_eq!( + parse_git_marker_path(b" relative/common \n", b"").expect("parse commondir marker"), + PathBuf::from(" relative/common") + ); + assert!(parse_git_marker_path(b"gitdir:/missing-space\n", b"gitdir: ").is_err()); +} + +#[test] +fn config_source_authority_requires_an_absolute_raw_path() { + let fixture = tempdir_for_native_git(); + let root = fixture.path().join("repo"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git(&root, &["init", "-q"]); + let authority = config_authority_for_root(&root); + let path = Path::new("relative/config"); + + let error = authority + .ensure_config_source_is_not_worktree_controlled(path, "test config") + .expect_err("relative config path"); + + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("test config"), "{error}"); + assert!(error.to_string().contains("relative/config"), "{error}"); +} + +#[test] +fn config_source_authority_preserves_and_rejects_a_worktree_crossing_spelling() { + let fixture = tempdir_for_native_git(); + let root = fixture.path().join("repo"); + let safe = fixture.path().join("safe"); + std::fs::create_dir_all(root.join("nested")).expect("create repository descendant"); + std::fs::create_dir_all(&safe).expect("create safe directory"); + run_git(&root, &["init", "-q"]); + let authority = config_authority_for_root(&root); + let raw = root + .join("nested") + .join("..") + .join("..") + .join("safe/config"); + + let error = authority + .ensure_config_source_is_not_worktree_controlled(&raw, "crossing config") + .expect_err("worktree-crossing config path"); + + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("crossing config"), "{error}"); + assert!( + error.to_string().contains(&raw.display().to_string()), + "{error}" + ); +} + +#[test] +fn config_source_authority_allows_protected_metadata_and_unrelated_external_paths() { + let fixture = tempdir_for_native_git(); + let root = fixture.path().join("repo"); + let external = fixture.path().join("external/config"); + std::fs::create_dir_all(&root).expect("create repository"); + std::fs::create_dir_all(external.parent().expect("external parent")) + .expect("create external directory"); + run_git(&root, &["init", "-q"]); + let authority = config_authority_for_root(&root); + + authority + .ensure_config_source_is_not_worktree_controlled( + &root.join(".git/config"), + "protected metadata config", + ) + .expect("protected metadata config"); + let canonical_config = + std::fs::canonicalize(root.join(".git/config")).expect("canonical metadata config"); + authority + .ensure_config_source_is_not_worktree_controlled( + &canonical_config, + "canonical protected metadata config", + ) + .expect("canonical protected metadata config"); + authority + .ensure_config_source_is_not_worktree_controlled(&external, "external config") + .expect("unrelated external config"); +} + +#[test] +fn config_source_authority_rejects_an_unregistered_related_repository_root() { + let fixture = tempdir_for_native_git(); + let root = fixture.path().join("repo"); + let alias = fixture.path().join("unregistered-related-root"); + std::fs::create_dir_all(&root).expect("create repository"); + std::fs::create_dir_all(&alias).expect("create related root"); + run_git(&root, &["init", "-q"]); + std::fs::write( + alias.join(".git"), + format!("gitdir: {}\n", root.join(".git").display()), + ) + .expect("write related metadata marker"); + let authority = config_authority_for_root(&root); + let path = alias.join("config"); + + let error = authority + .ensure_config_source_is_not_worktree_controlled(&path, "related config") + .expect_err("unregistered related repository config"); + + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("related config"), "{error}"); +} + +fn selected_git(locations: &RepositoryAuthority, directories: &[&Path]) -> PathBuf { let search_path = std::env::join_paths(directories).expect("PATH"); - GitRunner::from_search_path(locations, &search_path) + select_git_executable(locations, &search_path) .expect("trusted Git") - .executable + .argv0 +} + +fn assert_unsafe_metadata_route(result: Result, marker: &Path) { + match result { + Err(GitReadError::UnsafeRepositoryMetadata { path, reason }) => { + assert_same_affected_path(&path, marker); + assert_eq!(reason, "Git metadata route crosses a repository worktree"); + } + other => panic!("expected unsafe repository metadata, got {other:?}"), + } +} + +fn assert_unsafe_registry_route(result: Result, marker: &Path) { + match result { + Err(GitReadError::UnsafeRepositoryMetadata { path, reason }) => { + assert_same_affected_path(&path, marker); + assert_eq!( + reason, + "Git worktree registry route crosses a repository worktree" + ); + } + other => panic!("expected unsafe worktree registry route, got {other:?}"), + } +} + +#[cfg(unix)] +fn assert_unsafe_registry_route_at_one_of( + result: Result, + markers: &[&Path], +) { + match result { + Err(GitReadError::UnsafeRepositoryMetadata { path, reason }) => { + assert_eq!( + reason, + "Git worktree registry route crosses a repository worktree" + ); + assert!( + markers + .iter() + .any(|marker| affected_paths_match(&path, marker)), + "unexpected affected registry path: {}", + path.display() + ); + } + other => panic!("expected unsafe worktree registry route, got {other:?}"), + } +} + +fn assert_same_affected_path(actual: &Path, expected: &Path) { + assert!( + affected_paths_match(actual, expected), + "affected paths differ: actual={} expected={}", + actual.display(), + expected.display() + ); +} + +fn affected_paths_match(actual: &Path, expected: &Path) -> bool { + if actual.file_name() != expected.file_name() { + return false; + } + let Some(actual_parent) = actual.parent() else { + return false; + }; + let Some(expected_parent) = expected.parent() else { + return false; + }; + same_file::is_same_file(actual_parent, expected_parent).unwrap_or(false) +} + +#[test] +fn git_read_error_io_kind_table_is_exhaustive() { + let path = PathBuf::from("repository/.git"); + for (error, expected) in [ + (GitReadError::NoTrustedGit, io::ErrorKind::NotFound), + ( + GitReadError::NotRepository { path: path.clone() }, + io::ErrorKind::NotFound, + ), + ( + GitReadError::UnprovenPrimaryAuthority { + common_dir: "repository.git".to_string(), + }, + io::ErrorKind::PermissionDenied, + ), + ( + GitReadError::UnsafeRepositoryMetadata { + path: path.clone(), + reason: "crosses worktree".to_string(), + }, + io::ErrorKind::PermissionDenied, + ), + ( + GitReadError::InvalidRepositoryMetadata { + path, + reason: "malformed marker".to_string(), + }, + io::ErrorKind::InvalidData, + ), + ] { + assert_eq!(error.io_kind(), expected, "{error}"); + assert_eq!(error.into_io_error().kind(), expected); + } +} + +#[test] +fn malformed_metadata_preserves_path_reason_and_invalid_data_mapping() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repository"); + std::fs::create_dir_all(&root).expect("create repository root"); + let marker = root.join(".git"); + std::fs::write(&marker, "not-a-gitdir-marker\n").expect("write malformed marker"); + + match GitRunner::for_cwd(&root) { + Err(GitReadError::InvalidRepositoryMetadata { path, reason }) => { + assert_same_affected_path(&path, &marker); + assert!(reason.contains("malformed Git metadata marker"), "{reason}"); + } + other => panic!("expected invalid repository metadata, got {other:?}"), + } + let error = GitRunner::for_cwd_io(&root).expect_err("malformed metadata"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!( + error.to_string().contains("malformed Git metadata marker"), + "{error}" + ); + assert!(!error.to_string().contains("PATH"), "{error}"); +} + +#[cfg(unix)] +#[test] +fn cyclic_metadata_route_is_invalid_not_unsafe() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repository"); + let external = fixture.path().join("external"); + std::fs::create_dir_all(&root).expect("create repository root"); + std::fs::create_dir_all(&external).expect("create external directory"); + let route = external.join("entry"); + symlink("entry", &route).expect("create route cycle"); + let marker = root.join(".git"); + std::fs::write(&marker, format!("gitdir: {}\n", route.display())).expect("write cyclic marker"); + + match GitRunner::for_cwd(&root) { + Err(GitReadError::InvalidRepositoryMetadata { path, reason }) => { + assert_same_affected_path(&path, &marker); + assert!(!reason.is_empty()); + } + other => panic!("expected invalid repository metadata, got {other:?}"), + } + assert_eq!( + GitRunner::for_cwd_io(&root) + .expect_err("cyclic metadata route") + .kind(), + io::ErrorKind::InvalidData + ); +} + +#[cfg(unix)] +#[test] +fn symlinked_directory_metadata_marker_is_invalid() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repository"); + let external = fixture.path().join("external-metadata"); + std::fs::create_dir_all(&root).expect("create repository root"); + run_git(&root, &["init", "-q"]); + std::fs::rename(root.join(".git"), &external).expect("move metadata directory"); + symlink(&external, root.join(".git")).expect("symlink metadata marker"); + + match GitRunner::for_cwd(&root) { + Err(GitReadError::InvalidRepositoryMetadata { path, reason }) => { + assert_same_affected_path(&path, &root.join(".git")); + assert_eq!(reason, "symlinked Git metadata marker"); + } + other => panic!("expected invalid symlinked metadata marker, got {other:?}"), + } + assert_eq!( + GitRunner::for_cwd_io(&root) + .expect_err("symlinked metadata marker") + .kind(), + io::ErrorKind::InvalidData + ); +} + +#[cfg(windows)] +#[test] +fn directory_git_junction_to_external_metadata_is_rejected() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repository"); + let external = fixture.path().join("external-metadata"); + std::fs::create_dir_all(&root).expect("create repository root"); + run_git(&root, &["init", "-q"]); + std::fs::rename(root.join(".git"), &external).expect("move metadata directory"); + create_junction(&root.join(".git"), &external); + run_git(&root, &["rev-parse", "--absolute-git-dir"]); + + let error = GitRunner::for_cwd(&root).expect_err("nonstandard directory metadata route"); + match error { + GitReadError::UnsafeRepositoryMetadata { path, reason } => { + assert_same_affected_path(&path, &root.join(".git")); + assert_eq!(reason, "nonstandard Git metadata directory"); + } + GitReadError::InvalidRepositoryMetadata { path, reason } => { + assert_same_affected_path(&path, &root.join(".git")); + assert_eq!(reason, "symlinked Git metadata marker"); + } + other => panic!("expected rejected directory metadata junction, got {other:?}"), + } } #[cfg(unix)] @@ -121,10 +672,10 @@ fn resolver_skips_untrusted_path_entries_and_runs_external_candidate() { std::fs::create_dir_all(&repo_bin).expect("repo bin"); std::fs::create_dir_all(&outside).expect("outside bin"); std::fs::create_dir_all(&trusted_bin).expect("trusted bin"); - write_executable(&repo_bin.join("git"), "#!/bin/sh\nexit 1\n"); + write_git_candidate(&repo_bin); std::os::unix::fs::symlink(repo_bin.join("git"), outside.join("git")) .expect("outside symlink into repository"); - write_executable(&trusted_bin.join("git"), "#!/bin/sh\nprintf 'trusted\\n'\n"); + write_git_candidate(&trusted_bin); let path = std::env::join_paths([ PathBuf::from("relative"), @@ -134,10 +685,987 @@ fn resolver_skips_untrusted_path_entries_and_runs_external_candidate() { ]) .expect("PATH"); let locations = locations_for_root(&repo); - let runner = GitRunner::from_search_path(&locations, &path).expect("trusted Git"); - assert_eq!(runner.executable, trusted_bin.join("git")); - let output = runner.output(runner.command()).expect("run trusted Git"); - assert_eq!(output.stdout, b"trusted\n"); + let runner = GitRunner::from_search_path(locations, &path).expect("trusted Git"); + assert_eq!(runner.argv0, trusted_bin.join("git")); + let mut command = runner.command(); + command.arg("--version"); + let output = runner.output(command).expect("run trusted Git"); + assert!(output.status.success()); + assert!(output.stdout.starts_with(b"git version ")); +} + +#[cfg(unix)] +#[test] +fn resolver_skips_env_absolute_and_no_shebang_git_scripts() { + let temp_base = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp dir"); + let fixture = tempfile::tempdir_in(temp_base).expect("fixture"); + let repo = fixture.path().join("repo"); + let trusted = fixture.path().join("trusted"); + std::fs::create_dir_all(&repo).expect("create repository"); + write_git_candidate(&trusted); + + let mut script_dirs = Vec::new(); + for (name, prefix) in [ + ("env-shebang", "#!/usr/bin/env sh\n"), + ("absolute-shebang", "#!/bin/sh\n"), + ("no-shebang", ""), + ] { + let directory = fixture.path().join(name); + let marker = fixture.path().join(format!("{name}-ran")); + std::fs::create_dir_all(&directory).expect("create script directory"); + write_executable( + &directory.join("git"), + &format!("{prefix}touch '{}'\n", marker.display()), + ); + script_dirs.push((directory, marker)); + } + + let locations = locations_for_root(&repo); + let mut path_entries = script_dirs + .iter() + .map(|(directory, _)| directory.as_path()) + .collect::>(); + let scripts_only = std::env::join_paths(&path_entries).expect("scripts-only PATH"); + let error = match select_git_executable(&locations, &scripts_only) { + Ok(_) => panic!("selected a non-native Git wrapper"), + Err(error) => error, + }; + assert_eq!(error, GitReadError::NoTrustedGit); + let message = error.to_string(); + assert!(message.contains("native Git"), "{message}"); + assert!( + message.contains("script-based and non-native Git wrappers"), + "{message}" + ); + assert!(message.contains("outside the repository"), "{message}"); + assert!(message.contains("PATH"), "{message}"); + assert_eq!(error.io_kind(), io::ErrorKind::NotFound); + for (_, marker) in &script_dirs { + assert!( + !marker.exists(), + "non-native Git script executed: {marker:?}" + ); + } + path_entries.push(&trusted); + let path = std::env::join_paths(path_entries).expect("PATH"); + let runner = GitRunner::from_search_path(locations, &path).expect("native Git fallback"); + assert_eq!(runner.argv0, trusted.join("git")); + let mut command = runner.command(); + command.arg("--version"); + assert!( + runner + .output(command) + .expect("run native Git") + .status + .success() + ); + for (_, marker) in script_dirs { + assert!( + !marker.exists(), + "non-native Git script executed: {marker:?}" + ); + } +} + +#[cfg(unix)] +#[test] +fn selected_git_uses_sanitized_path_and_strips_loader_injection_environment() { + let temp_base = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp dir"); + let fixture = tempfile::tempdir_in(temp_base).expect("fixture"); + let repo = fixture.path().join("repo"); + let unsafe_bin = repo.join("bin"); + let trusted = fixture.path().join("trusted"); + std::fs::create_dir_all(&unsafe_bin).expect("create unsafe bin"); + std::fs::create_dir_all(&trusted).expect("create trusted bin"); + std::fs::copy( + std::env::current_exe().expect("current test executable"), + trusted.join("git"), + ) + .expect("copy native environment probe fixture"); + + let locations = locations_for_root(&repo); + let path = std::env::join_paths([&unsafe_bin, &trusted]).expect("PATH"); + let runner = GitRunner::from_search_path(locations, &path).expect("trusted native env"); + let mut command = runner.command(); + let injected = repo.join("inject"); + command + .arg("git_command::tests::native_environment_probe_child") + .arg("--exact") + .arg("--nocapture") + .env("CODEX_GIT_ENVIRONMENT_PROBE_CHILD", "1") + .env( + "CODEX_GIT_EXPECTED_SAFE_PATH", + std::fs::canonicalize(&trusted).expect("canonical trusted bin"), + ); + for name in [ + "DYLD_INSERT_LIBRARIES", + "LD_PRELOAD", + "LD_AUDIT", + "LIBPATH", + "SHLIB_PATH", + "GCONV_PATH", + "NIX_LD", + "NIX_LD_LIBRARY_PATH", + "CORECLR_ENABLE_PROFILING", + "COR_ENABLE_PROFILING", + "DOTNET_STARTUP_HOOKS", + ] { + command.env(name, &injected); + } + command.env("PATH", &path); + let output = runner.output(command).expect("run sanitized native env"); + assert!( + output.status.success(), + "native env failed with {}: stdout={} stderr={}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); +} + +#[cfg(unix)] +#[test] +fn native_environment_probe_child() { + if std::env::var_os("CODEX_GIT_ENVIRONMENT_PROBE_CHILD").is_none() { + return; + } + for name in [ + "DYLD_INSERT_LIBRARIES", + "LD_PRELOAD", + "LD_AUDIT", + "LIBPATH", + "SHLIB_PATH", + "GCONV_PATH", + "NIX_LD", + "NIX_LD_LIBRARY_PATH", + "CORECLR_ENABLE_PROFILING", + "COR_ENABLE_PROFILING", + "DOTNET_STARTUP_HOOKS", + ] { + assert!(std::env::var_os(name).is_none(), "{name} survived"); + } + assert_eq!( + std::env::var_os("PATH").expect("sanitized PATH"), + std::env::var_os("CODEX_GIT_EXPECTED_SAFE_PATH").expect("expected safe PATH") + ); +} + +#[test] +fn command_for_relative_cwd_uses_original_process_directory() { + let current = std::fs::canonicalize(std::env::current_dir().expect("current dir")) + .expect("canonical current dir"); + let fixture = tempfile::tempdir_in(¤t).expect("fixture"); + let repo = fixture.path().join("repo"); + std::fs::create_dir_all(&repo).expect("create repository"); + run_git(&repo, &["init", "-q"]); + let relative = repo.strip_prefix(¤t).expect("relative repository"); + let locations = repository_authority_for_cwd(&repo).expect("untrusted locations"); + let path = std::env::var_os("PATH").expect("PATH"); + let runner = GitRunner::from_search_path(locations, &path).expect("trusted Git"); + let mut command = runner + .command_for_cwd(relative) + .expect("relative command cwd"); + command.args(["rev-parse", "--show-toplevel"]); + crate::repository_authority::reset_bounded_marker_read_count(); + let output = runner.output(command).expect("run Git from relative cwd"); + assert!(output.status.success()); + assert_eq!( + std::fs::canonicalize(String::from_utf8_lossy(&output.stdout).trim()) + .expect("canonical Git root"), + std::fs::canonicalize(&repo).expect("canonical expected root") + ); + assert_eq!( + crate::repository_authority::bounded_marker_read_count(), + 0, + "standard repository should not reread marker bodies" + ); +} + +#[cfg(unix)] +#[test] +fn selected_runner_executes_pinned_target_after_path_hop_is_retargeted() { + let temp_base = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp dir"); + let fixture = tempfile::tempdir_in(temp_base).expect("fixture"); + let repo = fixture.path().join("repo"); + let switch = fixture.path().join("switch"); + let trusted = fixture.path().join("trusted"); + let attacker = fixture.path().join("attacker"); + let entry = fixture.path().join("entry"); + std::fs::create_dir_all(&repo).expect("create repository"); + std::fs::create_dir_all(&trusted).expect("create trusted target"); + std::fs::create_dir_all(&attacker).expect("create attacker target"); + std::fs::create_dir_all(&entry).expect("create PATH entry"); + std::fs::copy("/usr/bin/true", trusted.join("git")).expect("copy trusted native target"); + std::fs::copy("/usr/bin/false", attacker.join("git")).expect("copy attacker native target"); + std::os::unix::fs::symlink(&trusted, &switch).expect("trusted PATH hop"); + std::os::unix::fs::symlink(switch.join("git"), entry.join("git")) + .expect("external candidate through PATH hop"); + + let locations = locations_for_root(&repo); + let path = std::env::join_paths([&entry]).expect("PATH"); + let runner = GitRunner::from_search_path(locations, &path).expect("initial trusted target"); + std::fs::remove_file(&switch).expect("remove trusted PATH hop"); + std::os::unix::fs::symlink(&attacker, &switch).expect("retarget PATH hop"); + + let output = runner.output(runner.command()).expect("run selected Git"); + assert!(output.status.success(), "selected Git failed"); +} + +#[cfg(unix)] +#[test] +fn resolver_rejects_same_identity_symlink_alias_to_repository() { + let temp_base = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp dir"); + let fixture = tempfile::tempdir_in(temp_base).expect("fixture"); + let repo = fixture.path().join("repo"); + let repo_bin = repo.join("bin"); + let alias = fixture.path().join("repo-alias"); + let alias_bin = alias.join("bin"); + let trusted_bin = fixture.path().join("trusted-bin"); + std::fs::create_dir_all(&repo).expect("create repository"); + write_git_candidate(&repo_bin); + write_git_candidate(&trusted_bin); + std::os::unix::fs::symlink(&repo, &alias).expect("symlink repository alias"); + + let locations = locations_for_root(&repo); + assert_eq!( + selected_git(&locations, &[&alias_bin, &trusted_bin]), + trusted_bin.join(git_executable_name()) + ); +} + +#[cfg(target_os = "macos")] +#[test] +fn resolver_rejects_apfs_data_firmlink_alias_to_repository() { + let data_volume_temp = + std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp directory"); + let fixture = tempfile::tempdir_in(&data_volume_temp).expect("fixture under Data volume"); + let repo = fixture.path().join("repo"); + let repo_bin = repo.join("bin"); + let trusted_bin = fixture.path().join("trusted-bin"); + std::fs::create_dir_all(&repo).expect("create repository"); + write_git_candidate(&repo_bin); + write_git_candidate(&trusted_bin); + + let data_alias = PathBuf::from("/System/Volumes/Data") + .join(repo.strip_prefix("/").expect("absolute repository path")); + let alias_bin = data_alias.join("bin"); + if std::fs::metadata(&data_alias).is_err() { + eprintln!("APFS Data firmlink alias is unavailable; skipping native alias assertion"); + return; + } + assert!( + same_file::is_same_file(&data_alias, &repo).expect("compare APFS Data alias identity"), + "APFS Data spelling does not identify the fixture repository" + ); + + let locations = locations_for_root(&repo); + assert_eq!( + selected_git(&locations, &[&alias_bin, &trusted_bin]), + trusted_bin.join(git_executable_name()) + ); +} + +#[cfg(target_os = "macos")] +#[test] +fn metadata_routes_distinguish_apfs_worktree_hop_from_direct_metadata_alias() { + use std::os::unix::fs::symlink; + + let data_volume_temp = + std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp directory"); + let fixture = tempfile::tempdir_in(&data_volume_temp).expect("fixture under Data volume"); + let outer = fixture.path().join("outer"); + let root = outer.join("nested"); + let admin = outer.join(".git/modules/nested"); + std::fs::create_dir_all(&root).expect("create nested repository"); + run_git(&outer, &["init", "-q"]); + run_git(&root, &["init", "-q"]); + std::fs::create_dir_all(admin.parent().expect("module metadata parent")) + .expect("create module metadata parent"); + std::fs::rename(root.join(".git"), &admin).expect("move metadata into outer .git"); + let data_alias = PathBuf::from("/System/Volumes/Data") + .join(outer.strip_prefix("/").expect("absolute repository path")); + if std::fs::metadata(&data_alias).is_err() { + eprintln!("APFS Data firmlink alias is unavailable; skipping native route assertion"); + return; + } + assert!(same_file::is_same_file(&data_alias, &outer).expect("compare APFS root alias")); + + // A direct alternate spelling of proven outer metadata remains compatible. + std::fs::write( + root.join(".git"), + format!( + "gitdir: {}\n", + data_alias.join(".git/modules/nested").display() + ), + ) + .expect("write direct metadata alias marker"); + let runner = GitRunner::for_cwd(&root).expect("direct APFS metadata alias"); + let mut command = runner + .command_for_cwd(&root) + .expect("direct APFS alias command"); + command.args(["rev-parse", "--absolute-git-dir"]); + assert!( + runner + .output(command) + .expect("direct APFS alias rev-parse") + .status + .success() + ); + + // A different symlink entry reached through the same root identity is a + // mutable worktree hop even when it exits to the same external metadata. + symlink(&admin, outer.join("switch")).expect("worktree route switch"); + std::fs::write( + root.join(".git"), + format!("gitdir: {}\n", data_alias.join("switch").display()), + ) + .expect("write APFS worktree-hop marker"); + run_git(&root, &["rev-parse", "--absolute-git-dir"]); + assert_unsafe_metadata_route(repository_authority_for_cwd(&root), &root.join(".git")); +} + +#[cfg(windows)] +#[test] +fn resolver_rejects_same_identity_junction_alias_to_repository() { + let fixture = tempfile::tempdir().expect("fixture"); + let repo = fixture.path().join("repo"); + let repo_bin = repo.join("bin"); + let alias = fixture.path().join("repo-alias"); + let alias_bin = alias.join("bin"); + let trusted_bin = fixture.path().join("trusted-bin"); + std::fs::create_dir_all(&repo).expect("create repository"); + write_git_candidate(&repo_bin); + write_git_candidate(&trusted_bin); + create_junction(&alias, &repo); + + let locations = locations_for_root(&repo); + assert_eq!( + selected_git(&locations, &[&alias_bin, &trusted_bin]), + trusted_bin.join(git_executable_name()) + ); +} + +#[cfg(unix)] +#[test] +fn gitdir_route_through_current_worktree_is_denied_before_path_selection() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let external = fixture.path().join("external"); + let admin = external.join("admin"); + std::fs::create_dir_all(&root).expect("create repository"); + std::fs::create_dir_all(&external).expect("create external directory"); + run_git(&root, &["init", "-q"]); + std::fs::rename(root.join(".git"), &admin).expect("move metadata external"); + symlink(&admin, root.join("switch")).expect("worktree metadata switch"); + std::fs::write(root.join(".git"), "gitdir: switch\n").expect("write gitdir marker"); + run_git(&root, &["rev-parse", "--absolute-git-dir"]); + + assert_unsafe_metadata_route(repository_authority_for_cwd(&root), &root.join(".git")); + let error = GitRunner::for_cwd_io(&root).expect_err("unsafe metadata route"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("Git metadata route crosses")); + assert!(!error.to_string().contains("PATH")); +} + +#[cfg(unix)] +#[test] +fn gitdir_route_that_enters_and_exits_worktree_by_identity_is_denied() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let external = fixture.path().join("external"); + let admin = external.join("admin"); + let entry = external.join("entry"); + std::fs::create_dir_all(&root).expect("create repository"); + std::fs::create_dir_all(&external).expect("create external directory"); + run_git(&root, &["init", "-q"]); + std::fs::rename(root.join(".git"), &admin).expect("move metadata external"); + symlink(&root, &entry).expect("external entry into worktree"); + symlink(&admin, root.join("switch")).expect("worktree exit to metadata"); + std::fs::write( + root.join(".git"), + format!("gitdir: {}\n", entry.join("switch").display()), + ) + .expect("write identity-hop gitdir marker"); + run_git(&root, &["rev-parse", "--absolute-git-dir"]); + + assert_unsafe_metadata_route(repository_authority_for_cwd(&root), &root.join(".git")); +} + +#[cfg(unix)] +#[test] +fn gitdir_symlink_target_cannot_hide_mutable_worktree_pivot_before_parent_traversal() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let primary = fixture.path().join("primary"); + let current = fixture.path().join("current"); + let attacker = fixture.path().join("attacker"); + let external = fixture.path().join("external"); + std::fs::create_dir_all(primary.join("pivot")).expect("create worktree pivot"); + std::fs::create_dir_all(¤t).expect("create current worktree"); + std::fs::create_dir_all(&attacker).expect("create attacker repository"); + std::fs::create_dir_all(&external).expect("create external directory"); + run_git(&primary, &["init", "-q"]); + run_git(&attacker, &["init", "-q"]); + symlink("../primary/pivot/../.git", external.join("entry")) + .expect("external entry with hidden worktree pivot"); + std::fs::write( + current.join(".git"), + format!("gitdir: {}\n", external.join("entry").display()), + ) + .expect("write current gitdir marker"); + assert_eq!( + std::fs::canonicalize(run_git_stdout( + ¤t, + &["rev-parse", "--absolute-git-dir"] + )) + .expect("canonical initial Git dir"), + std::fs::canonicalize(primary.join(".git")).expect("canonical primary Git dir") + ); + + assert_unsafe_metadata_route( + repository_authority_for_cwd(¤t), + ¤t.join(".git"), + ); + + std::fs::remove_dir(primary.join("pivot")).expect("remove ordinary pivot"); + std::fs::create_dir_all(attacker.join("nested")).expect("create attacker nested directory"); + symlink(attacker.join("nested"), primary.join("pivot")).expect("retarget worktree pivot"); + assert_eq!( + std::fs::canonicalize(run_git_stdout( + ¤t, + &["rev-parse", "--absolute-git-dir"] + )) + .expect("canonical retargeted Git dir"), + std::fs::canonicalize(attacker.join(".git")).expect("canonical attacker Git dir") + ); + assert_unsafe_metadata_route( + repository_authority_for_cwd(¤t), + ¤t.join(".git"), + ); +} + +#[cfg(unix)] +#[test] +fn standard_directory_cwd_cannot_hide_mutable_worktree_pivot() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let outer = fixture.path().join("outer"); + let original = fixture.path().join("external-standard-repo"); + let attacker = fixture.path().join("attacker"); + let attacker_repo = attacker.join("external-standard-repo"); + std::fs::create_dir_all(outer.join("pivot")).expect("create worktree pivot"); + std::fs::create_dir_all(&original).expect("create original repository"); + std::fs::create_dir_all(&attacker_repo).expect("create attacker repository"); + run_git(&outer, &["init", "-q"]); + run_git(&original, &["init", "-q"]); + run_git(&attacker_repo, &["init", "-q"]); + + let raw = outer + .join("pivot") + .join("..") + .join("..") + .join("external-standard-repo"); + assert_eq!( + std::fs::canonicalize(run_git_stdout(&raw, &["rev-parse", "--show-toplevel"])) + .expect("canonical initial Git root"), + std::fs::canonicalize(&original).expect("canonical original repository") + ); + let exact_root_route = outer.join("..").join("external-standard-repo"); + repository_authority_for_cwd(&exact_root_route) + .expect("exact worktree root traversal remains valid"); + assert_unsafe_metadata_route(repository_authority_for_cwd(&raw), &raw.join(".git")); + + std::fs::remove_dir(outer.join("pivot")).expect("remove ordinary pivot"); + let attacker_target = attacker.join("deep/nested"); + std::fs::create_dir_all(&attacker_target).expect("create attacker pivot target"); + symlink(&attacker_target, outer.join("pivot")).expect("retarget worktree pivot"); + assert_eq!( + std::fs::canonicalize(run_git_stdout(&raw, &["rev-parse", "--show-toplevel"])) + .expect("canonical retargeted Git root"), + std::fs::canonicalize(&attacker_repo).expect("canonical attacker repository") + ); + assert_unsafe_metadata_route(repository_authority_for_cwd(&raw), &raw.join(".git")); +} + +#[cfg(unix)] +#[test] +fn command_cwd_is_bound_before_worktree_symlink_retarget() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let outer = fixture.path().join("outer"); + let original = fixture.path().join("original"); + let attacker = fixture.path().join("attacker"); + let alias = outer.join("nested"); + for repository in [&outer, &original, &attacker] { + std::fs::create_dir_all(repository).expect("create repository"); + run_git(repository, &["init", "-q"]); + } + symlink(&original, &alias).expect("create worktree-controlled cwd alias"); + + let runner = GitRunner::for_cwd(&alias).expect("runner for cwd alias"); + let mut pinned = runner + .command_for_cwd(&alias) + .expect("command pinned before retarget"); + pinned.args(["rev-parse", "--show-toplevel"]); + + std::fs::remove_file(&alias).expect("remove original cwd alias"); + symlink(&attacker, &alias).expect("retarget cwd alias"); + let error = match runner.command_for_cwd(&alias) { + Ok(_) => panic!("retargeted cwd alias was accepted"), + Err(error) => error, + }; + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!( + error + .to_string() + .contains("no longer resolves within the selected worktree"), + "{error}" + ); + + let output = runner.output(pinned).expect("run pinned cwd command"); + assert!(output.status.success()); + assert_eq!( + std::fs::canonicalize(String::from_utf8_lossy(&output.stdout).trim()) + .expect("canonical pinned Git root"), + std::fs::canonicalize(&original).expect("canonical original repository") + ); +} + +#[cfg(windows)] +#[test] +fn command_cwd_is_bound_before_worktree_junction_retarget() { + let fixture = tempfile::tempdir().expect("fixture"); + let outer = fixture.path().join("outer"); + let original = fixture.path().join("original"); + let attacker = fixture.path().join("attacker"); + let alias = outer.join("nested"); + for repository in [&outer, &original, &attacker] { + std::fs::create_dir_all(repository).expect("create repository"); + run_git(repository, &["init", "-q"]); + } + create_junction(&alias, &original); + + let runner = GitRunner::for_cwd(&alias).expect("runner for cwd junction"); + let mut pinned = runner + .command_for_cwd(&alias) + .expect("command pinned before retarget"); + pinned.args(["rev-parse", "--show-toplevel"]); + + std::fs::remove_dir(&alias).expect("remove original cwd junction"); + create_junction(&alias, &attacker); + let error = match runner.command_for_cwd(&alias) { + Ok(_) => panic!("retargeted cwd junction was accepted"), + Err(error) => error, + }; + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + + let output = runner.output(pinned).expect("run pinned cwd command"); + assert!(output.status.success()); + assert_eq!( + std::fs::canonicalize(String::from_utf8_lossy(&output.stdout).trim()) + .expect("canonical pinned Git root"), + std::fs::canonicalize(&original).expect("canonical original repository") + ); +} + +#[cfg(windows)] +#[test] +fn command_for_cwd_executes_from_a_canonical_windows_path() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git(&root, &["init", "-q"]); + let canonical_root = std::fs::canonicalize(&root).expect("canonical repository"); + + let runner = GitRunner::for_cwd(&root).expect("runner for canonical cwd"); + let mut command = runner + .command_for_cwd(&canonical_root) + .expect("command for canonical cwd"); + command.args(["rev-parse", "--show-toplevel"]); + let output = runner.output(command).expect("run Git from canonical cwd"); + assert!( + output.status.success(), + "Git rejected canonical cwd {}: {}", + canonical_root.display(), + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + std::fs::canonicalize(String::from_utf8_lossy(&output.stdout).trim()) + .expect("canonical Git root"), + canonical_root + ); +} + +#[test] +fn gitdir_terminal_worktree_root_is_never_promoted_to_metadata() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + run_git(fixture.path(), &["init", "--bare", path_text(&root)]); + std::fs::write(root.join(".git"), "gitdir: .\n").expect("write self-root marker"); + assert_eq!( + std::fs::canonicalize(run_git_stdout(&root, &["rev-parse", "--absolute-git-dir"])) + .expect("canonical native self-root Git dir"), + std::fs::canonicalize(&root).expect("canonical worktree root") + ); + assert_unsafe_metadata_route(repository_authority_for_cwd(&root), &root.join(".git")); +} + +#[cfg(unix)] +#[test] +fn commondir_routes_through_worktree_are_denied_before_path_selection() { + use std::os::unix::fs::symlink; + + for identity_entry in [false, true] { + let fixture = tempfile::tempdir().expect("fixture"); + let primary = fixture.path().join("primary"); + let linked = fixture.path().join("linked"); + let entry = fixture.path().join("entry"); + std::fs::create_dir_all(&primary).expect("create primary"); + run_git(&primary, &["init", "-q"]); + run_git( + &primary, + &["worktree", "add", "--orphan", path_text(&linked)], + ); + let admin = PathBuf::from({ + let mut command = Command::new("git"); + isolate_git_command_environment(&mut command); + let output = command + .args(["rev-parse", "--absolute-git-dir"]) + .current_dir(&linked) + .output() + .expect("resolve linked admin"); + assert!(output.status.success()); + String::from_utf8(output.stdout) + .expect("UTF-8 linked admin") + .trim() + .to_string() + }); + symlink(primary.join(".git"), linked.join("switch")).expect("worktree common-dir switch"); + let route = if identity_entry { + symlink(&linked, &entry).expect("external entry into linked worktree"); + entry.join("switch") + } else { + linked.join("switch") + }; + std::fs::write(admin.join("commondir"), format!("{}\n", route.display())) + .expect("rewrite commondir route"); + run_git(&linked, &["rev-parse", "--git-common-dir"]); + + assert_unsafe_metadata_route(repository_authority_for_cwd(&linked), &linked.join(".git")); + } +} + +#[cfg(unix)] +#[test] +fn active_gitdir_route_is_revalidated_before_every_child() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let admin = fixture.path().join("external-admin"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git( + fixture.path(), + &[ + "init", + "--separate-git-dir", + path_text(&admin), + path_text(&root), + ], + ); + let runner = GitRunner::for_cwd(&root).expect("runner for direct external gitdir"); + let mut first = runner.command_for_cwd(&root).expect("first Git command"); + first.args(["rev-parse", "--absolute-git-dir"]); + assert!( + runner + .output(first) + .expect("first Git child") + .status + .success() + ); + + symlink(&admin, root.join("switch")).expect("worktree gitdir switch"); + std::fs::write(root.join(".git"), "gitdir: switch\n").expect("retarget gitdir marker"); + let sentinel = fixture.path().join("git-child-ran"); + let mut second = runner.command(); + second + .args(["config", "--file"]) + .arg(&sentinel) + .args(["probe.value", "ran"]); + let error = runner + .output(second) + .expect_err("retargeted gitdir must block second child"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!( + !sentinel.exists(), + "Git child executed after gitdir retarget" + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn async_child_revalidates_active_gitdir_route_before_spawn() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let admin = fixture.path().join("external-admin"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git( + fixture.path(), + &[ + "init", + "--separate-git-dir", + path_text(&admin), + path_text(&root), + ], + ); + let runner = GitRunner::for_cwd(&root).expect("runner for direct external gitdir"); + let mut first = runner + .async_command_for_cwd(&root) + .expect("first async Git command"); + first.args(["rev-parse", "--absolute-git-dir"]); + assert!( + runner + .output_async(first) + .await + .expect("first async Git child") + .status + .success() + ); + + symlink(&admin, root.join("switch")).expect("worktree gitdir switch"); + std::fs::write(root.join(".git"), "gitdir: switch\n").expect("retarget gitdir marker"); + let sentinel = fixture.path().join("async-git-child-ran"); + let mut second = runner + .async_command_for_cwd(&root) + .expect("second async Git command"); + second + .args(["config", "--file"]) + .arg(&sentinel) + .args(["probe.value", "ran"]); + let error = runner + .output_async(second) + .await + .expect_err("retargeted gitdir must block async child"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert_eq!( + crate::status_guard::map_io_error("status", error), + GitReadError::AuthorityRefused { + operation: "status".to_string(), + } + ); + assert!( + !sentinel.exists(), + "async Git child executed after gitdir retarget" + ); +} + +#[cfg(unix)] +#[test] +fn active_commondir_route_is_revalidated_before_every_child() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let primary = fixture.path().join("primary"); + let linked = fixture.path().join("linked"); + std::fs::create_dir_all(&primary).expect("create primary"); + run_git(&primary, &["init", "-q"]); + run_git( + &primary, + &["worktree", "add", "--orphan", path_text(&linked)], + ); + let runner = GitRunner::for_cwd(&linked).expect("runner for linked worktree"); + let admin = runner + .authority + .active_git_dir() + .expect("active linked metadata") + .to_path_buf(); + let mut first = runner.command_for_cwd(&linked).expect("first Git command"); + first.args(["rev-parse", "--git-common-dir"]); + assert!( + runner + .output(first) + .expect("first Git child") + .status + .success() + ); + + symlink(primary.join(".git"), linked.join("switch")).expect("worktree common-dir switch"); + std::fs::write( + admin.join("commondir"), + format!("{}\n", linked.join("switch").display()), + ) + .expect("retarget commondir marker"); + let sentinel = fixture.path().join("git-child-ran"); + let mut second = runner.command(); + second + .args(["config", "--file"]) + .arg(&sentinel) + .args(["probe.value", "ran"]); + let error = runner + .output(second) + .expect_err("retargeted commondir must block second child"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!( + !sentinel.exists(), + "Git child executed after commondir retarget" + ); +} + +#[cfg(unix)] +#[test] +fn direct_external_separate_git_dir_absolute_and_relative_routes_execute_git() { + for relative in [false, true] { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let admin = fixture.path().join("external-admin"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git( + fixture.path(), + &[ + "init", + "--separate-git-dir", + path_text(&admin), + path_text(&root), + ], + ); + if relative { + std::fs::write(root.join(".git"), "gitdir: ../external-admin\n") + .expect("write relative gitdir marker"); + } + run_git(&root, &["rev-parse", "--absolute-git-dir"]); + let runner = GitRunner::for_cwd(&root).expect("separate-git-dir runner"); + let mut command = runner + .command_for_cwd(&root) + .expect("separate-git-dir command"); + command.args(["rev-parse", "--absolute-git-dir"]); + crate::repository_authority::reset_bounded_marker_read_count(); + assert!( + runner + .output(command) + .expect("separate-git-dir rev-parse") + .status + .success(), + "relative={relative}" + ); + assert_eq!( + crate::repository_authority::bounded_marker_read_count(), + 1, + "separate Git dir should reread only the active .git marker" + ); + } +} + +#[cfg(unix)] +#[test] +fn trusted_external_gitdir_symlink_chain_executes_git() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let external = fixture.path().join("external"); + let admin = external.join("admin"); + let alias_two = external.join("alias-two"); + let alias_one = external.join("alias-one"); + std::fs::create_dir_all(&root).expect("create repository"); + std::fs::create_dir_all(&external).expect("create external directory"); + run_git(&root, &["init", "-q"]); + std::fs::rename(root.join(".git"), &admin).expect("move metadata external"); + symlink(&admin, &alias_two).expect("second trusted alias"); + symlink(&alias_two, &alias_one).expect("first trusted alias"); + std::fs::write( + root.join(".git"), + format!("gitdir: {}\n", alias_one.display()), + ) + .expect("write trusted-chain marker"); + run_git(&root, &["rev-parse", "--absolute-git-dir"]); + + let runner = GitRunner::for_cwd(&root).expect("trusted-chain runner"); + let mut command = runner + .command_for_cwd(&root) + .expect("trusted-chain command"); + command.args(["rev-parse", "--absolute-git-dir"]); + assert!( + runner + .output(command) + .expect("trusted-chain rev-parse") + .status + .success() + ); +} + +#[test] +fn displaced_linked_admin_file_and_directory_routes_execute_git() { + for directory_marker in [false, true] { + for relative_common in [false, true] { + let fixture = tempfile::tempdir().expect("fixture"); + let primary = fixture.path().join("primary"); + let linked = fixture.path().join("linked"); + let displaced = fixture.path().join("external/admin"); + std::fs::create_dir_all(&primary).expect("create primary"); + run_git(&primary, &["init", "-q"]); + run_git( + &primary, + &["worktree", "add", "--orphan", path_text(&linked)], + ); + let original_admin = PathBuf::from(run_git_stdout( + &linked, + &["rev-parse", "--absolute-git-dir"], + )); + let admin = if directory_marker { + std::fs::remove_file(linked.join(".git")).expect("remove linked marker"); + std::fs::rename(&original_admin, linked.join(".git")) + .expect("move admin to directory marker"); + linked.join(".git") + } else { + std::fs::create_dir_all(displaced.parent().expect("displaced parent")) + .expect("create displaced parent"); + std::fs::rename(&original_admin, &displaced).expect("displace linked admin"); + std::fs::write( + linked.join(".git"), + format!("gitdir: {}\n", displaced.display()), + ) + .expect("redirect linked marker"); + displaced.clone() + }; + let common = if relative_common { + "../../primary/.git".to_string() + } else { + primary.join(".git").display().to_string() + }; + std::fs::write(admin.join("commondir"), format!("{common}\n")) + .expect("rewrite displaced commondir"); + run_git(&linked, &["rev-parse", "--git-common-dir"]); + + let runner = GitRunner::for_cwd(&linked).expect("displaced-admin runner"); + let mut command = runner + .command_for_cwd(&linked) + .expect("displaced-admin command"); + command.args(["rev-parse", "--git-common-dir"]); + crate::repository_authority::reset_bounded_marker_read_count(); + assert!( + runner + .output(command) + .expect("displaced-admin rev-parse") + .status + .success(), + "directory_marker={directory_marker} relative_common={relative_common}" + ); + assert_eq!( + crate::repository_authority::bounded_marker_read_count(), + if directory_marker { 1 } else { 2 }, + "displaced active marker read count" + ); + } + } } #[test] @@ -145,22 +1673,460 @@ fn linked_worktree_rejects_git_from_main_and_linked_worktrees() { let fixture = tempfile::tempdir().expect("fixture"); let main = fixture.path().join("main"); let linked = fixture.path().join("linked"); - let git_dir = main.join(".git/worktrees/linked"); let main_bin = main.join("bin"); - std::fs::create_dir_all(&git_dir).expect("linked Git directory"); - std::fs::create_dir_all(&linked).expect("linked worktree"); - std::fs::write( - linked.join(".git"), - format!("gitdir: {}\n", git_dir.display()), - ) - .expect("linked .git file"); + let trusted_bin = fixture.path().join("trusted-bin"); + std::fs::create_dir_all(&main).expect("create main worktree"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&linked)]); write_git_candidate(&main_bin); + write_runnable_git_candidate(&trusted_bin); - let locations = untrusted_git_locations_for_cwd(&linked).expect("untrusted locations"); + let locations = repository_authority_for_cwd(&linked).expect("untrusted locations"); assert!(path_is_untrusted( &main_bin.join(git_executable_name()), &locations )); + let runner = GitRunner::from_search_path( + locations, + &std::env::join_paths([&main_bin, &trusted_bin]).expect("PATH"), + ) + .expect("linked-worktree runner"); + let mut command = runner + .command_for_cwd(&linked) + .expect("linked-worktree command"); + command.args(["rev-parse", "--show-toplevel"]); + crate::repository_authority::reset_bounded_marker_read_count(); + assert!( + runner + .output(command) + .expect("linked-worktree rev-parse") + .status + .success() + ); + assert_eq!( + crate::repository_authority::bounded_marker_read_count(), + 2, + "linked worktree should reread active .git and commondir markers" + ); +} + +#[test] +fn registered_sibling_remains_untrusted_without_its_worktree_marker_or_root() { + let fixture = tempdir_for_native_git(); + let main = fixture.path().join("main"); + let sibling = fixture.path().join("sibling"); + let sibling_bin = sibling.join("bin"); + let trusted_bin = fixture.path().join("trusted-bin"); + std::fs::create_dir_all(&main).expect("create main worktree"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&sibling)]); + write_git_candidate(&sibling_bin); + write_git_candidate(&trusted_bin); + + for state in ["intact", "marker removed", "root recreated"] { + if state == "marker removed" { + std::fs::remove_file(sibling.join(".git")).expect("remove sibling .git marker"); + } else if state == "root recreated" { + std::fs::remove_dir_all(&sibling).expect("remove sibling root"); + write_git_candidate(&sibling_bin); + } + let locations = repository_authority_for_cwd(&main).expect("untrusted locations"); + assert!( + path_is_untrusted(&sibling_bin.join(git_executable_name()), &locations), + "registered sibling Git became trusted in state {state}" + ); + assert_eq!( + selected_git(&locations, &[&sibling_bin, &trusted_bin]), + trusted_bin.join(git_executable_name()), + "registered sibling Git selected in state {state}" + ); + } +} + +#[test] +fn git_generated_relative_registry_route_is_accepted() { + let fixture = tempfile::tempdir().expect("fixture"); + let main = fixture.path().join("main"); + let linked = fixture.path().join("linked"); + std::fs::create_dir_all(&main).expect("create main worktree"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&linked)]); + let admin = PathBuf::from(run_git_stdout( + &linked, + &["rev-parse", "--absolute-git-dir"], + )); + let relative_marker = PathBuf::from("..") + .join("..") + .join("..") + .join("..") + .join("linked") + .join(".git"); + std::fs::write( + admin.join("gitdir"), + format!("{}\n", relative_marker.display()), + ) + .expect("write Git-style relative registry marker"); + + let authority = repository_authority_for_cwd(&main).expect("relative registry authority"); + assert!( + authority + .contains_root(&std::fs::canonicalize(&linked).expect("canonical linked worktree")) + ); + GitRunner::for_cwd(&linked).expect("relative linked-worktree runner"); +} + +#[test] +fn registered_worktree_route_rejects_canceled_worktree_descendant() { + let fixture = tempfile::tempdir().expect("fixture"); + let main = fixture.path().join("main"); + let linked = fixture.path().join("linked"); + std::fs::create_dir_all(main.join("pivot")).expect("create worktree pivot"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&linked)]); + let admin = PathBuf::from(run_git_stdout( + &linked, + &["rev-parse", "--absolute-git-dir"], + )); + let registry_marker = admin.join("gitdir"); + let raw_marker = main.join("pivot").join("..").join("..").join("linked/.git"); + std::fs::write(®istry_marker, format!("{}\n", raw_marker.display())) + .expect("write registry route through worktree pivot"); + + assert_unsafe_registry_route(repository_authority_for_cwd(&main), ®istry_marker); + let error = GitRunner::for_cwd_io(&main).expect_err("unsafe registry route"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); +} + +#[test] +fn registered_route_rejects_root_that_is_also_outer_worktree_descendant() { + let fixture = tempfile::tempdir().expect("fixture"); + let route = overlapping_registered_route(fixture.path()); + + assert_eq!( + std::fs::canonicalize(&route.raw_marker).expect("canonical linked marker"), + std::fs::canonicalize(route.linked.join(".git")).expect("canonical expected marker") + ); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); +} + +#[test] +fn registered_route_allows_parent_cancellation_inside_protected_metadata() { + let fixture = tempfile::tempdir().expect("fixture"); + let route = metadata_alias_registered_route(fixture.path(), "main", "main"); + let protected_marker = route.main.join(".git").join("..").join("linked/.git"); + std::fs::write( + &route.registry_marker, + format!("{}\n", protected_marker.display()), + ) + .expect("write protected-metadata registry route"); + + assert_eq!( + std::fs::canonicalize(&protected_marker).expect("canonical protected route"), + std::fs::canonicalize(route.linked.join(".git")).expect("canonical linked marker") + ); + repository_authority_for_cwd(&route.main).expect("protected-metadata registry authority"); + GitRunner::for_cwd(&route.linked).expect("linked runner through protected metadata route"); +} + +#[cfg(unix)] +#[test] +fn metadata_alias_registered_route_is_rejected_before_and_after_symlink_retarget() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let route = metadata_alias_registered_route(fixture.path(), "main", "main"); + symlink(route.main.join(".git"), &route.pivot).expect("alias pivot to protected metadata"); + + assert_eq!( + std::fs::canonicalize(&route.raw_marker).expect("canonical metadata-alias route"), + std::fs::canonicalize(route.linked.join(".git")).expect("canonical linked marker") + ); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); + + std::fs::remove_file(&route.pivot).expect("remove metadata alias"); + let attacker_target = fixture.path().join("attacker/deep"); + let attacker_linked = fixture.path().join("attacker/linked"); + std::fs::create_dir_all(&attacker_target).expect("create attacker pivot target"); + std::fs::create_dir_all(&attacker_linked).expect("create attacker linked root"); + std::fs::write( + attacker_linked.join(".git"), + format!("gitdir: {}\n", route.linked_admin.display()), + ) + .expect("write attacker backlink"); + symlink(&attacker_target, &route.pivot).expect("retarget metadata alias"); + + assert_eq!( + std::fs::canonicalize(&route.raw_marker).expect("canonical retargeted route"), + std::fs::canonicalize(attacker_linked.join(".git")).expect("canonical attacker marker") + ); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); +} + +#[cfg(windows)] +#[test] +fn registered_route_rejects_unicode_case_junction_retarget() { + let fixture = tempfile::tempdir().expect("fixture"); + let route = metadata_alias_registered_route(fixture.path(), "Répo", "RÉPO"); + let raw_marker = fixture.path().join("RÉPO").join("pivot").join(".git"); + std::fs::write( + &route.registry_marker, + format!("{}\n", raw_marker.display()), + ) + .expect("write direct junction registry route"); + create_junction(&route.pivot, &route.linked); + + assert_eq!( + std::fs::canonicalize(&raw_marker).expect("canonical Unicode junction route"), + std::fs::canonicalize(route.linked.join(".git")).expect("canonical linked marker") + ); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); + + std::fs::remove_dir(&route.pivot).expect("remove metadata junction"); + let attacker_linked = fixture.path().join("attacker/linked"); + std::fs::create_dir_all(&attacker_linked).expect("create attacker linked root"); + std::fs::write( + attacker_linked.join(".git"), + format!("gitdir: {}\n", route.linked_admin.display()), + ) + .expect("write attacker backlink"); + create_junction(&route.pivot, &attacker_linked); + + assert_eq!( + std::fs::canonicalize(&raw_marker).expect("canonical retargeted route"), + std::fs::canonicalize(attacker_linked.join(".git")).expect("canonical attacker marker") + ); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); +} + +#[cfg(unix)] +#[test] +fn overlapping_registered_route_remains_rejected_after_symlink_retarget() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let route = overlapping_registered_route(fixture.path()); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); + + std::fs::remove_dir_all(&route.nested).expect("remove nested worktree"); + let attacker_parent = fixture.path().join("attacker/deep"); + let attacker_nested = attacker_parent.join("nested"); + let attacker_linked = attacker_parent.join("linked"); + std::fs::create_dir_all(&attacker_nested).expect("create attacker nested root"); + std::fs::create_dir_all(&attacker_linked).expect("create attacker linked root"); + std::fs::write( + attacker_nested.join(".git"), + format!("gitdir: {}\n", route.nested_admin.display()), + ) + .expect("write attacker nested backlink"); + std::fs::write( + attacker_linked.join(".git"), + format!("gitdir: {}\n", route.linked_admin.display()), + ) + .expect("write attacker linked backlink"); + symlink(&attacker_nested, &route.nested).expect("retarget nested worktree root"); + + assert_eq!( + std::fs::canonicalize(&route.raw_marker).expect("canonical retargeted marker"), + std::fs::canonicalize(attacker_linked.join(".git")).expect("canonical attacker marker") + ); + let nested_registry_marker = route.nested_admin.join("gitdir"); + assert_unsafe_registry_route_at_one_of( + repository_authority_for_cwd(&route.main), + &[&route.registry_marker, &nested_registry_marker], + ); +} + +#[cfg(windows)] +#[test] +fn overlapping_registered_route_remains_rejected_after_junction_retarget() { + let fixture = tempfile::tempdir().expect("fixture"); + let route = overlapping_registered_route(fixture.path()); + let pivot = route.nested.join("pivot"); + let raw_marker = pivot.join("linked/.git"); + std::fs::write( + &route.registry_marker, + format!("{}\n", raw_marker.display()), + ) + .expect("write direct overlapping registry route"); + create_junction(&pivot, &route.main); + + assert_eq!( + std::fs::canonicalize(&raw_marker).expect("canonical overlapping junction route"), + std::fs::canonicalize(route.linked.join(".git")).expect("canonical linked marker") + ); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); + + std::fs::remove_dir(&pivot).expect("remove overlapping junction"); + let attacker_parent = fixture.path().join("attacker/deep"); + let attacker_linked = attacker_parent.join("linked"); + std::fs::create_dir_all(&attacker_linked).expect("create attacker linked root"); + std::fs::write( + attacker_linked.join(".git"), + format!("gitdir: {}\n", route.linked_admin.display()), + ) + .expect("write attacker linked backlink"); + create_junction(&pivot, &attacker_parent); + + assert_eq!( + std::fs::canonicalize(&raw_marker).expect("canonical retargeted marker"), + std::fs::canonicalize(attacker_linked.join(".git")).expect("canonical attacker marker") + ); + assert_unsafe_registry_route( + repository_authority_for_cwd(&route.main), + &route.registry_marker, + ); +} + +#[cfg(unix)] +#[test] +fn registered_worktree_route_remains_rejected_after_pivot_retarget() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let main = fixture.path().join("main"); + let linked = fixture.path().join("linked"); + let attacker = fixture.path().join("attacker"); + std::fs::create_dir_all(main.join("pivot")).expect("create worktree pivot"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&linked)]); + let admin = PathBuf::from(run_git_stdout( + &linked, + &["rev-parse", "--absolute-git-dir"], + )); + let registry_marker = admin.join("gitdir"); + let raw_marker = main.join("pivot").join("..").join("..").join("linked/.git"); + std::fs::write(®istry_marker, format!("{}\n", raw_marker.display())) + .expect("write registry route through worktree pivot"); + assert_unsafe_registry_route(repository_authority_for_cwd(&main), ®istry_marker); + + std::fs::remove_dir(main.join("pivot")).expect("remove ordinary pivot"); + let attacker_target = attacker.join("deep/nested"); + let attacker_worktree = attacker.join("linked"); + std::fs::create_dir_all(&attacker_target).expect("create attacker pivot target"); + std::fs::create_dir_all(&attacker_worktree).expect("create attacker worktree"); + std::fs::write( + attacker_worktree.join(".git"), + format!("gitdir: {}\n", admin.display()), + ) + .expect("write attacker backlink"); + symlink(&attacker_target, main.join("pivot")).expect("retarget worktree pivot"); + + assert_unsafe_registry_route(repository_authority_for_cwd(&main), ®istry_marker); + assert!(matches!( + GitRunner::for_cwd(&main), + Err(GitReadError::UnsafeRepositoryMetadata { .. }) + )); +} + +#[test] +fn registered_worktree_backlink_mismatch_is_unsafe() { + let fixture = tempfile::tempdir().expect("fixture"); + let main = fixture.path().join("main"); + let linked = fixture.path().join("linked"); + std::fs::create_dir_all(&main).expect("create main worktree"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&linked)]); + let marker = linked.join(".git"); + std::fs::write( + &marker, + format!("gitdir: {}\n", main.join(".git").display()), + ) + .expect("rewrite linked-worktree backlink"); + + match repository_authority_for_cwd(&main) { + Err(GitReadError::UnsafeRepositoryMetadata { path, reason }) => { + assert_same_affected_path(&path, &marker); + assert_eq!(reason, "Git worktree registry backlink mismatch"); + } + other => panic!("expected unsafe registry backlink, got {other:?}"), + } + let error = GitRunner::for_cwd_io(&main).expect_err("mismatched worktree backlink"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("backlink mismatch"), "{error}"); + assert!(!error.to_string().contains("PATH"), "{error}"); +} + +#[test] +fn unsupported_worktree_registry_entry_is_invalid_with_entry_path() { + let fixture = tempfile::tempdir().expect("fixture"); + let main = fixture.path().join("main"); + std::fs::create_dir_all(&main).expect("create main worktree"); + run_git(&main, &["init", "-q"]); + let registry = main.join(".git/worktrees"); + std::fs::create_dir_all(®istry).expect("create worktree registry"); + let entry = registry.join("unsupported-entry"); + std::fs::write(&entry, "not a registry directory\n").expect("write invalid registry entry"); + + match repository_authority_for_cwd(&main) { + Err(GitReadError::InvalidRepositoryMetadata { path, reason }) => { + assert_same_affected_path(&path, &entry); + assert_eq!(reason, "unsupported Git worktree registry entry"); + } + other => panic!("expected invalid registry entry, got {other:?}"), + } + let error = GitRunner::for_cwd_io(&main).expect_err("unsupported registry entry"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!( + error + .to_string() + .contains("unsupported Git worktree registry entry"), + "{error}" + ); + assert!(!error.to_string().contains("PATH"), "{error}"); +} + +#[test] +fn per_child_active_route_revalidation_is_independent_of_registered_sibling_count() { + let fixture = tempfile::tempdir().expect("fixture"); + let main = fixture.path().join("main"); + let active = fixture.path().join("active"); + std::fs::create_dir_all(&main).expect("create primary"); + run_git(&main, &["init", "-q"]); + run_git(&main, &["worktree", "add", "--orphan", path_text(&active)]); + for index in 0..12 { + let sibling = fixture.path().join(format!("sibling-{index}")); + run_git(&main, &["worktree", "add", "--orphan", path_text(&sibling)]); + } + + let runner = GitRunner::for_cwd(&active).expect("runner with many registered siblings"); + crate::repository_authority::reset_bounded_marker_read_count(); + let mut command = runner + .command_for_cwd(&active) + .expect("active worktree command"); + command.args(["rev-parse", "--git-common-dir"]); + assert!( + runner + .output(command) + .expect("active worktree rev-parse") + .status + .success() + ); + assert_eq!( + crate::repository_authority::bounded_marker_read_count(), + 2, + "per-child validation must read only active .git and commondir markers" + ); } #[test] @@ -176,7 +2142,7 @@ fn nested_repository_rejects_git_from_enclosing_repository() { write_git_candidate(&outer_bin); write_git_candidate(&trusted_bin); - let locations = untrusted_git_locations_for_cwd(&nested).expect("untrusted locations"); + let locations = repository_authority_for_cwd(&nested).expect("untrusted locations"); assert!( path_is_untrusted(&outer_bin.join(git_executable_name()), &locations), "Git from an enclosing repository must remain repository-controlled" @@ -205,7 +2171,7 @@ fn symlinked_nested_repository_rejects_git_from_lexical_enclosing_repository() { write_git_candidate(&outer_bin); write_git_candidate(&trusted_bin); - let locations = untrusted_git_locations_for_cwd(&lexical_nested).expect("untrusted locations"); + let locations = repository_authority_for_cwd(&lexical_nested).expect("untrusted locations"); assert!( path_is_untrusted(&outer_bin.join(git_executable_name()), &locations), "Git from the lexical enclosing repository must remain repository-controlled" @@ -232,7 +2198,7 @@ fn nested_repository_rejects_git_from_enclosing_repository_main_worktree() { write_git_candidate(&main_bin); write_git_candidate(&trusted_bin); - let locations = untrusted_git_locations_for_cwd(&nested).expect("untrusted locations"); + let locations = repository_authority_for_cwd(&nested).expect("untrusted locations"); assert!( path_is_untrusted(&main_bin.join(git_executable_name()), &locations), "all worktrees of an enclosing repository must remain repository-controlled" @@ -274,9 +2240,9 @@ fn submodule_rejects_git_from_enclosing_superproject() { ], ); write_git_candidate(&outer_bin); - write_git_candidate(&trusted_bin); + write_runnable_git_candidate(&trusted_bin); - let locations = untrusted_git_locations_for_cwd(&submodule).expect("untrusted locations"); + let locations = repository_authority_for_cwd(&submodule).expect("untrusted locations"); assert!( path_is_untrusted(&outer_bin.join(git_executable_name()), &locations), "Git from a superproject must remain repository-controlled" @@ -285,6 +2251,28 @@ fn submodule_rejects_git_from_enclosing_superproject() { selected_git(&locations, &[&outer_bin, &trusted_bin]), trusted_bin.join(git_executable_name()) ); + let runner = GitRunner::from_search_path( + locations, + &std::env::join_paths([&outer_bin, &trusted_bin]).expect("PATH"), + ) + .expect("submodule runner"); + let mut command = runner + .command_for_cwd(&submodule) + .expect("submodule command"); + command.args(["rev-parse", "--show-toplevel"]); + crate::repository_authority::reset_bounded_marker_read_count(); + assert!( + runner + .output(command) + .expect("submodule rev-parse") + .status + .success() + ); + assert_eq!( + crate::repository_authority::bounded_marker_read_count(), + 1, + "submodule should reread only its active .git marker" + ); } #[test] @@ -305,13 +2293,62 @@ fn bare_backed_linked_worktree_allows_external_git_in_sibling_directory() { path_text(&linked), ], ); - write_git_candidate(&trusted_bin); + write_runnable_git_candidate(&trusted_bin); - let locations = untrusted_git_locations_for_cwd(&linked).expect("untrusted locations"); + let locations = repository_authority_for_cwd(&linked).expect("untrusted locations"); assert_eq!( selected_git(&locations, &[&trusted_bin]), trusted_bin.join(git_executable_name()) ); + let runner = GitRunner::from_search_path( + locations, + &std::env::join_paths([&trusted_bin]).expect("PATH"), + ) + .expect("bare-backed runner"); + let mut command = runner + .command_for_cwd(&linked) + .expect("bare-backed command"); + command.args(["rev-parse", "--git-common-dir"]); + crate::repository_authority::reset_bounded_marker_read_count(); + assert!( + runner + .output(command) + .expect("bare-backed rev-parse") + .status + .success() + ); + assert_eq!( + crate::repository_authority::bounded_marker_read_count(), + 2, + "bare-backed linked worktree should reread two active markers" + ); +} + +#[test] +fn linked_common_dir_nested_in_another_repo_is_rejected_before_path_selection() { + let fixture = tempfile::tempdir().expect("fixture"); + let outer = fixture.path().join("outer"); + let common = outer.join("nested-common.git"); + let linked = fixture.path().join("linked"); + run_git(fixture.path(), &["init", path_text(&outer)]); + std::fs::write(outer.join("seed.txt"), "seed\n").expect("write outer seed"); + run_git(&outer, &["add", "seed.txt"]); + commit_all(&outer, "outer seed"); + run_git(&outer, &["clone", "--bare", ".", path_text(&common)]); + run_git( + fixture.path(), + &[ + "--git-dir", + path_text(&common), + "worktree", + "add", + "-b", + "nested-common-linked", + path_text(&linked), + "HEAD", + ], + ); + assert_unsafe_metadata_route(repository_authority_for_cwd(&linked), &linked.join(".git")); } #[test] @@ -344,13 +2381,207 @@ fn separate_dot_git_dir_rejects_main_candidate_and_allows_unrelated_repo_candida write_git_candidate(&malformed_bin); std::fs::write(malformed.join(".git"), "not a gitdir").expect("malformed marker"); - let locations = untrusted_git_locations_for_cwd(&linked).expect("untrusted locations"); + let locations = repository_authority_for_cwd(&linked).expect("untrusted locations"); assert_eq!( selected_git(&locations, &[&main_bin, &malformed_bin, &unrelated_bin]), unrelated_bin.join(git_executable_name()) ); } +#[cfg(unix)] +#[test] +fn unproven_separate_primary_is_denied_before_any_path_git_executes() { + let temp_base = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp dir"); + for authority_config in ["non-bare", "included false", "bare 08", "bare overflow"] { + let fixture = tempfile::tempdir_in(&temp_base).expect("fixture"); + let primary = fixture.path().join("primary"); + let common = fixture.path().join("separate-common"); + let linked = fixture.path().join("linked"); + let primary_bin = primary.join("bin"); + let trusted_bin = fixture.path().join("trusted-bin"); + let executed = fixture.path().join("attacker-git-ran"); + std::fs::create_dir_all(&primary).expect("create primary"); + run_git( + fixture.path(), + &[ + "init", + "--separate-git-dir", + path_text(&common), + path_text(&primary), + ], + ); + std::fs::write(primary.join("seed"), "seed\n").expect("write seed"); + run_git(&primary, &["add", "seed"]); + commit_all(&primary, "seed"); + run_git( + &primary, + &[ + "worktree", + "add", + "-b", + "unproven-primary-linked", + path_text(&linked), + ], + ); + if authority_config == "included false" { + let included = primary.join("bare-override.config"); + std::fs::write(&included, "[core]\n\tbare = false\n") + .expect("write included bare override"); + let mut config = + std::fs::read_to_string(common.join("config")).expect("read common config"); + config.push_str(&format!( + "\n[core]\n\tbare = true\n[include]\n\tpath = {}\n", + included.display() + )); + std::fs::write(common.join("config"), config).expect("write ambiguous bare config"); + } else if let Some(value) = match authority_config { + "bare 08" => Some("08"), + "bare overflow" => Some("2147483648"), + _ => None, + } { + let mut config = + std::fs::read_to_string(common.join("config")).expect("read common config"); + config.push_str(&format!("\n[core]\n\tbare = {value}\n")); + std::fs::write(common.join("config"), config).expect("write malformed bare config"); + } + write_git_candidate(&trusted_bin); + std::fs::create_dir_all(&primary_bin).expect("create primary bin"); + std::fs::copy("/usr/bin/touch", primary_bin.join("git")) + .expect("copy attacker native executable"); + std::fs::remove_file(primary.join(".git")).expect("remove primary reverse marker"); + + let locations = repository_authority_for_cwd(&linked).expect("untrusted locations"); + let path = std::env::join_paths([&primary_bin, &trusted_bin]).expect("PATH"); + let error = match GitRunner::from_search_path(locations, &path) { + Ok(runner) => { + let mut command = runner.command(); + command.arg(&executed); + let _ = runner.output(command); + panic!("unproven separate primary selected a PATH Git"); + } + Err(error) => error, + }; + assert!(!executed.exists(), "attacker Git executed"); + assert!(matches!( + error, + GitReadError::UnprovenPrimaryAuthority { .. } + )); + } +} + +#[cfg(unix)] +#[test] +fn nested_repo_inside_linked_outer_denies_unproven_outer_primary_before_path_git() { + let temp_base = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp dir"); + let fixture = tempfile::tempdir_in(temp_base).expect("fixture"); + let primary = fixture.path().join("primary"); + let common = fixture.path().join("separate-common"); + let outer = fixture.path().join("outer"); + let nested = outer.join("nested"); + let primary_bin = primary.join("bin"); + let trusted_bin = fixture.path().join("trusted-bin"); + let executed = fixture.path().join("attacker-git-ran"); + std::fs::create_dir_all(&primary).expect("create primary"); + run_git( + fixture.path(), + &[ + "init", + "--separate-git-dir", + path_text(&common), + path_text(&primary), + ], + ); + std::fs::write(primary.join("seed"), "seed\n").expect("write seed"); + run_git(&primary, &["add", "seed"]); + commit_all(&primary, "seed"); + run_git( + &primary, + &[ + "worktree", + "add", + "-b", + "nested-unproven-outer", + path_text(&outer), + ], + ); + std::fs::create_dir_all(&nested).expect("create nested repository"); + run_git(&nested, &["init", "-q"]); + write_git_candidate(&trusted_bin); + std::fs::create_dir_all(&primary_bin).expect("create primary bin"); + std::fs::copy("/usr/bin/touch", primary_bin.join("git")) + .expect("copy attacker native executable"); + std::fs::remove_file(primary.join(".git")).expect("remove primary reverse marker"); + + let locations = repository_authority_for_cwd(&nested).expect("untrusted locations"); + let path = std::env::join_paths([&primary_bin, &trusted_bin]).expect("PATH"); + let error = match GitRunner::from_search_path(locations, &path) { + Ok(runner) => { + let mut command = runner.command(); + command.arg(&executed); + let _ = runner.output(command); + panic!("unproven enclosing linked repository selected a PATH Git"); + } + Err(error) => error, + }; + assert!(!executed.exists(), "attacker Git executed"); + assert!(matches!( + error, + GitReadError::UnprovenPrimaryAuthority { .. } + )); +} + +#[test] +fn explicit_absolute_core_worktree_is_recorded_before_path_selection() { + let fixture = tempdir_for_native_git(); + let primary = fixture.path().join("primary"); + let common = fixture.path().join("separate-common"); + let linked = fixture.path().join("linked"); + let primary_bin = primary.join("bin"); + let trusted_bin = fixture.path().join("trusted-bin"); + std::fs::create_dir_all(&primary).expect("create primary"); + run_git( + fixture.path(), + &[ + "init", + "--separate-git-dir", + path_text(&common), + path_text(&primary), + ], + ); + std::fs::write(primary.join("seed"), "seed\n").expect("write seed"); + run_git(&primary, &["add", "seed"]); + commit_all(&primary, "seed"); + run_git( + &primary, + &[ + "worktree", + "add", + "-b", + "explicit-core-worktree-linked", + path_text(&linked), + ], + ); + let mut config = std::fs::read_to_string(common.join("config")).expect("read common config"); + config.push_str(&format!( + "\n[core]\n\tworktree = {}\n", + git_config_path(&primary) + )); + std::fs::write(common.join("config"), config).expect("write explicit core.worktree"); + std::fs::remove_file(primary.join(".git")).expect("remove primary reverse marker"); + write_git_candidate(&primary_bin); + write_git_candidate(&trusted_bin); + + let locations = repository_authority_for_cwd(&linked).expect("untrusted locations"); + assert!( + locations.contains_root(&primary), + "explicit core.worktree was not recorded" + ); + assert_eq!( + selected_git(&locations, &[&primary_bin, &trusted_bin]), + trusted_bin.join(git_executable_name()) + ); +} + #[test] fn resolver_rejects_parent_traversal_spelled_through_repository() { let fixture = tempfile::tempdir().expect("fixture"); @@ -360,7 +2591,7 @@ fn resolver_rejects_parent_traversal_spelled_through_repository() { write_git_candidate(&trusted_bin); let locations = locations_for_root(&repo); - for root in &locations.roots { + for root in locations.roots() { // Append without PathBuf::push: it resolves `..` when `root` has a // verbatim Windows prefix, before the resolver can inspect the PATH // spelling. @@ -373,22 +2604,9 @@ fn resolver_rejects_parent_traversal_spelled_through_repository() { "raw PATH traversal was not rejected from {root:?}" ); - #[cfg(windows)] - if matches!( - root.components().next(), - Some(Component::Prefix(prefix)) if prefix.kind().is_verbatim() - ) { - assert_eq!( - split_paths[0].join(git_executable_name()), - std::fs::canonicalize(&trusted_bin) - .expect("canonical trusted bin") - .join(git_executable_name()) - ); - } - assert!( matches!( - GitRunner::from_search_path(&locations, &search_path), + select_git_executable(&locations, &search_path), Err(GitReadError::NoTrustedGit) ), "resolver accepted parent traversal from {root:?}" @@ -453,8 +2671,8 @@ fn resolver_rejects_unicode_case_alias_through_repository_junction() { let locations = locations_for_root(&repo); assert!( - !path_is_untrusted(&verbatim_case_alias, &locations), - "fixture must exercise the Unicode alias before canonical ancestry" + path_is_untrusted(&verbatim_case_alias, &locations), + "route observation missed the Unicode repository alias" ); assert!(search_directory_is_untrusted( &verbatim_case_alias, @@ -462,7 +2680,7 @@ fn resolver_rejects_unicode_case_alias_through_repository_junction() { )); let search_path = std::env::join_paths([verbatim_case_alias]).expect("PATH"); assert!(matches!( - GitRunner::from_search_path(&locations, &search_path), + GitRunner::from_search_path(locations, &search_path), Err(GitReadError::NoTrustedGit) )); } @@ -488,10 +2706,10 @@ fn resolver_fails_closed_for_unsupported_windows_device_namespaces() { #[cfg(windows)] #[test] fn resolver_selects_native_git_exe_only() { - assert!(paths_equal( - Path::new(r"C:\Repo\.git"), - Path::new(r"c:\repo\.GIT") - )); + let mixed_case = Path::new(r"C:\Repo\.git"); + let lower_case = Path::new(r"c:\repo\.GIT"); + assert!(crate::git_config::path_is_within(mixed_case, lower_case)); + assert!(crate::git_config::path_is_within(lower_case, mixed_case)); let fixture = tempfile::tempdir().expect("fixture"); let repo = fixture.path().join("repo"); let scripts = fixture.path().join("scripts"); @@ -500,9 +2718,13 @@ fn resolver_selects_native_git_exe_only() { std::fs::create_dir_all(&scripts).expect("scripts"); std::fs::create_dir_all(&native).expect("native"); std::fs::write(scripts.join("git.cmd"), "@exit /b 0\r\n").expect("script"); - std::fs::write(native.join("git.exe"), b"MZ").expect("native executable fixture"); + std::fs::copy(native_git_fixture(), native.join("git.exe")).expect("native executable fixture"); let locations = locations_for_root(&repo); let path = std::env::join_paths([scripts, native.clone()]).expect("PATH"); - let runner = GitRunner::from_search_path(&locations, &path).expect("native Git"); - assert_eq!(runner.executable, native.join("git.exe")); + let runner = GitRunner::from_search_path(locations, &path).expect("native Git"); + assert_eq!(runner.argv0, native.join("git.exe")); + assert_eq!( + runner.executable, + std::fs::canonicalize(native.join("git.exe")).expect("canonical native Git") + ); } diff --git a/codex-rs/git-utils/src/git_config.rs b/codex-rs/git-utils/src/git_config.rs index a08bdc8d31..b446e532e1 100644 --- a/codex-rs/git-utils/src/git_config.rs +++ b/codex-rs/git-utils/src/git_config.rs @@ -3,8 +3,12 @@ use std::io; use std::path::Component; use std::path::Path; +use crate::git_command::GitRunner; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum GitConfigScope { + Unknown, System, Global, Local, @@ -15,16 +19,30 @@ pub(crate) enum GitConfigScope { #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct GitConfigEntry { pub(crate) scope: GitConfigScope, - pub(crate) origin: String, + pub(crate) origin: GitConfigOrigin, pub(crate) key: String, pub(crate) value: String, } +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum GitConfigOrigin { + CommandLine, + File(std::path::PathBuf), +} + +#[cfg(test)] pub(crate) fn parse_effective_config( output: &[u8], ) -> io::Result> { + Ok(parse_config_entries(output)? + .into_iter() + .map(|entry| (entry.key.clone(), entry)) + .collect()) +} + +pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result> { if output.is_empty() { - return Ok(BTreeMap::new()); + return Ok(Vec::new()); } let Some(body) = output.strip_suffix(&[0]) else { return Err(invalid_config_output("unterminated Git config output")); @@ -34,13 +52,10 @@ pub(crate) fn parse_effective_config( return Err(invalid_config_output("incomplete Git config record")); } - let mut effective = BTreeMap::new(); + let mut entries = Vec::new(); for record in fields.chunks_exact(3) { let scope = parse_scope(record[0])?; - let origin = parse_utf8_field(record[1], "config origin")?; - if origin.is_empty() { - return Err(invalid_config_output("empty Git config origin")); - } + let origin = parse_config_origin(record[1])?; let entry = parse_utf8_field(record[2], "config key/value")?; let Some((key, value)) = entry.split_once('\n') else { return Err(invalid_config_output( @@ -52,24 +67,32 @@ pub(crate) fn parse_effective_config( } let entry = GitConfigEntry { scope, - origin: origin.to_string(), + origin, key: key.to_string(), value: value.to_string(), }; - effective.insert(key.to_string(), entry); + entries.push(entry); } - Ok(effective) + Ok(entries) } /// Parse the `--show-origin` form used by Git versions that predate /// `config --show-scope`. The record order still reflects effective config /// precedence, which is what helper selection relies on. Scope is retained as /// best-effort metadata only; command-line entries remain distinguishable. +#[cfg(test)] pub(crate) fn parse_effective_config_with_origins( output: &[u8], ) -> io::Result> { + Ok(parse_config_entries_with_origins(output)? + .into_iter() + .map(|entry| (entry.key.clone(), entry)) + .collect()) +} + +pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result> { if output.is_empty() { - return Ok(BTreeMap::new()); + return Ok(Vec::new()); } let Some(body) = output.strip_suffix(&[0]) else { return Err(invalid_config_output("unterminated Git config output")); @@ -79,12 +102,9 @@ pub(crate) fn parse_effective_config_with_origins( return Err(invalid_config_output("incomplete Git config record")); } - let mut effective = BTreeMap::new(); + let mut entries = Vec::new(); for record in fields.chunks_exact(2) { - let origin = parse_utf8_field(record[0], "config origin")?; - if origin.is_empty() { - return Err(invalid_config_output("empty Git config origin")); - } + let origin = parse_config_origin(record[0])?; let entry = parse_utf8_field(record[1], "config key/value")?; let Some((key, value)) = entry.split_once('\n') else { return Err(invalid_config_output( @@ -94,24 +114,284 @@ pub(crate) fn parse_effective_config_with_origins( if key.is_empty() { return Err(invalid_config_output("empty Git config key")); } - let scope = if origin == "command line:" { + let scope = if origin == GitConfigOrigin::CommandLine { GitConfigScope::Command } else { // Older Git does not expose the scope. Selection depends on the // emitted precedence order, not on this informational label. GitConfigScope::Local }; - effective.insert( - key.to_string(), - GitConfigEntry { - scope, - origin: origin.to_string(), - key: key.to_string(), - value: value.to_string(), - }, - ); + entries.push(GitConfigEntry { + scope, + origin, + key: key.to_string(), + value: value.to_string(), + }); } - Ok(effective) + Ok(entries) +} + +pub(crate) fn read_effective_config_entries_with_fallback( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + probe: &str, +) -> io::Result> { + read_config_entries_with_fallback( + git, + cwd, + git_config_args, + pattern, + probe, + /*follow_includes*/ true, + /*config_file*/ None, + ) +} + +pub(crate) fn read_config_entries_without_includes( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + probe: &str, + config_file: Option<&Path>, +) -> io::Result> { + read_config_entries_with_fallback( + git, + cwd, + git_config_args, + pattern, + probe, + /*follow_includes*/ false, + config_file, + ) +} + +pub(crate) async fn read_config_entries_without_includes_async( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + probe: &str, + config_file: Option<&Path>, +) -> io::Result> { + read_config_entries_with_fallback_async( + git, + cwd, + git_config_args, + pattern, + probe, + /*follow_includes*/ false, + config_file, + ) + .await +} + +fn read_config_entries_with_fallback( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + probe: &str, + follow_includes: bool, + config_file: Option<&Path>, +) -> io::Result> { + let scoped = run_effective_config_query( + git, + cwd, + git_config_args, + pattern, + /*show_scope*/ true, + follow_includes, + config_file, + )?; + if scoped + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + return parse_config_entries(&scoped.stdout); + } + + let legacy = run_effective_config_query( + git, + cwd, + git_config_args, + pattern, + /*show_scope*/ false, + follow_includes, + config_file, + )?; + if !legacy + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + return Err(io::Error::other(format!( + "git {probe} config probe failed with status {}: {}", + legacy.status, + String::from_utf8_lossy(&legacy.stderr).trim() + ))); + } + parse_config_entries_with_origins(&legacy.stdout) +} + +async fn read_config_entries_with_fallback_async( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + probe: &str, + follow_includes: bool, + config_file: Option<&Path>, +) -> io::Result> { + let scoped = run_effective_config_query_async( + git, + cwd, + git_config_args, + pattern, + /*show_scope*/ true, + follow_includes, + config_file, + ) + .await?; + if scoped + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + return parse_config_entries(&scoped.stdout); + } + + let legacy = run_effective_config_query_async( + git, + cwd, + git_config_args, + pattern, + /*show_scope*/ false, + follow_includes, + config_file, + ) + .await?; + if !legacy + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + return Err(io::Error::other(format!( + "git {probe} config probe failed with status {}: {}", + legacy.status, + String::from_utf8_lossy(&legacy.stderr).trim() + ))); + } + parse_config_entries_with_origins(&legacy.stdout) +} + +pub(crate) fn read_effective_config_with_fallback( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + probe: &str, +) -> io::Result> { + Ok( + read_effective_config_entries_with_fallback(git, cwd, git_config_args, pattern, probe)? + .into_iter() + .map(|entry| (entry.key.clone(), entry)) + .collect(), + ) +} + +pub(crate) async fn read_effective_config_with_fallback_async( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + probe: &str, +) -> io::Result> { + Ok(read_config_entries_with_fallback_async( + git, + cwd, + git_config_args, + pattern, + probe, + /*follow_includes*/ true, + /*config_file*/ None, + ) + .await? + .into_iter() + .map(|entry| (entry.key.clone(), entry)) + .collect()) +} + +fn run_effective_config_query( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + show_scope: bool, + follow_includes: bool, + config_file: Option<&Path>, +) -> io::Result { + let mut command = git.command_for_cwd(cwd)?; + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(git_config_args) + .arg("config"); + if let Some(config_file) = config_file { + command.arg("--file").arg(config_file); + } + command.arg("--null"); + if show_scope { + command.arg("--show-scope"); + } + command.args([ + "--show-origin", + if follow_includes { + "--includes" + } else { + "--no-includes" + }, + "--get-regexp", + pattern, + ]); + git.output(command) +} + +async fn run_effective_config_query_async( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], + pattern: &str, + show_scope: bool, + follow_includes: bool, + config_file: Option<&Path>, +) -> io::Result { + let mut command = git.async_command_for_cwd(cwd)?; + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(git_config_args) + .arg("config"); + if let Some(config_file) = config_file { + command.arg("--file").arg(config_file); + } + command.arg("--null"); + if show_scope { + command.arg("--show-scope"); + } + command.args([ + "--show-origin", + if follow_includes { + "--includes" + } else { + "--no-includes" + }, + "--get-regexp", + pattern, + ]); + git.output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await } pub(crate) fn path_is_within(path: &Path, root: &Path) -> bool { @@ -141,6 +421,7 @@ fn components_equal(left: Component<'_>, right: Component<'_>) -> bool { fn parse_scope(scope: &[u8]) -> io::Result { match scope { + b"unknown" => Ok(GitConfigScope::Unknown), b"system" => Ok(GitConfigScope::System), b"global" => Ok(GitConfigScope::Global), b"local" => Ok(GitConfigScope::Local), @@ -150,6 +431,32 @@ fn parse_scope(scope: &[u8]) -> io::Result { } } +fn parse_config_origin(origin: &[u8]) -> io::Result { + if origin == b"command line:" { + return Ok(GitConfigOrigin::CommandLine); + } + let path = origin + .strip_prefix(b"file:") + .ok_or_else(|| invalid_config_output("unsupported Git config origin"))?; + if path.is_empty() || path.contains(&0) { + return Err(invalid_config_output("empty Git config origin")); + } + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt; + + Ok(GitConfigOrigin::File(std::path::PathBuf::from( + std::ffi::OsString::from_vec(path.to_vec()), + ))) + } + #[cfg(not(unix))] + { + Ok(GitConfigOrigin::File(std::path::PathBuf::from( + parse_utf8_field(path, "Git config origin path")?, + ))) + } +} + fn parse_utf8_field<'a>(field: &'a [u8], name: &str) -> io::Result<&'a str> { std::str::from_utf8(field).map_err(|_| invalid_config_output(&format!("non-UTF-8 {name}"))) } diff --git a/codex-rs/git-utils/src/git_config_sources.rs b/codex-rs/git-utils/src/git_config_sources.rs new file mode 100644 index 0000000000..60687cc804 --- /dev/null +++ b/codex-rs/git-utils/src/git_config_sources.rs @@ -0,0 +1,263 @@ +use std::collections::BTreeSet; +use std::io; +use std::path::Path; +#[cfg(test)] +use std::path::PathBuf; + +use crate::git_command::GitRunner; +use crate::git_config::read_config_entries_without_includes; +use crate::git_config::read_config_entries_without_includes_async; + +mod include_graph; +mod path_safety; +mod primary_sources; + +use include_graph::IncludeGraphBudget; +use include_graph::validate_include_entries; +use include_graph::validate_include_entries_async; +use path_safety::normalize_absolute_path; +use path_safety::resolve_literal_path; +use primary_sources::default_system_config_source_candidates; +use primary_sources::default_system_config_source_candidates_async; +use primary_sources::is_disabled_primary_config_path; +use primary_sources::legacy_primary_config_source_candidates; +use primary_sources::selected_git_home_config_candidates; +use primary_sources::selected_git_home_config_candidates_async; +use primary_sources::selected_git_prefix_system_candidate; +use primary_sources::selected_git_prefix_system_candidate_async; + +const INCLUDE_CONFIG_PATTERN: &str = r"^include(\.path|if\..*\.path)$"; +const MAX_CONFIG_INCLUDE_DEPTH: usize = 10; +const MAX_CONFIG_INCLUDE_FILES: usize = 1024; + +/// Reject configuration that an untrusted worktree writer can change between +/// a policy probe and the Git command it guards. +pub(crate) fn ensure_no_worktree_config_sources( + git: &GitRunner, + git_root: &Path, + git_config_args: &[String], +) -> io::Result<()> { + futures::executor::block_on(ensure_no_worktree_config_sources_impl( + SourceExecution::Blocking(git), + git_root, + git_config_args, + )) +} + +/// Async counterpart to [`ensure_no_worktree_config_sources`] for bounded +/// status reads. It uses the same source classification and include-graph +/// policy while spawning every selected-Git query through the authority-bound +/// Tokio runner. +pub(crate) async fn ensure_no_worktree_config_sources_async( + git: &GitRunner, + git_root: &Path, + git_config_args: &[String], +) -> io::Result<()> { + ensure_no_worktree_config_sources_impl(SourceExecution::Async(git), git_root, git_config_args) + .await +} + +#[derive(Clone, Copy)] +enum SourceExecution<'a> { + Blocking(&'a GitRunner), + Async(&'a GitRunner), +} + +impl<'a> SourceExecution<'a> { + fn git(self) -> &'a GitRunner { + match self { + Self::Blocking(git) | Self::Async(git) => git, + } + } + + async fn selected_home_candidates(self, cwd: &Path) -> io::Result> { + match self { + Self::Blocking(git) => selected_git_home_config_candidates(git, cwd), + Self::Async(git) => selected_git_home_config_candidates_async(git, cwd).await, + } + } + + async fn selected_prefix_candidate(self, cwd: &Path) -> io::Result> { + match self { + Self::Blocking(git) => selected_git_prefix_system_candidate(git, cwd), + Self::Async(git) => selected_git_prefix_system_candidate_async(git, cwd).await, + } + } + + async fn read_include_entries( + self, + cwd: &Path, + git_config_args: &[String], + config_file: Option<&Path>, + ) -> io::Result> { + match self { + Self::Blocking(git) => read_config_entries_without_includes( + git, + cwd, + git_config_args, + INCLUDE_CONFIG_PATTERN, + "include", + config_file, + ), + Self::Async(git) => { + read_config_entries_without_includes_async( + git, + cwd, + git_config_args, + INCLUDE_CONFIG_PATTERN, + "include", + config_file, + ) + .await + } + } + } + + async fn validate_entries( + self, + git_root: &Path, + entries: Vec, + depth: usize, + pending: &mut Vec<(std::path::PathBuf, usize)>, + budget: &mut IncludeGraphBudget, + ) -> io::Result<()> { + match self { + Self::Blocking(git) => { + validate_include_entries(git, git_root, entries, depth, pending, budget) + } + Self::Async(git) => { + validate_include_entries_async(git, git_root, entries, depth, pending, budget).await + } + } + } + + async fn default_system_candidates( + self, + cwd: &Path, + ) -> io::Result> { + match self { + Self::Blocking(git) => default_system_config_source_candidates(git, cwd), + Self::Async(git) => default_system_config_source_candidates_async(git, cwd).await, + } + } +} + +async fn ensure_no_worktree_config_sources_impl( + execution: SourceExecution<'_>, + git_root: &Path, + git_config_args: &[String], +) -> io::Result<()> { + let git_root = normalize_absolute_path(std::fs::canonicalize(git_root)?)?; + let git = execution.git(); + + // Environment, HOME, and XDG paths are attacker-controlled byte strings. + // Classify their exact OsString spelling before selected Git can open or + // newline-delimit one of them. + for (description, candidate) in legacy_primary_config_source_candidates()? { + if !is_disabled_primary_config_path(&candidate) { + reject_source(git, &git_root, &candidate, description)?; + } + } + for candidate in execution.selected_home_candidates(&git_root).await? { + reject_source(git, &git_root, &candidate, "selected Git HOME config")?; + } + if let Some(candidate) = execution.selected_prefix_candidate(&git_root).await? { + reject_source( + git, + &git_root, + &candidate, + "selected Git prefix system config", + )?; + } + let entries = execution + .read_include_entries(&git_root, git_config_args, /*config_file*/ None) + .await?; + let mut pending = Vec::new(); + let mut include_budget = IncludeGraphBudget::default(); + execution + .validate_entries( + &git_root, + entries, + /*depth*/ 1, + &mut pending, + &mut include_budget, + ) + .await?; + let mut visited = BTreeSet::new(); + while let Some((config_path, depth)) = pending.pop() { + if depth > MAX_CONFIG_INCLUDE_DEPTH { + return Err(path_safety::invalid_config_source( + "Git config include depth exceeded", + )); + } + match std::fs::canonicalize(&config_path) { + Ok(_) => {} + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + continue; + } + Err(error) => return Err(error), + } + if !visited.insert(config_path.clone()) { + continue; + } + if visited.len() > MAX_CONFIG_INCLUDE_FILES { + return Err(path_safety::invalid_config_source( + "too many Git config include files", + )); + } + // The same file reached through two spellings can resolve a relative + // child include differently. Deduplicate only the exact source + // spelling, not its canonical target. + let entries = execution + .read_include_entries(&git_root, &[], Some(&config_path)) + .await?; + execution + .validate_entries( + &git_root, + entries, + depth + 1, + &mut pending, + &mut include_budget, + ) + .await?; + } + // `git var` loads repository config before reporting modern default-system + // paths. Delay that supplemental probe until the complete no-includes + // source graph above has been classified. + for (description, candidate) in execution.default_system_candidates(&git_root).await? { + if !is_disabled_primary_config_path(&candidate) { + reject_source(git, &git_root, &candidate, description)?; + } + } + Ok(()) +} + +fn reject_source( + git: &GitRunner, + cwd: &Path, + candidate: &Path, + description: &str, +) -> io::Result<()> { + let absolute = resolve_literal_path(candidate, cwd); + git.ensure_config_source_is_not_worktree_controlled(&absolute, description) +} + +#[cfg(all(test, not(windows)))] +use crate::git_config::GitConfigEntry; +#[cfg(all(test, not(windows)))] +use codex_utils_absolute_path::AbsolutePathBuf; +#[cfg(test)] +use include_graph::expand_git_config_path; +#[cfg(all(test, not(windows)))] +use include_graph::resolve_include_path; +#[cfg(test)] +use path_safety::windows_config_path_is_ambiguous; + +#[cfg(test)] +#[path = "git_config_sources_tests.rs"] +mod tests; diff --git a/codex-rs/git-utils/src/git_config_sources/include_graph.rs b/codex-rs/git-utils/src/git_config_sources/include_graph.rs new file mode 100644 index 0000000000..eb9ff5f589 --- /dev/null +++ b/codex-rs/git-utils/src/git_config_sources/include_graph.rs @@ -0,0 +1,248 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use super::path_safety::CONFIG_PATH_KEY; +use super::path_safety::invalid_config_source; +use super::path_safety::reject_raw_ambiguous_windows_config_path; +use super::path_safety::resolve_literal_path; +use super::reject_source; +use crate::git_command::GitRunner; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; +use crate::git_config::GitConfigEntry; +use crate::git_config::GitConfigOrigin; + +#[derive(Debug)] +pub(super) struct IncludeGraphBudget { + remaining_directives: usize, +} + +impl Default for IncludeGraphBudget { + fn default() -> Self { + Self { + remaining_directives: super::MAX_CONFIG_INCLUDE_FILES, + } + } +} + +impl IncludeGraphBudget { + fn reserve_directive(&mut self) -> io::Result<()> { + let Some(remaining) = self.remaining_directives.checked_sub(1) else { + return Err(invalid_config_source("too many Git config includes")); + }; + self.remaining_directives = remaining; + Ok(()) + } + + #[cfg(test)] + pub(super) fn with_limit(limit: usize) -> Self { + Self { + remaining_directives: limit, + } + } +} + +pub(super) fn validate_include_entries( + git: &GitRunner, + git_root: &Path, + entries: Vec, + depth: usize, + pending: &mut Vec<(PathBuf, usize)>, + budget: &mut IncludeGraphBudget, +) -> io::Result<()> { + for entry in entries { + if !is_include_path(&entry.key) { + return Err(invalid_config_source("unexpected Git config include key")); + } + if let Some(origin) = config_file_origin(&entry, git_root)? { + reject_source(git, git_root, &origin, "Git config origin")?; + } + // Consume one graph-wide slot before a path expansion can launch a Git + // child. Every accepted directive also becomes at most one pending + // file, so this caps both process fan-out and queued traversal work. + budget.reserve_directive()?; + let include = resolve_include_path(git, git_root, &entry)?; + reject_source(git, git_root, &include, "Git config include")?; + pending.push((include, depth)); + } + Ok(()) +} + +pub(super) async fn validate_include_entries_async( + git: &GitRunner, + git_root: &Path, + entries: Vec, + depth: usize, + pending: &mut Vec<(PathBuf, usize)>, + budget: &mut IncludeGraphBudget, +) -> io::Result<()> { + for entry in entries { + if !is_include_path(&entry.key) { + return Err(invalid_config_source("unexpected Git config include key")); + } + if let Some(origin) = config_file_origin(&entry, git_root)? { + reject_source(git, git_root, &origin, "Git config origin")?; + } + // Keep this check before the await: an over-limit directive must not + // start another expansion child. + budget.reserve_directive()?; + let include = resolve_include_path_async(git, git_root, &entry).await?; + reject_source(git, git_root, &include, "Git config include")?; + pending.push((include, depth)); + } + Ok(()) +} + +fn config_file_origin(entry: &GitConfigEntry, cwd: &Path) -> io::Result> { + match &entry.origin { + GitConfigOrigin::CommandLine => Ok(None), + GitConfigOrigin::File(path) => Ok(Some(resolve_literal_path(path, cwd))), + } +} + +fn is_include_path(key: &str) -> bool { + key == "include.path" || key.starts_with("includeif.") && key.ends_with(".path") +} + +pub(super) fn resolve_include_path( + git: &GitRunner, + cwd: &Path, + entry: &GitConfigEntry, +) -> io::Result { + let raw = entry.value.as_str(); + if raw.is_empty() { + return Err(invalid_config_source("empty Git config include path")); + } + // Unlike generic `git config --path`, include.path treats `:(...)` as + // literal path text. Bypass the generic path expander for those spellings + // so the validated path exactly matches Git's include loader. + let expanded = if raw.starts_with(":(") { + PathBuf::from(raw) + } else { + expand_git_config_path(git, cwd, raw)? + }; + reject_raw_ambiguous_windows_config_path( + expanded + .to_str() + .ok_or_else(|| invalid_config_source("non-UTF-8 Git include path"))?, + )?; + let base = match config_file_origin(entry, cwd)? { + Some(origin) => origin + .parent() + .ok_or_else(|| invalid_config_source("Git config origin has no parent"))? + .to_path_buf(), + None if expanded.is_absolute() => cwd.to_path_buf(), + None => { + return Err(invalid_config_source( + "relative Git config include has no file origin", + )); + } + }; + Ok(resolve_literal_path(expanded, &base)) +} + +async fn resolve_include_path_async( + git: &GitRunner, + cwd: &Path, + entry: &GitConfigEntry, +) -> io::Result { + let raw = entry.value.as_str(); + if raw.is_empty() { + return Err(invalid_config_source("empty Git config include path")); + } + let expanded = if raw.starts_with(":(") { + PathBuf::from(raw) + } else { + expand_git_config_path_async(git, cwd, raw).await? + }; + reject_raw_ambiguous_windows_config_path( + expanded + .to_str() + .ok_or_else(|| invalid_config_source("non-UTF-8 Git include path"))?, + )?; + let base = match config_file_origin(entry, cwd)? { + Some(origin) => origin + .parent() + .ok_or_else(|| invalid_config_source("Git config origin has no parent"))? + .to_path_buf(), + None if expanded.is_absolute() => cwd.to_path_buf(), + None => { + return Err(invalid_config_source( + "relative Git config include has no file origin", + )); + } + }; + Ok(resolve_literal_path(expanded, &base)) +} + +pub(super) fn expand_git_config_path( + git: &GitRunner, + cwd: &Path, + raw: &str, +) -> io::Result { + let mut command = git.command_for_cwd(cwd)?; + command + .arg("-c") + .arg(format!("{CONFIG_PATH_KEY}={raw}")) + .args([ + "config", + "--null", + "--no-includes", + "--path", + "--get", + CONFIG_PATH_KEY, + ]); + let output = git.output(command)?; + if !output.status.success() { + return Err(io::Error::other(format!( + "git include path expansion failed with status {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + parse_expanded_config_path(&output.stdout) +} + +async fn expand_git_config_path_async( + git: &GitRunner, + cwd: &Path, + raw: &str, +) -> io::Result { + let mut command = git.async_command_for_cwd(cwd)?; + command + .arg("-c") + .arg(format!("{CONFIG_PATH_KEY}={raw}")) + .args([ + "config", + "--null", + "--no-includes", + "--path", + "--get", + CONFIG_PATH_KEY, + ]); + let output = git + .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await?; + if !output.status.success() { + return Err(io::Error::other(format!( + "git include path expansion failed with status {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + parse_expanded_config_path(&output.stdout) +} + +fn parse_expanded_config_path(output: &[u8]) -> io::Result { + let value = output + .strip_suffix(&[0]) + .ok_or_else(|| invalid_config_source("unterminated Git include path expansion"))?; + if value.is_empty() || value.contains(&0) { + return Err(invalid_config_source( + "ambiguous Git include path expansion", + )); + } + let value = std::str::from_utf8(value) + .map_err(|_| invalid_config_source("non-UTF-8 Git include path expansion"))?; + Ok(PathBuf::from(value)) +} diff --git a/codex-rs/git-utils/src/git_config_sources/path_safety.rs b/codex-rs/git-utils/src/git_config_sources/path_safety.rs new file mode 100644 index 0000000000..42509affdf --- /dev/null +++ b/codex-rs/git-utils/src/git_config_sources/path_safety.rs @@ -0,0 +1,56 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use codex_utils_absolute_path::AbsolutePathBuf; + +pub(super) const CONFIG_PATH_KEY: &str = "codex.config-source.path"; + +#[cfg(unix)] +pub(super) fn git_var_path_from_bytes(path: &[u8]) -> io::Result { + use std::os::unix::ffi::OsStringExt; + + Ok(PathBuf::from(std::ffi::OsString::from_vec(path.to_vec()))) +} + +#[cfg(not(unix))] +pub(super) fn git_var_path_from_bytes(path: &[u8]) -> io::Result { + Ok(PathBuf::from(std::str::from_utf8(path).map_err(|_| { + invalid_config_source("non-UTF-8 Git config source path") + })?)) +} + +pub(super) fn resolve_literal_path(path: impl AsRef, base: &Path) -> PathBuf { + let path = path.as_ref(); + if path.is_absolute() { + path.to_path_buf() + } else { + base.join(path) + } +} + +pub(super) fn normalize_absolute_path(path: impl AsRef) -> io::Result { + Ok(AbsolutePathBuf::from_absolute_path(path)?.into_path_buf()) +} + +#[cfg(windows)] +pub(super) fn reject_raw_ambiguous_windows_config_path(path: &str) -> io::Result<()> { + if windows_config_path_is_ambiguous(path) { + return Err(invalid_config_source("ambiguous Windows Git config path")); + } + Ok(()) +} + +#[cfg(not(windows))] +pub(super) fn reject_raw_ambiguous_windows_config_path(_path: &str) -> io::Result<()> { + Ok(()) +} + +#[cfg(any(windows, test))] +pub(super) fn windows_config_path_is_ambiguous(path: &str) -> bool { + crate::path_authority::windows_path_is_ambiguous(path) +} + +pub(super) fn invalid_config_source(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} diff --git a/codex-rs/git-utils/src/git_config_sources/primary_sources.rs b/codex-rs/git-utils/src/git_config_sources/primary_sources.rs new file mode 100644 index 0000000000..eba7ede571 --- /dev/null +++ b/codex-rs/git-utils/src/git_config_sources/primary_sources.rs @@ -0,0 +1,390 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use super::path_safety::CONFIG_PATH_KEY; +use super::path_safety::git_var_path_from_bytes; +use super::path_safety::invalid_config_source; +use crate::git_command::GitRunner; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; + +pub(super) fn default_system_config_source_candidates( + git: &GitRunner, + cwd: &Path, +) -> io::Result> { + if git_env_bool("GIT_CONFIG_NOSYSTEM")? || std::env::var_os("GIT_CONFIG_SYSTEM").is_some() { + return Ok(Vec::new()); + } + // `GIT_CONFIG_SYSTEM` was added to `git var` in Git 2.42. The PSEC-4394 + // boundary treats the selected Git installation and its non-environment + // compile-time system config as host-owned trusted inputs. For older Git, + // the exact custom ETC_GITCONFIG path is therefore a documented residual; + // the derivable prefix/ProgramData paths are still checked separately and + // the no-includes graph validates every directive the system file exposes. + let Some(paths) = git_var_config_paths(git, cwd, "GIT_CONFIG_SYSTEM")? else { + return Ok(Vec::new()); + }; + Ok(paths + .into_iter() + .map(|path| ("GIT_CONFIG_SYSTEM", path)) + .collect()) +} + +pub(super) async fn default_system_config_source_candidates_async( + git: &GitRunner, + cwd: &Path, +) -> io::Result> { + if git_env_bool("GIT_CONFIG_NOSYSTEM")? || std::env::var_os("GIT_CONFIG_SYSTEM").is_some() { + return Ok(Vec::new()); + } + let Some(paths) = git_var_config_paths_async(git, cwd, "GIT_CONFIG_SYSTEM").await? else { + return Ok(Vec::new()); + }; + Ok(paths + .into_iter() + .map(|path| ("GIT_CONFIG_SYSTEM", path)) + .collect()) +} + +pub(super) fn selected_git_home_config_candidates( + git: &GitRunner, + cwd: &Path, +) -> io::Result> { + if std::env::var_os("GIT_CONFIG_GLOBAL").is_some() { + return Ok(Vec::new()); + } + #[cfg(not(windows))] + if std::env::var_os("HOME").is_none() { + return Ok(Vec::new()); + } + let dot_gitconfig = selected_git_path_candidate(git, cwd, "~/.gitconfig")?; + let mut candidates = vec![dot_gitconfig.clone()]; + if std::env::var_os("XDG_CONFIG_HOME").is_none_or(|path| path.is_empty()) { + let home = dot_gitconfig + .parent() + .ok_or_else(|| invalid_config_source("selected Git HOME has no parent"))?; + candidates.push(home.join(".config/git/config")); + } + Ok(candidates) +} + +pub(super) async fn selected_git_home_config_candidates_async( + git: &GitRunner, + cwd: &Path, +) -> io::Result> { + if std::env::var_os("GIT_CONFIG_GLOBAL").is_some() { + return Ok(Vec::new()); + } + #[cfg(not(windows))] + if std::env::var_os("HOME").is_none() { + return Ok(Vec::new()); + } + let dot_gitconfig = selected_git_path_candidate_async(git, cwd, "~/.gitconfig").await?; + let mut candidates = vec![dot_gitconfig.clone()]; + if std::env::var_os("XDG_CONFIG_HOME").is_none_or(|path| path.is_empty()) { + let home = dot_gitconfig + .parent() + .ok_or_else(|| invalid_config_source("selected Git HOME has no parent"))?; + candidates.push(home.join(".config/git/config")); + } + Ok(candidates) +} + +pub(super) fn selected_git_prefix_system_candidate( + git: &GitRunner, + cwd: &Path, +) -> io::Result> { + if git_env_bool("GIT_CONFIG_NOSYSTEM")? || std::env::var_os("GIT_CONFIG_SYSTEM").is_some() { + return Ok(None); + } + selected_git_path_candidate(git, cwd, "%(prefix)/etc/gitconfig").map(Some) +} + +pub(super) async fn selected_git_prefix_system_candidate_async( + git: &GitRunner, + cwd: &Path, +) -> io::Result> { + if git_env_bool("GIT_CONFIG_NOSYSTEM")? || std::env::var_os("GIT_CONFIG_SYSTEM").is_some() { + return Ok(None); + } + selected_git_path_candidate_async(git, cwd, "%(prefix)/etc/gitconfig") + .await + .map(Some) +} + +fn selected_git_path_candidate(git: &GitRunner, cwd: &Path, raw: &str) -> io::Result { + let tempdir = tempfile::tempdir()?; + let nonexistent_git_dir = tempdir.path().join("nonexistent-git-dir"); + let disabled_config = if cfg!(windows) { "NUL" } else { "/dev/null" }; + let mut command = git.command_for_cwd(cwd)?; + command + .env("GIT_CONFIG_GLOBAL", disabled_config) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_COUNT", "0") + .env_remove("GIT_CONFIG_PARAMETERS") + .arg("--git-dir") + .arg(&nonexistent_git_dir) + .arg("-c") + .arg(format!("{CONFIG_PATH_KEY}={raw}")) + .args([ + "config", + "--null", + "--no-includes", + "--path", + "--get", + CONFIG_PATH_KEY, + ]); + let output = git.output(command)?; + if !output.status.success() { + return Err(io::Error::other(format!( + "isolated selected Git path expansion failed with status {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + parse_selected_git_path(&output.stdout) +} + +async fn selected_git_path_candidate_async( + git: &GitRunner, + cwd: &Path, + raw: &str, +) -> io::Result { + let tempdir = tempfile::tempdir()?; + let nonexistent_git_dir = tempdir.path().join("nonexistent-git-dir"); + let disabled_config = if cfg!(windows) { "NUL" } else { "/dev/null" }; + let mut command = git.async_command_for_cwd(cwd)?; + command + .env("GIT_CONFIG_GLOBAL", disabled_config) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_COUNT", "0") + .env_remove("GIT_CONFIG_PARAMETERS") + .arg("--git-dir") + .arg(&nonexistent_git_dir) + .arg("-c") + .arg(format!("{CONFIG_PATH_KEY}={raw}")) + .args([ + "config", + "--null", + "--no-includes", + "--path", + "--get", + CONFIG_PATH_KEY, + ]); + let output = git + .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await?; + if !output.status.success() { + return Err(io::Error::other(format!( + "isolated selected Git path expansion failed with status {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + parse_selected_git_path(&output.stdout) +} + +fn parse_selected_git_path(output: &[u8]) -> io::Result { + let value = output + .strip_suffix(&[0]) + .ok_or_else(|| invalid_config_source("unterminated selected Git path"))?; + if value.is_empty() || value.contains(&0) { + return Err(invalid_config_source("ambiguous selected Git path")); + } + git_var_path_from_bytes(value) +} + +fn git_var_config_paths( + git: &GitRunner, + cwd: &Path, + variable: &str, +) -> io::Result>> { + let mut command = git.command_for_cwd(cwd)?; + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(["var", variable]); + let output = git.output(command)?; + parse_git_var_config_paths_result( + output.status.code(), + &output.stdout, + &output.stderr, + variable, + ) +} + +async fn git_var_config_paths_async( + git: &GitRunner, + cwd: &Path, + variable: &str, +) -> io::Result>> { + let mut command = git.async_command_for_cwd(cwd)?; + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(["var", variable]); + let output = git + .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await?; + parse_git_var_config_paths_result( + output.status.code(), + &output.stdout, + &output.stderr, + variable, + ) +} + +pub(super) fn parse_git_var_config_paths_result( + status_code: Option, + stdout: &[u8], + stderr: &[u8], + variable: &str, +) -> io::Result>> { + match status_code { + Some(0) => parse_git_var_paths(stdout).map(Some), + Some(1) if stdout.is_empty() && stderr.is_empty() => Ok(Some(Vec::new())), + // These variables were added in Git 2.42. Older Git reports usage + // status 129; fall back to its documented environment/home sources. + Some(129) => Ok(None), + _ => Err(io::Error::other(format!( + "git {variable} source probe failed with status {status_code:?}: {}", + String::from_utf8_lossy(stderr).trim() + ))), + } +} + +fn parse_git_var_paths(output: &[u8]) -> io::Result> { + output + .split(|byte| *byte == b'\n') + .filter(|path| !path.is_empty()) + .map(|path| { + let path = path.strip_suffix(b"\r").unwrap_or(path); + git_var_path_from_bytes(path) + }) + .collect() +} + +pub(super) fn legacy_primary_config_source_candidates() -> io::Result> +{ + let mut candidates = Vec::new(); + match std::env::var_os("GIT_CONFIG_GLOBAL") { + Some(path) if !path.is_empty() => { + candidates.push(("GIT_CONFIG_GLOBAL", PathBuf::from(path))); + } + Some(_) => {} + None => { + let homes = git_home_directories(); + match std::env::var_os("XDG_CONFIG_HOME") { + Some(xdg) if !xdg.is_empty() => candidates.push(( + "XDG_CONFIG_HOME Git config", + PathBuf::from(xdg).join("git/config"), + )), + _ => { + #[cfg(windows)] + if let Some(app_data) = std::env::var_os("APPDATA") + && !app_data.is_empty() + { + candidates.push(( + "APPDATA Git config", + PathBuf::from(app_data).join("Git/config"), + )); + } + for home in &homes { + candidates.push(( + "HOME XDG Git config", + home_config_path(home, ".config/git/config"), + )); + } + } + } + for home in &homes { + candidates.push(("HOME Git config", home_config_path(home, ".gitconfig"))); + } + } + } + if !git_env_bool("GIT_CONFIG_NOSYSTEM")? { + match std::env::var_os("GIT_CONFIG_SYSTEM") { + Some(path) if !path.is_empty() => { + candidates.push(("GIT_CONFIG_SYSTEM", PathBuf::from(path))); + } + Some(_) => {} + None => { + #[cfg(windows)] + if let Some(program_data) = std::env::var_os("PROGRAMDATA") + && !program_data.is_empty() + { + candidates.push(( + "PROGRAMDATA Git config", + PathBuf::from(program_data).join("Git/config"), + )); + } + } + } + } + Ok(candidates) +} + +fn git_home_directories() -> Vec { + if let Some(home) = std::env::var_os("HOME") { + return vec![home]; + } + #[cfg(windows)] + { + let mut homes = Vec::new(); + if let (Some(drive), Some(path)) = + (std::env::var_os("HOMEDRIVE"), std::env::var_os("HOMEPATH")) + { + let mut home = drive; + home.push(path); + homes.push(home); + } + if let Some(profile) = std::env::var_os("USERPROFILE") + && !homes.contains(&profile) + { + homes.push(profile); + } + homes + } + #[cfg(not(windows))] + Vec::new() +} + +fn home_config_path(home: &std::ffi::OsStr, suffix: &str) -> PathBuf { + if home.is_empty() { + PathBuf::from(std::path::MAIN_SEPARATOR.to_string()).join(suffix) + } else { + PathBuf::from(home).join(suffix) + } +} + +fn git_env_bool(name: &str) -> io::Result { + let Some(value) = std::env::var_os(name) else { + return Ok(false); + }; + let value = value + .to_str() + .ok_or_else(|| invalid_config_source("non-UTF-8 Git boolean environment value"))?; + match value.to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Ok(true), + "" | "0" | "false" | "no" | "off" => Ok(false), + value => value + .parse::() + .ok() + // Supported Git releases disagree on whether INT_MIN is a valid + // numeric boolean. Accept only their shared symmetric range so a + // value approved here cannot make the selected Git fail later. + .filter(|value| (-i64::from(i32::MAX)..=i64::from(i32::MAX)).contains(value)) + .map(|value| value != 0) + .ok_or_else(|| invalid_config_source("invalid Git boolean environment value")), + } +} + +#[cfg(windows)] +pub(super) fn is_disabled_primary_config_path(path: &Path) -> bool { + path.as_os_str() + .to_str() + .is_some_and(|path| path.eq_ignore_ascii_case("NUL")) +} + +#[cfg(not(windows))] +pub(super) fn is_disabled_primary_config_path(_path: &Path) -> bool { + false +} diff --git a/codex-rs/git-utils/src/git_config_sources_tests.rs b/codex-rs/git-utils/src/git_config_sources_tests.rs new file mode 100644 index 0000000000..152b0529c5 --- /dev/null +++ b/codex-rs/git-utils/src/git_config_sources_tests.rs @@ -0,0 +1,1654 @@ +use super::*; +use pretty_assertions::assert_eq; +use std::ffi::OsStr; + +fn run(cwd: &Path, args: &[&str]) -> (i32, String, String) { + let mut command = std::process::Command::new("git"); + crate::safe_git::isolate_git_command_environment(&mut command); + let output = command + .args(args) + .current_dir(cwd) + .output() + .expect("run Git"); + ( + output.status.code().unwrap_or(-1), + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + ) +} + +fn run_success(cwd: &Path, args: &[&str]) -> String { + let (code, stdout, stderr) = run(cwd, args); + assert_eq!(code, 0, "git {args:?}: {stderr}"); + stdout.trim().to_string() +} + +fn init_repo() -> tempfile::TempDir { + let repo = tempfile::tempdir().expect("tempdir"); + init_repo_at(repo.path()); + repo +} + +fn init_repo_at(root: &Path) { + std::fs::create_dir_all(root).expect("create repository directory"); + run_success(root, &["init"]); + run_success(root, &["config", "user.email", "codex@example.com"]); + run_success(root, &["config", "user.name", "Codex"]); + std::fs::write(root.join("file.txt"), "orig\n").expect("write file"); + run_success(root, &["add", "file.txt"]); + run_success(root, &["commit", "-m", "seed"]); +} + +#[cfg(windows)] +fn create_junction(path: &Path, target: &Path) { + // Bazel's GNU Windows runner can surface temporary paths with `/` + // separators. `mklink` treats those separators as option prefixes, so + // pass native separators to the cmd.exe built-in. + let path = path.as_os_str().to_string_lossy().replace('/', "\\"); + let target = target.as_os_str().to_string_lossy().replace('/', "\\"); + let output = std::process::Command::new("cmd.exe") + .args(["/D", "/C", "mklink", "/J"]) + .arg(path) + .arg(target) + .output() + .expect("create junction"); + assert!( + output.status.success(), + "mklink failed: stdout={} stderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn guard(root: &Path) -> io::Result<()> { + let git = GitRunner::for_cwd_io(root)?; + ensure_no_worktree_config_sources(&git, root, &[]) +} + +fn add_include(root: &Path, key: &str, value: &str) { + run_success(root, &["config", "--add", key, value]); +} + +fn assert_worktree_rejection(error: io::Error) { + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("worktree-controlled"), "{error}"); +} + +fn run_isolated_source_test(test_name: &str, env: &[(&str, &OsStr)], removed: &[&str]) { + let mut command = std::process::Command::new(std::env::current_exe().expect("test binary")); + crate::safe_git::isolate_git_command_environment(&mut command); + command + .arg(test_name) + .arg("--exact") + .arg("--nocapture") + .env("CODEX_GIT_CONFIG_SOURCE_CHILD", "1") + .env("RUST_TEST_THREADS", "1"); + for (name, value) in env { + command.env(name, value); + } + for name in removed { + command.env_remove(name); + } + let output = command.output().expect("run isolated source test"); + assert!( + output.status.success(), + "isolated test {test_name} failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn allows_protected_metadata_and_external_config_sources() { + let repo = init_repo(); + let root = repo.path(); + guard(root).expect("ordinary metadata config"); + + std::fs::write( + root.join(".git/protected.gitconfig"), + "[user]\nname = protected\n", + ) + .expect("write protected config"); + add_include(root, "include.path", "protected.gitconfig"); + guard(root).expect("protected metadata include"); + std::fs::create_dir(root.join(".git/subdir")).expect("create metadata subdirectory"); + add_include(root, "include.path", "subdir/../protected.gitconfig"); + guard(root).expect("metadata-local parent traversal"); + + let external = tempfile::tempdir().expect("external config directory"); + let external_config = external.path().join("safe.gitconfig"); + std::fs::write(&external_config, "[user]\nemail = safe@example.com\n") + .expect("write external config"); + add_include( + root, + "include.path", + external_config.to_str().expect("UTF-8 external path"), + ); + guard(root).expect("external include"); + add_include( + root, + "include.path", + external + .path() + .join("missing.gitconfig") + .to_str() + .expect("UTF-8 missing external path"), + ); + guard(root).expect("missing external include"); +} + +#[test] +fn rejects_empty_primary_global_and_system_sources_in_the_worktree() { + const TEST_NAME: &str = "git_config_sources::tests::rejects_empty_primary_global_and_system_sources_in_the_worktree"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + let root = repo.path(); + let unsafe_config = root.join("empty-primary.gitconfig"); + std::fs::write(&unsafe_config, "").expect("write empty primary config"); + let safe = tempfile::NamedTempFile::new().expect("safe external config"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("GIT_CONFIG_GLOBAL", unsafe_config.as_os_str()), + ("GIT_CONFIG_SYSTEM", safe.path().as_os_str()), + ], + &[], + ); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("GIT_CONFIG_GLOBAL", safe.path().as_os_str()), + ("GIT_CONFIG_SYSTEM", unsafe_config.as_os_str()), + ], + &[], + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + assert_worktree_rejection(guard(&root).expect_err("unsafe primary config source")); +} + +#[test] +fn rejects_missing_home_and_xdg_sources_in_the_worktree() { + const TEST_NAME: &str = + "git_config_sources::tests::rejects_missing_home_and_xdg_sources_in_the_worktree"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + let root = repo.path(); + let xdg = root.join("xdg"); + std::fs::create_dir(&xdg).expect("create XDG root"); + let safe_system = tempfile::NamedTempFile::new().expect("safe system config"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("HOME", root.as_os_str()), + ("XDG_CONFIG_HOME", xdg.as_os_str()), + ("GIT_CONFIG_SYSTEM", safe_system.path().as_os_str()), + ], + &["GIT_CONFIG_GLOBAL"], + ); + return; + } + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + assert_worktree_rejection(guard(&root).expect_err("unsafe HOME/XDG source")); +} + +#[test] +fn allows_explicitly_disabled_global_and_system_sources() { + const TEST_NAME: &str = + "git_config_sources::tests::allows_explicitly_disabled_global_and_system_sources"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_GLOBAL", OsStr::new("")), + ("GIT_CONFIG_SYSTEM", OsStr::new("")), + ], + &[], + ); + return; + } + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + guard(&root).expect("disabled primary config sources"); +} + +#[cfg(unix)] +#[test] +fn allows_unset_home_when_git_has_no_global_source() { + const TEST_NAME: &str = + "git_config_sources::tests::allows_unset_home_when_git_has_no_global_source"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + &[ + "HOME", + "XDG_CONFIG_HOME", + "GIT_CONFIG_GLOBAL", + "GIT_CONFIG_SYSTEM", + ], + ); + return; + } + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + guard(&root).expect("Git without HOME or global config"); +} + +#[test] +fn supports_pre_242_git_without_system_var_enumeration() { + assert_eq!( + primary_sources::parse_git_var_config_paths_result( + Some(129), + b"", + b"usage: git var (-l | )\n", + "GIT_CONFIG_SYSTEM", + ) + .expect("pre-2.42 fallback"), + None + ); +} + +#[cfg(unix)] +#[test] +fn rejects_newline_bearing_raw_global_source_before_git_normalizes_it() { + const TEST_NAME: &str = "git_config_sources::tests::rejects_newline_bearing_raw_global_source_before_git_normalizes_it"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let parent = tempfile::tempdir().expect("fixture parent"); + let root = parent.path().join("repo"); + init_repo_at(&root); + let newline_dir = parent.path().join("external\n"); + std::fs::create_dir(&newline_dir).expect("create newline path component"); + let unsafe_config = root.join("global.gitconfig"); + std::fs::write(&unsafe_config, "").expect("write unsafe global config"); + let raw = newline_dir.join("../repo/global.gitconfig"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("GIT_CONFIG_GLOBAL", raw.as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + &["GIT_CONFIG_SYSTEM"], + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + assert_worktree_rejection(guard(&root).expect_err("newline raw global source")); +} + +#[cfg(unix)] +#[test] +fn ignores_non_utf8_values_for_unrelated_global_keys() { + const TEST_NAME: &str = + "git_config_sources::tests::ignores_non_utf8_values_for_unrelated_global_keys"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + let global = tempfile::NamedTempFile::new().expect("external global config"); + std::fs::write(global.path(), b"[user]\nname = \xff\n") + .expect("write non-UTF-8 unrelated config value"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_GLOBAL", global.path().as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + &["GIT_CONFIG_SYSTEM"], + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + guard(&root).expect("unrelated non-UTF-8 global value"); +} + +#[cfg(all(unix, not(target_os = "macos")))] +#[test] +fn preserves_non_utf8_unix_repository_and_config_origin_paths() { + use std::os::unix::ffi::OsStringExt; + + const TEST_NAME: &str = + "git_config_sources::tests::preserves_non_utf8_unix_repository_and_config_origin_paths"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let parent = tempfile::tempdir().expect("non-UTF-8 fixture parent"); + let root = parent + .path() + .join(std::ffi::OsString::from_vec(b"repo-\xff".to_vec())); + init_repo_at(&root); + let safe = tempfile::NamedTempFile::new().expect("safe included config"); + add_include( + &root, + "include.path", + safe.path().to_str().expect("UTF-8 safe include"), + ); + let global = parent + .path() + .join(std::ffi::OsString::from_vec(b"global-\xff".to_vec())); + std::fs::write( + &global, + format!("[include]\npath = {}\n", safe.path().display()), + ) + .expect("write non-UTF-8 global path"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("GIT_CONFIG_GLOBAL", global.as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + &["GIT_CONFIG_SYSTEM"], + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + guard(&root).expect("non-UTF-8 repository and config origins"); +} + +#[cfg(unix)] +#[test] +fn rejects_worktree_fifo_primary_source_without_opening_it() { + const TEST_NAME: &str = + "git_config_sources::tests::rejects_worktree_fifo_primary_source_without_opening_it"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + let fifo = repo.path().join("global.fifo"); + let status = std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .expect("run mkfifo"); + assert!(status.success(), "mkfifo failed: {status}"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_GLOBAL", fifo.as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + &["GIT_CONFIG_SYSTEM"], + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + assert_worktree_rejection(guard(&root).expect_err("worktree FIFO config source")); +} + +#[test] +fn git_config_nosystem_accepts_cross_version_boolean_values() { + const TEST_NAME: &str = + "git_config_sources::tests::git_config_nosystem_accepts_cross_version_boolean_values"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + let unsafe_system = repo.path().join("system.gitconfig"); + std::fs::write(&unsafe_system, "").expect("write unsafe system config"); + for (value, expected) in [ + ("1", "ignored"), + ("2", "ignored"), + ("-1", "ignored"), + ("01", "ignored"), + ("+1", "ignored"), + ("2147483647", "ignored"), + ("-2147483647", "ignored"), + ("true", "ignored"), + ("yes", "ignored"), + ("on", "ignored"), + ("", "rejected"), + ("0", "rejected"), + ("-0", "rejected"), + ("false", "rejected"), + ("no", "rejected"), + ("off", "rejected"), + ("not-a-bool", "invalid"), + ("2147483648", "invalid"), + ("-2147483648", "invalid"), + ("-2147483649", "invalid"), + ] { + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("CODEX_GIT_CONFIG_SOURCE_EXPECTED", OsStr::new(expected)), + ("GIT_CONFIG_GLOBAL", OsStr::new("")), + ("GIT_CONFIG_SYSTEM", unsafe_system.as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new(value)), + ], + &[], + ); + } + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + match std::env::var("CODEX_GIT_CONFIG_SOURCE_EXPECTED") + .expect("expected child outcome") + .as_str() + { + "ignored" => guard(&root).expect("system source disabled"), + "rejected" => assert_worktree_rejection(guard(&root).expect_err("system source enabled")), + "invalid" => assert_eq!( + guard(&root).expect_err("invalid NOSYSTEM value").kind(), + io::ErrorKind::InvalidData + ), + expected => panic!("unexpected child outcome {expected}"), + } +} + +#[cfg(windows)] +#[test] +fn rejects_both_windows_home_candidates_when_home_is_absent() { + const TEST_NAME: &str = + "git_config_sources::tests::rejects_both_windows_home_candidates_when_home_is_absent"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + let external_profile = tempfile::tempdir().expect("external USERPROFILE"); + for home in [repo.path().to_path_buf(), repo.path().join("future-home")] { + let home = home.to_str().expect("UTF-8 Windows test path"); + assert!(home.len() >= 3 && home.as_bytes()[1] == b':', "{home}"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ("HOMEDRIVE", OsStr::new(&home[..2])), + ("HOMEPATH", OsStr::new(&home[2..])), + ("USERPROFILE", external_profile.path().as_os_str()), + ], + &[ + "HOME", + "XDG_CONFIG_HOME", + "GIT_CONFIG_GLOBAL", + "GIT_CONFIG_SYSTEM", + ], + ); + } + let external_home = external_profile + .path() + .to_str() + .expect("UTF-8 external Windows home"); + assert!( + external_home.len() >= 3 && external_home.as_bytes()[1] == b':', + "{external_home}" + ); + for profile in [ + repo.path().to_path_buf(), + repo.path().join("future-profile"), + ] { + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ("HOMEDRIVE", OsStr::new(&external_home[..2])), + ("HOMEPATH", OsStr::new(&external_home[2..])), + ("USERPROFILE", profile.as_os_str()), + ], + &[ + "HOME", + "XDG_CONFIG_HOME", + "GIT_CONFIG_GLOBAL", + "GIT_CONFIG_SYSTEM", + ], + ); + } + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + assert_worktree_rejection(guard(&root).expect_err("Windows synthesized HOME source")); +} + +#[cfg(windows)] +#[test] +fn allows_exact_windows_nul_for_both_primary_config_channels() { + const TEST_NAME: &str = + "git_config_sources::tests::allows_exact_windows_nul_for_both_primary_config_channels"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let repo = init_repo(); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("GIT_CONFIG_GLOBAL", OsStr::new("NUL")), + ("GIT_CONFIG_SYSTEM", OsStr::new("NUL")), + ], + &["GIT_CONFIG_NOSYSTEM"], + ); + return; + } + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + guard(&root).expect("exact NUL disables primary config channels"); +} + +#[cfg(windows)] +#[test] +fn windows_appdata_global_config_matches_native_git_selection_and_precedence() { + const TEST_NAME: &str = "git_config_sources::tests::windows_appdata_global_config_matches_native_git_selection_and_precedence"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + for xdg in [None, Some(OsStr::new(""))] { + for existing in [true, false] { + let repo = init_repo(); + let appdata = repo.path().join("appdata"); + if existing { + let config = appdata.join("Git/config"); + std::fs::create_dir_all(config.parent().expect("APPDATA config parent")) + .expect("create APPDATA config parent"); + std::fs::write(&config, "[codex]\nappdata-marker = selected\n") + .expect("write APPDATA config"); + } + let external_home = tempfile::tempdir().expect("external HOME"); + let mut env = vec![ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ( + "CODEX_GIT_CONFIG_SOURCE_EXPECTED", + OsStr::new(if existing { + "reject-existing-appdata" + } else { + "reject-missing-appdata" + }), + ), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ("HOME", external_home.path().as_os_str()), + ("APPDATA", appdata.as_os_str()), + ]; + if let Some(xdg) = xdg { + env.push(("XDG_CONFIG_HOME", xdg)); + } + let mut removed = vec![ + "GIT_CONFIG_GLOBAL", + "GIT_CONFIG_SYSTEM", + "HOMEDRIVE", + "HOMEPATH", + "USERPROFILE", + ]; + if xdg.is_none() { + removed.push("XDG_CONFIG_HOME"); + } + run_isolated_source_test(TEST_NAME, &env, &removed); + } + } + + let repo = init_repo(); + let appdata = repo.path().join("appdata"); + let appdata_config = appdata.join("Git/config"); + std::fs::create_dir_all(appdata_config.parent().expect("APPDATA config parent")) + .expect("create APPDATA config parent"); + std::fs::write(&appdata_config, "[codex]\nappdata-marker = appdata\n") + .expect("write APPDATA config"); + let external_home = tempfile::tempdir().expect("external HOME"); + let external_xdg = tempfile::tempdir().expect("external XDG_CONFIG_HOME"); + let xdg_config = external_xdg.path().join("git/config"); + std::fs::create_dir_all(xdg_config.parent().expect("XDG config parent")) + .expect("create XDG config parent"); + std::fs::write(&xdg_config, "[codex]\nappdata-marker = xdg\n").expect("write XDG config"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ("CODEX_GIT_CONFIG_SOURCE_EXPECTED", OsStr::new("allow-xdg")), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ("HOME", external_home.path().as_os_str()), + ("APPDATA", appdata.as_os_str()), + ("XDG_CONFIG_HOME", external_xdg.path().as_os_str()), + ], + &[ + "GIT_CONFIG_GLOBAL", + "GIT_CONFIG_SYSTEM", + "HOMEDRIVE", + "HOMEPATH", + "USERPROFILE", + ], + ); + + let external_global = tempfile::NamedTempFile::new().expect("external global config"); + std::fs::write( + external_global.path(), + "[codex]\nappdata-marker = explicit\n", + ) + .expect("write explicit global config"); + run_isolated_source_test( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", repo.path().as_os_str()), + ( + "CODEX_GIT_CONFIG_SOURCE_EXPECTED", + OsStr::new("allow-explicit-global"), + ), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ("HOME", repo.path().as_os_str()), + ("APPDATA", appdata.as_os_str()), + ("XDG_CONFIG_HOME", repo.path().as_os_str()), + ("GIT_CONFIG_GLOBAL", external_global.path().as_os_str()), + ], + &["GIT_CONFIG_SYSTEM", "HOMEDRIVE", "HOMEPATH", "USERPROFILE"], + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + let expected = + std::env::var("CODEX_GIT_CONFIG_SOURCE_EXPECTED").expect("expected child outcome"); + if expected != "reject-missing-appdata" { + let output = std::process::Command::new("git") + .args(["config", "--global", "--get", "codex.appdata-marker"]) + .current_dir(&root) + .output() + .expect("run native Git global config query"); + assert!( + output.status.success(), + "native Git global query failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let actual = String::from_utf8_lossy(&output.stdout); + let native_expected = match expected.as_str() { + "reject-existing-appdata" => "selected", + "allow-xdg" => "xdg", + "allow-explicit-global" => "explicit", + expected => panic!("unexpected child outcome {expected}"), + }; + assert_eq!( + actual.trim(), + native_expected, + "native Git global selection" + ); + } + match expected.as_str() { + "reject-existing-appdata" | "reject-missing-appdata" => { + assert_worktree_rejection(guard(&root).expect_err("worktree APPDATA config")); + } + "allow-xdg" => guard(&root).expect("nonempty XDG suppresses APPDATA"), + "allow-explicit-global" => { + guard(&root).expect("explicit global config suppresses HOME, XDG, and APPDATA") + } + expected => panic!("unexpected child outcome {expected}"), + } +} + +#[test] +fn rejects_empty_nonempty_absolute_missing_and_conditional_worktree_includes() { + for (name, body, include_key, include_value) in [ + ( + "empty", + "", + "include.path".to_string(), + "../driver-config".to_string(), + ), + ( + "nonempty", + "[user]\nname = worktree\n", + "include.path".to_string(), + "../driver-config".to_string(), + ), + ( + "missing", + "", + "include.path".to_string(), + "../future.gitconfig".to_string(), + ), + ( + "inactive includeIf", + "", + "includeIf.gitdir:/definitely/not/this/repository/**.path".to_string(), + "../driver-config".to_string(), + ), + ( + "case-insensitive gitdir includeIf", + "", + "includeIf.gitdir/i:/definitely/not/this/repository/**.path".to_string(), + "../driver-config".to_string(), + ), + ( + "onbranch includeIf", + "", + "includeIf.onbranch:definitely-never/**.path".to_string(), + "../driver-config".to_string(), + ), + ( + "hasconfig includeIf", + "", + "includeIf.hasconfig:remote.*.url:https://never.example/**.path".to_string(), + "../driver-config".to_string(), + ), + ] { + let repo = init_repo(); + let root = repo.path(); + if name != "missing" { + std::fs::write(root.join("driver-config"), body).expect("write config fixture"); + } + add_include(root, &include_key, &include_value); + assert_worktree_rejection(guard(root).expect_err(name)); + } + + let repo = init_repo(); + let root = repo.path(); + let config = root.join("absolute.gitconfig"); + std::fs::write(&config, "").expect("write absolute config"); + add_include( + root, + "include.path", + config.to_str().expect("UTF-8 config path"), + ); + assert_worktree_rejection(guard(root).expect_err("absolute include")); + + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write conditional config"); + let git_dir = run_success(root, &["rev-parse", "--absolute-git-dir"]).replace('\\', "/"); + add_include( + root, + &format!("includeIf.gitdir:{git_dir}/.path"), + "../driver-config", + ); + assert_worktree_rejection(guard(root).expect_err("active includeIf")); +} + +#[test] +fn command_scoped_include_paths_follow_the_same_boundary() { + let repo = init_repo(); + let root = repo.path(); + let git = GitRunner::for_cwd_io(root).expect("Git runner"); + let unsafe_config = root.join("command.gitconfig"); + std::fs::write(&unsafe_config, "").expect("write worktree config"); + let unsafe_args = vec![ + "-c".to_string(), + format!("include.path={}", unsafe_config.display()), + ]; + assert_worktree_rejection( + ensure_no_worktree_config_sources(&git, root, &unsafe_args) + .expect_err("command-scoped worktree include"), + ); + + let external = tempfile::NamedTempFile::new().expect("safe external config"); + let safe_args = vec![ + "-c".to_string(), + format!("include.path={}", external.path().display()), + ]; + ensure_no_worktree_config_sources(&git, root, &safe_args) + .expect("command-scoped external include"); + + let relative_args = vec![ + "-c".to_string(), + "include.path=relative.gitconfig".to_string(), + ]; + assert!( + ensure_no_worktree_config_sources(&git, root, &relative_args).is_err(), + "relative command includes must fail closed" + ); +} + +#[test] +fn rejects_every_duplicate_and_nested_include_target() { + for unsafe_first in [true, false] { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write unsafe config"); + let external = tempfile::NamedTempFile::new().expect("safe external config"); + let safe = external.path().to_str().expect("UTF-8 safe path"); + let values = if unsafe_first { + ["../driver-config", safe] + } else { + [safe, "../driver-config"] + }; + for value in values { + add_include(root, "include.path", value); + } + assert_worktree_rejection(guard(root).expect_err("duplicate include")); + } + + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write nested target"); + let external = tempfile::tempdir().expect("external config directory"); + let outer = external.path().join("outer.gitconfig"); + let nested = root.join("driver-config"); + run_success( + root, + &[ + "config", + "--file", + outer.to_str().expect("UTF-8 outer path"), + "include.path", + nested.to_str().expect("UTF-8 nested path"), + ], + ); + add_include( + root, + "include.path", + outer.to_str().expect("UTF-8 outer path"), + ); + assert_worktree_rejection(guard(root).expect_err("nested include")); +} + +#[cfg(unix)] +#[test] +fn rejects_symlink_aliases_across_the_worktree_and_metadata_boundaries() { + use std::os::unix::fs::symlink; + + let repo = init_repo(); + let root = repo.path(); + let external = tempfile::tempdir().expect("external directory"); + std::fs::write(external.path().join("safe.gitconfig"), "").expect("write safe config"); + symlink(external.path(), root.join("inside-link")).expect("inside to outside link"); + add_include(root, "include.path", "../inside-link/safe.gitconfig"); + assert_worktree_rejection(guard(root).expect_err("worktree symlink alias")); + + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write worktree target"); + let external = tempfile::tempdir().expect("external directory"); + symlink(root, external.path().join("outside-link")).expect("outside to inside link"); + add_include( + root, + "include.path", + external + .path() + .join("outside-link/driver-config") + .to_str() + .expect("UTF-8 alias path"), + ); + assert_worktree_rejection(guard(root).expect_err("external symlink alias")); + + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write escaped target"); + symlink(root, root.join(".git/config-link")).expect("metadata escape link"); + add_include(root, "include.path", "config-link/driver-config"); + assert_worktree_rejection(guard(root).expect_err("metadata symlink escape")); + + let repo = init_repo(); + let root = repo.path(); + let external = tempfile::tempdir().expect("external directory"); + symlink( + root.join("future-config"), + external.path().join("dangling-link"), + ) + .expect("dangling link into worktree"); + add_include( + root, + "include.path", + external + .path() + .join("dangling-link/config") + .to_str() + .expect("UTF-8 dangling alias"), + ); + assert_worktree_rejection(guard(root).expect_err("dangling symlink alias")); + + let repo = init_repo(); + let root = repo.path(); + let entry = tempfile::tempdir().expect("external entry directory"); + let exit = tempfile::tempdir().expect("external exit directory"); + std::fs::write(exit.path().join("safe.gitconfig"), "").expect("write exit config"); + symlink(root, entry.path().join("through-worktree")).expect("link into worktree"); + symlink(exit.path(), root.join("back-out")).expect("worktree-controlled exit link"); + add_include( + root, + "include.path", + entry + .path() + .join("through-worktree/back-out/safe.gitconfig") + .to_str() + .expect("UTF-8 nested alias"), + ); + assert_worktree_rejection(guard(root).expect_err("nested symlink traversal")); + + let repo = init_repo(); + let root = repo.path(); + let entry = tempfile::tempdir().expect("external entry directory"); + let exit = tempfile::tempdir().expect("external exit directory"); + std::fs::write(exit.path().join("safe.gitconfig"), "").expect("write chained config"); + symlink(exit.path(), root.join("workspace-link")).expect("workspace link out"); + symlink( + root.join("workspace-link"), + entry.path().join("direct-chain"), + ) + .expect("external link to workspace link"); + add_include( + root, + "include.path", + entry + .path() + .join("direct-chain/safe.gitconfig") + .to_str() + .expect("UTF-8 direct chain"), + ); + assert_worktree_rejection(guard(root).expect_err("direct symlink chain")); + + let repo = init_repo(); + let root = repo.path(); + std::fs::create_dir(root.join("subdir")).expect("create symlink target"); + std::fs::write(root.join("evil.gitconfig"), "[user]\nname = worktree\n") + .expect("write worktree config"); + std::fs::write( + root.join(".git/evil.gitconfig"), + "[user]\nname = metadata\n", + ) + .expect("write metadata decoy"); + symlink(root.join("subdir"), root.join(".git/link")).expect("metadata link to worktree"); + add_include(root, "include.path", "link/../evil.gitconfig"); + assert_worktree_rejection(guard(root).expect_err("symlink parent traversal")); + + let repo = init_repo(); + let root = repo.path(); + std::fs::create_dir(root.join("pivot")).expect("create worktree pivot"); + std::fs::write(root.join(".git/protected.gitconfig"), "") + .expect("write protected metadata config"); + add_include( + root, + "include.path", + root.join("pivot/../.git/protected.gitconfig") + .to_str() + .expect("UTF-8 pivot path"), + ); + assert_worktree_rejection(guard(root).expect_err("raw path pivots through worktree")); +} + +#[cfg(unix)] +#[test] +fn rejects_external_symlink_target_with_hidden_worktree_pivot_to_protected_config() { + use std::os::unix::fs::symlink; + + let repo = init_repo(); + let root = std::fs::canonicalize(repo.path()).expect("canonical repository"); + let external = tempfile::tempdir().expect("external alias directory"); + let protected = root.join(".git/protected.gitconfig"); + std::fs::write(&protected, "[codex]\n\tpivot = protected\n").expect("write protected config"); + std::fs::create_dir(root.join("pivot")).expect("create ordinary worktree pivot"); + let entry = external.path().join("entry"); + symlink(root.join("pivot/../.git/protected.gitconfig"), &entry) + .expect("external symlink target with raw worktree pivot"); + add_include( + &root, + "include.path", + entry.to_str().expect("UTF-8 entry path"), + ); + assert_eq!( + run_success(&root, &["config", "--includes", "--get", "codex.pivot"]), + "protected" + ); + assert_worktree_rejection( + guard(&root).expect_err("hidden pivot inside external symlink target"), + ); +} + +#[cfg(target_os = "macos")] +#[test] +fn rejects_apfs_alias_symlink_target_with_hidden_worktree_pivot() { + use std::os::unix::fs::symlink; + + let temp = std::fs::canonicalize(std::env::temp_dir()).expect("canonical temp directory"); + let parent = tempfile::tempdir_in(temp).expect("Data-volume fixture"); + let root = parent.path().join("repo"); + init_repo_at(&root); + let root = std::fs::canonicalize(root).expect("canonical repository"); + let data_alias = PathBuf::from("/System/Volumes/Data") + .join(root.strip_prefix("/").expect("absolute repository path")); + if std::fs::metadata(&data_alias).is_err() { + eprintln!("APFS Data alias unavailable; skipping native pivot assertion"); + return; + } + let protected = root.join(".git/protected.gitconfig"); + std::fs::write(&protected, "[codex]\n\tpivot = protected\n").expect("write protected config"); + std::fs::create_dir(root.join("pivot")).expect("create ordinary worktree pivot"); + let external = tempfile::tempdir().expect("external alias directory"); + let entry = external.path().join("entry"); + symlink(data_alias.join("pivot/../.git/protected.gitconfig"), &entry) + .expect("APFS alias target with raw worktree pivot"); + add_include( + &root, + "include.path", + entry.to_str().expect("UTF-8 entry path"), + ); + assert_eq!( + run_success(&root, &["config", "--includes", "--get", "codex.pivot"]), + "protected" + ); + assert_worktree_rejection(guard(&root).expect_err("APFS hidden pivot inside symlink target")); +} + +#[cfg(unix)] +#[test] +fn rejects_unregistered_same_common_worktree_used_only_as_alias_intermediate() { + use std::os::unix::fs::symlink; + + let parent = tempfile::tempdir().expect("fixture"); + let main = parent.path().join("main"); + let linked = parent.path().join("linked"); + let stale = parent.path().join("stale-unregistered"); + let external = parent.path().join("external"); + let safe = external.join("safe.gitconfig"); + let entry = external.join("entry"); + init_repo_at(&main); + run_success( + &main, + &[ + "worktree", + "add", + "-b", + "same-common-active", + linked.to_str().expect("UTF-8 linked path"), + ], + ); + std::fs::create_dir_all(&stale).expect("create stale worktree"); + std::fs::write( + stale.join(".git"), + format!("gitdir: {}\n", main.join(".git").display()), + ) + .expect("write stale same-common marker"); + std::fs::create_dir_all(&external).expect("create external directory"); + std::fs::write(&safe, "[codex]\n\tsameCommon = protected\n") + .expect("write external safe config"); + symlink(&safe, stale.join("switch")).expect("stale worktree controlled switch"); + symlink(stale.join("switch"), &entry).expect("external entry through stale worktree"); + add_include( + &linked, + "include.path", + entry.to_str().expect("UTF-8 entry path"), + ); + assert_eq!( + run_success( + &linked, + &["config", "--includes", "--get", "codex.sameCommon"] + ), + "protected" + ); + assert!( + guard(&linked).is_err(), + "unregistered same-common route intermediate must fail closed" + ); +} + +#[cfg(windows)] +#[test] +fn rejects_windows_junction_aliases_across_worktree_and_metadata_boundaries() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write worktree config"); + let external = tempfile::tempdir().expect("external directory"); + create_junction(&external.path().join("into-worktree"), root); + add_include( + root, + "include.path", + external + .path() + .join("into-worktree/driver-config") + .to_str() + .expect("UTF-8 junction path"), + ); + assert_worktree_rejection(guard(root).expect_err("external junction into worktree")); + + let repo = init_repo(); + let root = repo.path(); + let external = tempfile::tempdir().expect("external directory"); + std::fs::write(external.path().join("safe.gitconfig"), "").expect("write external config"); + create_junction(&root.join("out-of-worktree"), external.path()); + add_include(root, "include.path", "../out-of-worktree/safe.gitconfig"); + assert_worktree_rejection(guard(root).expect_err("worktree junction to external")); + + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write worktree config"); + create_junction(&root.join(".git/metadata-escape"), root); + add_include(root, "include.path", "metadata-escape/driver-config"); + assert_worktree_rejection(guard(root).expect_err("metadata junction escape")); + + let repo = init_repo(); + let root = repo.path(); + let entry = tempfile::tempdir().expect("external entry directory"); + let exit = tempfile::tempdir().expect("external exit directory"); + std::fs::write(exit.path().join("safe.gitconfig"), "").expect("write external config"); + create_junction(&entry.path().join("through-worktree"), root); + create_junction(&root.join("back-out"), exit.path()); + add_include( + root, + "include.path", + entry + .path() + .join("through-worktree/back-out/safe.gitconfig") + .to_str() + .expect("UTF-8 multi-hop junction path"), + ); + assert_worktree_rejection(guard(root).expect_err("multi-hop junction traversal")); + + let repo = init_repo(); + let root = repo.path(); + let external = tempfile::tempdir().expect("external directory"); + create_junction(&external.path().join("into-worktree"), root); + add_include( + root, + "include.path", + external + .path() + .join("into-worktree/future.gitconfig") + .to_str() + .expect("UTF-8 missing junction target"), + ); + assert_worktree_rejection(guard(root).expect_err("junction missing suffix")); +} + +#[test] +fn linked_worktree_metadata_is_allowed_but_linked_worktree_config_is_rejected() { + let parent = tempfile::tempdir().expect("worktree parent"); + let main = parent.path().join("main"); + let linked = parent.path().join("linked"); + init_repo_at(&main); + run_success( + &main, + &[ + "worktree", + "add", + "-b", + "config-guard-linked", + linked.to_str().expect("UTF-8 linked path"), + ], + ); + + let git_dir = PathBuf::from(run_success(&linked, &["rev-parse", "--absolute-git-dir"])); + let protected = git_dir.join("protected.gitconfig"); + std::fs::write(&protected, "[user]\nname = linked\n").expect("write linked metadata config"); + add_include( + &linked, + "include.path", + protected.to_str().expect("UTF-8 protected path"), + ); + guard(&linked).expect("linked metadata include"); + run_success(&linked, &["config", "--unset-all", "include.path"]); + + std::fs::write(main.join("driver-config"), "").expect("write main-worktree config"); + add_include( + &linked, + "include.path", + main.join("driver-config") + .to_str() + .expect("UTF-8 main-worktree config"), + ); + assert_worktree_rejection(guard(&linked).expect_err("main worktree include")); + run_success(&linked, &["config", "--unset-all", "include.path"]); + add_include( + &linked, + "include.path", + main.join("future.gitconfig") + .to_str() + .expect("UTF-8 missing main-worktree config"), + ); + assert_worktree_rejection(guard(&linked).expect_err("missing main worktree include")); + run_success(&linked, &["config", "--unset-all", "include.path"]); + + let unsafe_config = linked.join("driver-config"); + std::fs::write(&unsafe_config, "").expect("write linked worktree config"); + add_include( + &linked, + "include.path", + unsafe_config.to_str().expect("UTF-8 unsafe path"), + ); + assert_worktree_rejection(guard(&linked).expect_err("linked worktree include")); +} + +#[test] +fn enclosing_repository_sibling_worktrees_are_always_untrusted() { + let parent = tempfile::tempdir().expect("fixture parent"); + let outer = parent.path().join("outer"); + let sibling = parent.path().join("sibling"); + init_repo_at(&outer); + run_success( + &outer, + &[ + "worktree", + "add", + "-b", + "config-guard-sibling", + sibling.to_str().expect("UTF-8 sibling worktree"), + ], + ); + let nested = outer.join("nested"); + init_repo_at(&nested); + + std::fs::write(sibling.join("driver-config"), "").expect("write sibling config"); + add_include( + &nested, + "include.path", + sibling + .join("driver-config") + .to_str() + .expect("UTF-8 sibling config"), + ); + assert_worktree_rejection(guard(&nested).expect_err("enclosing repo sibling config")); + + run_success(&nested, &["config", "--unset-all", "include.path"]); + std::fs::remove_dir_all(&sibling).expect("remove sibling but retain registry entry"); + add_include( + &nested, + "include.path", + sibling + .join("future.gitconfig") + .to_str() + .expect("UTF-8 missing sibling config"), + ); + assert_worktree_rejection(guard(&nested).expect_err("missing enclosing repo sibling config")); + + let nested_primary = outer.join("inner-primary"); + let inner_linked = parent.path().join("inner-linked"); + init_repo_at(&nested_primary); + run_success( + &nested_primary, + &[ + "worktree", + "add", + "-b", + "inner-linked-from-outer", + inner_linked.to_str().expect("UTF-8 inner linked worktree"), + ], + ); + for candidate in [ + outer.join("outer.txt"), + outer.join("future-outer.gitconfig"), + ] { + if candidate.file_name() == Some(OsStr::new("outer.txt")) { + std::fs::write(&candidate, "").expect("write outer config source"); + } + add_include( + &inner_linked, + "include.path", + candidate.to_str().expect("UTF-8 outer config source"), + ); + assert_worktree_rejection( + guard(&inner_linked).expect_err("enclosing primary config source"), + ); + run_success(&inner_linked, &["config", "--unset-all", "include.path"]); + } + add_include( + &inner_linked, + "include.path", + sibling + .join("future-from-inner.gitconfig") + .to_str() + .expect("UTF-8 enclosing sibling source"), + ); + assert_worktree_rejection( + guard(&inner_linked).expect_err("enclosing sibling from linked inner worktree"), + ); + run_success(&inner_linked, &["config", "--unset-all", "include.path"]); +} + +#[cfg(unix)] +#[test] +fn preserves_symlinked_caller_ancestry_and_each_include_spelling() { + use std::os::unix::fs::symlink; + + let parent = tempfile::tempdir().expect("fixture parent"); + let outer = parent.path().join("outer"); + let nested = parent.path().join("external-nested"); + init_repo_at(&outer); + init_repo_at(&nested); + std::fs::write(outer.join("driver-config"), "").expect("write outer config"); + symlink(&nested, outer.join("nested-link")).expect("link nested cwd through outer repo"); + add_include( + &nested, + "include.path", + outer + .join("driver-config") + .to_str() + .expect("UTF-8 outer config"), + ); + let git = GitRunner::for_cwd_io(&outer.join("nested-link")) + .expect("Git runner from symlinked nested cwd"); + assert_worktree_rejection( + ensure_no_worktree_config_sources(&git, &nested, &[]) + .expect_err("logical outer ancestry config"), + ); + + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("driver-config"), "").expect("write unsafe child config"); + let external = tempfile::tempdir().expect("external include tree"); + let shared = external.path().join("shared.gitconfig"); + std::fs::write(&shared, "[include]\npath = child.gitconfig\n") + .expect("write shared parent config"); + let unsafe_dir = external.path().join("unsafe-spelling"); + let safe_dir = external.path().join("safe-spelling"); + std::fs::create_dir(&unsafe_dir).expect("create unsafe spelling directory"); + std::fs::create_dir(&safe_dir).expect("create safe spelling directory"); + symlink(&shared, unsafe_dir.join("parent.gitconfig")) + .expect("unsafe spelling of shared parent"); + symlink(&shared, safe_dir.join("parent.gitconfig")).expect("safe spelling of shared parent"); + symlink( + root.join("driver-config"), + unsafe_dir.join("child.gitconfig"), + ) + .expect("unsafe relative child"); + std::fs::write(safe_dir.join("child.gitconfig"), "").expect("safe relative child"); + add_include( + root, + "include.path", + unsafe_dir + .join("parent.gitconfig") + .to_str() + .expect("UTF-8 unsafe spelling"), + ); + add_include( + root, + "include.path", + safe_dir + .join("parent.gitconfig") + .to_str() + .expect("UTF-8 safe spelling"), + ); + assert_worktree_rejection(guard(root).expect_err("unsafe relative alias child")); + + let parent = tempfile::tempdir().expect("linked-main dangling fixture"); + let main = parent.path().join("main"); + let linked = parent.path().join("linked"); + init_repo_at(&main); + run_success( + &main, + &[ + "worktree", + "add", + "-b", + "config-guard-dangling-main", + linked.to_str().expect("UTF-8 linked worktree"), + ], + ); + let external = tempfile::tempdir().expect("external dangling alias directory"); + symlink( + main.join("future.gitconfig"), + external.path().join("dangling-main-config"), + ) + .expect("dangling alias into main worktree"); + add_include( + &linked, + "include.path", + external + .path() + .join("dangling-main-config") + .to_str() + .expect("UTF-8 dangling main alias"), + ); + assert_worktree_rejection(guard(&linked).expect_err("dangling alias into main worktree")); +} + +#[cfg(target_os = "macos")] +#[test] +fn rejects_apfs_data_firmlink_aliases_for_existing_and_missing_worktree_configs() { + let data_root = Path::new("/System/Volumes/Data"); + if !data_root.is_dir() { + return; + } + let home = PathBuf::from(std::env::var_os("HOME").expect("HOME")); + let temp_parent = home.join(".cache/codex-git-utils-tests"); + std::fs::create_dir_all(&temp_parent).expect("create test temp parent"); + + for exists in [true, false] { + let repo = tempfile::Builder::new() + .prefix("firmlink-config-") + .tempdir_in(&temp_parent) + .expect("home tempdir"); + let root = repo.path(); + init_repo_at(root); + if exists { + std::fs::write(root.join("driver-config"), "").expect("write aliased config"); + } + let alias = data_root + .join(root.strip_prefix("/").expect("absolute repository path")) + .join("driver-config"); + add_include( + root, + "include.path", + alias.to_str().expect("UTF-8 firmlink alias"), + ); + assert_worktree_rejection(guard(root).expect_err("APFS firmlink alias")); + } + + let family = tempfile::Builder::new() + .prefix("firmlink-linked-family-") + .tempdir_in(&temp_parent) + .expect("home linked-family tempdir"); + let main = family.path().join("main"); + let linked = family.path().join("linked"); + init_repo_at(&main); + run_success( + &main, + &[ + "worktree", + "add", + "-b", + "firmlink-linked-main", + linked.to_str().expect("UTF-8 linked path"), + ], + ); + for exists in [true, false] { + let name = if exists { + "driver-config" + } else { + "future.gitconfig" + }; + if exists { + std::fs::write(main.join(name), "").expect("write main config"); + } + let alias = data_root + .join(main.strip_prefix("/").expect("absolute main path")) + .join(name); + add_include( + &linked, + "include.path", + alias.to_str().expect("UTF-8 main firmlink alias"), + ); + assert_worktree_rejection(guard(&linked).expect_err("main firmlink alias")); + run_success(&linked, &["config", "--unset-all", "include.path"]); + } + std::fs::write(main.join(".git/protected.gitconfig"), "") + .expect("write protected main metadata config"); + let protected_alias = data_root + .join(main.strip_prefix("/").expect("absolute main path")) + .join(".git/protected.gitconfig"); + add_include( + &linked, + "include.path", + protected_alias + .to_str() + .expect("UTF-8 protected metadata alias"), + ); + guard(&linked).expect("protected metadata firmlink alias"); +} + +#[test] +fn include_path_expansion_supports_git_prefix() { + let repo = init_repo(); + let root = repo.path(); + let git = GitRunner::for_cwd_io(root).expect("Git runner"); + let prefix = + expand_git_config_path(&git, root, "%(prefix)/etc/gitconfig").expect("expand Git prefix"); + assert!(prefix.is_absolute()); +} + +#[cfg(unix)] +#[tokio::test] +async fn async_include_budget_stops_before_over_limit_expansion_launch() { + use std::os::unix::fs::PermissionsExt; + + let repo = init_repo(); + let external = tempfile::tempdir().expect("external include fixture"); + let fake_git = external.path().join("git"); + std::fs::write( + &fake_git, + "#!/bin/sh\n\ + printf 'launch\\n' >>\"$0.log\"\n\ + value=\n\ + for arg in \"$@\"; do\n\ + case \"$arg\" in\n\ + codex.config-source.path=*) value=${arg#codex.config-source.path=} ;;\n\ + esac\n\ + done\n\ + printf '%s\\0' \"$value\"\n", + ) + .expect("write fake Git"); + let mut permissions = std::fs::metadata(&fake_git) + .expect("stat fake Git") + .permissions(); + permissions.set_mode(0o700); + std::fs::set_permissions(&fake_git, permissions).expect("make fake Git executable"); + + let git = GitRunner::from_executable_for_test(repo.path(), fake_git.clone()) + .expect("authority-bound fake Git"); + let entries = (0..3) + .map(|index| GitConfigEntry { + scope: crate::git_config::GitConfigScope::Command, + origin: crate::git_config::GitConfigOrigin::CommandLine, + key: "include.path".to_string(), + value: external + .path() + .join(format!("include-{index}.gitconfig")) + .to_string_lossy() + .into_owned(), + }) + .collect(); + let mut pending = Vec::new(); + let mut budget = IncludeGraphBudget::with_limit(2); + + let error = validate_include_entries_async( + &git, + repo.path(), + entries, + /*depth*/ 1, + &mut pending, + &mut budget, + ) + .await + .expect_err("third include must exceed the traversal budget"); + + assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error}"); + assert!( + error.to_string().contains("too many Git config includes"), + "{error}" + ); + assert_eq!(pending.len(), 2); + let launches = + std::fs::read_to_string(fake_git.with_extension("log")).expect("read fake Git launch log"); + assert_eq!(launches.lines().count(), 2, "{launches}"); +} + +#[cfg(not(windows))] +#[test] +fn include_path_expansion_preserves_colon_parentheses_as_literal_text() { + let repo = init_repo(); + let root = repo.path(); + let git = GitRunner::for_cwd_io(root).expect("Git runner"); + let optional = GitConfigEntry { + scope: crate::git_config::GitConfigScope::Local, + origin: crate::git_config::GitConfigOrigin::File(".git/config".into()), + key: "include.path".to_string(), + value: ":(optional)../future.gitconfig".to_string(), + }; + let optional_path = resolve_include_path(&git, root, &optional).expect("resolve optional path"); + assert_eq!( + AbsolutePathBuf::resolve_path_against_base(optional_path, root).as_path(), + root.join(".git/:(optional)../future.gitconfig") + ); + + let unknown = GitConfigEntry { + value: ":(unknown)../future.gitconfig".to_string(), + ..optional + }; + let unknown_path = + resolve_include_path(&git, root, &unknown).expect("resolve literal unknown path"); + assert_eq!( + AbsolutePathBuf::resolve_path_against_base(unknown_path, root).as_path(), + root.join(".git/:(unknown)../future.gitconfig") + ); + + for spelling in [":(optional)", ":(unknown)"] { + let external = tempfile::tempdir().expect("external literal config directory"); + let literal_dir = external.path().join(spelling); + std::fs::create_dir(&literal_dir).expect("create literal include directory"); + std::fs::write(literal_dir.join("child"), "[probe]\nvalue = literal\n") + .expect("write literal include child"); + let parent = external.path().join("parent.gitconfig"); + std::fs::write(&parent, format!("[include]\npath = {spelling}/child\n")) + .expect("write literal parent config"); + let value = run_success( + root, + &[ + "config", + "--file", + parent.to_str().expect("UTF-8 parent path"), + "--includes", + "--get", + "probe.value", + ], + ); + assert_eq!(value, "literal"); + add_include( + root, + "include.path", + parent.to_str().expect("UTF-8 parent path"), + ); + guard(root).expect("literal include path is external"); + run_success(root, &["config", "--unset-all", "include.path"]); + } +} + +#[test] +fn windows_path_validator_rejects_namespaces_streams_and_alias_components() { + for path in [ + r"\??\C:\repo\config", + r"\\?\GLOBALROOT\Device\config", + r"\\.\pipe\config", + r"C:\repo\config:stream", + r"C:relative\config", + r":(optional)..\future.gitconfig", + r":(unknown)..\future.gitconfig", + r"C:\repo\NUL.gitconfig", + r"C:\repo\COM¹.gitconfig", + r"C:\repo\LPT³.gitconfig", + r"C:\repo\trailing.\config", + ] { + assert!(windows_config_path_is_ambiguous(path), "{path:?}"); + } + for path in [ + r"C:\external\config", + r"\\server\share\config", + r"\\?\C:\repo\.git\config", + r"\\.\C:\repo\.git\config", + r"\\?\UNC\server\share\config", + r"\\.\UNC\server\share\config", + r"..\driver-config", + r".\driver-config", + ] { + assert!(!windows_config_path_is_ambiguous(path), "{path:?}"); + } +} diff --git a/codex-rs/git-utils/src/git_config_tests.rs b/codex-rs/git-utils/src/git_config_tests.rs index 0e2bae1a8a..77a055997a 100644 --- a/codex-rs/git-utils/src/git_config_tests.rs +++ b/codex-rs/git-utils/src/git_config_tests.rs @@ -12,7 +12,7 @@ command\0command line:\0merge.Name.driver\nhelper %A %B\0"; entries.get("filter.demo.clean"), Some(&GitConfigEntry { scope: GitConfigScope::Local, - origin: "file:/repo/.git/config".to_string(), + origin: GitConfigOrigin::File("/repo/.git/config".into()), key: "filter.demo.clean".to_string(), value: String::new(), }) @@ -21,13 +21,56 @@ command\0command line:\0merge.Name.driver\nhelper %A %B\0"; entries.get("merge.Name.driver"), Some(&GitConfigEntry { scope: GitConfigScope::Command, - origin: "command line:".to_string(), + origin: GitConfigOrigin::CommandLine, key: "merge.Name.driver".to_string(), value: "helper %A %B".to_string(), }) ); } +#[test] +fn entry_parsers_preserve_duplicate_include_directives_in_order() { + let scoped = b"local\0file:.git/config\0include.path\n../unsafe.gitconfig\0\ +local\0file:.git/config\0include.path\n/absolute/external.gitconfig\0"; + let legacy = b"file:.git/config\0include.path\n../unsafe.gitconfig\0\ +file:.git/config\0include.path\n/absolute/external.gitconfig\0"; + let expected_scoped = vec![ + GitConfigEntry { + scope: GitConfigScope::Local, + origin: GitConfigOrigin::File(".git/config".into()), + key: "include.path".to_string(), + value: "../unsafe.gitconfig".to_string(), + }, + GitConfigEntry { + scope: GitConfigScope::Local, + origin: GitConfigOrigin::File(".git/config".into()), + key: "include.path".to_string(), + value: "/absolute/external.gitconfig".to_string(), + }, + ]; + assert_eq!( + parse_config_entries(scoped).expect("scoped entries"), + expected_scoped + ); + assert_eq!( + parse_config_entries_with_origins(legacy).expect("legacy entries"), + expected_scoped + ); +} + +#[cfg(unix)] +#[test] +fn config_origin_parser_preserves_non_utf8_unix_path_bytes() { + use std::os::unix::ffi::OsStrExt; + + let entries = parse_config_entries(b"local\0file:/tmp/config-\xff\0include.path\n/tmp/safe\0") + .expect("non-UTF-8 config origin"); + let GitConfigOrigin::File(path) = &entries[0].origin else { + panic!("expected file origin"); + }; + assert_eq!(path.as_os_str().as_bytes(), b"/tmp/config-\xff"); +} + #[test] fn rejects_malformed_config_records() { for output in [ @@ -51,7 +94,7 @@ command line:\0merge.Name.driver\nhelper %A %B\0"; entries.get("filter.demo.clean"), Some(&GitConfigEntry { scope: GitConfigScope::Local, - origin: "file:/repo/.git/config".to_string(), + origin: GitConfigOrigin::File("/repo/.git/config".into()), key: "filter.demo.clean".to_string(), value: String::new(), }) @@ -60,7 +103,7 @@ command line:\0merge.Name.driver\nhelper %A %B\0"; entries.get("merge.Name.driver"), Some(&GitConfigEntry { scope: GitConfigScope::Command, - origin: "command line:".to_string(), + origin: GitConfigOrigin::CommandLine, key: "merge.Name.driver".to_string(), value: "helper %A %B".to_string(), }) diff --git a/codex-rs/git-utils/src/git_executable.rs b/codex-rs/git-utils/src/git_executable.rs new file mode 100644 index 0000000000..656ff1254e --- /dev/null +++ b/codex-rs/git-utils/src/git_executable.rs @@ -0,0 +1,292 @@ +use std::ffi::OsStr; +use std::ffi::OsString; +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use crate::errors::GitReadError; +use crate::repository_authority::RepositoryAuthority; +#[cfg(windows)] +use std::path::Component; +#[cfg(windows)] +use std::path::Prefix; + +pub(crate) struct SelectedGitExecutable { + pub(crate) executable: PathBuf, + #[cfg(any(unix, test))] + pub(crate) argv0: PathBuf, + pub(crate) safe_path: OsString, +} + +pub(crate) fn select_git_executable( + authority: &RepositoryAuthority, + search_path: &OsStr, +) -> Result { + let mut safe_directories = Vec::new(); + let mut selected = None; + for directory in std::env::split_paths(search_path) { + if !directory.is_absolute() || search_directory_is_untrusted(&directory, authority) { + continue; + } + let Ok(canonical_directory) = std::fs::canonicalize(&directory) else { + continue; + }; + if path_is_untrusted(&canonical_directory, authority) + || !std::fs::metadata(&canonical_directory).is_ok_and(|metadata| metadata.is_dir()) + { + continue; + } + push_unique_path(&mut safe_directories, canonical_directory); + + if selected.is_some() { + continue; + } + let candidate = directory.join(git_executable_name()); + if path_is_untrusted(&candidate, authority) { + continue; + } + let Ok(canonical_candidate) = std::fs::canonicalize(&candidate) else { + continue; + }; + if path_is_untrusted(&canonical_candidate, authority) + || !is_native_executable_file(&canonical_candidate) + { + continue; + } + if let Some(parent) = canonical_candidate.parent() { + push_unique_path(&mut safe_directories, parent.to_path_buf()); + } + #[cfg(any(unix, test))] + let selected_candidate = (canonical_candidate, candidate); + #[cfg(not(any(unix, test)))] + let selected_candidate = canonical_candidate; + selected = Some(selected_candidate); + } + #[cfg(any(unix, test))] + let (executable, argv0) = selected.ok_or(GitReadError::NoTrustedGit)?; + #[cfg(not(any(unix, test)))] + let executable = selected.ok_or(GitReadError::NoTrustedGit)?; + let safe_path = + std::env::join_paths(safe_directories).map_err(|_| GitReadError::NoTrustedGit)?; + Ok(SelectedGitExecutable { + executable, + #[cfg(any(unix, test))] + argv0, + safe_path, + }) +} + +pub(crate) fn harden_git_launch_environment( + command: &mut std::process::Command, + safe_path: &OsStr, +) { + let mut names = std::env::vars_os() + .map(|(name, _)| name) + .filter(|name| startup_injection_variable(name)) + .collect::>(); + names.extend( + command + .get_envs() + .filter(|&(name, _)| startup_injection_variable(name)) + .map(|(name, _)| name.to_os_string()), + ); + for name in names { + command.env_remove(name); + } + command.env("PATH", safe_path); + #[cfg(windows)] + command.env("NoDefaultCurrentDirectoryInExePath", "1"); +} + +fn startup_injection_variable(name: &OsStr) -> bool { + let name = name.to_string_lossy().to_ascii_uppercase(); + name.starts_with("DYLD_") + || name.starts_with("LD_") + || name == "LIBPATH" + || name == "SHLIB_PATH" + || name.starts_with("CORECLR_") + || name.starts_with("COR_") + || name.starts_with("DOTNET_") + || name == "GCONV_PATH" + || name == "NIX_LD" + || name == "NIX_LD_LIBRARY_PATH" +} + +pub(crate) fn path_is_untrusted(path: &Path, authority: &RepositoryAuthority) -> bool { + authority.path_is_untrusted_for_executable(path) +} + +pub(crate) fn search_directory_is_untrusted( + directory: &Path, + authority: &RepositoryAuthority, +) -> bool { + #[cfg(windows)] + if windows_path_requires_fail_closed(directory) + || windows_path_has_untrusted_canonical_ancestor(directory, authority) + { + return true; + } + path_is_untrusted(directory, authority) +} + +fn push_unique_path(paths: &mut Vec, path: PathBuf) { + if !paths.iter().any(|existing| existing == &path) { + paths.push(path); + } +} + +#[cfg(windows)] +pub(crate) fn windows_path_requires_fail_closed(path: &Path) -> bool { + let mut components = path.components(); + let supported_namespace = match components.next() { + Some(Component::Prefix(prefix)) => match prefix.kind() { + Prefix::Disk(_) + | Prefix::VerbatimDisk(_) + | Prefix::UNC(_, _) + | Prefix::VerbatimUNC(_, _) => true, + Prefix::DeviceNS(device) => windows_device_namespace_is_filesystem(device), + Prefix::Verbatim(namespace) => namespace + .to_str() + .is_some_and(|namespace| namespace.eq_ignore_ascii_case("UNC")), + }, + _ => false, + }; + !supported_namespace || components.any(|component| matches!(component, Component::ParentDir)) +} + +#[cfg(windows)] +fn windows_device_namespace_is_filesystem(device: &OsStr) -> bool { + let bytes = device.as_encoded_bytes(); + bytes.eq_ignore_ascii_case(b"UNC") + || matches!(bytes, [drive, b':'] if drive.is_ascii_alphabetic()) +} + +#[cfg(windows)] +fn windows_path_has_untrusted_canonical_ancestor( + path: &Path, + authority: &RepositoryAuthority, +) -> bool { + let Ok(canonical_path) = std::fs::canonicalize(path) else { + return true; + }; + if path_is_untrusted(&canonical_path, authority) { + return true; + } + for ancestor in path.ancestors().skip(1) { + let canonical_ancestor = match std::fs::canonicalize(ancestor) { + Ok(canonical_ancestor) => canonical_ancestor, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::InvalidInput + ) => + { + continue; + } + Err(_) => return true, + }; + if path_is_untrusted(&canonical_ancestor, authority) { + return true; + } + } + false +} + +#[cfg(windows)] +pub(crate) fn git_executable_name() -> &'static str { + "git.exe" +} + +#[cfg(not(windows))] +pub(crate) fn git_executable_name() -> &'static str { + "git" +} + +#[cfg(target_os = "macos")] +pub(crate) fn is_native_executable_file(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + + let Ok(metadata) = std::fs::metadata(path) else { + return false; + }; + if !metadata.is_file() || metadata.permissions().mode() & 0o111 == 0 { + return false; + } + let Ok(bytes) = read_prefix(path, /*length*/ 4) else { + return false; + }; + matches!( + bytes.as_slice(), + [0xfe, 0xed, 0xfa, 0xce] + | [0xfe, 0xed, 0xfa, 0xcf] + | [0xce, 0xfa, 0xed, 0xfe] + | [0xcf, 0xfa, 0xed, 0xfe] + | [0xca, 0xfe, 0xba, 0xbe] + | [0xbe, 0xba, 0xfe, 0xca] + | [0xca, 0xfe, 0xba, 0xbf] + | [0xbf, 0xba, 0xfe, 0xca] + ) +} + +#[cfg(all(unix, not(target_os = "macos")))] +pub(crate) fn is_native_executable_file(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + + let Ok(metadata) = std::fs::metadata(path) else { + return false; + }; + metadata.is_file() + && metadata.permissions().mode() & 0o111 != 0 + && read_prefix(path, /*length*/ 4).is_ok_and(|bytes| bytes == b"\x7fELF") +} + +#[cfg(windows)] +pub(crate) fn is_native_executable_file(path: &Path) -> bool { + use std::io::Read; + use std::io::Seek; + use std::io::SeekFrom; + + if !path + .extension() + .and_then(OsStr::to_str) + .is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) + { + return false; + } + let Ok(metadata) = std::fs::metadata(path) else { + return false; + }; + if !metadata.is_file() || metadata.len() < 68 { + return false; + } + let Ok(mut file) = std::fs::File::open(path) else { + return false; + }; + let mut dos = [0_u8; 64]; + if file.read_exact(&mut dos).is_err() || &dos[..2] != b"MZ" { + return false; + } + let offset = u32::from_le_bytes([dos[60], dos[61], dos[62], dos[63]]) as u64; + if offset > 1024 * 1024 || offset + 4 > metadata.len() { + return false; + } + let mut signature = [0_u8; 4]; + file.seek(SeekFrom::Start(offset)).is_ok() + && file.read_exact(&mut signature).is_ok() + && signature == *b"PE\0\0" +} + +#[cfg(not(any(unix, windows)))] +pub(crate) fn is_native_executable_file(_path: &Path) -> bool { + false +} + +#[cfg(unix)] +fn read_prefix(path: &Path, length: usize) -> io::Result> { + use std::io::Read; + + let mut file = std::fs::File::open(path)?; + let mut bytes = vec![0; length]; + file.read_exact(&mut bytes)?; + Ok(bytes) +} diff --git a/codex-rs/git-utils/src/info.rs b/codex-rs/git-utils/src/info.rs index 1a24d9f9a6..ed01289d85 100644 --- a/codex-rs/git-utils/src/info.rs +++ b/codex-rs/git-utils/src/info.rs @@ -3,6 +3,8 @@ use std::collections::HashSet; use std::ffi::OsStr; use std::path::Path; use std::path::PathBuf; +use std::sync::atomic::AtomicU8; +use std::sync::atomic::Ordering; use codex_file_system::ExecutorFileSystem; use codex_file_system::FindUpErrorPolicy; @@ -19,9 +21,11 @@ use ts_rs::TS; use crate::GitReadError; use crate::GitSha; use crate::git_command::GitRunner; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; +use crate::repository_authority::is_authority_refusal; use crate::safe_git::DISABLED_HOOKS_PATH; use crate::safe_git::GIT_COMMAND_TIMEOUT; -use crate::status_guard::selected_executable_filter_from; +use crate::status_guard::prepare_status_filter_guard_within_deadline; /// Return `true` if the project folder specified by the `Config` is inside a /// Git repository. @@ -292,19 +296,67 @@ pub async fn get_has_changes(cwd: &Path) -> Option { } pub async fn try_get_has_changes(cwd: &Path) -> Result { - let git = GitRunner::for_cwd(cwd)?; - if let Some((driver, path)) = selected_executable_filter_from(&git, cwd).await? { - return Err(GitReadError::SelectedExecutableFilter { - driver, - path: String::from_utf8_lossy(&path).into_owned(), - }); + // One deadline covers preparation, fsmonitor detection, and final status. + // It cancels active Git children through the runner's kill-on-drop handle; + // synchronous filesystem authority checks are not preemptible mid-call. + let phase = AtomicU8::new(StatusReadPhase::Preparation as u8); + match timeout( + GIT_COMMAND_TIMEOUT, + Box::pin(try_get_has_changes_within_deadline(cwd, &phase)), + ) + .await + { + Ok(result) => result, + Err(_) => Err(GitReadError::CommandTimedOut { + operation: StatusReadPhase::from_u8(phase.load(Ordering::Relaxed)) + .operation() + .to_string(), + }), } - let fsmonitor = detect_local_fsmonitor_override(&git, cwd).await; +} + +#[derive(Clone, Copy)] +#[repr(u8)] +enum StatusReadPhase { + Preparation, + Fsmonitor, + Status, +} + +impl StatusReadPhase { + fn from_u8(value: u8) -> Self { + match value { + value if value == Self::Fsmonitor as u8 => Self::Fsmonitor, + value if value == Self::Status as u8 => Self::Status, + _ => Self::Preparation, + } + } + + fn operation(self) -> &'static str { + match self { + Self::Preparation => "statusFilterPreparation", + Self::Fsmonitor => "statusFsmonitor", + Self::Status => "status", + } + } +} + +async fn try_get_has_changes_within_deadline( + cwd: &Path, + phase: &AtomicU8, +) -> Result { + let git = GitRunner::for_cwd(cwd)?; + let (git_root, filter_guard) = + Box::pin(prepare_status_filter_guard_within_deadline(&git, cwd)).await?; + phase.store(StatusReadPhase::Fsmonitor as u8, Ordering::Relaxed); + let fsmonitor = detect_local_fsmonitor_override(&git, &git_root).await; + phase.store(StatusReadPhase::Status as u8, Ordering::Relaxed); let output = try_run_git_command_with_timeout_from( &git, &["status", "--porcelain", "--ignore-submodules=dirty"], - cwd, + &git_root, fsmonitor, + filter_guard.git_config_args(), "status", ) .await?; @@ -436,9 +488,15 @@ impl crate::FsmonitorProbeRunner for LocalFsmonitorProbeRunner<'_> { async fn run_probe(&mut self, args: &[&str]) -> Option> { // Both probes are fast, bounded metadata queries that do not inspect the // worktree or index, so do not reduce the requested command's timeout. - let mut command = self.git.tokio_command(); - command.args(args).current_dir(self.cwd).kill_on_drop(true); - match timeout(GIT_COMMAND_TIMEOUT, self.git.output_tokio(command)).await { + let mut command = self.git.async_command_for_cwd(self.cwd).ok()?; + command.args(args); + match timeout( + GIT_COMMAND_TIMEOUT, + self.git + .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES), + ) + .await + { Ok(Ok(output)) if output.status.success() => Some(output.stdout), _ => None, } @@ -456,7 +514,7 @@ async fn run_git_command_with_timeout_from( cwd: &Path, fsmonitor: crate::FsmonitorOverride, ) -> Option { - try_run_git_command_with_timeout_from(git, args, cwd, fsmonitor, "gitMetadata") + try_run_git_command_with_timeout_from(git, args, cwd, fsmonitor, &[], "gitMetadata") .await .ok() } @@ -466,25 +524,52 @@ async fn try_run_git_command_with_timeout_from( args: &[&str], cwd: &Path, fsmonitor: crate::FsmonitorOverride, + extra_git_config_args: &[String], operation: &str, ) -> Result { let disabled_hooks = format!("core.hooksPath={DISABLED_HOOKS_PATH}"); - let mut command = git.tokio_command(); + let mut command = git.async_command_for_cwd(cwd).map_err(|error| { + if is_authority_refusal(&error) { + return GitReadError::AuthorityRefused { + operation: operation.to_string(), + }; + } + match error.kind() { + std::io::ErrorKind::InvalidData => GitReadError::InvalidOutput { + operation: operation.to_string(), + }, + _ => GitReadError::CommandFailed { + operation: operation.to_string(), + exit_code: None, + }, + } + })?; command .env("GIT_OPTIONAL_LOCKS", "0") // Keep internal Git commands independent of repository-selected hooks // while preserving built-in fsmonitor acceleration. .args(["-c", &disabled_hooks]) .args(["-c", fsmonitor.git_config_arg()]) - .args(args) - .current_dir(cwd) - .kill_on_drop(true); - match timeout(GIT_COMMAND_TIMEOUT, git.output_tokio(command)).await { + // Keep the owning guard alive in the caller and append its private + // include last so it wins inherited and repository filter config. + .args(extra_git_config_args) + .args(args); + match timeout( + GIT_COMMAND_TIMEOUT, + git.output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES), + ) + .await + { Err(_) => Err(GitReadError::CommandTimedOut { operation: operation.to_string(), }), - Ok(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => { - Err(GitReadError::NoTrustedGit) + Ok(Err(error)) if is_authority_refusal(&error) => Err(GitReadError::AuthorityRefused { + operation: operation.to_string(), + }), + Ok(Err(error)) if error.kind() == std::io::ErrorKind::InvalidData => { + Err(GitReadError::InvalidOutput { + operation: operation.to_string(), + }) } Ok(Err(_)) => Err(GitReadError::CommandFailed { operation: operation.to_string(), @@ -938,6 +1023,7 @@ pub async fn current_branch_name(cwd: &Path) -> Option { #[cfg(test)] mod tests { use super::*; + use pretty_assertions::assert_eq; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; @@ -966,6 +1052,25 @@ mod tests { .to_string() } + #[cfg(unix)] + fn resolved_git_executable() -> PathBuf { + let output = std::process::Command::new("/bin/sh") + .args(["-c", "command -v git"]) + .output() + .expect("resolve real Git executable"); + assert!(output.status.success(), "resolve real Git executable"); + PathBuf::from( + String::from_utf8(output.stdout) + .expect("real Git path should be UTF-8") + .trim(), + ) + } + + #[cfg(unix)] + fn shell_quote_path(path: &Path) -> String { + format!("'{}'", path.to_string_lossy().replace('\'', "'\\''")) + } + #[cfg(unix)] fn commit_all(cwd: &Path, message: &str) { run_git( @@ -1097,11 +1202,18 @@ mod tests { #[tokio::test] async fn fsmonitor_override_rejects_configured_helper() { let temp_dir = tempfile::tempdir().expect("create temp dir"); + let init_status = std::process::Command::new("git") + .args(["init", "-q"]) + .current_dir(temp_dir.path()) + .status() + .expect("initialize test repository"); + assert_eq!(init_status.code(), Some(0), "initialize test repository"); let git = temp_dir.path().join("git"); let log = temp_dir.path().join("git.log"); std::fs::write( &git, "#!/bin/sh\n\ + if [ \"$1\" = -C ]; then shift 2; fi\n\ printf '%s\\n' \"$*\" >>\"$0.log\"\n\ case \"$1\" in\n\ config) printf '/tmp/fsmonitor-helper\\000' ;;\n\ @@ -1118,7 +1230,8 @@ mod tests { // The config response mirrors: // git -c core.fsmonitor=/tmp/fsmonitor-helper \ // config --null --get core.fsmonitor - let git = GitRunner::from_executable_for_test(git); + let git = GitRunner::from_executable_for_test(temp_dir.path(), git) + .expect("authority-bound fake Git"); let fsmonitor = detect_local_fsmonitor_override(&git, temp_dir.path()).await; let output = run_git_command_with_timeout_from( &git, @@ -1165,17 +1278,22 @@ mod tests { let git = temp_dir.path().join("git"); let global_config = temp_dir.path().join("git.global"); let log = temp_dir.path().join("git.log"); + let real_git = shell_quote_path(&resolved_git_executable()); std::fs::write( &git, - "#!/bin/sh\n\ + format!( + "#!/bin/sh\n\ + cwd=.\n\ + if [ \"$1\" = -C ]; then cwd=$2; shift 2; fi\n\ printf '%s\\n' \"$*\" >>\"$0.log\"\n\ case \"$1\" in\n\ config)\n\ - GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=\"$0.global\" exec git \"$@\"\n\ + GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=\"$0.global\" exec {real_git} -C \"$cwd\" \"$@\"\n\ ;;\n\ version) printf 'feature: fsmonitor--daemon\\n' ;;\n\ *) printf 'worktree output\\n' ;;\n\ - esac\n", + esac\n" + ), ) .expect("write layered-config Git"); let mut permissions = std::fs::metadata(&git) @@ -1210,7 +1328,8 @@ mod tests { "write local built-in fsmonitor config" ); - let git = GitRunner::from_executable_for_test(git); + let git = + GitRunner::from_executable_for_test(&repo, git).expect("authority-bound layered Git"); let fsmonitor = detect_local_fsmonitor_override(&git, repo.as_path()).await; let output = run_git_command_with_timeout_from( &git, diff --git a/codex-rs/git-utils/src/lib.rs b/codex-rs/git-utils/src/lib.rs index ff8c432da8..63d01dfe8d 100644 --- a/codex-rs/git-utils/src/lib.rs +++ b/codex-rs/git-utils/src/lib.rs @@ -9,12 +9,16 @@ mod exact_staging; mod fsmonitor; mod git_command; mod git_config; +mod git_config_sources; +mod git_executable; mod info; mod local_only; mod merge_driver; mod operations; mod patch_paths; +mod path_authority; mod platform; +mod repository_authority; mod reverse_staging; mod safe_git; mod status_guard; diff --git a/codex-rs/git-utils/src/merge_driver.rs b/codex-rs/git-utils/src/merge_driver.rs index 265fd6c9a8..5120f321aa 100644 --- a/codex-rs/git-utils/src/merge_driver.rs +++ b/codex-rs/git-utils/src/merge_driver.rs @@ -81,12 +81,11 @@ fn read_merge_attributes( } input.rewind()?; - let mut command = git.command(); + let mut command = git.command_for_cwd(cwd)?; command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) .args(["check-attr", "--stdin", "-z", "merge"]) - .current_dir(cwd) .stdin(Stdio::from(input)); let output = git.output(command)?; if !output.status.success() { diff --git a/codex-rs/git-utils/src/merge_driver_race_tests.rs b/codex-rs/git-utils/src/merge_driver_race_tests.rs index 3ef1b8b265..4d43b9ed36 100644 --- a/codex-rs/git-utils/src/merge_driver_race_tests.rs +++ b/codex-rs/git-utils/src/merge_driver_race_tests.rs @@ -34,6 +34,22 @@ fn run_success(cwd: &Path, args: &[&str]) -> String { stdout } +fn run_success_with_apply_config(cwd: &Path, args: &[&str]) -> String { + let mut configured_args = crate::apply::configured_git_config_parts(); + configured_args.extend(args.iter().map(ToString::to_string)); + let configured_args = configured_args + .iter() + .map(String::as_str) + .collect::>(); + run_success(cwd, &configured_args) +} + +fn read_file_normalized(path: &Path) -> String { + std::fs::read_to_string(path) + .expect("read file") + .replace("\r\n", "\n") +} + fn init_repo() -> tempfile::TempDir { let repo = tempfile::tempdir().expect("repo tempdir"); let root = repo.path(); @@ -191,12 +207,9 @@ fn clean_reverse_checks_worktree_before_staging_and_skips_merge_driver() { assert_eq!(result.applied_paths, vec!["file.txt"]); assert!(result.cmd_for_log.contains("--index")); assert!(!result.cmd_for_log.contains("--3way")); - assert_eq!( - std::fs::read_to_string(root.join("file.txt")).expect("read restored file"), - "old\n" - ); + assert_eq!(read_file_normalized(&root.join("file.txt")), "old\n"); assert!(!configured_marker_exists(root, "codex.oldmergeran")); - assert!(run_success(root, &["status", "--porcelain"]).is_empty()); + assert!(run_success_with_apply_config(root, &["status", "--porcelain"]).is_empty()); } #[derive(Clone, Copy, Debug)] @@ -245,14 +258,14 @@ fn clean_reverse_stages_missing_delete_and_rename_endpoints() { assert!(result.cmd_for_log.contains("--index"), "{topology:?}"); assert!(!result.cmd_for_log.contains("--3way"), "{topology:?}"); assert_eq!( - std::fs::read_to_string(root.join("old.txt")).expect("restored old file"), + read_file_normalized(&root.join("old.txt")), "old\n", "{topology:?}" ); assert!(!root.join("new.txt").exists(), "{topology:?}"); assert!(!configured_marker_exists(root, "codex.oldmergeran")); assert!( - run_success(root, &["status", "--porcelain"]).is_empty(), + run_success_with_apply_config(root, &["status", "--porcelain"]).is_empty(), "{topology:?}" ); } @@ -283,7 +296,7 @@ fn selected_empty_and_equals_named_drivers_reject_without_marker_or_index_mutati before_contents, "{driver:?}" ); - assert!(run_success(root, &["status", "--porcelain"]).is_empty()); + assert!(run_success_with_apply_config(root, &["status", "--porcelain"]).is_empty()); } } diff --git a/codex-rs/git-utils/src/merge_driver_tests.rs b/codex-rs/git-utils/src/merge_driver_tests.rs index df1c0016b1..5e67af5927 100644 --- a/codex-rs/git-utils/src/merge_driver_tests.rs +++ b/codex-rs/git-utils/src/merge_driver_tests.rs @@ -1,6 +1,7 @@ use super::*; use crate::apply::ApplyGitRequest; use crate::apply::apply_git_patch; +use crate::git_config::GitConfigOrigin; use crate::git_config::GitConfigScope; use std::ffi::OsStr; @@ -43,7 +44,9 @@ fn apply_allows_unused_global_merge_driver() { .expect("allow unrelated global merge driver"); assert_eq!(result.exit_code, 0); assert_eq!( - std::fs::read_to_string(root.join("file.txt")).expect("read file"), + std::fs::read_to_string(root.join("file.txt")) + .expect("read file") + .replace("\r\n", "\n"), "new\n" ); let (marker_code, _, _) = run(root, &["git", "config", "--get", "codex.mergeran"]); @@ -124,7 +127,7 @@ fn apply_rejects_global_merge_driver_before_three_way() { std::fs::read_to_string(root.join("file.txt")).expect("read ours"), "ours\n" ); - let (status_code, status, status_err) = run(root, &["git", "status", "--porcelain"]); + let (status_code, status, status_err) = status_with_apply_config(root); assert_eq!(status_code, 0, "status: {status_err}"); assert!(status.is_empty(), "worktree/index changed: {status}"); } @@ -220,7 +223,7 @@ fn apply_allows_clean_patch_with_selected_merge_driver() { ); let (marker_code, _, _) = run(root, &["git", "config", "--get", "codex.mergeran"]); assert_ne!(marker_code, 0, "merge driver must not run"); - let (status_code, status, status_err) = run(root, &["git", "status", "--porcelain"]); + let (status_code, status, status_err) = status_with_apply_config(root); assert_eq!(status_code, 0, "status: {status_err}"); assert_eq!( status.trim(), @@ -282,7 +285,7 @@ fn reverse_apply_allows_clean_patch_with_selected_merge_driver() { ); let (marker_code, _, _) = run(root, &["git", "config", "--get", "codex.mergeran"]); assert_ne!(marker_code, 0, "merge driver must not run"); - let (status_code, status, status_err) = run(root, &["git", "status", "--porcelain"]); + let (status_code, status, status_err) = status_with_apply_config(root); assert_eq!(status_code, 0, "status: {status_err}"); assert!( status.is_empty(), @@ -512,7 +515,7 @@ fn config_entries(values: [(&str, &str); N]) -> BTreeMap (i32, String, String) { ) } +fn status_with_apply_config(cwd: &Path) -> (i32, String, String) { + let mut args = vec!["git".to_string()]; + args.extend(crate::apply::configured_git_config_parts()); + args.extend(["status".to_string(), "--porcelain".to_string()]); + let args = args.iter().map(String::as_str).collect::>(); + run(cwd, &args) +} + fn run_isolated_merge_test(test_name: &str, env: &[(&str, &OsStr)]) { let mut command = std::process::Command::new(std::env::current_exe().expect("test binary")); isolate_git_command_environment(&mut command); diff --git a/codex-rs/git-utils/src/operations.rs b/codex-rs/git-utils/src/operations.rs index 1564b81a19..27c3e17ec4 100644 --- a/codex-rs/git-utils/src/operations.rs +++ b/codex-rs/git-utils/src/operations.rs @@ -110,8 +110,7 @@ where } let command_string = build_command_string(&args_vec); let git = GitRunner::for_cwd_io(dir)?; - let mut command = git.command(); - command.current_dir(dir); + let mut command = git.command_for_cwd(dir)?; if let Some(envs) = env { for (key, value) in envs { command.env(key, value); diff --git a/codex-rs/git-utils/src/patch_paths.rs b/codex-rs/git-utils/src/patch_paths.rs index b3a945510d..a77118c735 100644 --- a/codex-rs/git-utils/src/patch_paths.rs +++ b/codex-rs/git-utils/src/patch_paths.rs @@ -11,6 +11,7 @@ use crate::apply::write_temp_patch; use crate::exact_staging::update_index_exact_paths; use crate::git_command::GitRunner; use crate::git_config::path_is_within; +use crate::git_config_sources::ensure_no_worktree_config_sources; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct PatchPathInventory { @@ -18,15 +19,21 @@ pub(crate) struct PatchPathInventory { pub(crate) effective_paths: Vec, } +/// Extract requested-orientation and effective paths with Git from a cwd whose +/// config sources have already been authorized for `git_config_args`. pub(crate) fn extract_patch_path_inventory( git: &GitRunner, + authorized_cwd: &Path, patch_path: &Path, revert: bool, + git_config_args: &[String], ) -> io::Result { - let primary_paths = git_apply_numstat_paths(git, patch_path, revert)?; + let primary_paths = + git_apply_numstat_paths(git, authorized_cwd, patch_path, revert, git_config_args)?; // `git apply --numstat` reports only the destination of a rename. Parse the // opposite orientation too so both endpoints are included in the result. - let opposite_paths = git_apply_numstat_paths(git, patch_path, !revert)?; + let opposite_paths = + git_apply_numstat_paths(git, authorized_cwd, patch_path, !revert, git_config_args)?; if primary_paths.len() != opposite_paths.len() { return Err(io::Error::new( io::ErrorKind::InvalidData, @@ -60,10 +67,15 @@ pub(crate) fn extract_patch_path_inventory( pub(crate) fn extract_effective_paths_from_patch( git: &GitRunner, + authorized_cwd: &Path, patch_path: &Path, revert: bool, + git_config_args: &[String], ) -> io::Result> { - Ok(extract_patch_path_inventory(git, patch_path, revert)?.effective_paths) + Ok( + extract_patch_path_inventory(git, authorized_cwd, patch_path, revert, git_config_args)? + .effective_paths, + ) } /// Best-effort extraction of the paths Git would apply. @@ -71,33 +83,43 @@ pub(crate) fn extract_effective_paths_from_patch( /// Security-sensitive callers must use the fallible internal extractor so an /// invalid or ambiguous patch is rejected instead of becoming an empty list. pub fn extract_paths_from_patch(diff_text: &str) -> Vec { + let Ok(cwd) = std::env::current_dir() else { + return Vec::new(); + }; + extract_paths_from_patch_from_cwd(diff_text, &cwd) +} + +fn extract_paths_from_patch_from_cwd(diff_text: &str, cwd: &Path) -> Vec { let Ok((tmpdir, patch_path)) = write_temp_patch(diff_text) else { return Vec::new(); }; - let paths = std::env::current_dir() - .ok() - .and_then(|cwd| GitRunner::for_cwd(&cwd).ok()) - .and_then(|git| { - extract_effective_paths_from_patch(&git, &patch_path, /*revert*/ false).ok() - }) - .unwrap_or_default(); + let paths = (|| -> io::Result> { + let git = GitRunner::for_cwd_io(cwd)?; + let git_root = crate::get_git_repo_root(cwd) + .ok_or_else(|| io::Error::other("not a Git repository"))?; + let git_root = std::fs::canonicalize(git_root)?; + ensure_no_worktree_config_sources(&git, &git_root, &[])?; + extract_effective_paths_from_patch(&git, &git_root, &patch_path, /*revert*/ false, &[]) + })() + .unwrap_or_default(); drop(tmpdir); paths } fn git_apply_numstat_paths( git: &GitRunner, + authorized_cwd: &Path, patch_path: &Path, revert: bool, + git_config_args: &[String], ) -> io::Result> { - let mut cmd = git.command(); + let mut cmd = git.command_for_cwd(authorized_cwd)?; + cmd.args(git_config_args); cmd.args(["apply", "--numstat", "-z"]); if revert { cmd.arg("-R"); } - cmd.arg("--") - .arg(patch_path) - .current_dir(patch_path.parent().unwrap_or_else(|| Path::new("."))); + cmd.arg("--").arg(patch_path); let out = git.output(cmd)?; if !out.status.success() { return Err(io::Error::new( @@ -253,10 +275,18 @@ fn invalid_windows_patch_component(component: &str) -> bool { /// Stage only the files that actually exist on disk for the given diff. pub fn stage_paths(git_root: &Path, diff: &str) -> io::Result<()> { let git = GitRunner::for_cwd_io(git_root)?; + let git_config_args = safe_git_config_parts(); + ensure_no_worktree_config_sources(&git, git_root, &git_config_args)?; let (tmpdir, patch_path) = write_temp_patch(diff)?; - let paths = extract_effective_paths_from_patch(&git, &patch_path, /*revert*/ true)?; + let paths = extract_effective_paths_from_patch( + &git, + git_root, + &patch_path, + /*revert*/ true, + &git_config_args, + )?; let _guard = tmpdir; - stage_effective_paths(&git, git_root, &paths, &safe_git_config_parts()) + stage_effective_paths(&git, git_root, &paths, &git_config_args) } pub(crate) fn stage_effective_paths( diff --git a/codex-rs/git-utils/src/patch_paths_tests.rs b/codex-rs/git-utils/src/patch_paths_tests.rs index db5f967ae4..bcfea1e478 100644 --- a/codex-rs/git-utils/src/patch_paths_tests.rs +++ b/codex-rs/git-utils/src/patch_paths_tests.rs @@ -64,13 +64,23 @@ fn read_file_normalized(path: &Path) -> String { fn effective_paths(diff: &str, revert: bool) -> io::Result> { let (tmpdir, patch_path) = write_temp_patch(diff)?; - let cwd = std::env::current_dir()?; - let git = GitRunner::for_cwd_io(&cwd)?; - let paths = extract_effective_paths_from_patch(&git, &patch_path, revert)?; + let repo = init_repo(); + let cwd = repo.path(); + let git = GitRunner::for_cwd_io(cwd)?; + let git_root = + crate::get_git_repo_root(cwd).ok_or_else(|| io::Error::other("not a Git repository"))?; + let git_root = std::fs::canonicalize(git_root)?; + ensure_no_worktree_config_sources(&git, &git_root, &[])?; + let paths = extract_effective_paths_from_patch(&git, &git_root, &patch_path, revert, &[])?; drop(tmpdir); Ok(paths) } +fn best_effort_paths(diff: &str) -> Vec { + let repo = init_repo(); + extract_paths_from_patch_from_cwd(diff, repo.path()) +} + #[test] fn effective_paths_cover_supported_patch_headers() { let cases = [ @@ -129,7 +139,7 @@ fn effective_paths_cover_supported_patch_headers() { "{name}, revert={revert}" ); } - assert_eq!(extract_paths_from_patch(diff), expected, "{name}"); + assert_eq!(best_effort_paths(diff), expected, "{name}"); } let nul_rename_paths = parse_numstat_paths(b"0\t0\t\0old name.txt\0new name.txt\0") @@ -149,7 +159,7 @@ fn effective_paths_follow_git_for_mismatched_headers() { effective_paths(mismatch, /*revert*/ true).unwrap(), expected ); - assert_eq!(extract_paths_from_patch(mismatch), expected); + assert_eq!(best_effort_paths(mismatch), expected); } #[test] @@ -1477,95 +1487,27 @@ fn exact_staging_preserves_sparse_checkout_policy() { assert!(!index_entry(root, "inside/untracked.txt").is_empty()); } -#[cfg(unix)] #[test] fn sparse_rule_probe_failure_is_closed_only_for_sparse_repositories() { - use std::os::unix::fs::PermissionsExt; - - const TEST_NAME: &str = - "patch_paths::tests::sparse_rule_probe_failure_is_closed_only_for_sparse_repositories"; - if let Some(mode) = std::env::var_os("CODEX_GIT_UTILS_FAKE_SPARSE_MODE") { - let root = PathBuf::from( - std::env::var_os("CODEX_GIT_UTILS_TARGET_REPO").expect("target repository"), - ); - let result = exact_stage(&root, &["file.txt"], &["file.txt"]); - if mode == "sparse" { - assert_ne!(result.exit_code, 0); - assert!(result.stderr.contains("fake unsupported check-rules")); - assert!(index_entry(&root, "file.txt").is_empty()); - } else if mode == "legacy" { - assert_ne!(result.exit_code, 0); - assert!(result.stderr.contains("built-in Git command")); - assert!(index_entry(&root, "file.txt").is_empty()); - assert!( - !PathBuf::from( - std::env::var_os("CODEX_GIT_UTILS_SPARSE_HELPER_MARKER") - .expect("helper marker"), - ) - .exists(), - "legacy Git must not dispatch a PATH-resolved sparse helper" - ); - } else { - assert_eq!(result.exit_code, 0, "{}", result.stderr); - assert!(!index_entry(&root, "file.txt").is_empty()); - } - return; - } - - let wrapper_dir = tempfile::tempdir().expect("wrapper directory"); - let wrapper = wrapper_dir.path().join("git"); - std::fs::write( - &wrapper, - "#!/bin/sh\nprevious=\nfor argument in \"$@\"; do\n if [ \"$CODEX_GIT_UTILS_FAKE_SPARSE_MODE\" = legacy ] && [ \"$argument\" = --list-cmds=builtins ]; then\n echo add\n echo config\n exit 0\n fi\n if [ \"$previous\" = sparse-checkout ] && [ \"$argument\" = check-rules ]; then\n echo fake unsupported check-rules >&2\n exit 129\n fi\n previous=$argument\ndone\nexec \"$CODEX_GIT_UTILS_REAL_GIT\" \"$@\"\n", - ) - .expect("write Git wrapper"); - let mut permissions = std::fs::metadata(&wrapper).unwrap().permissions(); - permissions.set_mode(0o755); - std::fs::set_permissions(&wrapper, permissions).expect("make wrapper executable"); - let sparse_helper = wrapper_dir.path().join("git-sparse-checkout"); - std::fs::write( - &sparse_helper, - "#!/bin/sh\n: > \"$CODEX_GIT_UTILS_SPARSE_HELPER_MARKER\"\nexit 0\n", - ) - .expect("write malicious sparse helper"); - let mut permissions = std::fs::metadata(&sparse_helper).unwrap().permissions(); - permissions.set_mode(0o755); - std::fs::set_permissions(&sparse_helper, permissions).expect("make sparse helper executable"); - let real_git = [ - "/usr/bin/git", - "/opt/homebrew/bin/git", - "/usr/local/bin/git", - ] - .into_iter() - .map(PathBuf::from) - .find(|path| path.is_file()) - .expect("native Git outside the test wrapper"); - let wrapper_path = std::env::join_paths([wrapper_dir.path()]).expect("wrapper PATH"); - let helper_marker = wrapper_dir.path().join("sparse-helper-ran"); - - for mode in ["ordinary", "sparse", "legacy"] { + for sparse in [false, true] { let repo = init_repo(); let root = repo.path(); - if matches!(mode, "sparse" | "legacy") { + if sparse { assert_eq!( run(root, &["git", "config", "core.sparseCheckout", "true"]).0, 0 ); } std::fs::write(root.join("file.txt"), "new\n").expect("write staging file"); - run_isolated_test( - TEST_NAME, - &[ - ("CODEX_GIT_UTILS_FAKE_SPARSE_MODE", OsStr::new(mode)), - ("CODEX_GIT_UTILS_TARGET_REPO", root.as_os_str()), - ("CODEX_GIT_UTILS_REAL_GIT", real_git.as_os_str()), - ( - "CODEX_GIT_UTILS_SPARSE_HELPER_MARKER", - helper_marker.as_os_str(), - ), - ("PATH", wrapper_path.as_os_str()), - ], - ); + let result = exact_stage(root, &["file.txt"], &["file.txt"]); + if sparse { + assert_ne!(result.exit_code, 0); + assert!(result.stderr.contains("sparse-checkout"), "{result:?}"); + assert!(index_entry(root, "file.txt").is_empty()); + } else { + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert!(!index_entry(root, "file.txt").is_empty()); + } } } @@ -2049,7 +1991,11 @@ fn staging_allows_optional_smudge_only_but_refuses_required_or_malformed_smudge( assert_eq!(staged, "selected.txt\n"); } else { let error = result.expect_err("refuse required or malformed smudge-only target"); - assert_eq!(error.kind(), io::ErrorKind::Unsupported); + assert_eq!( + error.kind(), + io::ErrorKind::Unsupported, + "required={required}: {error}" + ); assert_eq!(git_index_bytes(root), before); } } diff --git a/codex-rs/git-utils/src/path_authority.rs b/codex-rs/git-utils/src/path_authority.rs new file mode 100644 index 0000000000..c27f9e698c --- /dev/null +++ b/codex-rs/git-utils/src/path_authority.rs @@ -0,0 +1,478 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use same_file::Handle; + +use crate::git_config::path_is_within; + +mod cancellation; +mod route_walker; +#[cfg(any(windows, test))] +mod windows_path; + +use route_walker::RawRouteObservation; +use route_walker::RouteObservationSnapshot; +#[cfg(windows)] +use route_walker::invalid_data; +use route_walker::observe_route; +#[cfg(any(windows, test))] +pub(crate) use windows_path::windows_authority_path_is_ambiguous; +#[cfg(any(windows, test))] +pub(crate) use windows_path::windows_path_is_ambiguous; + +#[derive(Clone, Copy, Eq, PartialEq)] +enum PathBoundary { + Worktree, + Metadata, +} + +#[derive(Clone, Copy, Eq, PartialEq)] +enum CandidateBoundary { + Outside, + Metadata, + ExactWorktree, + Worktree, +} + +#[derive(Debug, Default)] +pub(crate) struct RepositoryRouteBoundaries { + worktree_roots: Vec, + metadata_dirs: Vec, + worktree_identities: Vec, + metadata_identities: Vec, +} + +pub(crate) struct RouteInspection { + pub(crate) crosses_worktree: bool, + pub(crate) touches_worktree: bool, + pub(crate) crosses_metadata: bool, + pub(crate) observed_paths: Vec, +} + +impl RepositoryRouteBoundaries { + pub(crate) fn inspect_route(&self, route: &Path) -> io::Result { + inspect_route(route, self) + } + + pub(crate) fn contains_known_boundary(&self, path: &Path) -> io::Result { + Ok(classify_candidate( + path, + &self.worktree_roots, + &self.metadata_dirs, + &self.worktree_identities, + &self.metadata_identities, + )? != CandidateBoundary::Outside) + } +} + +pub(crate) fn repository_route_boundaries( + roots: &[PathBuf], + common_dirs: &[PathBuf], +) -> io::Result { + let mut worktree_roots = Vec::new(); + for root in roots { + push_unique_location(&mut worktree_roots, root.clone())?; + } + let worktree_identities = directory_identities(&worktree_roots)?; + + let mut metadata_dirs = Vec::new(); + for root in &worktree_roots { + let marker = root.join(".git"); + let Ok(metadata) = std::fs::symlink_metadata(&marker) else { + continue; + }; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + continue; + } + let canonical_root = std::fs::canonicalize(root)?; + let canonical_marker = std::fs::canonicalize(&marker)?; + if canonical_marker == canonical_root.join(".git") { + push_unique_location(&mut metadata_dirs, marker)?; + } + } + for common in common_dirs { + let within_standard_metadata = metadata_dirs + .iter() + .any(|metadata| path_is_within(common, metadata)); + let within_worktree = worktree_roots + .iter() + .any(|root| path_is_within(common, root)) + || nearest_identity_boundary(common, &worktree_identities, &[])? + == Some(PathBoundary::Worktree); + if within_standard_metadata || !within_worktree { + push_unique_location(&mut metadata_dirs, common.clone())?; + } + } + + let metadata_identities = directory_identities(&metadata_dirs)?; + Ok(RepositoryRouteBoundaries { + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + }) +} + +fn push_unique_location(paths: &mut Vec, path: PathBuf) -> io::Result<()> { + for existing in paths.iter() { + if paths_refer_to_same_location(existing, &path)? { + return Ok(()); + } + } + paths.push(path); + Ok(()) +} + +fn paths_refer_to_same_location(left: &Path, right: &Path) -> io::Result { + if path_is_within(left, right) && path_is_within(right, left) { + return Ok(true); + } + if let (Ok(left), Ok(right)) = (Handle::from_path(left), Handle::from_path(right)) { + return Ok(left == right); + } + match (std::fs::canonicalize(left), std::fs::canonicalize(right)) { + (Ok(left), Ok(right)) => Ok(left == right), + (Err(left), _) if is_missing(&left) => Ok(false), + (_, Err(right)) if is_missing(&right) => Ok(false), + (Err(error), _) | (_, Err(error)) => Err(error), + } +} + +fn is_missing(error: &io::Error) -> bool { + matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) +} + +fn inspect_route( + route: &Path, + boundaries: &RepositoryRouteBoundaries, +) -> io::Result { + #[cfg(windows)] + { + let route = route + .to_str() + .ok_or_else(|| invalid_data("non-UTF-8 Windows authority path"))?; + if windows_path_is_ambiguous(route) { + return Ok(RouteInspection { + crosses_worktree: true, + touches_worktree: true, + crosses_metadata: true, + observed_paths: Vec::new(), + }); + } + } + + let observation = observe_route(route)?; + let crosses_worktree = observation_crosses_worktree( + &observation, + &boundaries.worktree_roots, + &boundaries.metadata_dirs, + &boundaries.worktree_identities, + &boundaries.metadata_identities, + )?; + let observed_paths = observation.observed_paths(); + let mut touches_worktree = false; + let mut crosses_metadata = false; + for path in &observed_paths { + match classify_candidate( + path, + &boundaries.worktree_roots, + &boundaries.metadata_dirs, + &boundaries.worktree_identities, + &boundaries.metadata_identities, + )? { + CandidateBoundary::Worktree | CandidateBoundary::ExactWorktree => { + touches_worktree = true; + } + CandidateBoundary::Metadata => crosses_metadata = true, + CandidateBoundary::Outside => {} + } + } + Ok(RouteInspection { + crosses_worktree, + touches_worktree, + crosses_metadata, + observed_paths, + }) +} + +fn observation_crosses_worktree( + observation: &RouteObservationSnapshot, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + let raw_pivot = raw_observation_has_worktree_descendant_pivot( + &observation.raw, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )?; + let normalized_crosses = strict_candidate_crosses( + &observation.raw.normalized, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )?; + let projected_crosses = strict_candidate_crosses( + &observation.raw.projected, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )?; + if raw_pivot || normalized_crosses || projected_crosses { + return Ok(true); + } + for hop in &observation.symlink_hops { + // A symlink entry located directly under an exact worktree root is + // already a mutable descendant; classify its parent strictly. + if strict_candidate_crosses( + &hop.parent, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? || intermediate_candidate_crosses( + &hop.entry, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? || raw_observation_has_worktree_descendant_pivot( + &hop.target, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? || intermediate_observation_crosses( + &hop.target, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? || raw_observation_has_worktree_descendant_pivot( + &hop.projected, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? || terminal_observation_crosses( + &hop.projected, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? { + return Ok(true); + } + } + Ok(false) +} + +fn intermediate_observation_crosses( + observation: &RawRouteObservation, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + Ok(intermediate_candidate_crosses( + &observation.normalized, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? || intermediate_candidate_crosses( + &observation.projected, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )?) +} + +fn terminal_observation_crosses( + observation: &RawRouteObservation, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + Ok(strict_candidate_crosses( + &observation.normalized, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? || strict_candidate_crosses( + &observation.projected, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )?) +} + +fn strict_candidate_crosses( + path: &Path, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + Ok(matches!( + classify_candidate( + path, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )?, + CandidateBoundary::ExactWorktree | CandidateBoundary::Worktree + )) +} + +fn intermediate_candidate_crosses( + path: &Path, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + // Exact roots remain valid intermediates for Git-generated active metadata + // routes such as a nested submodule's `nested/../.git/modules/...`. + Ok(classify_candidate( + path, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )? == CandidateBoundary::Worktree) +} + +fn raw_observation_has_worktree_descendant_pivot( + observation: &RawRouteObservation, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + for prefix in &observation.normalized_prefixes { + // Active metadata routes are revalidated before each child, so an + // exact nested root is allowed here. Retained registry and standard + // directory routes use the stricter role-aware cancellation policy. + let boundary = classify_candidate( + prefix, + worktree_roots, + metadata_dirs, + worktree_identities, + metadata_identities, + )?; + if boundary == CandidateBoundary::Worktree { + return Ok(true); + } + } + Ok(false) +} + +fn classify_candidate( + path: &Path, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + if metadata_dirs + .iter() + .any(|metadata| path_is_within(path, metadata)) + { + return Ok(CandidateBoundary::Metadata); + } + if worktree_roots + .iter() + .any(|root| path_is_within(path, root) && path_is_within(root, path)) + { + return Ok(CandidateBoundary::ExactWorktree); + } + if worktree_roots.iter().any(|root| path_is_within(path, root)) { + return Ok(CandidateBoundary::Worktree); + } + for (depth, ancestor) in path.ancestors().enumerate() { + let metadata = match std::fs::metadata(ancestor) { + Ok(metadata) if metadata.is_dir() => metadata, + Ok(_) => continue, + Err(error) if is_missing(&error) => continue, + Err(error) => return Err(error), + }; + let identity = Handle::from_path(ancestor)?; + if metadata_identities.contains(&identity) { + return Ok(CandidateBoundary::Metadata); + } + if worktree_identities.contains(&identity) { + return Ok(if depth == 0 && metadata.is_dir() { + CandidateBoundary::ExactWorktree + } else { + CandidateBoundary::Worktree + }); + } + } + Ok(CandidateBoundary::Outside) +} + +fn directory_identities(paths: &[PathBuf]) -> io::Result> { + paths + .iter() + .filter_map(|path| match std::fs::metadata(path) { + Ok(metadata) if metadata.is_dir() => Some(Handle::from_path(path)), + Ok(_) => None, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + None + } + Err(error) => Some(Err(error)), + }) + .collect() +} + +fn nearest_identity_boundary( + path: &Path, + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result> { + for ancestor in path.ancestors() { + let metadata = match std::fs::metadata(ancestor) { + Ok(metadata) => metadata, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + continue; + } + Err(error) => return Err(error), + }; + if !metadata.is_dir() { + continue; + } + let identity = Handle::from_path(ancestor)?; + if metadata_identities.contains(&identity) { + return Ok(Some(PathBoundary::Metadata)); + } + if worktree_identities.contains(&identity) { + return Ok(Some(PathBoundary::Worktree)); + } + } + Ok(None) +} diff --git a/codex-rs/git-utils/src/path_authority/cancellation.rs b/codex-rs/git-utils/src/path_authority/cancellation.rs new file mode 100644 index 0000000000..d18f9f91bf --- /dev/null +++ b/codex-rs/git-utils/src/path_authority/cancellation.rs @@ -0,0 +1,161 @@ +use std::io; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use same_file::Handle; + +use crate::git_config::path_is_within; + +use super::CandidateBoundary; +use super::RepositoryRouteBoundaries; +use super::classify_candidate; +use super::is_missing; +use super::route_walker::RouteObservationSnapshot; +use super::route_walker::observe_route; +#[cfg(windows)] +use super::windows_path_is_ambiguous; + +impl RepositoryRouteBoundaries { + pub(crate) fn route_cancels_worktree_descendant(&self, route: &Path) -> io::Result { + if route_requires_fail_closed(route)? { + return Ok(true); + } + observation_cancels_worktree_descendant(&observe_route(route)?, self) + } + + pub(crate) fn retained_route_is_untrusted(&self, route: &Path) -> io::Result { + if route_requires_fail_closed(route)? { + return Ok(true); + } + let observation = observe_route(route)?; + if observation_cancels_worktree_descendant(&observation, self)? { + return Ok(true); + } + // Unlike active metadata, retained registry routes are not rebound + // before every child. A symlink or junction entry below a worktree is + // therefore mutable authority even when it currently aliases metadata. + // Parent identity classification covers Windows Unicode case aliases. + for hop in &observation.symlink_hops { + if matches!( + classify_candidate( + &hop.parent, + &self.worktree_roots, + &self.metadata_dirs, + &self.worktree_identities, + &self.metadata_identities, + )?, + CandidateBoundary::ExactWorktree | CandidateBoundary::Worktree + ) { + return Ok(true); + } + } + Ok(false) + } +} + +fn observation_cancels_worktree_descendant( + observation: &RouteObservationSnapshot, + boundaries: &RepositoryRouteBoundaries, +) -> io::Result { + if raw_spelling_cancels_worktree_descendant(&observation.raw.spelling, boundaries)? { + return Ok(true); + } + for hop in &observation.symlink_hops { + if raw_spelling_cancels_worktree_descendant(&hop.target.spelling, boundaries)? + || raw_spelling_cancels_worktree_descendant(&hop.projected.spelling, boundaries)? + { + return Ok(true); + } + } + Ok(false) +} + +fn route_requires_fail_closed(route: &Path) -> io::Result { + #[cfg(windows)] + { + let route = route.to_str().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "non-UTF-8 Windows authority path", + ) + })?; + Ok(windows_path_is_ambiguous(route)) + } + #[cfg(not(windows))] + { + let _ = route; + Ok(false) + } +} + +fn raw_spelling_cancels_worktree_descendant( + spelling: &Path, + boundaries: &RepositoryRouteBoundaries, +) -> io::Result { + let mut prefix = PathBuf::new(); + for component in spelling.components() { + match component { + Component::ParentDir => { + if candidate_is_proper_worktree_descendant( + &prefix, + &boundaries.worktree_roots, + &boundaries.metadata_dirs, + &boundaries.worktree_identities, + &boundaries.metadata_identities, + )? { + return Ok(true); + } + prefix.pop(); + } + Component::CurDir => {} + _ => prefix.push(component.as_os_str()), + } + } + Ok(false) +} + +pub(super) fn candidate_is_proper_worktree_descendant( + path: &Path, + worktree_roots: &[PathBuf], + metadata_dirs: &[PathBuf], + worktree_identities: &[Handle], + metadata_identities: &[Handle], +) -> io::Result { + if metadata_dirs + .iter() + .any(|metadata| path_is_within(path, metadata)) + { + return Ok(false); + } + + // A worktree-controlled spelling cannot become trusted merely because a + // mutable symlink or junction currently aliases protected metadata. Keep + // genuinely metadata-spelled paths exempt above, but reject lexical + // worktree descendants before following identities. + if worktree_roots + .iter() + .any(|root| path_is_within(path, root) && !path_is_within(root, path)) + { + return Ok(true); + } + + let mut ancestor_identities = Vec::new(); + for (depth, ancestor) in path.ancestors().enumerate() { + match std::fs::metadata(ancestor) { + Ok(metadata) if metadata.is_dir() => {} + Ok(_) => continue, + Err(error) if is_missing(&error) => continue, + Err(error) => return Err(error), + } + let identity = Handle::from_path(ancestor)?; + if metadata_identities.contains(&identity) { + return Ok(false); + } + ancestor_identities.push((depth, identity)); + } + + Ok(ancestor_identities + .into_iter() + .any(|(depth, identity)| depth > 0 && worktree_identities.contains(&identity))) +} diff --git a/codex-rs/git-utils/src/path_authority/route_walker.rs b/codex-rs/git-utils/src/path_authority/route_walker.rs new file mode 100644 index 0000000000..12f14df273 --- /dev/null +++ b/codex-rs/git-utils/src/path_authority/route_walker.rs @@ -0,0 +1,247 @@ +use std::collections::BTreeSet; +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use codex_utils_absolute_path::AbsolutePathBuf; + +#[cfg(windows)] +use super::windows_path::windows_path_is_ambiguous; + +#[derive(Clone, Debug)] +pub(super) struct RawRouteObservation { + pub(super) spelling: PathBuf, + pub(super) normalized_prefixes: Vec, + pub(super) normalized: PathBuf, + pub(super) projected: PathBuf, +} + +#[derive(Clone, Debug)] +pub(super) struct SymlinkRouteObservation { + pub(super) entry: PathBuf, + pub(super) parent: PathBuf, + pub(super) target: RawRouteObservation, + pub(super) projected: RawRouteObservation, +} + +#[derive(Clone, Debug)] +pub(super) struct RouteObservationSnapshot { + pub(super) raw: RawRouteObservation, + pub(super) symlink_hops: Vec, +} + +impl RouteObservationSnapshot { + pub(super) fn observed_paths(&self) -> Vec { + let mut paths = Vec::new(); + append_raw_observation_paths(&mut paths, &self.raw); + for hop in &self.symlink_hops { + push_unique_spelling(&mut paths, hop.parent.clone()); + push_unique_spelling(&mut paths, hop.entry.clone()); + append_raw_observation_paths(&mut paths, &hop.target); + append_raw_observation_paths(&mut paths, &hop.projected); + } + paths + } +} + +#[derive(Clone, Debug)] +struct SymlinkRouteHop { + entry: PathBuf, + parent: PathBuf, + target: PathBuf, + projected: PathBuf, +} + +pub(super) fn observe_route(path: &Path) -> io::Result { + let raw = observe_raw_route(path)?; + let symlink_hops = symlink_route_hops(path)? + .into_iter() + .map(|hop| { + Ok(SymlinkRouteObservation { + entry: hop.entry, + parent: hop.parent, + target: observe_raw_route(&hop.target)?, + projected: observe_raw_route(&hop.projected)?, + }) + }) + .collect::>>()?; + Ok(RouteObservationSnapshot { raw, symlink_hops }) +} + +fn observe_raw_route(route: &Path) -> io::Result { + let base = route + .ancestors() + .last() + .ok_or_else(|| invalid_data("authority path has no root"))?; + let normalized = AbsolutePathBuf::resolve_path_against_base(route, base).into_path_buf(); + let normalized_prefixes = route + .ancestors() + .map(|prefix| AbsolutePathBuf::resolve_path_against_base(prefix, base).into_path_buf()) + .collect(); + let projected = project_through_longest_existing_ancestor(route)?; + Ok(RawRouteObservation { + spelling: route.to_path_buf(), + normalized_prefixes, + normalized, + projected, + }) +} + +fn append_raw_observation_paths(paths: &mut Vec, observation: &RawRouteObservation) { + for prefix in &observation.normalized_prefixes { + push_unique_spelling(paths, prefix.clone()); + } + push_unique_spelling(paths, observation.projected.clone()); +} + +fn push_unique_spelling(paths: &mut Vec, path: PathBuf) { + if !paths.iter().any(|existing| existing == &path) { + paths.push(path); + } +} + +fn symlink_route_hops(path: &Path) -> io::Result> { + let mut hops = Vec::new(); + let mut seen = BTreeSet::new(); + collect_symlink_route_hops(path, /*depth*/ 0, &mut seen, &mut hops)?; + Ok(hops) +} + +fn collect_symlink_route_hops( + path: &Path, + depth: usize, + seen: &mut BTreeSet, + hops: &mut Vec, +) -> io::Result<()> { + if depth > 40 { + return Err(invalid_data("authority path symlink cycle")); + } + if !seen.insert(path.to_path_buf()) { + return Ok(()); + } + for ancestor in path.ancestors() { + match std::fs::symlink_metadata(ancestor) { + Ok(_) => match read_link_if_symlink(ancestor) { + Ok(Some(target)) => { + let parent = ancestor + .parent() + .ok_or_else(|| invalid_data("authority symlink has no parent"))?; + let target = resolve_literal_path(target, parent); + #[cfg(windows)] + if target.to_str().is_none_or(windows_path_is_ambiguous) { + return Err(invalid_data("ambiguous Windows authority symlink")); + } + let suffix = path + .strip_prefix(ancestor) + .map_err(|_| invalid_data("failed to project authority symlink path"))?; + let projected = resolve_literal_path(suffix, &target); + hops.push(SymlinkRouteHop { + entry: ancestor.to_path_buf(), + parent: parent.to_path_buf(), + target, + projected: projected.clone(), + }); + collect_symlink_route_hops(&projected, depth + 1, seen, hops)?; + } + Ok(None) => {} + Err(error) => return Err(error), + }, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => {} + Err(error) => return Err(error), + } + } + Ok(()) +} + +fn read_link_if_symlink(path: &Path) -> io::Result> { + match std::fs::read_link(path) { + Ok(target) => Ok(Some(target)), + Err(error) if read_link_error_means_not_symlink(&error) => Ok(None), + Err(error) => Err(error), + } +} + +fn read_link_error_means_not_symlink(error: &io::Error) -> bool { + #[cfg(windows)] + { + // Win32 reports this for ordinary files and directories passed to + // `std::fs::read_link`; it is the Windows equivalent of EINVAL here. + const ERROR_NOT_A_REPARSE_POINT: i32 = 4390; + error.raw_os_error() == Some(ERROR_NOT_A_REPARSE_POINT) + } + #[cfg(not(windows))] + { + error.kind() == io::ErrorKind::InvalidInput + } +} + +fn project_through_longest_existing_ancestor(path: &Path) -> io::Result { + project_path(path, /*symlink_depth*/ 0) +} + +fn project_path(path: &Path, symlink_depth: usize) -> io::Result { + if symlink_depth > 40 { + return Err(invalid_data("too many authority path symlinks")); + } + if let Ok(canonical) = std::fs::canonicalize(path) { + return Ok(canonical); + } + for ancestor in path.ancestors() { + if std::fs::symlink_metadata(ancestor).is_ok() + && let Ok(target) = std::fs::read_link(ancestor) + { + let parent = ancestor + .parent() + .ok_or_else(|| invalid_data("authority symlink has no parent"))?; + let target = resolve_literal_path(target, parent); + #[cfg(windows)] + if target.to_str().is_none_or(windows_path_is_ambiguous) { + return Err(invalid_data("ambiguous Windows authority symlink")); + } + let suffix = path + .strip_prefix(ancestor) + .map_err(|_| invalid_data("failed to project authority path"))?; + return project_path(&resolve_literal_path(suffix, &target), symlink_depth + 1); + } + } + for ancestor in path.ancestors() { + match std::fs::canonicalize(ancestor) { + Ok(canonical) => { + let suffix = path + .strip_prefix(ancestor) + .map_err(|_| invalid_data("failed to project authority path"))?; + return Ok( + AbsolutePathBuf::resolve_path_against_base(suffix, canonical).into_path_buf(), + ); + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => {} + Err(error) => return Err(error), + } + } + Err(invalid_data("authority path has no existing ancestor")) +} + +fn resolve_literal_path(path: impl AsRef, base: &Path) -> PathBuf { + let path = path.as_ref(); + if path.is_absolute() { + path.to_path_buf() + } else { + base.join(path) + } +} + +pub(super) fn invalid_data(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +#[cfg(test)] +#[path = "route_walker_tests.rs"] +mod tests; diff --git a/codex-rs/git-utils/src/path_authority/route_walker_tests.rs b/codex-rs/git-utils/src/path_authority/route_walker_tests.rs new file mode 100644 index 0000000000..1b7604d93a --- /dev/null +++ b/codex-rs/git-utils/src/path_authority/route_walker_tests.rs @@ -0,0 +1,18 @@ +use pretty_assertions::assert_eq; + +use super::read_link_if_symlink; + +#[test] +fn ordinary_paths_are_not_treated_as_failed_symlink_reads() { + let fixture = tempfile::tempdir().expect("fixture"); + let directory = fixture.path().join("directory"); + let file = fixture.path().join("file"); + std::fs::create_dir(&directory).expect("directory"); + std::fs::write(&file, b"ordinary file").expect("file"); + + assert_eq!( + read_link_if_symlink(&directory).expect("ordinary directory"), + None + ); + assert_eq!(read_link_if_symlink(&file).expect("ordinary file"), None); +} diff --git a/codex-rs/git-utils/src/path_authority/windows_path.rs b/codex-rs/git-utils/src/path_authority/windows_path.rs new file mode 100644 index 0000000000..46b8ddcd8a --- /dev/null +++ b/codex-rs/git-utils/src/path_authority/windows_path.rs @@ -0,0 +1,69 @@ +pub(crate) fn windows_path_is_ambiguous(path: &str) -> bool { + let path = path.replace('/', "\\"); + if path.starts_with(r"\??\") { + return true; + } + let path = if path + .get(..8) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(r"\\?\UNC\")) + || path + .get(..8) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(r"\\.\UNC\")) + { + format!(r"\\{}", &path[8..]) + } else if path.starts_with(r"\\?\") || path.starts_with(r"\\.\") { + let path = &path[4..]; + if !matches!(path.as_bytes(), [drive, b':', b'\\', ..] if drive.is_ascii_alphabetic()) { + return true; + } + path.to_string() + } else { + path + }; + let bytes = path.as_bytes(); + let remainder = if matches!(bytes, [drive, b':', separator, ..] + if drive.is_ascii_alphabetic() && *separator == b'\\') + { + &path[3..] + } else { + path.as_str() + }; + if remainder.contains(':') { + return true; + } + remainder.split('\\').any(|component| { + !matches!(component, "." | "..") + && (component.ends_with(['.', ' ']) || windows_reserved_component(component)) + }) +} + +pub(crate) fn windows_authority_path_is_ambiguous(path: &str) -> bool { + windows_path_is_ambiguous(path) + || path + .replace('/', "\\") + .split('\\') + .any(|component| component == "..") +} + +fn windows_reserved_component(component: &str) -> bool { + let stem = component + .trim_end_matches(['.', ' ']) + .split_once('.') + .map_or(component, |(stem, _)| stem); + stem.eq_ignore_ascii_case("AUX") + || stem.eq_ignore_ascii_case("CON") + || stem.eq_ignore_ascii_case("CONIN$") + || stem.eq_ignore_ascii_case("CONOUT$") + || stem.eq_ignore_ascii_case("NUL") + || stem.eq_ignore_ascii_case("PRN") + || ["COM", "LPT"].iter().any(|prefix| { + let Some(rest) = stem.get(3..) else { + return false; + }; + let mut chars = rest.chars(); + stem.get(..3) + .is_some_and(|candidate| candidate.eq_ignore_ascii_case(prefix)) + && matches!(chars.next(), Some('1'..='9' | '¹' | '²' | '³')) + && chars.as_str().is_empty() + }) +} diff --git a/codex-rs/git-utils/src/repository_authority.rs b/codex-rs/git-utils/src/repository_authority.rs new file mode 100644 index 0000000000..065d58f7cf --- /dev/null +++ b/codex-rs/git-utils/src/repository_authority.rs @@ -0,0 +1,522 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use codex_utils_absolute_path::AbsolutePathBuf; +use same_file::Handle; + +use helpers::RegisteredWorktree; +use helpers::RegisteredWorktreeReadError; +use helpers::registry_error; + +mod authority; +mod helpers; +mod plain_config; +pub(crate) use authority::RepositoryAuthority; +pub(crate) use plain_config::CommonConfigAuthority; +pub(crate) use plain_config::inspect_plain_common_config_authority; + +#[derive(Debug)] +struct RepositoryAuthorityRefusal { + message: String, +} + +impl std::fmt::Display for RepositoryAuthorityRefusal { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for RepositoryAuthorityRefusal {} + +/// Preserve the provenance of an explicit repository-authority policy +/// refusal while retaining `io::Error` at the Git runner boundary. +pub(crate) fn authority_refusal(message: impl Into) -> io::Error { + io::Error::new( + io::ErrorKind::PermissionDenied, + RepositoryAuthorityRefusal { + message: message.into(), + }, + ) +} + +pub(crate) fn is_authority_refusal(error: &io::Error) -> bool { + error + .get_ref() + .is_some_and(::is::) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum RepositoryMetadataKind { + StandardPrimary, + SeparatePrimary, + Linked, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct ResolvedRepositoryMetadata { + pub(crate) marker: PathBuf, + pub(crate) git_dir: PathBuf, + pub(crate) common_dir: PathBuf, + pub(crate) kind: RepositoryMetadataKind, + pub(crate) routes: Vec, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct RepositoryMetadataRoute { + pub(crate) spelling: PathBuf, + pub(crate) target: PathBuf, + pub(crate) kind: RepositoryMetadataRouteKind, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum RepositoryMetadataRouteKind { + Traversal, + StandardDirectory, +} + +pub(crate) fn read_bounded_marker(path: &Path) -> io::Result> { + #[cfg(test)] + BOUNDED_MARKER_READ_COUNT.with(|count| count.set(count.get() + 1)); + read_bounded_file(path, 64 * 1024, "Git metadata marker is too large") +} + +#[cfg(test)] +thread_local! { + static BOUNDED_MARKER_READ_COUNT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +pub(crate) fn reset_bounded_marker_read_count() { + BOUNDED_MARKER_READ_COUNT.with(|count| count.set(0)); +} + +#[cfg(test)] +pub(crate) fn bounded_marker_read_count() -> usize { + BOUNDED_MARKER_READ_COUNT.with(std::cell::Cell::get) +} + +pub(crate) fn parse_marker_path(contents: &[u8], prefix: &[u8]) -> io::Result { + let contents = contents + .strip_prefix(prefix) + .ok_or_else(|| invalid_data("malformed Git metadata marker"))?; + let contents = trim_trailing_ascii_whitespace(contents); + if contents.is_empty() || contents.contains(&0) { + return Err(invalid_data("empty Git metadata marker path")); + } + bytes_to_path(contents) +} + +pub(crate) fn resolve_repository_metadata( + dot_git: &Path, +) -> io::Result { + let metadata = std::fs::symlink_metadata(dot_git)?; + if metadata.file_type().is_symlink() { + return Err(invalid_data("symlinked Git metadata marker")); + } + let marker_is_directory = metadata.is_dir(); + let (git_dir, git_dir_route, default_kind) = if marker_is_directory { + ( + std::fs::canonicalize(dot_git)?, + Some(( + dot_git.to_path_buf(), + RepositoryMetadataRouteKind::StandardDirectory, + )), + RepositoryMetadataKind::StandardPrimary, + ) + } else if metadata.is_file() { + let contents = read_bounded_marker(dot_git)?; + let route = raw_path_against( + parse_marker_path(&contents, b"gitdir: ")?, + dot_git + .parent() + .ok_or_else(|| invalid_data("Git metadata marker has no parent"))?, + ); + let git_dir = std::fs::canonicalize(&route)?; + ( + git_dir, + Some((route, RepositoryMetadataRouteKind::Traversal)), + RepositoryMetadataKind::SeparatePrimary, + ) + } else { + return Err(invalid_data("unsupported Git metadata marker")); + }; + let commondir = git_dir.join("commondir"); + match std::fs::symlink_metadata(&commondir) { + Ok(metadata) => { + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(invalid_data("unsupported Git common-dir marker")); + } + let contents = read_bounded_marker(&commondir)?; + let route = raw_path_against(parse_marker_path(&contents, b"")?, &git_dir); + let common_dir = std::fs::canonicalize(&route)?; + let mut routes = git_dir_route + .map(|(spelling, kind)| RepositoryMetadataRoute { + spelling, + target: git_dir.clone(), + kind, + }) + .into_iter() + .collect::>(); + routes.push(RepositoryMetadataRoute { + spelling: route, + target: common_dir.clone(), + kind: RepositoryMetadataRouteKind::Traversal, + }); + return Ok(ResolvedRepositoryMetadata { + marker: dot_git.to_path_buf(), + git_dir, + common_dir, + kind: RepositoryMetadataKind::Linked, + routes, + }); + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => {} + Err(error) => return Err(error), + } + + if git_dir + .parent() + .is_some_and(|parent| parent.file_name() == Some(std::ffi::OsStr::new("worktrees"))) + { + let common_dir = git_dir + .parent() + .and_then(Path::parent) + .ok_or_else(|| invalid_data("linked Git admin dir has no common parent"))?; + let common_dir = std::fs::canonicalize(common_dir)?; + let routes = git_dir_route + .map(|(spelling, kind)| RepositoryMetadataRoute { + spelling, + target: git_dir.clone(), + kind, + }) + .into_iter() + .collect(); + return Ok(ResolvedRepositoryMetadata { + marker: dot_git.to_path_buf(), + git_dir, + common_dir, + kind: RepositoryMetadataKind::Linked, + routes, + }); + } + + Ok(ResolvedRepositoryMetadata { + marker: dot_git.to_path_buf(), + common_dir: git_dir.clone(), + git_dir: git_dir.clone(), + kind: default_kind, + routes: git_dir_route + .map(|(spelling, kind)| RepositoryMetadataRoute { + spelling, + target: git_dir, + kind, + }) + .into_iter() + .collect(), + }) +} + +pub(crate) fn repository_common_dir_for_candidate_root(root: &Path) -> io::Result> { + let marker = root.join(".git"); + match std::fs::symlink_metadata(&marker) { + Ok(_) => resolve_repository_metadata(&marker).map(|metadata| Some(metadata.common_dir)), + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + Ok(None) + } + Err(error) => Err(error), + } +} + +pub(crate) fn linked_common_dir_for_root(root: &Path) -> io::Result> { + let marker = root.join(".git"); + let metadata = match std::fs::symlink_metadata(&marker) { + Ok(metadata) => metadata, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(None); + } + Err(error) => return Err(error), + }; + if metadata.file_type().is_symlink() { + return Err(invalid_data("symlinked Git metadata marker")); + } + if !metadata.is_file() && !metadata.is_dir() { + return Ok(None); + } + let resolved = resolve_repository_metadata(&marker)?; + Ok((resolved.kind == RepositoryMetadataKind::Linked).then_some(resolved.common_dir)) +} + +fn registered_worktrees( + common_dir: &Path, +) -> Result, RegisteredWorktreeReadError> { + let worktrees = common_dir.join("worktrees"); + match std::fs::symlink_metadata(&worktrees) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {} + Ok(_) => { + return Err(registry_error( + &worktrees, + invalid_data("unsupported Git worktree registry"), + )); + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(Vec::new()); + } + Err(error) => return Err(registry_error(&worktrees, error)), + } + + let mut registrations = Vec::new(); + let entries = + std::fs::read_dir(&worktrees).map_err(|error| registry_error(&worktrees, error))?; + for entry in entries { + let admin_dir = entry + .map_err(|error| registry_error(&worktrees, error))? + .path(); + let metadata = std::fs::symlink_metadata(&admin_dir) + .map_err(|error| registry_error(&admin_dir, error))?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(registry_error( + &admin_dir, + invalid_data("unsupported Git worktree registry entry"), + )); + } + let gitdir_marker = admin_dir.join("gitdir"); + let metadata = std::fs::symlink_metadata(&gitdir_marker) + .map_err(|error| registry_error(&gitdir_marker, error))?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(registry_error( + &gitdir_marker, + invalid_data("unsupported Git worktree gitdir marker"), + )); + } + let contents = read_bounded_marker(&gitdir_marker) + .map_err(|error| registry_error(&gitdir_marker, error))?; + let marker_route = raw_path_against( + parse_marker_path(&contents, b"") + .map_err(|error| registry_error(&gitdir_marker, error))?, + &admin_dir, + ); + #[cfg(windows)] + if marker_route + .to_str() + .is_none_or(crate::path_authority::windows_path_is_ambiguous) + { + return Err(registry_error( + &gitdir_marker, + invalid_data("ambiguous Windows Git worktree path"), + )); + } + // Git writes this protected registry marker from real paths (either + // absolute or relative). Normalize it only after retaining the raw + // route long enough to apply platform path grammar. + let marker = resolve_path_against(marker_route.clone(), &admin_dir); + if marker.file_name() != Some(std::ffi::OsStr::new(".git")) { + return Err(registry_error( + &gitdir_marker, + invalid_data("malformed Git worktree gitdir marker"), + )); + } + let root = marker + .parent() + .ok_or_else(|| { + registry_error( + &gitdir_marker, + invalid_data("Git worktree marker has no parent"), + ) + })? + .to_path_buf(); + registrations.push(RegisteredWorktree { + root, + admin_dir, + marker_route, + }); + } + Ok(registrations) +} + +pub(crate) fn primary_authority_is_proven( + current_root: &Path, + common_dir: &Path, + roots: &[PathBuf], +) -> io::Result { + for root in roots { + if directories_refer_to_same_location(root, current_root).unwrap_or(false) { + continue; + } + let marker = root.join(".git"); + match std::fs::symlink_metadata(&marker) { + Ok(_) => { + let resolved = resolve_repository_metadata(&marker)?; + if resolved.kind != RepositoryMetadataKind::Linked + && directories_refer_to_same_location(&resolved.common_dir, common_dir)? + { + return Ok(true); + } + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => {} + Err(error) => return Err(error), + } + } + Ok(false) +} + +pub(crate) fn directories_refer_to_same_location(left: &Path, right: &Path) -> io::Result { + let left_metadata = match std::fs::metadata(left) { + Ok(metadata) => metadata, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(false); + } + Err(error) => return Err(error), + }; + let right_metadata = match std::fs::metadata(right) { + Ok(metadata) => metadata, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(false); + } + Err(error) => return Err(error), + }; + if !left_metadata.is_dir() || !right_metadata.is_dir() { + return Ok(false); + } + Ok(Handle::from_path(left)? == Handle::from_path(right)?) +} + +pub(crate) fn path_has_untrusted_root_identity_ancestor(path: &Path, roots: &[PathBuf]) -> bool { + let mut root_identities = Vec::new(); + for root in roots { + match std::fs::metadata(root) { + Ok(metadata) if metadata.is_dir() => match Handle::from_path(root) { + Ok(identity) => root_identities.push(identity), + Err(_) => return true, + }, + Ok(_) => return true, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => {} + Err(_) => return true, + } + } + if root_identities.is_empty() { + return false; + } + + let start = match std::fs::metadata(path) { + Ok(metadata) if metadata.is_dir() => path, + Ok(_) => path.parent().unwrap_or(path), + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + path.parent().unwrap_or(path) + } + Err(_) => return true, + }; + for ancestor in start.ancestors() { + match std::fs::metadata(ancestor) { + Ok(metadata) if metadata.is_dir() => match Handle::from_path(ancestor) { + Ok(identity) if root_identities.contains(&identity) => return true, + Ok(_) => {} + Err(_) => return true, + }, + Ok(_) => continue, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => {} + Err(_) => return true, + } + } + false +} + +fn read_bounded_file(path: &Path, max_bytes: u64, too_large: &str) -> io::Result> { + use std::io::Read; + + let file = std::fs::File::open(path)?; + let mut contents = Vec::new(); + file.take(max_bytes + 1).read_to_end(&mut contents)?; + if contents.len() as u64 > max_bytes { + return Err(invalid_data(too_large)); + } + Ok(contents) +} + +fn resolve_path_against(path: PathBuf, base: &Path) -> PathBuf { + AbsolutePathBuf::resolve_path_against_base(path, base).into_path_buf() +} + +fn raw_path_against(path: PathBuf, base: &Path) -> PathBuf { + if path.is_absolute() { + path + } else { + base.join(path) + } +} + +fn bytes_to_path(bytes: &[u8]) -> io::Result { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt; + + Ok(PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec()))) + } + #[cfg(not(unix))] + { + Ok(PathBuf::from(std::str::from_utf8(bytes).map_err(|_| { + invalid_data("non-UTF-8 Git filesystem path") + })?)) + } +} + +fn trim_trailing_ascii_whitespace(mut value: &[u8]) -> &[u8] { + while value.last().is_some_and(u8::is_ascii_whitespace) { + value = &value[..value.len() - 1]; + } + value +} + +fn invalid_data(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +#[cfg(test)] +#[path = "repository_authority_tests.rs"] +mod tests; diff --git a/codex-rs/git-utils/src/repository_authority/authority.rs b/codex-rs/git-utils/src/repository_authority/authority.rs new file mode 100644 index 0000000000..6c9b517e82 --- /dev/null +++ b/codex-rs/git-utils/src/repository_authority/authority.rs @@ -0,0 +1,398 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use crate::errors::GitReadError; +use crate::git_config::path_is_within; +use crate::path_authority::RepositoryRouteBoundaries; +use crate::path_authority::repository_route_boundaries; + +use super::CommonConfigAuthority; +use super::RegisteredWorktree; +use super::ResolvedRepositoryMetadata; +use super::authority_refusal; +use super::directories_refer_to_same_location; +use super::helpers::common_dir_is_within_untrusted_root; +use super::helpers::invalid_metadata; +use super::helpers::paths_equal; +use super::helpers::push_unique; +use super::helpers::validated_logical_process_cwd; +use super::inspect_plain_common_config_authority; +use super::linked_common_dir_for_root; +use super::primary_authority_is_proven; +use super::registered_worktrees; +use super::resolve_repository_metadata; + +mod policy; + +/// Repository and filesystem authority retained for the lifetime of one +/// trusted Git runner. +#[derive(Debug)] +pub(crate) struct RepositoryAuthority { + active_worktree_root: PathBuf, + roots: Vec, + worktree_roots: Vec, + common_dirs: Vec, + unproven_primary_common_dir: Option, + metadata_snapshots: Vec, + registered_worktrees: Vec, + active_metadata: Option, + route_boundaries: RepositoryRouteBoundaries, +} + +impl RepositoryAuthority { + pub(crate) fn discover(cwd: &Path) -> Result { + let lexical_cwd = if cwd.is_absolute() { + cwd.to_path_buf() + } else { + std::env::current_dir() + .map_err(|_| GitReadError::NotRepository { + path: cwd.to_path_buf(), + })? + .join(cwd) + }; + let canonical_cwd = + std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository { + path: cwd.to_path_buf(), + })?; + let worktree_root = crate::get_git_repo_root(&canonical_cwd) + .and_then(|root| std::fs::canonicalize(root).ok()) + .unwrap_or_else(|| canonical_cwd.clone()); + let mut authority = Self { + active_worktree_root: worktree_root.clone(), + roots: Vec::new(), + worktree_roots: Vec::new(), + common_dirs: Vec::new(), + unproven_primary_common_dir: None, + metadata_snapshots: Vec::new(), + registered_worktrees: Vec::new(), + active_metadata: None, + route_boundaries: RepositoryRouteBoundaries::default(), + }; + authority.record_repository_ancestry(&worktree_root)?; + + // Canonicalization can erase a repository-controlled symlink prefix. + // Retain the requested spelling so lexical enclosing repositories stay + // in the authority boundary. + let lexical_base = if lexical_cwd.is_dir() { + lexical_cwd + } else { + lexical_cwd + .parent() + .ok_or_else(|| GitReadError::NotRepository { + path: cwd.to_path_buf(), + })? + .to_path_buf() + }; + authority.record_repository_ancestry(&lexical_base)?; + if let Some(logical_cwd) = validated_logical_process_cwd(&canonical_cwd) { + authority.record_repository_ancestry(&logical_cwd)?; + } + authority.record_preselection_primary_authorities()?; + authority.active_metadata = authority + .metadata_snapshots + .iter() + .find(|snapshot| snapshot.marker == worktree_root.join(".git")) + .cloned(); + authority.route_boundaries = + repository_route_boundaries(&authority.worktree_roots, &authority.common_dirs) + .map_err(|error| invalid_metadata(&worktree_root, error))?; + authority.validate_registered_worktree_routes()?; + authority.validate_metadata_routes()?; + Ok(authority) + } + + pub(crate) fn ensure_primary_authority(&self) -> Result<(), GitReadError> { + if let Some(common_dir) = &self.unproven_primary_common_dir { + return Err(GitReadError::UnprovenPrimaryAuthority { + common_dir: common_dir.display().to_string(), + }); + } + Ok(()) + } + + pub(crate) fn active_worktree_root(&self) -> Option<&Path> { + self.active_metadata + .as_ref() + .map(|_| self.active_worktree_root.as_path()) + } + + pub(crate) fn path_is_untrusted_for_executable(&self, path: &Path) -> bool { + self.path_is_untrusted_for_executable_result(path) + .unwrap_or(true) + } + + pub(crate) fn revalidate_active_repository_metadata(&self) -> io::Result<()> { + let Some(expected) = &self.active_metadata else { + return Ok(()); + }; + let actual = resolve_repository_metadata(&expected.marker).map_err(|error| { + authority_refusal(format!( + "repository metadata changed during Git operation at {}: {error}", + expected.marker.display() + )) + })?; + if &actual != expected { + return Err(authority_refusal(format!( + "repository metadata changed during Git operation at {}", + expected.marker.display() + ))); + } + self.validate_snapshot_routes(&actual).map_err(|error| { + authority_refusal(format!( + "repository metadata changed during Git operation at {}: {error}", + expected.marker.display() + )) + }) + } + + #[cfg(test)] + pub(crate) fn from_test_locations( + roots: Vec, + worktree_roots: Vec, + common_dirs: Vec, + ) -> Result { + let route_boundaries = repository_route_boundaries(&worktree_roots, &common_dirs) + .map_err(|error| invalid_metadata(Path::new(""), error))?; + Ok(Self { + active_worktree_root: worktree_roots + .first() + .or_else(|| roots.first()) + .cloned() + .unwrap_or_default(), + roots, + worktree_roots, + common_dirs, + unproven_primary_common_dir: None, + metadata_snapshots: Vec::new(), + registered_worktrees: Vec::new(), + active_metadata: None, + route_boundaries, + }) + } + + #[cfg(all(test, unix))] + pub(crate) fn active_git_dir(&self) -> Option<&Path> { + self.active_metadata + .as_ref() + .map(|metadata| metadata.git_dir.as_path()) + } + + #[cfg(test)] + pub(crate) fn contains_root(&self, root: &Path) -> bool { + self.roots + .iter() + .any(|candidate| paths_equal(candidate, root)) + } + + #[cfg(test)] + pub(crate) fn roots(&self) -> &[PathBuf] { + &self.roots + } + + fn record_preselection_primary_authorities(&mut self) -> Result<(), GitReadError> { + let mut inspected_common_dirs: Vec = Vec::new(); + loop { + let roots = self.roots.clone(); + let mut next = None; + for root in roots { + let Some(common_dir) = linked_common_dir_for_root(&root) + .map_err(|error| invalid_metadata(&root.join(".git"), error))? + else { + continue; + }; + let already_inspected = inspected_common_dirs.iter().try_fold( + false, + |found, inspected| -> Result { + Ok(found + || directories_refer_to_same_location(inspected, &common_dir) + .map_err(|error| invalid_metadata(&common_dir, error))?) + }, + )?; + if !already_inspected { + next = Some((root, common_dir)); + break; + } + } + let Some((linked_root, common_dir)) = next else { + return Ok(()); + }; + inspected_common_dirs.push(common_dir.clone()); + if primary_authority_is_proven(&linked_root, &common_dir, &self.roots) + .map_err(|error| invalid_metadata(&common_dir, error))? + { + continue; + } + if common_dir_is_within_untrusted_root(&common_dir, &self.roots) { + self.unproven_primary_common_dir.get_or_insert(common_dir); + continue; + } + match inspect_plain_common_config_authority(&common_dir) + .map_err(|error| invalid_metadata(&common_dir, error))? + { + CommonConfigAuthority::Bare => {} + CommonConfigAuthority::Worktree(root) => { + self.record_repository_ancestry(&root)?; + } + CommonConfigAuthority::Unproven => { + self.unproven_primary_common_dir.get_or_insert(common_dir); + } + } + } + } + + fn record_repository_ancestry(&mut self, start: &Path) -> Result<(), GitReadError> { + push_unique(&mut self.roots, start.to_path_buf()); + push_unique(&mut self.worktree_roots, start.to_path_buf()); + self.record_repository_marker(start)?; + for ancestor in start.parent().into_iter().flat_map(Path::ancestors) { + let marker = ancestor.join(".git"); + match std::fs::symlink_metadata(&marker) { + Ok(_) => { + push_unique(&mut self.roots, ancestor.to_path_buf()); + push_unique(&mut self.worktree_roots, ancestor.to_path_buf()); + let canonical_root = std::fs::canonicalize(ancestor) + .map_err(|error| invalid_metadata(&marker, error))?; + push_unique(&mut self.roots, canonical_root.clone()); + push_unique(&mut self.worktree_roots, canonical_root); + self.record_repository_marker(ancestor)?; + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(invalid_metadata(&marker, error)), + } + } + Ok(()) + } + + fn record_repository_marker(&mut self, worktree_root: &Path) -> Result<(), GitReadError> { + let marker = worktree_root.join(".git"); + let snapshot = match std::fs::symlink_metadata(&marker) { + Ok(_) => resolve_repository_metadata(&marker) + .map_err(|error| invalid_metadata(&marker, error))?, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(invalid_metadata(&marker, error)), + }; + let common_dir = snapshot.common_dir.clone(); + if !self + .metadata_snapshots + .iter() + .any(|known| known.marker == snapshot.marker) + { + self.metadata_snapshots.push(snapshot); + } + if !path_is_within(&common_dir, worktree_root) { + push_unique(&mut self.roots, common_dir.clone()); + } + push_unique(&mut self.common_dirs, common_dir.clone()); + self.record_registered_worktrees(&common_dir)?; + self.record_common_dir_ancestry(common_dir) + } + + fn record_registered_worktrees(&mut self, common_dir: &Path) -> Result<(), GitReadError> { + let registrations = registered_worktrees(common_dir) + .map_err(|error| invalid_metadata(&error.path, error.source))?; + for registration in registrations { + if !self + .registered_worktrees + .iter() + .any(|known| known.admin_dir == registration.admin_dir) + { + self.registered_worktrees.push(registration.clone()); + } + let already_known = self + .roots + .iter() + .any(|known| paths_equal(known, ®istration.root)); + push_unique(&mut self.roots, registration.root.clone()); + push_unique(&mut self.worktree_roots, registration.root.clone()); + if let Ok(canonical_root) = std::fs::canonicalize(®istration.root) { + push_unique(&mut self.roots, canonical_root.clone()); + push_unique(&mut self.worktree_roots, canonical_root); + } + self.validate_registered_worktree_backlink(®istration)?; + if !already_known { + self.record_repository_ancestry(®istration.root)?; + } + } + Ok(()) + } + + fn validate_registered_worktree_backlink( + &self, + registration: &RegisteredWorktree, + ) -> Result<(), GitReadError> { + match std::fs::metadata(®istration.root) { + Ok(metadata) if metadata.is_dir() => {} + Ok(_) => { + return Err(GitReadError::InvalidRepositoryMetadata { + path: registration.root.clone(), + reason: "registered Git worktree is not a directory".to_string(), + }); + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(()); + } + Err(error) => return Err(invalid_metadata(®istration.root, error)), + } + let marker = registration.root.join(".git"); + match std::fs::symlink_metadata(&marker) { + Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {} + Ok(_) => { + return Err(GitReadError::InvalidRepositoryMetadata { + path: marker, + reason: "unsupported registered Git worktree marker".to_string(), + }); + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(()); + } + Err(error) => return Err(invalid_metadata(&marker, error)), + } + let resolved = resolve_repository_metadata(&marker) + .map_err(|error| invalid_metadata(&marker, error))?; + if !directories_refer_to_same_location(&resolved.git_dir, ®istration.admin_dir) + .map_err(|error| invalid_metadata(&marker, error))? + { + return Err(GitReadError::UnsafeRepositoryMetadata { + path: marker, + reason: "Git worktree registry backlink mismatch".to_string(), + }); + } + Ok(()) + } + + fn record_common_dir_ancestry(&mut self, common_dir: PathBuf) -> Result<(), GitReadError> { + for ancestor in common_dir.parent().into_iter().flat_map(Path::ancestors) { + let marker = ancestor.join(".git"); + match std::fs::symlink_metadata(&marker) { + Ok(_) => { + let canonical_root = std::fs::canonicalize(ancestor) + .map_err(|error| invalid_metadata(&marker, error))?; + let already_known = self.roots.iter().any(|root| { + paths_equal(root, ancestor) || paths_equal(root, &canonical_root) + }); + push_unique(&mut self.roots, ancestor.to_path_buf()); + push_unique(&mut self.worktree_roots, ancestor.to_path_buf()); + push_unique(&mut self.roots, canonical_root.clone()); + push_unique(&mut self.worktree_roots, canonical_root); + if !already_known { + self.record_repository_marker(ancestor)?; + } + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(invalid_metadata(&marker, error)), + } + } + Ok(()) + } +} diff --git a/codex-rs/git-utils/src/repository_authority/authority/policy.rs b/codex-rs/git-utils/src/repository_authority/authority/policy.rs new file mode 100644 index 0000000000..7539bc48a3 --- /dev/null +++ b/codex-rs/git-utils/src/repository_authority/authority/policy.rs @@ -0,0 +1,175 @@ +use std::collections::BTreeSet; +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use crate::errors::GitReadError; +use crate::git_config::path_is_within; + +use super::super::RepositoryMetadataRouteKind; +use super::super::ResolvedRepositoryMetadata; +use super::super::authority_refusal; +use super::super::directories_refer_to_same_location; +use super::super::helpers::canonical_existing_ancestors; +use super::super::helpers::invalid_metadata; +use super::super::helpers::paths_equal; +use super::super::repository_common_dir_for_candidate_root; +use super::RepositoryAuthority; + +impl RepositoryAuthority { + pub(crate) fn canonical_command_cwd(&self, cwd: &Path) -> io::Result { + let canonical = std::fs::canonicalize(cwd)?; + let inspection = self.route_boundaries.inspect_route(cwd)?; + if (inspection.touches_worktree || inspection.crosses_worktree) + && !path_is_within(&canonical, &self.active_worktree_root) + { + return Err(authority_refusal(format!( + "refusing Git command cwd that no longer resolves within the selected worktree: {}", + cwd.display() + ))); + } + Ok(canonical) + } + + pub(crate) fn ensure_config_source_is_not_worktree_controlled( + &self, + path: &Path, + description: &str, + ) -> io::Result<()> { + if !path.is_absolute() { + return Err(worktree_controlled_config_source(path, description)); + } + let inspection = self.route_boundaries.inspect_route(path)?; + if inspection.crosses_worktree { + return Err(worktree_controlled_config_source(path, description)); + } + for observed in inspection.observed_paths { + if self.route_boundaries.contains_known_boundary(&observed)? { + continue; + } + if self.has_related_repository_ancestor(&observed)? { + return Err(worktree_controlled_config_source(path, description)); + } + } + Ok(()) + } + + pub(super) fn path_is_untrusted_for_executable_result(&self, path: &Path) -> io::Result { + let inspection = self.route_boundaries.inspect_route(path)?; + if inspection.touches_worktree || inspection.crosses_metadata { + return Ok(true); + } + for candidate in inspection.observed_paths { + if self.route_boundaries.contains_known_boundary(&candidate)? { + continue; + } + if self.has_related_repository_ancestor(&candidate)? { + return Ok(true); + } + } + Ok(false) + } + + fn has_related_repository_ancestor(&self, path: &Path) -> io::Result { + let mut ancestors = path.ancestors().map(Path::to_path_buf).collect::>(); + ancestors.extend(canonical_existing_ancestors(path)?); + let mut seen = BTreeSet::new(); + for ancestor in ancestors { + if !seen.insert(ancestor.clone()) { + continue; + } + let Some(common_dir) = repository_common_dir_for_candidate_root(&ancestor)? else { + continue; + }; + for protected in &self.common_dirs { + if directories_refer_to_same_location(protected, &common_dir)? { + return Ok(true); + } + } + } + Ok(false) + } + + pub(super) fn validate_metadata_routes(&self) -> Result<(), GitReadError> { + for snapshot in &self.metadata_snapshots { + self.validate_snapshot_routes(snapshot)?; + } + Ok(()) + } + + pub(super) fn validate_registered_worktree_routes(&self) -> Result<(), GitReadError> { + for registration in &self.registered_worktrees { + if self + .route_boundaries + .retained_route_is_untrusted(®istration.marker_route) + .map_err(|error| invalid_metadata(®istration.admin_dir.join("gitdir"), error))? + { + return Err(GitReadError::UnsafeRepositoryMetadata { + path: registration.admin_dir.join("gitdir"), + reason: "Git worktree registry route crosses a repository worktree".to_string(), + }); + } + } + Ok(()) + } + + pub(super) fn validate_snapshot_routes( + &self, + snapshot: &ResolvedRepositoryMetadata, + ) -> Result<(), GitReadError> { + for route in &snapshot.routes { + if route.kind == RepositoryMetadataRouteKind::StandardDirectory { + let root = route.spelling.parent().ok_or_else(|| { + GitReadError::InvalidRepositoryMetadata { + path: route.spelling.clone(), + reason: "Git metadata directory has no worktree parent".to_string(), + } + })?; + let expected = std::fs::canonicalize(root) + .map_err(|error| invalid_metadata(root, error))? + .join(".git"); + if !paths_equal(&route.target, &expected) { + return Err(GitReadError::UnsafeRepositoryMetadata { + path: snapshot.marker.clone(), + reason: "nonstandard Git metadata directory".to_string(), + }); + } + if self + .route_boundaries + .route_cancels_worktree_descendant(&route.spelling) + .map_err(|error| invalid_metadata(&route.spelling, error))? + { + return Err(GitReadError::UnsafeRepositoryMetadata { + path: snapshot.marker.clone(), + reason: "Git metadata route crosses a repository worktree".to_string(), + }); + } + continue; + } + let spelling_crosses = self + .route_boundaries + .inspect_route(&route.spelling) + .map_err(|error| invalid_metadata(&route.spelling, error))? + .crosses_worktree; + let target_crosses = self + .route_boundaries + .inspect_route(&route.target) + .map_err(|error| invalid_metadata(&route.target, error))? + .crosses_worktree; + if spelling_crosses || target_crosses { + return Err(GitReadError::UnsafeRepositoryMetadata { + path: snapshot.marker.clone(), + reason: "Git metadata route crosses a repository worktree".to_string(), + }); + } + } + Ok(()) + } +} + +fn worktree_controlled_config_source(path: &Path, description: &str) -> io::Error { + authority_refusal(format!( + "refusing to use worktree-controlled {description}: {}", + path.display() + )) +} diff --git a/codex-rs/git-utils/src/repository_authority/helpers.rs b/codex-rs/git-utils/src/repository_authority/helpers.rs new file mode 100644 index 0000000000..e05969ce52 --- /dev/null +++ b/codex-rs/git-utils/src/repository_authority/helpers.rs @@ -0,0 +1,89 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use crate::errors::GitReadError; +use crate::git_config::path_is_within; + +use super::directories_refer_to_same_location; +use super::path_has_untrusted_root_identity_ancestor; + +#[derive(Clone, Debug)] +pub(super) struct RegisteredWorktree { + pub(super) root: PathBuf, + pub(super) admin_dir: PathBuf, + pub(super) marker_route: PathBuf, +} + +#[derive(Debug)] +pub(super) struct RegisteredWorktreeReadError { + pub(super) path: PathBuf, + pub(super) source: io::Error, +} + +pub(super) fn registry_error(path: &Path, source: io::Error) -> RegisteredWorktreeReadError { + RegisteredWorktreeReadError { + path: path.to_path_buf(), + source, + } +} + +pub(super) fn common_dir_is_within_untrusted_root(common_dir: &Path, roots: &[PathBuf]) -> bool { + for root in roots { + if directories_refer_to_same_location(common_dir, root).unwrap_or(false) { + continue; + } + if path_is_within(common_dir, root) + || path_has_untrusted_root_identity_ancestor(common_dir, std::slice::from_ref(root)) + { + return true; + } + } + false +} + +pub(super) fn canonical_existing_ancestors(path: &Path) -> io::Result> { + let mut canonical = Vec::new(); + for ancestor in path.ancestors() { + match std::fs::canonicalize(ancestor) { + Ok(path) => canonical.push(path), + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => {} + Err(error) => return Err(error), + } + } + Ok(canonical) +} + +pub(super) fn validated_logical_process_cwd(canonical_cwd: &Path) -> Option { + let process_cwd = std::fs::canonicalize(std::env::current_dir().ok()?).ok()?; + if !paths_equal(&process_cwd, canonical_cwd) { + return None; + } + let logical_cwd = PathBuf::from(std::env::var_os("PWD")?); + if !logical_cwd.is_absolute() { + return None; + } + let canonical_logical_cwd = std::fs::canonicalize(&logical_cwd).ok()?; + paths_equal(&canonical_logical_cwd, canonical_cwd).then_some(logical_cwd) +} + +pub(super) fn push_unique(paths: &mut Vec, path: PathBuf) { + if !paths.iter().any(|existing| paths_equal(existing, &path)) { + paths.push(path); + } +} + +pub(super) fn paths_equal(left: &Path, right: &Path) -> bool { + path_is_within(left, right) && path_is_within(right, left) +} + +pub(super) fn invalid_metadata(path: &Path, error: io::Error) -> GitReadError { + GitReadError::InvalidRepositoryMetadata { + path: path.to_path_buf(), + reason: error.to_string(), + } +} diff --git a/codex-rs/git-utils/src/repository_authority/plain_config.rs b/codex-rs/git-utils/src/repository_authority/plain_config.rs new file mode 100644 index 0000000000..b3a4253b77 --- /dev/null +++ b/codex-rs/git-utils/src/repository_authority/plain_config.rs @@ -0,0 +1,137 @@ +use std::io; +use std::path::Path; +use std::path::PathBuf; + +use super::bytes_to_path; +use super::read_bounded_file; + +#[derive(Debug, Eq, PartialEq)] +pub(crate) enum CommonConfigAuthority { + Bare, + Worktree(PathBuf), + Unproven, +} + +pub(crate) fn inspect_plain_common_config_authority( + common_dir: &Path, +) -> io::Result { + let config_path = common_dir.join("config"); + let metadata = match std::fs::symlink_metadata(&config_path) { + Ok(metadata) => metadata, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(CommonConfigAuthority::Unproven); + } + Err(error) => return Err(error), + }; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Ok(CommonConfigAuthority::Unproven); + } + let bytes = read_bounded_file( + &config_path, + 1024 * 1024, + "Git common config is too large for authority proof", + )?; + let config = match gix::config::File::from_bytes_no_includes( + &bytes, + gix::config::file::Metadata::default(), + gix::config::file::init::Options::default(), + ) { + Ok(config) => config, + Err(_) => return Ok(CommonConfigAuthority::Unproven), + }; + if config.sections_by_name("include").is_some() + || config.sections_by_name("includeIf").is_some() + { + return Ok(CommonConfigAuthority::Unproven); + } + let bare = match unique_explicit_value(&config, "core", "bare") { + Ok(Some(value)) => match explicit_boolean(value.as_ref()) { + Some(value) => Some(value), + None => return Ok(CommonConfigAuthority::Unproven), + }, + Ok(None) => None, + Err(()) => return Ok(CommonConfigAuthority::Unproven), + }; + match unique_explicit_value(&config, "extensions", "worktreeConfig") { + Ok(Some(value)) if explicit_boolean(value.as_ref()) == Some(false) => {} + Ok(None) => {} + Ok(Some(_)) | Err(()) => return Ok(CommonConfigAuthority::Unproven), + } + let worktree = match unique_explicit_value(&config, "core", "worktree") { + Ok(Some(value)) => Some(value), + Ok(None) => None, + Err(()) => return Ok(CommonConfigAuthority::Unproven), + }; + if let Some(worktree) = worktree { + if bare == Some(true) { + return Ok(CommonConfigAuthority::Unproven); + } + let worktree = bytes_to_path(&worktree)?; + if worktree.as_os_str().is_empty() || !worktree.is_absolute() { + return Ok(CommonConfigAuthority::Unproven); + } + #[cfg(windows)] + if worktree + .to_str() + .is_none_or(crate::path_authority::windows_authority_path_is_ambiguous) + { + return Ok(CommonConfigAuthority::Unproven); + } + return Ok(CommonConfigAuthority::Worktree(worktree)); + } + Ok(if bare == Some(true) { + CommonConfigAuthority::Bare + } else { + CommonConfigAuthority::Unproven + }) +} + +fn unique_explicit_value( + config: &gix::config::File<'_>, + section_name: &str, + value_name: &str, +) -> Result>, ()> { + let Some(sections) = config.sections_by_name(section_name) else { + return Ok(None); + }; + let mut occurrences = 0usize; + let mut explicit_values = Vec::new(); + for section in sections { + if section.header().subsection_name().is_some() { + return Err(()); + } + occurrences += section + .value_names() + .filter(|name| { + let name: &str = name.as_ref(); + name.eq_ignore_ascii_case(value_name) + }) + .count(); + explicit_values.extend( + section + .values(value_name) + .into_iter() + .map(|value| value.as_ref().to_vec()), + ); + } + match (occurrences, explicit_values.len()) { + (0, 0) => Ok(None), + (1, 1) => Ok(explicit_values.pop()), + _ => Err(()), + } +} + +fn explicit_boolean(value: &[u8]) -> Option { + if value.eq_ignore_ascii_case(b"true") { + Some(true) + } else if value.eq_ignore_ascii_case(b"false") { + Some(false) + } else { + None + } +} diff --git a/codex-rs/git-utils/src/repository_authority_tests.rs b/codex-rs/git-utils/src/repository_authority_tests.rs new file mode 100644 index 0000000000..0447fa0d82 --- /dev/null +++ b/codex-rs/git-utils/src/repository_authority_tests.rs @@ -0,0 +1,270 @@ +use super::*; + +#[test] +fn unreadable_metadata_is_invalid_not_a_proven_policy_crossing() { + let marker = PathBuf::from("repository/.git/commondir"); + let error = super::helpers::invalid_metadata( + &marker, + io::Error::new( + io::ErrorKind::PermissionDenied, + "metadata marker is unreadable", + ), + ); + assert_eq!( + error, + crate::errors::GitReadError::InvalidRepositoryMetadata { + path: marker, + reason: "metadata marker is unreadable".to_string(), + } + ); + assert_eq!(error.io_kind(), io::ErrorKind::InvalidData); +} + +fn write_common_config(body: &[u8]) -> tempfile::TempDir { + let common = tempfile::tempdir().expect("common dir"); + std::fs::write(common.path().join("config"), body).expect("write common config"); + common +} + +fn git_config_path(path: &Path) -> String { + let path = path.to_string_lossy(); + #[cfg(windows)] + let path = path.replace('\\', "/"); + #[cfg(not(windows))] + let path = path.into_owned(); + format!("\"{}\"", path.replace('\\', "\\\\").replace('"', "\\\"")) +} + +fn native_bare_value(config: &Path, includes: bool) -> io::Result> { + let mut command = std::process::Command::new("git"); + crate::safe_git::isolate_git_command_environment(&mut command); + command + .args(["config", "--file"]) + .arg(config) + .arg(if includes { + "--includes" + } else { + "--no-includes" + }) + .args(["--type=bool", "--get", "core.bare"]); + let output = command.output()?; + match output.status.code() { + Some(0) => Ok(Some( + String::from_utf8_lossy(&output.stdout).trim() == "true", + )), + Some(1) if output.stdout.is_empty() => Ok(None), + _ => Err(io::Error::other(format!( + "native core.bare query failed: {}", + String::from_utf8_lossy(&output.stderr) + ))), + } +} + +#[test] +fn plain_common_bare_parser_matches_native_boolean_syntax_and_is_stricter_on_duplicates() { + for (name, body, expected, native) in [ + ( + "explicit true", + b"[core]\n\tbare = true\n".as_slice(), + CommonConfigAuthority::Bare, + Some(true), + ), + ( + "implicit true", + b"[core]\n\tbare\n".as_slice(), + CommonConfigAuthority::Unproven, + Some(true), + ), + ( + "quoted true", + b"[core]\n\tbare = \"true\"\n".as_slice(), + CommonConfigAuthority::Bare, + Some(true), + ), + ( + "false", + b"[core]\n\tbare = false\n".as_slice(), + CommonConfigAuthority::Unproven, + Some(false), + ), + ( + "duplicate last true", + b"[core]\n\tbare = false\n\tbare = true\n".as_slice(), + CommonConfigAuthority::Unproven, + Some(true), + ), + ( + "duplicate last false", + b"[core]\n\tbare = true\n\tbare = false\n".as_slice(), + CommonConfigAuthority::Unproven, + Some(false), + ), + ( + "mixed implicit then explicit", + b"[core]\n\tbare\n\tbare = true\n".as_slice(), + CommonConfigAuthority::Unproven, + Some(true), + ), + ( + "mixed explicit then implicit", + b"[core]\n\tbare = false\n\tbare\n".as_slice(), + CommonConfigAuthority::Unproven, + Some(true), + ), + ( + "mixed case duplicate", + b"[core]\n\tbare = false\n\tBaRe = true\n".as_slice(), + CommonConfigAuthority::Unproven, + Some(true), + ), + ] { + let common = write_common_config(body); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect(name), + expected, + "authority result for {name}" + ); + assert_eq!( + native_bare_value(&common.path().join("config"), /*includes*/ false).expect(name), + native, + "native result for {name}" + ); + } +} + +#[test] +fn common_bare_proof_accepts_only_explicit_boolean_literals() { + for (name, body) in [ + ("empty", b"[core]\n\tbare =\n".as_slice()), + ("yes", b"[core]\n\tbare = yes\n".as_slice()), + ("on", b"[core]\n\tbare = on\n".as_slice()), + ("one", b"[core]\n\tbare = 1\n".as_slice()), + ("leading zero", b"[core]\n\tbare = 08\n".as_slice()), + ( + "positive overflow", + b"[core]\n\tbare = 2147483648\n".as_slice(), + ), + ( + "negative overflow", + b"[core]\n\tbare = -2147483649\n".as_slice(), + ), + ( + "i64 max", + b"[core]\n\tbare = 9223372036854775807\n".as_slice(), + ), + ] { + let common = write_common_config(body); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect(name), + CommonConfigAuthority::Unproven, + "authority result for {name}" + ); + } +} + +#[test] +fn common_bare_proof_rejects_includes_worktree_config_and_relative_worktree() { + let include_target = tempfile::NamedTempFile::new().expect("included config"); + std::fs::write(include_target.path(), "[core]\n\tbare = false\n") + .expect("write included config"); + let common = write_common_config( + format!( + "[core]\n\tbare = true\n[include]\n\tpath = {}\n", + git_config_path(include_target.path()) + ) + .as_bytes(), + ); + assert_eq!( + native_bare_value(&common.path().join("config"), /*includes*/ false) + .expect("direct native bare"), + Some(true) + ); + assert_eq!( + native_bare_value(&common.path().join("config"), /*includes*/ true) + .expect("included native bare"), + Some(false) + ); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect("include authority"), + CommonConfigAuthority::Unproven + ); + + for body in [ + b"[core]\n\tbare = true\n[includeIf \"gitdir:**\"]\n\tpath = /tmp/ignored\n".as_slice(), + b"[core]\n\tbare = true\n[extensions]\n\tworktreeConfig = true\n".as_slice(), + b"[core]\n\tbare = true\n\tworktree = relative/path\n".as_slice(), + b"[core]\n\tbare = true\n[extensions]\n\tworktreeConfig\n".as_slice(), + b"[core]\n\tbare = true\n[extensions]\n\tworktreeConfig = false\n\tworktreeConfig\n" + .as_slice(), + b"[core]\n\tbare = true\n\tworktree\n".as_slice(), + b"[core]\n\tbare = true\n\tworktree = /tmp/one\n\tworktree\n".as_slice(), + b"[core \"unexpected\"]\n\tbare = true\n".as_slice(), + b"[extensions \"unexpected\"]\n\tworktreeConfig = false\n[core]\n\tbare = true\n" + .as_slice(), + ] { + let common = write_common_config(body); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect("ambiguous authority"), + CommonConfigAuthority::Unproven + ); + } +} + +#[test] +fn common_config_absolute_worktree_is_returned_as_authority() { + let worktree = tempfile::tempdir().expect("worktree"); + let common = write_common_config( + format!( + "[core]\n\tworktree = {}\n", + git_config_path(worktree.path()) + ) + .as_bytes(), + ); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect("worktree authority"), + CommonConfigAuthority::Worktree(worktree.path().to_path_buf()) + ); +} + +#[test] +fn common_config_rejects_contradictory_or_malformed_bare_with_absolute_worktree() { + let worktree = tempfile::tempdir().expect("worktree"); + for (name, bare) in [("contradictory bare", "true"), ("malformed bare", "08")] { + let common = write_common_config( + format!( + "[core]\n\tbare = {bare}\n\tworktree = {}\n", + git_config_path(worktree.path()) + ) + .as_bytes(), + ); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect(name), + CommonConfigAuthority::Unproven, + "authority result for {name}" + ); + } +} + +#[test] +fn windows_authority_path_grammar_rejects_ambiguous_primary_spellings() { + for path in [ + r"C:\primary.\repo", + r"C:\primary \repo", + r"C:\primary:stream\repo", + r"C:\NUL\repo", + r"\\?\GLOBALROOT\Device\HarddiskVolume1\repo", + r"\??\C:\primary\repo", + r"C:\outside\..\primary", + ] { + assert!( + crate::path_authority::windows_authority_path_is_ambiguous(path), + "ambiguous Windows authority path accepted: {path:?}" + ); + } + for path in [r"C:\primary\repo", r"\\server\share\primary\repo"] { + assert!( + !crate::path_authority::windows_authority_path_is_ambiguous(path), + "ordinary Windows authority path rejected: {path:?}" + ); + } +} diff --git a/codex-rs/git-utils/src/reverse_apply_tests.rs b/codex-rs/git-utils/src/reverse_apply_tests.rs index 3315b4a828..37fd0dac57 100644 --- a/codex-rs/git-utils/src/reverse_apply_tests.rs +++ b/codex-rs/git-utils/src/reverse_apply_tests.rs @@ -36,7 +36,7 @@ fn run(cwd: &Path, args: &[&str], input: Option<&[u8]>) -> std::process::Output } fn run_success(cwd: &Path, args: &[&str]) -> Vec { - let output = run(cwd, args, None); + let output = run(cwd, args, /*input*/ None); assert!( output.status.success(), "git {args:?}: {}", @@ -56,6 +56,26 @@ fn init_repo() -> tempfile::TempDir { repo } +fn read_file_normalized(path: &Path) -> String { + std::fs::read_to_string(path) + .expect("read file") + .replace("\r\n", "\n") +} + +fn run_success_with_apply_config(root: &Path, command_args: &[&str]) -> Vec { + let mut configured_args = configured_git_config_parts(); + configured_args.extend(command_args.iter().map(ToString::to_string)); + let configured_args = configured_args + .iter() + .map(String::as_str) + .collect::>(); + run_success(root, &configured_args) +} + +fn status_porcelain_with_apply_config(root: &Path) -> Vec { + run_success_with_apply_config(root, &["status", "--porcelain"]) +} + fn request(root: &Path, patch: &str) -> ApplyGitRequest { ApplyGitRequest { cwd: root.to_path_buf(), @@ -191,9 +211,9 @@ fn reverse_rename_accepts_each_partially_staged_form() { let result = apply_git_patch(&request(root, &patch)).expect("safe partial rename reverse"); assert_eq!(result.exit_code, 0, "{}", result.stderr); assert_eq!(result.applied_paths, vec!["old.txt"]); - assert_eq!(std::fs::read(root.join("old.txt")).unwrap(), b"old\n"); + assert_eq!(read_file_normalized(&root.join("old.txt")), "old\n"); assert!(!root.join("new.txt").exists()); - assert!(run_success(root, &["status", "--porcelain"]).is_empty()); + assert!(status_porcelain_with_apply_config(root).is_empty()); } } @@ -201,13 +221,13 @@ fn reverse_rename_accepts_each_partially_staged_form() { fn reverse_staged_delete_succeeds_but_recreated_worktree_is_refused() { let (repo, patch) = topology_fixture(Topology::Delete); let root = repo.path(); - run_success(root, &["rm", "-q", "old.txt"]); + run_success_with_apply_config(root, &["rm", "-q", "old.txt"]); let result = apply_git_patch(&request(root, &patch)).expect("already-staged reverse delete"); assert_eq!(result.exit_code, 0, "{}", result.stderr); assert_eq!(result.applied_paths, vec!["old.txt"]); - assert!(run_success(root, &["status", "--porcelain"]).is_empty()); + assert!(status_porcelain_with_apply_config(root).is_empty()); - run_success(root, &["rm", "-q", "old.txt"]); + run_success_with_apply_config(root, &["rm", "-q", "old.txt"]); std::fs::write(root.join("old.txt"), b"recreated\n").unwrap(); assert_refused_without_mutation(root, &patch); } @@ -374,7 +394,7 @@ fn reverse_mode_only_change_succeeds_when_repository_ignores_filemode() { & 0o777, base_mode ); - assert!(run_success(root, &["status", "--porcelain"]).is_empty()); + assert!(status_porcelain_with_apply_config(root).is_empty()); } } @@ -412,11 +432,11 @@ fn reverse_content_only_change_preserves_executable_index_mode_when_filemode_is_ assert_eq!(result.exit_code, 0, "{}", result.stderr); assert_eq!(result.applied_paths, vec!["script.sh"]); - assert_eq!(std::fs::read(root.join("script.sh")).unwrap(), b"old\n"); + assert_eq!(read_file_normalized(&root.join("script.sh")), "old\n"); let index = String::from_utf8(run_success(root, &["ls-files", "--stage", "script.sh"])).unwrap(); assert!(index.starts_with("100755 "), "{index}"); - assert!(run_success(root, &["status", "--porcelain"]).is_empty()); + assert!(status_porcelain_with_apply_config(root).is_empty()); } #[test] @@ -451,10 +471,7 @@ fn reverse_handles_unborn_empty_index_and_refuses_unborn_index_state() { let result = apply_git_patch(&request(clean.path(), DELETE_PATCH)).expect("unborn reverse add"); assert_eq!(result.exit_code, 0, "{}", result.stderr); assert_eq!(result.applied_paths, vec!["old.txt"]); - assert_eq!( - std::fs::read(clean.path().join("old.txt")).unwrap(), - b"old\n" - ); + assert_eq!(read_file_normalized(&clean.path().join("old.txt")), "old\n"); for intent_to_add in [false, true] { let repo = init_repo(); diff --git a/codex-rs/git-utils/src/reverse_staging.rs b/codex-rs/git-utils/src/reverse_staging.rs index 9f58269972..0f7cd21ea1 100644 --- a/codex-rs/git-utils/src/reverse_staging.rs +++ b/codex-rs/git-utils/src/reverse_staging.rs @@ -214,7 +214,7 @@ fn read_reverse_index_entries( paths: &[String], git_config_args: &[String], ) -> io::Result>> { - let mut command = git.command(); + let mut command = git.command_for_cwd(git_root)?; command .args(git_config_args) .args([ @@ -225,8 +225,7 @@ fn read_reverse_index_entries( "-z", "--", ]) - .args(paths) - .current_dir(git_root); + .args(paths); let output = git.output(command)?; if !output.status.success() { return Err(io::Error::other(format!( @@ -371,14 +370,13 @@ fn run_path_list_command( args: &[&str], operation: &str, ) -> io::Result> { - let mut command = git.command(); + let mut command = git.command_for_cwd(git_root)?; command .args(git_config_args) .args(extra_git_args) .args(args) .arg("--") - .args(paths) - .current_dir(git_root); + .args(paths); let output = git.output(command)?; if !output.status.success() { return Err(io::Error::other(format!( diff --git a/codex-rs/git-utils/src/safe_git.rs b/codex-rs/git-utils/src/safe_git.rs index 2da9d5e1b7..87ecde2f63 100644 --- a/codex-rs/git-utils/src/safe_git.rs +++ b/codex-rs/git-utils/src/safe_git.rs @@ -1,5 +1,6 @@ use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::ffi::OsString; use std::io; use std::io::Seek; use std::io::Write; @@ -10,12 +11,23 @@ use std::process::Stdio; use tokio::time::Duration; use crate::git_command::GitRunner; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; use crate::git_config::GitConfigEntry; -use crate::git_config::parse_effective_config; -use crate::git_config::parse_effective_config_with_origins; +use crate::git_config::read_effective_config_with_fallback as read_effective_config_unchecked; +use crate::git_config::read_effective_config_with_fallback_async as read_effective_config_unchecked_async; +use crate::git_config_sources::ensure_no_worktree_config_sources; +use crate::git_config_sources::ensure_no_worktree_config_sources_async; +#[path = "filter_sentinel.rs"] +mod filter_sentinel; +pub(crate) use filter_sentinel::SentinelFilterProbeBudget; +pub(crate) use filter_sentinel::SentinelFilterProbeResolution; +pub(crate) use filter_sentinel::classify_sentinel_filter_probes; +pub(crate) use filter_sentinel::sentinel_filter_probe_config_args; pub(crate) const DISABLED_HOOKS_PATH: &str = if cfg!(windows) { "NUL" } else { "/dev/null" }; -pub(crate) const EXECUTABLE_FILTER_CONFIG_PATTERN: &str = r"^filter\..*\.(clean|smudge|process)$"; +pub(crate) const EXECUTABLE_FILTER_CONFIG_PATTERN: &str = + r"^filter\..*\.(clean|smudge|process|required)$"; +pub(crate) const MAX_EXECUTABLE_FILTER_DRIVERS: usize = 256; /// Timeout for internal Git commands to prevent freezing on large repositories. pub(crate) const GIT_COMMAND_TIMEOUT: Duration = Duration::from_secs(5); @@ -56,15 +68,40 @@ impl GitConfigOverrideFile { value: &str, description: &str, ) -> io::Result<()> { - let mut command = git.command(); - command - .args(["config", "--file"]) - .arg(&self.config_path) - .arg("--add") - .arg(key) - .arg(value) - .current_dir(cwd); + let mut command = git.command_for_cwd(cwd)?; + command.args(self.add_value_args(key, value)); let output = git.output(command)?; + Self::check_add_value_output(output, description) + } + + pub(crate) async fn add_value_async( + &self, + git: &GitRunner, + cwd: &Path, + key: &str, + value: &str, + description: &str, + ) -> io::Result<()> { + let mut command = git.async_command_for_cwd(cwd)?; + command.args(self.add_value_args(key, value)); + let output = git + .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await?; + Self::check_add_value_output(output, description) + } + + fn add_value_args(&self, key: &str, value: &str) -> [OsString; 6] { + [ + OsString::from("config"), + OsString::from("--file"), + self.config_path.as_os_str().to_os_string(), + OsString::from("--add"), + OsString::from(key), + OsString::from(value), + ] + } + + fn check_add_value_output(output: std::process::Output, description: &str) -> io::Result<()> { if !output.status.success() { return Err(io::Error::other(format!( "failed to write {description} (status {}): {}", @@ -84,6 +121,7 @@ pub(crate) enum FilterAttributeValue { pub(crate) struct GitFilterNeutralization { config_override: Option, + filter_config: BTreeMap, } impl GitFilterNeutralization { @@ -93,8 +131,35 @@ impl GitFilterNeutralization { .map(GitConfigOverrideFile::git_config_args) .unwrap_or_default() } + + #[cfg(test)] + pub(crate) fn filter_value(&self, driver: &str, name: &str) -> Option<&str> { + effective_filter_value(&self.filter_config, driver, name) + } + + pub(crate) fn selected_filter_policy( + &self, + driver: &str, + required: Option, + ) -> SelectedFilterPolicy { + classify_selected_filter(&self.filter_config, driver, required) + } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum SelectedFilterPolicy { + Refused, + NeedsRequiredValue, + Allowed, +} + +const FILTER_NEUTRALIZATION_PLAN: [(&str, &str); 4] = [ + ("clean", ""), + ("smudge", ""), + ("process", ""), + ("required", "false"), +]; + const ISOLATED_GIT_ENVIRONMENT: [&str; 11] = [ "GIT_DIR", "GIT_WORK_TREE", @@ -122,12 +187,6 @@ pub(crate) fn isolate_git_command_environment(command: &mut Command) { } } -pub(crate) fn isolate_tokio_git_command_environment(command: &mut tokio::process::Command) { - for name in ISOLATED_GIT_ENVIRONMENT { - command.env_remove(name); - } -} - pub(crate) fn ensure_no_selected_executable_git_filters( git: &GitRunner, cwd: &Path, @@ -165,29 +224,54 @@ fn ensure_no_selected_executable_git_filters_for( git_config_args: &[String], execution: FilterExecution, ) -> io::Result { - let entries = read_filter_config(git, cwd, git_config_args)?; - let neutralized_drivers = executable_filter_drivers_for(&entries, execution)?; - let target_drivers = match execution { - FilterExecution::AnyWorktreeOperation => neutralized_drivers.clone(), - FilterExecution::GitAdd => executable_filter_drivers(&entries)?, - }; - if target_drivers.is_empty() { + let entries = read_filter_config(git, cwd, git_config_args).map_err(|error| { + if matches!(execution, FilterExecution::GitAdd) + && error.kind() == io::ErrorKind::InvalidData + { + io::Error::new( + io::ErrorKind::Unsupported, + format!("refusing malformed Git filter configuration: {error}"), + ) + } else { + error + } + })?; + let executable_drivers = executable_filter_drivers(&entries)?; + if executable_drivers.is_empty() { return Ok(GitFilterNeutralization { config_override: None, + filter_config: entries, }); } + let guard = executable_filter_guard(git, cwd, entries, &executable_drivers)?; let paths = paths .iter() .map(|path| path.as_bytes().to_vec()) .collect::>(); - let attributes = read_filter_attributes(git, cwd, &paths, git_config_args, &target_drivers)?; + let attributes = read_filter_attributes( + git, + cwd, + &paths, + git_config_args, + &executable_drivers, + &guard, + )?; + let mut required_cache = BTreeMap::new(); for (path, driver) in &attributes { - if !target_drivers.contains(driver) { + if !executable_drivers.contains(driver) { continue; } - let refused = neutralized_drivers.contains(driver) - || matches!(execution, FilterExecution::GitAdd) - && git_filter_required(git, cwd, driver, git_config_args)?; + let refused = match execution { + FilterExecution::AnyWorktreeOperation => true, + FilterExecution::GitAdd => git_add_filter_is_refused( + git, + cwd, + &guard.filter_config, + driver, + git_config_args, + &mut required_cache, + )?, + }; if refused { return Err(io::Error::new( io::ErrorKind::Unsupported, @@ -198,12 +282,29 @@ fn ensure_no_selected_executable_git_filters_for( )); } } - if neutralized_drivers.is_empty() { - return Ok(GitFilterNeutralization { - config_override: None, - }); + Ok(guard) +} + +fn git_add_filter_is_refused( + git: &GitRunner, + cwd: &Path, + entries: &BTreeMap, + driver: &str, + git_config_args: &[String], + required_cache: &mut BTreeMap, +) -> io::Result { + let required = required_cache.get(driver).copied(); + match classify_selected_filter(entries, driver, required) { + SelectedFilterPolicy::Refused => return Ok(true), + SelectedFilterPolicy::Allowed => return Ok(false), + SelectedFilterPolicy::NeedsRequiredValue => {} } - executable_filter_guard(git, cwd, entries, &neutralized_drivers) + let required = git_filter_required(git, cwd, driver, git_config_args)?; + required_cache.insert(driver.to_string(), required); + Ok(matches!( + classify_selected_filter(entries, driver, Some(required)), + SelectedFilterPolicy::Refused + )) } fn executable_filter_guard( @@ -213,34 +314,64 @@ fn executable_filter_guard( executable_drivers: &BTreeSet, ) -> io::Result { let config_override = GitConfigOverrideFile::new("filter-neutralization.gitconfig")?; + let mut guard = GitFilterNeutralization { + config_override: None, + filter_config, + }; for driver in executable_drivers { - debug_assert!(["clean", "smudge", "process"].into_iter().any(|name| { - effective_filter_value(&filter_config, driver, name) - .is_some_and(|value| !value.is_empty()) - })); + debug_assert_executable_filter_driver(&guard.filter_config, driver); let description = format!("Git filter neutralization for {driver:?}"); - for command in ["clean", "smudge", "process"] { - config_override.add_value( - git, - cwd, - &format!("filter.{driver}.{command}"), - "", - &description, - )?; + for (key, value) in filter_neutralization_entries(driver) { + config_override.add_value(git, cwd, &key, value, &description)?; + } + } + guard.config_override = Some(config_override); + Ok(guard) +} + +pub(crate) async fn executable_filter_guard_async( + git: &GitRunner, + cwd: &Path, + filter_config: BTreeMap, + executable_drivers: &BTreeSet, +) -> io::Result { + validate_executable_driver_count(executable_drivers)?; + if executable_drivers.is_empty() { + return Ok(GitFilterNeutralization { + config_override: None, + filter_config, + }); + } + let config_override = GitConfigOverrideFile::new("filter-neutralization.gitconfig")?; + for driver in executable_drivers { + debug_assert_executable_filter_driver(&filter_config, driver); + let description = format!("Git filter neutralization for {driver:?}"); + for (key, value) in filter_neutralization_entries(driver) { + config_override + .add_value_async(git, cwd, &key, value, &description) + .await?; } - config_override.add_value( - git, - cwd, - &format!("filter.{driver}.required"), - "false", - &description, - )?; } Ok(GitFilterNeutralization { config_override: Some(config_override), + filter_config, }) } +fn validate_executable_driver_count(executable_drivers: &BTreeSet) -> io::Result<()> { + if executable_drivers.len() > MAX_EXECUTABLE_FILTER_DRIVERS { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Git filter driver count {} exceeds the status guard limit {}", + executable_drivers.len(), + MAX_EXECUTABLE_FILTER_DRIVERS + ), + )); + } + Ok(()) +} + #[derive(Clone, Copy)] enum FilterExecution { AnyWorktreeOperation, @@ -268,6 +399,22 @@ fn read_filter_config( ) } +pub(crate) async fn read_filter_config_async( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], +) -> io::Result> { + ensure_no_worktree_config_sources_async(git, cwd, git_config_args).await?; + read_effective_config_unchecked_async( + git, + cwd, + git_config_args, + EXECUTABLE_FILTER_CONFIG_PATTERN, + "filter", + ) + .await +} + pub(crate) fn read_effective_config_with_fallback( git: &GitRunner, cwd: &Path, @@ -275,56 +422,8 @@ pub(crate) fn read_effective_config_with_fallback( pattern: &str, probe: &str, ) -> io::Result> { - let scoped = - run_effective_config_query(git, cwd, git_config_args, pattern, /*show_scope*/ true)?; - if scoped - .status - .code() - .is_some_and(|code| code == 0 || code == 1) - { - return parse_effective_config(&scoped.stdout); - } - - let legacy = run_effective_config_query( - git, - cwd, - git_config_args, - pattern, - /*show_scope*/ false, - )?; - if !legacy - .status - .code() - .is_some_and(|code| code == 0 || code == 1) - { - return Err(io::Error::other(format!( - "git {probe} config probe failed with status {}: {}", - legacy.status, - String::from_utf8_lossy(&legacy.stderr).trim() - ))); - } - parse_effective_config_with_origins(&legacy.stdout) -} - -fn run_effective_config_query( - git: &GitRunner, - cwd: &Path, - git_config_args: &[String], - pattern: &str, - show_scope: bool, -) -> io::Result { - let mut command = git.command(); - command - .env("GIT_OPTIONAL_LOCKS", "0") - .args(git_config_args) - .args(["config", "--null"]); - if show_scope { - command.arg("--show-scope"); - } - command - .args(["--show-origin", "--includes", "--get-regexp", pattern]) - .current_dir(cwd); - git.output(command) + ensure_no_worktree_config_sources(git, cwd, git_config_args)?; + read_effective_config_unchecked(git, cwd, git_config_args, pattern, probe) } fn read_filter_attributes( @@ -333,6 +432,7 @@ fn read_filter_attributes( paths: &[Vec], git_config_args: &[String], executable_drivers: &BTreeSet, + neutralization: &GitFilterNeutralization, ) -> io::Result, String>> { if paths.is_empty() { return Ok(BTreeMap::new()); @@ -341,7 +441,7 @@ fn read_filter_attributes( write_nul_paths(&mut input, paths)?; input.rewind()?; - let mut command = git.command(); + let mut command = git.command_for_cwd(cwd)?; command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) @@ -355,7 +455,6 @@ fn read_filter_attributes( "-z", "filter", ]) - .current_dir(cwd) .stdin(Stdio::from(input)); let output = git.output(command)?; if !output.status.success() { @@ -366,7 +465,14 @@ fn read_filter_attributes( ))); } let attributes = parse_filter_attributes(&output.stdout, paths)?; - resolve_filter_attribute_sentinels(git, cwd, attributes, git_config_args, executable_drivers) + resolve_filter_attribute_sentinels( + git, + cwd, + attributes, + git_config_args, + executable_drivers, + neutralization, + ) } fn resolve_filter_attribute_sentinels( @@ -375,8 +481,10 @@ fn resolve_filter_attribute_sentinels( attributes: BTreeMap, FilterAttributeValue>, git_config_args: &[String], executable_drivers: &BTreeSet, + neutralization: &GitFilterNeutralization, ) -> io::Result, String>> { let mut resolved = BTreeMap::new(); + let mut probe_budget = SentinelFilterProbeBudget::default(); for (path, attribute) in attributes { match attribute { FilterAttributeValue::Driver(driver) => { @@ -390,6 +498,8 @@ fn resolve_filter_attribute_sentinels( &path, &driver, git_config_args, + neutralization, + &mut probe_budget, )? { resolved.insert(path, driver); @@ -400,39 +510,37 @@ fn resolve_filter_attribute_sentinels( Ok(resolved) } -/// `git check-attr` serializes both its three special states and literal -/// driver names with the same `set`, `unset`, and `unspecified` strings. Ask -/// Git to resolve the ambiguity with every command for that driver overridden -/// to empty. A required literal driver fails while a special state succeeds. -/// Retrying with the driver optional distinguishes that expected failure from -/// an unrelated probe error. No filter process or shell is started. +/// Disambiguate Git's sentinel spellings with required/optional probes. The +/// shared guard blanks every known executable driver before either probe. fn sentinel_spelling_selects_filter_driver( git: &GitRunner, cwd: &Path, path: &[u8], driver: &str, git_config_args: &[String], + neutralization: &GitFilterNeutralization, + probe_budget: &mut SentinelFilterProbeBudget, ) -> io::Result { - let required = run_sentinel_selection_probe( + let probe = SentinelSelectionProbe { git, cwd, path, driver, git_config_args, - /*required*/ true, - )?; - if required.status.success() { + neutralization, + }; + let required = probe.run(/*required*/ true, probe_budget)?; + if classify_sentinel_filter_probes(required.status.success(), /*optional_succeeded*/ None) + == SentinelFilterProbeResolution::SpecialAttributeState + { return Ok(false); } - let optional = run_sentinel_selection_probe( - git, - cwd, - path, - driver, - git_config_args, - /*required*/ false, - )?; - if optional.status.success() { + let optional = probe.run(/*required*/ false, probe_budget)?; + if classify_sentinel_filter_probes( + required.status.success(), + /*optional_succeeded*/ Some(optional.status.success()), + ) == SentinelFilterProbeResolution::LiteralDriver + { return Ok(true); } Err(io::Error::other(format!( @@ -443,39 +551,47 @@ fn sentinel_spelling_selects_filter_driver( ))) } -fn run_sentinel_selection_probe( - git: &GitRunner, - cwd: &Path, - path: &[u8], - driver: &str, - git_config_args: &[String], - required: bool, -) -> io::Result { - let mut command = git.command(); - command - .env("GIT_OPTIONAL_LOCKS", "0") - .args(git_config_args) - .args([ - "-c", - &format!("core.hooksPath={DISABLED_HOOKS_PATH}"), - "-c", - "core.fsmonitor=false", - "-c", - &format!("filter.{driver}.required={required}"), - "-c", - &format!("filter.{driver}.clean="), - "-c", - &format!("filter.{driver}.smudge="), - "-c", - &format!("filter.{driver}.process="), - "hash-object", - "--stdin", - ]) - .arg("--path") - .arg(git_path_argument(path)?) - .current_dir(cwd) - .stdin(Stdio::null()); - git.output(command) +struct SentinelSelectionProbe<'a> { + git: &'a GitRunner, + cwd: &'a Path, + path: &'a [u8], + driver: &'a str, + git_config_args: &'a [String], + neutralization: &'a GitFilterNeutralization, +} + +impl SentinelSelectionProbe<'_> { + fn run( + &self, + required: bool, + probe_budget: &mut SentinelFilterProbeBudget, + ) -> io::Result { + let probe_config_args = sentinel_filter_probe_config_args( + self.neutralization.git_config_args(), + self.driver, + required, + )?; + let path = git_path_argument(self.path)?; + let mut command = self.git.command_for_cwd(self.cwd)?; + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(self.git_config_args) + .args([ + "-c", + &format!("core.hooksPath={DISABLED_HOOKS_PATH}"), + "-c", + "core.fsmonitor=false", + ]) + .args(&probe_config_args) + .args(["hash-object", "--stdin"]) + .arg("--path") + .arg(path) + .stdin(Stdio::null()); + probe_budget.ensure_probe_available()?; + let output = self.git.output(command)?; + probe_budget.record_completed_probe(); + Ok(output) + } } #[cfg(unix)] @@ -502,6 +618,7 @@ fn selected_executable_filter_for( Ok(selected_filter(&executable_drivers, attributes)) } +#[cfg(test)] pub(crate) fn selected_filter( drivers: &BTreeSet, attributes: &BTreeMap, String>, @@ -559,21 +676,58 @@ fn effective_filter_value<'a>( .map(|entry| entry.value.as_str()) } +fn filter_neutralization_entries( + driver: &str, +) -> impl Iterator + '_ { + FILTER_NEUTRALIZATION_PLAN + .into_iter() + .map(move |(name, value)| (format!("filter.{driver}.{name}"), value)) +} + +fn debug_assert_executable_filter_driver(entries: &BTreeMap, driver: &str) { + debug_assert!(["clean", "smudge", "process"].into_iter().any(|name| { + effective_filter_value(entries, driver, name).is_some_and(|value| !value.is_empty()) + })); +} + +fn classify_selected_filter( + entries: &BTreeMap, + driver: &str, + required: Option, +) -> SelectedFilterPolicy { + if ["clean", "process"].into_iter().any(|name| { + effective_filter_value(entries, driver, name).is_some_and(|value| !value.is_empty()) + }) { + return SelectedFilterPolicy::Refused; + } + match required { + None => SelectedFilterPolicy::NeedsRequiredValue, + Some(true) => SelectedFilterPolicy::Refused, + Some(false) => SelectedFilterPolicy::Allowed, + } +} + fn git_filter_required( git: &GitRunner, cwd: &Path, driver: &str, git_config_args: &[String], ) -> io::Result { - let mut command = git.command(); + let mut command = git.command_for_cwd(cwd)?; command .env("GIT_OPTIONAL_LOCKS", "0") .args(git_config_args) .args(["config", "--type=bool", "--get"]) - .arg(format!("filter.{driver}.required")) - .current_dir(cwd); + .arg(format!("filter.{driver}.required")); let output = git.output(command)?; - if output.status.code() == Some(1) && output.stderr.is_empty() { + parse_git_filter_required_output(&output, driver) +} + +pub(crate) fn parse_git_filter_required_output( + output: &std::process::Output, + driver: &str, +) -> io::Result { + if output.status.code() == Some(1) && output.stdout.is_empty() && output.stderr.is_empty() { return Ok(false); } if !output.status.success() { diff --git a/codex-rs/git-utils/src/safe_git_tests.rs b/codex-rs/git-utils/src/safe_git_tests.rs index 2fabd4efe0..8fa73d0386 100644 --- a/codex-rs/git-utils/src/safe_git_tests.rs +++ b/codex-rs/git-utils/src/safe_git_tests.rs @@ -7,8 +7,8 @@ use crate::git_config::GitConfigScope; #[cfg(unix)] use crate::patch_paths::stage_paths; use crate::status_guard::git_root_from_stdout; +use crate::status_guard::prepare_status_filter_guard; use crate::status_guard::resolve_git_root_async; -use crate::status_guard::selected_executable_filter_from; use crate::try_get_has_changes; use pretty_assertions::assert_eq; use std::collections::BTreeMap; @@ -18,8 +18,71 @@ use std::ffi::OsStr; use std::path::Path; #[cfg(unix)] use std::path::PathBuf; +use std::process::Output; use tokio::process::Command as TokioCommand; +const FILTER_MARKER_KEY: &str = "codex.sentinelprobe-ran"; +const FILTER_MARKER_COMMAND: &str = + "git config codex.sentinelprobe-ran true && git hash-object --stdin"; + +#[test] +fn status_filter_driver_limit_is_exact() { + let at_limit = (0..MAX_EXECUTABLE_FILTER_DRIVERS) + .map(|index| format!("driver-{index}")) + .collect::>(); + assert!(validate_executable_driver_count(&at_limit).is_ok()); + + let mut over_limit = at_limit; + over_limit.insert("one-too-many".to_string()); + let error = validate_executable_driver_count(&over_limit) + .expect_err("driver after exact limit must be refused"); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidData); +} + +fn run_git(cwd: &Path, args: &[&str]) -> Output { + let mut command = std::process::Command::new("git"); + isolate_git_command_environment(&mut command); + command + .current_dir(cwd) + .args(args) + .output() + .expect("run Git") +} + +fn run_git_success(cwd: &Path, args: &[&str]) -> Output { + let output = run_git(cwd, args); + assert!( + output.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + output +} + +fn init_filter_repo() -> tempfile::TempDir { + let repo = tempfile::tempdir().expect("tempdir"); + run_git_success(repo.path(), &["init"]); + std::fs::write(repo.path().join("file.txt"), "content\n").expect("write file"); + repo +} + +fn configure_marker_filter(cwd: &Path, driver: &str) { + run_git_success( + cwd, + &[ + "config", + &format!("filter.{driver}.clean"), + FILTER_MARKER_COMMAND, + ], + ); +} + +fn marker_filter_ran(cwd: &Path) -> bool { + run_git(cwd, &["config", "--get", FILTER_MARKER_KEY]) + .status + .success() +} + #[test] fn selected_filter_policy_allows_unused_and_rejects_selected_at_every_scope() { let config_dir = tempfile::tempdir().expect("config"); @@ -27,6 +90,7 @@ fn selected_filter_policy_allows_unused_and_rejects_selected_at_every_scope() { std::fs::write(&config, "").expect("config file"); for scope in [ + GitConfigScope::Unknown, GitConfigScope::System, GitConfigScope::Global, GitConfigScope::Local, @@ -98,16 +162,105 @@ fn git_add_filter_policy_rejects_clean_and_process_but_allows_smudge_only() { } #[test] -fn required_config_is_not_treated_as_an_executable_command() { +fn selected_filter_checkin_policy_table_is_canonical() { + for (command, required, expected) in [ + ("clean", None, SelectedFilterPolicy::Refused), + ("process", None, SelectedFilterPolicy::Refused), + ("smudge", None, SelectedFilterPolicy::NeedsRequiredValue), + ("smudge", Some(false), SelectedFilterPolicy::Allowed), + ("smudge", Some(true), SelectedFilterPolicy::Refused), + ] { + let entries = filter_entries( + GitConfigScope::Local, + Path::new(".git/config"), + &format!("filter.demo.{command}"), + "helper-command", + ); + assert_eq!( + classify_selected_filter(&entries, "demo", required), + expected, + "{command} required={required:?}" + ); + } +} + +#[tokio::test] +async fn sync_and_async_filter_guards_share_the_neutralization_plan() { + let repo = init_filter_repo(); + let root = repo.path(); + let git = GitRunner::for_cwd_io(root).expect("Git runner"); let entries = filter_entries( + GitConfigScope::Local, + Path::new(".git/config"), + "filter.demo.smudge", + "helper-command", + ); + let drivers = BTreeSet::from(["demo".to_string()]); + + let sync_guard = executable_filter_guard(&git, root, entries.clone(), &drivers) + .expect("sync neutralization"); + let async_guard = executable_filter_guard_async(&git, root, entries, &drivers) + .await + .expect("async neutralization"); + let read_plan = |guard: &GitFilterNeutralization| { + read_filter_config(&git, root, guard.git_config_args()) + .expect("read effective neutralization") + .into_iter() + .filter(|(key, _entry)| key.starts_with("filter.demo.")) + .map(|(key, entry)| (key, entry.value)) + .collect::>() + }; + let expected = filter_neutralization_entries("demo") + .map(|(key, value)| (key, value.to_string())) + .collect::>(); + + assert_eq!(read_plan(&sync_guard), expected); + assert_eq!(read_plan(&async_guard), expected); +} + +#[test] +fn filter_snapshot_retains_required_without_treating_it_as_executable() { + let mut entries = filter_entries( + GitConfigScope::Local, + Path::new("config"), + "filter.demo.smudge", + "smudge-command", + ); + entries.extend(filter_entries( GitConfigScope::Command, Path::new("command line:"), "filter.demo.required", "true", - ); + )); assert_eq!( executable_filter_drivers(&entries).expect("executable drivers"), - BTreeSet::new() + BTreeSet::from(["demo".to_string()]) + ); + let selected = BTreeMap::from([(b"file.txt".to_vec(), "demo".to_string())]); + assert_eq!( + selected_executable_filter_for(&entries, &selected, FilterExecution::GitAdd) + .expect("Git add filter policy"), + None + ); + let neutralization = GitFilterNeutralization { + config_override: None, + filter_config: entries, + }; + assert_eq!( + neutralization.filter_value("demo", "required"), + Some("true") + ); + + let required_only = filter_entries( + GitConfigScope::Local, + Path::new("config"), + "filter.demo.required", + "true", + ); + assert!( + executable_filter_drivers(&required_only) + .expect("required-only config") + .is_empty() ); } @@ -149,6 +302,211 @@ fn filter_attribute_parser_rejects_malformed_or_unexpected_records() { } } +#[test] +fn sentinel_probe_primitives_preserve_order_budget_and_truth_table() { + assert_eq!( + classify_sentinel_filter_probes( + /*required_succeeded*/ true, /*optional_succeeded*/ None, + ), + SentinelFilterProbeResolution::SpecialAttributeState + ); + assert_eq!( + classify_sentinel_filter_probes( + /*required_succeeded*/ false, /*optional_succeeded*/ None, + ), + SentinelFilterProbeResolution::NeedsOptionalProbe + ); + assert_eq!( + classify_sentinel_filter_probes( + /*required_succeeded*/ false, + /*optional_succeeded*/ Some(true), + ), + SentinelFilterProbeResolution::LiteralDriver + ); + assert_eq!( + classify_sentinel_filter_probes( + /*required_succeeded*/ false, + /*optional_succeeded*/ Some(false), + ), + SentinelFilterProbeResolution::ProbeFailure + ); + + let neutralization = vec![ + "-c".to_string(), + "include.path=/private/filter-neutralization.gitconfig".to_string(), + ]; + assert_eq!( + sentinel_filter_probe_config_args(&neutralization, "set", /*required*/ true) + .expect("sentinel config args"), + vec![ + "-c", + "include.path=/private/filter-neutralization.gitconfig", + "-c", + "filter.set.required=true", + ] + ); + assert_eq!( + sentinel_filter_probe_config_args(&neutralization, "ordinary", /*required*/ true) + .expect_err("reject non-sentinel config argument") + .kind(), + io::ErrorKind::InvalidInput + ); + + let mut budget = SentinelFilterProbeBudget::default(); + assert_eq!(SentinelFilterProbeBudget::max_probes(), 16); + for _ in 0..SentinelFilterProbeBudget::max_probes() { + budget.ensure_probe_available().expect("probe in budget"); + budget.record_completed_probe(); + } + assert_eq!( + budget + .ensure_probe_available() + .expect_err("hard probe budget") + .to_string(), + "refusing to continue Git filter sentinel disambiguation after 16 child probes (hard limit: 16)" + ); +} + +#[test] +fn sentinel_special_states_and_literal_driver_names_remain_distinct() { + for (driver, special_rule) in [ + ("set", "file.txt filter\n"), + ("unset", "file.txt -filter\n"), + ("unspecified", ""), + ] { + let repo = init_filter_repo(); + let root = repo.path(); + configure_marker_filter(root, driver); + let git = GitRunner::for_cwd_io(root).expect("trusted Git"); + + std::fs::write(root.join(".gitattributes"), special_rule).expect("write special attribute"); + ensure_no_selected_executable_git_filters(&git, root, &["file.txt".to_string()], &[]) + .expect("allow special attribute state"); + assert!(!marker_filter_ran(root), "special {driver}"); + + std::fs::write( + root.join(".gitattributes"), + format!("file.txt filter={driver}\n"), + ) + .expect("write literal attribute"); + let result = + ensure_no_selected_executable_git_filters(&git, root, &["file.txt".to_string()], &[]); + let error = match result { + Ok(_) => panic!("accepted literal sentinel-named driver {driver}"), + Err(error) => error, + }; + assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{driver}"); + assert!(!marker_filter_ran(root), "literal {driver}"); + } +} + +#[test] +fn sentinel_probe_neutralizes_every_known_driver_after_attribute_swap() { + for alternate_driver in ["race", "x=y"] { + let repo = init_filter_repo(); + let root = repo.path(); + configure_marker_filter(root, "set"); + configure_marker_filter(root, alternate_driver); + std::fs::write(root.join(".gitattributes"), "file.txt filter\n") + .expect("write initial attribute"); + + let git = GitRunner::for_cwd_io(root).expect("trusted Git"); + let entries = read_filter_config(&git, root, &[]).expect("filter config"); + let executable_drivers = executable_filter_drivers(&entries).expect("executable drivers"); + let neutralization = executable_filter_guard(&git, root, entries, &executable_drivers) + .expect("filter neutralization"); + let output = run_git_success(root, &["check-attr", "-z", "filter", "--", "file.txt"]); + let attributes = parse_filter_attributes(&output.stdout, &[b"file.txt".to_vec()]) + .expect("initial attribute snapshot"); + + std::fs::write( + root.join(".gitattributes"), + format!("file.txt filter={alternate_driver}\n"), + ) + .expect("swap attribute after snapshot"); + let resolved = resolve_filter_attribute_sentinels( + &git, + root, + attributes, + &[], + &executable_drivers, + &neutralization, + ) + .expect("resolve stale sentinel snapshot safely"); + assert!(resolved.is_empty(), "{alternate_driver}"); + assert!(!marker_filter_ran(root), "{alternate_driver}"); + } +} + +#[test] +fn high_cardinality_ordinary_sentinels_stop_at_hard_child_probe_budget() { + let repo = init_filter_repo(); + let root = repo.path(); + configure_marker_filter(root, "unspecified"); + let git = GitRunner::for_cwd_io(root).expect("trusted Git"); + let entries = read_filter_config(&git, root, &[]).expect("filter config"); + let executable_drivers = executable_filter_drivers(&entries).expect("executable drivers"); + let neutralization = executable_filter_guard(&git, root, entries, &executable_drivers) + .expect("filter neutralization"); + let attributes = (0..=SentinelFilterProbeBudget::max_probes()) + .map(|index| { + ( + format!("ordinary-{index}.txt").into_bytes(), + FilterAttributeValue::AmbiguousSentinel("unspecified".to_string()), + ) + }) + .collect(); + + let error = resolve_filter_attribute_sentinels( + &git, + root, + attributes, + &[], + &executable_drivers, + &neutralization, + ) + .expect_err("refuse sentinel work beyond hard child-probe budget"); + assert_eq!( + error.to_string(), + "refusing to continue Git filter sentinel disambiguation after 16 child probes (hard limit: 16)" + ); + assert!(!marker_filter_ran(root)); +} + +#[test] +fn unrelated_sentinel_probe_failures_remain_generic_and_fail_closed() { + let repo = init_filter_repo(); + let root = repo.path(); + configure_marker_filter(root, "set"); + std::fs::write(root.join(".gitattributes"), "file.txt filter\n") + .expect("write special attribute"); + let git = GitRunner::for_cwd_io(root).expect("trusted Git"); + let entries = read_filter_config(&git, root, &[]).expect("filter config"); + let executable_drivers = executable_filter_drivers(&entries).expect("executable drivers"); + let neutralization = executable_filter_guard(&git, root, entries, &executable_drivers) + .expect("filter neutralization"); + let mut budget = SentinelFilterProbeBudget::default(); + let malformed_config = ["-c".to_string(), "=".to_string()]; + + let error = sentinel_spelling_selects_filter_driver( + &git, + root, + b"file.txt", + "set", + &malformed_config, + &neutralization, + &mut budget, + ) + .expect_err("malformed config must fail both probes"); + assert_eq!(error.kind(), io::ErrorKind::Other); + assert!( + error + .to_string() + .starts_with("git filter attribute selection probe failed with required status") + ); + assert!(!marker_filter_ran(root)); +} + fn filter_entries( scope: GitConfigScope, origin: &Path, @@ -156,9 +514,9 @@ fn filter_entries( value: &str, ) -> BTreeMap { let origin = if origin == Path::new("command line:") { - "command line:".to_string() + crate::git_config::GitConfigOrigin::CommandLine } else { - format!("file:{}", origin.display()) + crate::git_config::GitConfigOrigin::File(origin.to_path_buf()) }; BTreeMap::from([( key.to_string(), @@ -193,7 +551,7 @@ fn run_isolated_test(test_name: &str, env: &[(&str, &OsStr)]) { ); } -async fn run_git(repo_path: &Path, args: &[&str]) { +async fn run_git_async(repo_path: &Path, args: &[&str]) { let output = TokioCommand::new("git") .args(args) .current_dir(repo_path) @@ -211,12 +569,12 @@ async fn run_git(repo_path: &Path, args: &[&str]) { async fn create_test_git_repo(temp_dir: &tempfile::TempDir) -> std::path::PathBuf { let repo_path = temp_dir.path().join("repo"); std::fs::create_dir(&repo_path).expect("create repo dir"); - run_git(&repo_path, &["init"]).await; - run_git(&repo_path, &["config", "user.name", "Test User"]).await; - run_git(&repo_path, &["config", "user.email", "test@example.com"]).await; + run_git_async(&repo_path, &["init"]).await; + run_git_async(&repo_path, &["config", "user.name", "Test User"]).await; + run_git_async(&repo_path, &["config", "user.email", "test@example.com"]).await; std::fs::write(repo_path.join("test.txt"), "test content").expect("write test file"); - run_git(&repo_path, &["add", "."]).await; - run_git(&repo_path, &["commit", "-m", "initial"]).await; + run_git_async(&repo_path, &["add", "."]).await; + run_git_async(&repo_path, &["commit", "-m", "initial"]).await; repo_path } @@ -225,9 +583,9 @@ async fn ordinary_apply_allows_an_unselected_executable_filter() { let temp_dir = tempfile::tempdir().expect("create temp dir"); let repo_path = create_test_git_repo(&temp_dir).await; std::fs::write(repo_path.join("test.txt"), "old\n").expect("write fixture"); - run_git(&repo_path, &["add", "test.txt"]).await; - run_git(&repo_path, &["commit", "-m", "normalize fixture"]).await; - run_git( + run_git_async(&repo_path, &["add", "test.txt"]).await; + run_git_async(&repo_path, &["commit", "-m", "normalize fixture"]).await; + run_git_async( &repo_path, &[ "config", @@ -259,9 +617,9 @@ async fn configure_clean_filter(repo_path: &Path, tracked_path: &str) { format!("{tracked_path} filter=x=y\n"), ) .expect("write attributes"); - run_git(repo_path, &["add", ".gitattributes"]).await; - run_git(repo_path, &["commit", "-m", "attributes"]).await; - run_git( + run_git_async(repo_path, &["add", ".gitattributes"]).await; + run_git_async(repo_path, &["commit", "-m", "attributes"]).await; + run_git_async( repo_path, &[ "config", @@ -290,19 +648,19 @@ async fn configured_filter_ran(repo_path: &Path) -> bool { async fn add_submodule_with_clean_filter(parent: &Path) { let source = tempfile::tempdir().expect("submodule source"); let source_path = source.path(); - run_git(source_path, &["init"]).await; - run_git(source_path, &["config", "user.name", "Test User"]).await; - run_git(source_path, &["config", "user.email", "test@example.com"]).await; + run_git_async(source_path, &["init"]).await; + run_git_async(source_path, &["config", "user.name", "Test User"]).await; + run_git_async(source_path, &["config", "user.email", "test@example.com"]).await; std::fs::write(source_path.join("nested.txt"), "original\n").expect("nested file"); std::fs::write( source_path.join(".gitattributes"), "nested.txt filter=codex-test\n", ) .expect("nested attributes"); - run_git(source_path, &["add", "."]).await; - run_git(source_path, &["commit", "-m", "seed"]).await; + run_git_async(source_path, &["add", "."]).await; + run_git_async(source_path, &["commit", "-m", "seed"]).await; - run_git( + run_git_async( parent, &[ "-c", @@ -314,9 +672,9 @@ async fn add_submodule_with_clean_filter(parent: &Path) { ], ) .await; - run_git(parent, &["commit", "-m", "add submodule"]).await; + run_git_async(parent, &["commit", "-m", "add submodule"]).await; let nested = parent.join("nested"); - run_git( + run_git_async( &nested, &[ "config", @@ -353,7 +711,7 @@ async fn get_has_changes_distinguishes_filter_sentinels_from_literal_driver_name let temp_dir = tempfile::tempdir().expect("create temp dir"); let repo_path = create_test_git_repo(&temp_dir).await; let clean_key = format!("filter.{driver}.clean"); - run_git( + run_git_async( &repo_path, &[ "config", @@ -370,8 +728,8 @@ async fn get_has_changes_distinguishes_filter_sentinels_from_literal_driver_name }; std::fs::write(repo_path.join(".gitattributes"), sentinel) .expect("write sentinel attribute"); - run_git(&repo_path, &["add", ".gitattributes"]).await; - run_git(&repo_path, &["commit", "-m", "sentinel attribute"]).await; + run_git_async(&repo_path, &["add", ".gitattributes"]).await; + run_git_async(&repo_path, &["commit", "-m", "sentinel attribute"]).await; assert_eq!(try_get_has_changes(&repo_path).await, Ok(false), "{driver}"); assert!(!configured_filter_ran(&repo_path).await, "{driver}"); @@ -415,7 +773,7 @@ async fn checked_has_changes_accepts_non_utf8_repository_root() { .path() .join(OsString::from_vec(b"repo-\xff".to_vec())); std::fs::create_dir(&repo_path).expect("create non-UTF-8 repository directory"); - run_git(&repo_path, &["init"]).await; + run_git_async(&repo_path, &["init"]).await; assert_eq!(try_get_has_changes(&repo_path).await, Ok(false)); } @@ -444,7 +802,8 @@ async fn root_probe_distinguishes_repository_command_failure() { permissions.set_mode(0o755); std::fs::set_permissions(&failing_git, permissions).expect("mark failing Git executable"); - let git = GitRunner::from_executable_for_test(failing_git); + let git = GitRunner::from_executable_for_test(&repo_path, failing_git) + .expect("authority-bound failing Git"); assert_eq!( resolve_git_root_async(&git, &repo_path).await, Err(GitReadError::CommandFailed { @@ -463,9 +822,9 @@ async fn legacy_git_without_show_scope_uses_origin_fallback() { let repo_path = create_test_git_repo(&temp_dir).await; std::fs::write(repo_path.join(".gitattributes"), "test.txt filter=legacy\n") .expect("attributes"); - run_git(&repo_path, &["add", ".gitattributes"]).await; - run_git(&repo_path, &["commit", "-m", "attributes"]).await; - run_git( + run_git_async(&repo_path, &["add", ".gitattributes"]).await; + run_git_async(&repo_path, &["commit", "-m", "attributes"]).await; + run_git_async( &repo_path, &["config", "filter.legacy.clean", "git hash-object --stdin"], ) @@ -495,10 +854,16 @@ async fn legacy_git_without_show_scope_uses_origin_fallback() { permissions.set_mode(0o755); std::fs::set_permissions(&wrapper, permissions).expect("legacy Git executable"); - let git = GitRunner::from_executable_for_test(wrapper); + let git = GitRunner::from_executable_for_test(&repo_path, wrapper) + .expect("authority-bound legacy Git"); assert_eq!( - selected_executable_filter_from(&git, &repo_path).await, - Ok(Some(("legacy".to_string(), b"test.txt".to_vec()))) + prepare_status_filter_guard(&git, &repo_path) + .await + .map(|_| ()), + Err(GitReadError::SelectedExecutableFilter { + driver: "legacy".to_string(), + path: "test.txt".to_string(), + }) ); } @@ -510,7 +875,7 @@ async fn get_has_changes_rejects_core_worktree_redirection_before_running_filter std::fs::create_dir(&redirected).expect("redirected worktree"); std::fs::write(redirected.join(".gitattributes"), "test.txt filter=x=y\n").expect("attributes"); std::fs::write(redirected.join("test.txt"), "redirected content\n").expect("redirected file"); - run_git( + run_git_async( &repo_path, &[ "config", @@ -519,7 +884,7 @@ async fn get_has_changes_rejects_core_worktree_redirection_before_running_filter ], ) .await; - run_git( + run_git_async( &repo_path, &[ "config", @@ -543,8 +908,8 @@ async fn legacy_git_config_cannot_hide_a_selected_local_filter_from_probe() { let repo_path = create_test_git_repo(&temp_dir).await; std::fs::write(repo_path.join(".gitattributes"), "test.txt filter=evil\n") .expect("attributes"); - run_git(&repo_path, &["add", ".gitattributes"]).await; - run_git(&repo_path, &["commit", "-m", "attributes"]).await; + run_git_async(&repo_path, &["add", ".gitattributes"]).await; + run_git_async(&repo_path, &["commit", "-m", "attributes"]).await; let marker = temp_dir.path().join("filter-ran"); let filter = repo_path.join("clean.sh"); @@ -558,7 +923,7 @@ async fn legacy_git_config_cannot_hide_a_selected_local_filter_from_probe() { .permissions(); permissions.set_mode(0o755); std::fs::set_permissions(&filter, permissions).expect("filter executable"); - run_git( + run_git_async( &repo_path, &[ "config", @@ -635,7 +1000,7 @@ async fn apply_and_stage_reject_global_relative_filter_without_running_it() { .permissions(); permissions.set_mode(0o755); std::fs::set_permissions(repo_path.join("clean.sh"), permissions).expect("filter executable"); - run_git( + run_git_async( &repo_path, &[ "-c", @@ -646,7 +1011,7 @@ async fn apply_and_stage_reject_global_relative_filter_without_running_it() { ], ) .await; - run_git( + run_git_async( &repo_path, &["-c", "filter.evil.clean=", "commit", "-m", "fixture"], ) @@ -687,8 +1052,8 @@ async fn nested_cwd_rejects_global_lfs_filter_without_running_it() { std::fs::create_dir(&repo_bin).expect("repository bin"); std::fs::write(repo_path.join(".gitattributes"), "test.txt filter=lfs\n") .expect("attributes"); - run_git(&repo_path, &["add", ".gitattributes"]).await; - run_git(&repo_path, &["commit", "-m", "attributes"]).await; + run_git_async(&repo_path, &["add", ".gitattributes"]).await; + run_git_async(&repo_path, &["commit", "-m", "attributes"]).await; std::fs::write(repo_path.join("test.txt"), "changed\n").expect("modify tracked file"); let config_dir = tempfile::tempdir().expect("config tempdir"); diff --git a/codex-rs/git-utils/src/status_guard.rs b/codex-rs/git-utils/src/status_guard.rs index fbcf5fb9af..bc5512753e 100644 --- a/codex-rs/git-utils/src/status_guard.rs +++ b/codex-rs/git-utils/src/status_guard.rs @@ -6,69 +6,131 @@ use std::path::Path; use std::path::PathBuf; use std::process::Stdio; -use tokio::process::Command as TokioCommand; +#[cfg(test)] use tokio::time::timeout; use crate::GitReadError; +use crate::git_command::GitAsyncCommand; use crate::git_command::GitRunner; -use crate::git_config::GitConfigEntry; -use crate::git_config::parse_effective_config; -use crate::git_config::parse_effective_config_with_origins; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; +use crate::repository_authority::is_authority_refusal; use crate::safe_git::DISABLED_HOOKS_PATH; -use crate::safe_git::EXECUTABLE_FILTER_CONFIG_PATTERN; use crate::safe_git::FilterAttributeValue; +#[cfg(test)] use crate::safe_git::GIT_COMMAND_TIMEOUT; +use crate::safe_git::GitFilterNeutralization; +use crate::safe_git::SelectedFilterPolicy; +use crate::safe_git::SentinelFilterProbeBudget; +use crate::safe_git::SentinelFilterProbeResolution; +use crate::safe_git::classify_sentinel_filter_probes; use crate::safe_git::executable_filter_drivers; +use crate::safe_git::executable_filter_guard_async; use crate::safe_git::git_path_argument; use crate::safe_git::parse_filter_attributes; +use crate::safe_git::parse_git_filter_required_output; use crate::safe_git::parse_nul_paths; -use crate::safe_git::selected_filter; +use crate::safe_git::read_filter_config_async; +use crate::safe_git::sentinel_filter_probe_config_args; use crate::safe_git::write_nul_paths; -pub(crate) async fn selected_executable_filter_from( +const MAX_STATUS_TRACKED_PATHS: usize = 250_000; + +#[cfg(test)] +pub(crate) async fn prepare_status_filter_guard( git: &GitRunner, cwd: &Path, -) -> Result)>, GitReadError> { - let git_root = resolve_git_root_async(git, cwd).await?; - let entries = read_filter_config_async(git, &git_root).await?; +) -> Result<(PathBuf, GitFilterNeutralization), GitReadError> { + timeout( + GIT_COMMAND_TIMEOUT, + Box::pin(prepare_status_filter_guard_within_deadline(git, cwd)), + ) + .await + .map_err(|_| GitReadError::CommandTimedOut { + operation: "statusFilterPreparation".to_string(), + })? +} + +pub(crate) async fn prepare_status_filter_guard_within_deadline( + git: &GitRunner, + cwd: &Path, +) -> Result<(PathBuf, GitFilterNeutralization), GitReadError> { + let requested_cwd = std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository { + path: cwd.to_path_buf(), + })?; + let authorized_root = git + .active_worktree_root() + .ok_or_else(|| GitReadError::NotRepository { + path: requested_cwd.clone(), + })? + .to_path_buf(); + // Source authorization precedes the first config-consuming Git child and + // is performed once for the retained active repository authority. + let entries = read_filter_config_async(git, &authorized_root, &[]) + .await + .map_err(|error| map_io_error("filterConfig", error))?; + let git_root = resolve_git_root_async(git, &requested_cwd).await?; let executable_drivers = executable_filter_drivers(&entries).map_err(|_| invalid_output("filterConfig"))?; + let filter_guard = executable_filter_guard_async(git, &git_root, entries, &executable_drivers) + .await + .map_err(|error| map_io_error("filterNeutralization", error))?; if executable_drivers.is_empty() { - return Ok(None); + return Ok((git_root, filter_guard)); } - let paths = read_paths_async(git, &git_root, PathSelection::Tracked).await?; + + let paths = read_tracked_paths_async(git, &git_root).await?; let attributes = read_filter_attributes_async(git, &git_root, &paths).await?; - let attributes = - resolve_filter_attribute_sentinels_async(git, &git_root, attributes, &executable_drivers) - .await?; - Ok(selected_filter(&executable_drivers, &attributes)) + let attributes = resolve_filter_attribute_sentinels_async( + git, + &git_root, + attributes, + &executable_drivers, + &filter_guard, + ) + .await?; + let mut required_cache = BTreeMap::new(); + for (path, driver) in attributes { + if !executable_drivers.contains(&driver) { + continue; + } + let mut policy = + filter_guard.selected_filter_policy(&driver, required_cache.get(&driver).copied()); + if policy == SelectedFilterPolicy::NeedsRequiredValue { + let required = git_filter_required_async(git, &git_root, &driver).await?; + required_cache.insert(driver.clone(), required); + policy = filter_guard.selected_filter_policy(&driver, Some(required)); + } + if policy == SelectedFilterPolicy::Refused { + return Err(GitReadError::SelectedExecutableFilter { + driver, + path: String::from_utf8_lossy(&path).into_owned(), + }); + } + } + Ok((git_root, filter_guard)) } pub(crate) async fn resolve_git_root_async( git: &GitRunner, - cwd: &Path, + requested_cwd: &Path, ) -> Result { - let requested_cwd = std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository { - path: cwd.to_path_buf(), - })?; - let expected_root = crate::get_git_repo_root(&requested_cwd) - .and_then(|root| std::fs::canonicalize(root).ok()) + let expected_root = git + .active_worktree_root() .ok_or_else(|| GitReadError::NotRepository { - path: requested_cwd.clone(), - })?; - let mut command = git.tokio_command(); - command - .env("GIT_OPTIONAL_LOCKS", "0") - .args([ - "-c", - &format!("core.hooksPath={DISABLED_HOOKS_PATH}"), - "-c", - "core.fsmonitor=false", - "rev-parse", - "--show-toplevel", - ]) - .current_dir(&requested_cwd) - .kill_on_drop(true); + path: requested_cwd.to_path_buf(), + })? + .to_path_buf(); + let mut command = git + .async_command_for_cwd(requested_cwd) + .map_err(|error| map_io_error("resolveGitRoot", error))?; + command.env("GIT_OPTIONAL_LOCKS", "0").args([ + "-c", + &format!("core.hooksPath={DISABLED_HOOKS_PATH}"), + "-c", + "core.fsmonitor=false", + "rev-parse", + "--show-toplevel", + ]); let output = command_output(git, command, "resolveGitRoot").await?; if !output.status.success() { return Err(command_failed("resolveGitRoot", output.status.code())); @@ -107,88 +169,31 @@ pub(crate) fn git_root_from_stdout(output: Vec) -> Result Result, GitReadError> { - let scoped = run_filter_config_query_async(git, cwd, /*show_scope*/ true).await?; - if scoped - .status - .code() - .is_some_and(|code| code == 0 || code == 1) - { - return parse_effective_config(&scoped.stdout).map_err(|_| invalid_output("filterConfig")); - } - - let legacy = run_filter_config_query_async(git, cwd, /*show_scope*/ false).await?; - if !legacy - .status - .code() - .is_some_and(|code| code == 0 || code == 1) - { - return Err(command_failed("filterConfig", legacy.status.code())); - } - parse_effective_config_with_origins(&legacy.stdout).map_err(|_| invalid_output("filterConfig")) -} - -async fn run_filter_config_query_async( - git: &GitRunner, - cwd: &Path, - show_scope: bool, -) -> Result { - let mut command = git.tokio_command(); - command.args(["config", "--null"]); - if show_scope { - command.arg("--show-scope"); - } - command - .args([ - "--show-origin", - "--includes", - "--get-regexp", - EXECUTABLE_FILTER_CONFIG_PATTERN, - ]) - .current_dir(cwd) - .kill_on_drop(true); - command_output(git, command, "filterConfig").await -} - -#[derive(Clone, Copy)] -enum PathSelection { - Tracked, -} - -async fn read_paths_async( - git: &GitRunner, - cwd: &Path, - selection: PathSelection, ) -> Result>, GitReadError> { - let mut command = git.tokio_command(); - let hooks_config = format!("core.hooksPath={DISABLED_HOOKS_PATH}"); - let mut args = vec![ + let mut command = git + .async_command_for_cwd(cwd) + .map_err(|error| map_io_error("trackedPaths", error))?; + command.env("GIT_OPTIONAL_LOCKS", "0").args([ "-c", - hooks_config.as_str(), + &format!("core.hooksPath={DISABLED_HOOKS_PATH}"), "-c", "core.fsmonitor=false", "ls-files", "-z", - ]; - match selection { - PathSelection::Tracked => args.push("--cached"), - } - command - .env("GIT_OPTIONAL_LOCKS", "0") - .args(args) - .current_dir(cwd) - .kill_on_drop(true); - let operation = match selection { - PathSelection::Tracked => "trackedPaths", - }; - let output = command_output(git, command, operation).await?; + "--cached", + ]); + let output = command_output(git, command, "trackedPaths").await?; if !output.status.success() { - return Err(command_failed(operation, output.status.code())); + return Err(command_failed("trackedPaths", output.status.code())); } - parse_nul_paths(&output.stdout).map_err(|_| invalid_output(operation)) + let paths = parse_nul_paths(&output.stdout).map_err(|_| invalid_output("trackedPaths"))?; + if paths.len() > MAX_STATUS_TRACKED_PATHS { + return Err(invalid_output("trackedPaths")); + } + Ok(paths) } async fn read_filter_attributes_async( @@ -199,14 +204,16 @@ async fn read_filter_attributes_async( if paths.is_empty() { return Ok(BTreeMap::new()); } - let mut input = tempfile::tempfile() - .map_err(|_| command_failed("filterAttributes", /*exit_code*/ None))?; + let mut input = + tempfile::tempfile().map_err(|error| map_io_error("filterAttributes", error))?; write_nul_paths(&mut input, paths).map_err(|_| invalid_output("filterAttributes"))?; input .rewind() - .map_err(|_| command_failed("filterAttributes", /*exit_code*/ None))?; + .map_err(|error| map_io_error("filterAttributes", error))?; - let mut command = git.tokio_command(); + let mut command = git + .async_command_for_cwd(cwd) + .map_err(|error| map_io_error("filterAttributes", error))?; command .env("GIT_OPTIONAL_LOCKS", "0") .args([ @@ -219,9 +226,7 @@ async fn read_filter_attributes_async( "-z", "filter", ]) - .current_dir(cwd) - .stdin(Stdio::from(input)) - .kill_on_drop(true); + .stdin(Stdio::from(input)); let output = command_output(git, command, "filterAttributes").await?; if !output.status.success() { return Err(command_failed("filterAttributes", output.status.code())); @@ -234,8 +239,10 @@ async fn resolve_filter_attribute_sentinels_async( cwd: &Path, attributes: BTreeMap, FilterAttributeValue>, executable_drivers: &BTreeSet, + filter_guard: &GitFilterNeutralization, ) -> Result, String>, GitReadError> { let mut resolved = BTreeMap::new(); + let mut probe_budget = SentinelFilterProbeBudget::default(); for (path, attribute) in attributes { match attribute { FilterAttributeValue::Driver(driver) => { @@ -243,8 +250,15 @@ async fn resolve_filter_attribute_sentinels_async( } FilterAttributeValue::AmbiguousSentinel(driver) => { if executable_drivers.contains(&driver) - && sentinel_spelling_selects_filter_driver_async(git, cwd, &path, &driver) - .await? + && sentinel_spelling_selects_filter_driver_async( + git, + cwd, + &path, + &driver, + filter_guard, + &mut probe_budget, + ) + .await? { resolved.insert(path, driver); } @@ -259,15 +273,37 @@ async fn sentinel_spelling_selects_filter_driver_async( cwd: &Path, path: &[u8], driver: &str, + filter_guard: &GitFilterNeutralization, + probe_budget: &mut SentinelFilterProbeBudget, ) -> Result { - let required = - run_sentinel_selection_probe_async(git, cwd, path, driver, /*required*/ true).await?; - if required.status.success() { + let required = run_sentinel_selection_probe_async( + git, + cwd, + path, + driver, + /*required*/ true, + filter_guard, + probe_budget, + ) + .await?; + if classify_sentinel_filter_probes(required.status.success(), /*optional_succeeded*/ None) + == SentinelFilterProbeResolution::SpecialAttributeState + { return Ok(false); } - let optional = - run_sentinel_selection_probe_async(git, cwd, path, driver, /*required*/ false).await?; - if optional.status.success() { + let optional = run_sentinel_selection_probe_async( + git, + cwd, + path, + driver, + /*required*/ false, + filter_guard, + probe_budget, + ) + .await?; + if classify_sentinel_filter_probes(required.status.success(), Some(optional.status.success())) + == SentinelFilterProbeResolution::LiteralDriver + { return Ok(true); } Err(command_failed( @@ -282,9 +318,21 @@ async fn run_sentinel_selection_probe_async( path: &[u8], driver: &str, required: bool, + filter_guard: &GitFilterNeutralization, + probe_budget: &mut SentinelFilterProbeBudget, ) -> Result { + probe_budget.ensure_probe_available().map_err(|_| { + GitReadError::FilterSelectionProbeLimitExceeded { + max_probes: SentinelFilterProbeBudget::max_probes(), + } + })?; let path = git_path_argument(path).map_err(|_| invalid_output("filterAttributeSelection"))?; - let mut command = git.tokio_command(); + let probe_config_args = + sentinel_filter_probe_config_args(filter_guard.git_config_args(), driver, required) + .map_err(|_| invalid_output("filterAttributeSelection"))?; + let mut command = git + .async_command_for_cwd(cwd) + .map_err(|error| map_io_error("filterAttributeSelection", error))?; command .env("GIT_OPTIONAL_LOCKS", "0") .args([ @@ -292,39 +340,56 @@ async fn run_sentinel_selection_probe_async( &format!("core.hooksPath={DISABLED_HOOKS_PATH}"), "-c", "core.fsmonitor=false", - "-c", - &format!("filter.{driver}.required={required}"), - "-c", - &format!("filter.{driver}.clean="), - "-c", - &format!("filter.{driver}.smudge="), - "-c", - &format!("filter.{driver}.process="), - "hash-object", - "--stdin", ]) + .args(&probe_config_args) + .args(["hash-object", "--stdin"]) .arg("--path") .arg(path) - .current_dir(cwd) - .stdin(Stdio::null()) - .kill_on_drop(true); - command_output(git, command, "filterAttributeSelection").await + .stdin(Stdio::null()); + let output = command_output(git, command, "filterAttributeSelection").await?; + probe_budget.record_completed_probe(); + Ok(output) +} + +async fn git_filter_required_async( + git: &GitRunner, + cwd: &Path, + driver: &str, +) -> Result { + let mut command = git + .async_command_for_cwd(cwd) + .map_err(|error| map_io_error("filterRequired", error))?; + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(["config", "--type=bool", "--get"]) + .arg(format!("filter.{driver}.required")); + let output = command_output(git, command, "filterRequired").await?; + parse_git_filter_required_output(&output, driver) + .map_err(|error| map_io_error("filterRequired", error)) } async fn command_output( git: &GitRunner, - command: TokioCommand, + command: GitAsyncCommand, operation: &str, ) -> Result { - match timeout(GIT_COMMAND_TIMEOUT, git.output_tokio(command)).await { - Err(_) => Err(GitReadError::CommandTimedOut { + git.output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await + .map_err(|error| map_io_error(operation, error)) +} + +pub(crate) fn map_io_error(operation: &str, error: io::Error) -> GitReadError { + if is_authority_refusal(&error) { + return GitReadError::AuthorityRefused { operation: operation.to_string(), - }), - Ok(Err(error)) if error.kind() == io::ErrorKind::NotFound => { - Err(GitReadError::NoTrustedGit) - } - Ok(Err(_)) => Err(command_failed(operation, /*exit_code*/ None)), - Ok(Ok(output)) => Ok(output), + }; + } + match error.kind() { + io::ErrorKind::TimedOut => GitReadError::CommandTimedOut { + operation: operation.to_string(), + }, + io::ErrorKind::InvalidData => invalid_output(operation), + _ => command_failed(operation, /*exit_code*/ None), } } @@ -340,3 +405,7 @@ fn invalid_output(operation: &str) -> GitReadError { operation: operation.to_string(), } } + +#[cfg(test)] +#[path = "status_guard_tests.rs"] +mod tests; diff --git a/codex-rs/git-utils/src/status_guard_tests.rs b/codex-rs/git-utils/src/status_guard_tests.rs new file mode 100644 index 0000000000..276ceaf16e --- /dev/null +++ b/codex-rs/git-utils/src/status_guard_tests.rs @@ -0,0 +1,431 @@ +#![cfg(unix)] + +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::path::PathBuf; + +use pretty_assertions::assert_eq; +use tokio::process::Command; + +use super::*; + +async fn run_git(cwd: &Path, args: &[&str]) -> std::process::Output { + let output = Command::new("git") + .args(args) + .current_dir(cwd) + .output() + .await + .expect("run Git"); + assert!( + output.status.success(), + "git {args:?} failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + output +} + +async fn init_repo(temp_dir: &tempfile::TempDir, file_count: usize) -> PathBuf { + let repo = temp_dir.path().join("repo"); + std::fs::create_dir(&repo).expect("create repository"); + run_git(&repo, &["init", "-q"]).await; + run_git(&repo, &["config", "user.name", "Test User"]).await; + run_git(&repo, &["config", "user.email", "test@example.com"]).await; + for index in 0..file_count { + std::fs::write(repo.join(format!("file-{index}.txt")), "contents\n") + .expect("write tracked file"); + } + if file_count == 0 { + std::fs::write(repo.join("test.txt"), "contents\n").expect("write tracked file"); + } + run_git(&repo, &["add", "."]).await; + run_git(&repo, &["commit", "-m", "seed"]).await; + repo +} + +fn real_git() -> PathBuf { + let output = std::process::Command::new("/bin/sh") + .args(["-c", "command -v git"]) + .output() + .expect("resolve Git"); + assert!(output.status.success(), "resolve Git"); + PathBuf::from( + String::from_utf8(output.stdout) + .expect("Git path UTF-8") + .trim(), + ) +} + +fn shell_quote(path: &Path) -> String { + format!("'{}'", path.to_string_lossy().replace('\'', "'\\''")) +} + +fn write_wrapper(path: &Path, body: &str) { + std::fs::write(path, body).expect("write Git wrapper"); + let mut permissions = std::fs::metadata(path) + .expect("read wrapper metadata") + .permissions(); + permissions.set_mode(0o755); + std::fs::set_permissions(path, permissions).expect("mark wrapper executable"); +} + +#[test] +fn io_error_mapping_preserves_authority_provenance() { + for error in [ + std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "ordinary filesystem denial", + ), + std::io::Error::new(std::io::ErrorKind::NotFound, "ordinary missing file"), + ] { + assert_eq!( + map_io_error("filterAttributes", error), + GitReadError::CommandFailed { + operation: "filterAttributes".to_string(), + exit_code: None, + } + ); + } + + assert_eq!( + map_io_error( + "resolveGitRoot", + crate::repository_authority::authority_refusal("policy refusal"), + ), + GitReadError::AuthorityRefused { + operation: "resolveGitRoot".to_string(), + } + ); +} + +#[tokio::test] +async fn dropping_status_preparation_kills_the_active_git_child() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, 0).await; + let wrapper = temp_dir.path().join("git-wrapper"); + let pid_file = wrapper.with_extension("pid"); + let blocker = wrapper.with_extension("block"); + let completed = wrapper.with_extension("completed"); + let mkfifo = std::process::Command::new("mkfifo") + .arg(&blocker) + .status() + .expect("create blocking FIFO"); + assert!(mkfifo.success(), "create blocking FIFO"); + write_wrapper( + &wrapper, + "#!/bin/sh\n\ + printf '%s\\n' \"$$\" >\"$0.pid\"\n\ + IFS= read -r line <\"$0.block\"\n\ + : >\"$0.completed\"\n\ + exit 0\n", + ); + let git = std::sync::Arc::new( + GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner"), + ); + let task_git = std::sync::Arc::clone(&git); + let task_repo = repo.clone(); + let task = + tokio::spawn(async move { prepare_status_filter_guard(&task_git, &task_repo).await }); + + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !pid_file.exists() { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("status preparation should launch its first Git child"); + let pid = std::fs::read_to_string(&pid_file) + .expect("read direct Git child PID") + .trim() + .to_string(); + task.abort(); + let error = match task.await { + Err(error) => error, + Ok(_) => panic!("caller cancellation should abort status preparation"), + }; + assert!(error.is_cancelled(), "{error}"); + + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + let alive = std::process::Command::new("/bin/kill") + .args(["-0", &pid]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .expect("probe direct Git child PID") + .success(); + if !alive { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("direct Git child should disappear after caller cancellation"); + assert!( + !completed.exists(), + "direct Git child completed instead of being cancelled" + ); +} + +async fn filter_marker_is_set(repo: &Path, key: &str) -> bool { + Command::new("git") + .args(["config", "--get", key]) + .current_dir(repo) + .status() + .await + .expect("read filter marker") + .success() +} + +#[tokio::test] +async fn prepared_guard_neutralizes_filter_selected_after_the_probe() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, 0).await; + run_git( + &repo, + &[ + "config", + "filter.race.clean", + "git config codex.race-ran true && git hash-object --stdin", + ], + ) + .await; + + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + let (root, guard) = prepare_status_filter_guard(&git, &repo) + .await + .expect("prepare status guard"); + std::fs::write(repo.join(".gitattributes"), "test.txt filter=race\n") + .expect("select filter after probe"); + + let mut command = git + .async_command_for_cwd(&root) + .expect("authorized status cwd"); + command + .args(["-c", &format!("core.hooksPath={DISABLED_HOOKS_PATH}")]) + .args(["-c", "core.fsmonitor=false"]) + .args(guard.git_config_args()) + .args(["status", "--porcelain"]); + let output = git.output_async(command).await.expect("run guarded status"); + + assert!(output.status.success(), "guarded status succeeds"); + assert!(!filter_marker_is_set(&repo, "codex.race-ran").await); +} + +#[tokio::test] +async fn optional_smudge_only_filter_is_allowed_but_required_is_refused() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, 0).await; + std::fs::write(repo.join(".gitattributes"), "test.txt filter=smudge-only\n") + .expect("select smudge filter"); + run_git(&repo, &["add", ".gitattributes"]).await; + run_git(&repo, &["commit", "-m", "attributes"]).await; + run_git( + &repo, + &[ + "config", + "filter.smudge-only.smudge", + "git config codex.smudge-ran true && cat", + ], + ) + .await; + + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + prepare_status_filter_guard(&git, &repo) + .await + .expect("allow optional smudge-only filter"); + assert!(!filter_marker_is_set(&repo, "codex.smudge-ran").await); + + run_git(&repo, &["config", "filter.smudge-only.required", "true"]).await; + assert_eq!( + prepare_status_filter_guard(&git, &repo).await.map(|_| ()), + Err(GitReadError::SelectedExecutableFilter { + driver: "smudge-only".to_string(), + path: "test.txt".to_string(), + }) + ); + assert!(!filter_marker_is_set(&repo, "codex.smudge-ran").await); +} + +#[tokio::test] +async fn optional_smudge_required_value_is_queried_once_per_driver() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, 2).await; + std::fs::write( + repo.join(".gitattributes"), + "file-0.txt filter=smudge-only\nfile-1.txt filter=smudge-only\n", + ) + .expect("select smudge filter for two paths"); + run_git(&repo, &["add", ".gitattributes"]).await; + run_git(&repo, &["commit", "-m", "attributes"]).await; + run_git( + &repo, + &[ + "config", + "filter.smudge-only.smudge", + "git config codex.smudge-ran true && cat", + ], + ) + .await; + + let wrapper = temp_dir.path().join("git-wrapper"); + let log = temp_dir.path().join("git-wrapper.log"); + let real_git = shell_quote(&real_git()); + write_wrapper( + &wrapper, + &format!( + "#!/bin/sh\nprintf '%s\\n' \"$*\" >>{}\nexec {real_git} \"$@\"\n", + shell_quote(&log) + ), + ); + let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner"); + + prepare_status_filter_guard(&git, &repo) + .await + .expect("allow optional smudge-only filter"); + let required_queries = std::fs::read_to_string(log) + .expect("read wrapper log") + .lines() + .filter(|line| line.contains(" config --type=bool --get filter.smudge-only.required")) + .count(); + assert_eq!(required_queries, 1); + assert!(!filter_marker_is_set(&repo, "codex.smudge-ran").await); +} + +#[tokio::test] +async fn sentinel_probe_neutralizes_a_race_selected_known_driver() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, 0).await; + std::fs::write(repo.join(".gitattributes"), "test.txt filter\n") + .expect("write sentinel attribute"); + run_git(&repo, &["add", ".gitattributes"]).await; + run_git(&repo, &["commit", "-m", "sentinel attribute"]).await; + for driver in ["set", "race"] { + run_git( + &repo, + &[ + "config", + &format!("filter.{driver}.clean"), + "git config codex.probe-filter-ran true && git hash-object --stdin", + ], + ) + .await; + } + + let wrapper = temp_dir.path().join("git-wrapper"); + let real_git = shell_quote(&real_git()); + let attributes = shell_quote(&repo.join(".gitattributes")); + write_wrapper( + &wrapper, + &format!( + "#!/bin/sh\nfor arg in \"$@\"; do\n if [ \"$arg\" = check-attr ]; then\n {real_git} \"$@\" >\"$0.output\"\n status=$?\n printf 'test.txt filter=race\\n' >{attributes}\n /bin/cat \"$0.output\"\n /bin/rm -f \"$0.output\"\n exit $status\n fi\ndone\nexec {real_git} \"$@\"\n" + ), + ); + let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner"); + + prepare_status_filter_guard(&git, &repo) + .await + .expect("probe remains non-executing across attribute race"); + assert!(!filter_marker_is_set(&repo, "codex.probe-filter-ran").await); +} + +#[tokio::test] +async fn sentinel_probe_budget_fails_closed_at_the_exact_process_limit() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let max_probes = SentinelFilterProbeBudget::max_probes(); + let repo = init_repo(&temp_dir, max_probes + 4).await; + run_git( + &repo, + &[ + "config", + "filter.unspecified.clean", + "git config codex.budget-filter-ran true && git hash-object --stdin", + ], + ) + .await; + + let wrapper = temp_dir.path().join("git-wrapper"); + let log = temp_dir.path().join("git-wrapper.log"); + let real_git = shell_quote(&real_git()); + write_wrapper( + &wrapper, + &format!( + "#!/bin/sh\nprintf '%s\\n' \"$*\" >>{}\nexec {real_git} \"$@\"\n", + shell_quote(&log) + ), + ); + let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner"); + + let result = tokio::time::timeout( + std::time::Duration::from_secs(10), + Box::pin(prepare_status_filter_guard_within_deadline(&git, &repo)), + ) + .await + .expect("sentinel budget test should complete"); + assert_eq!( + result.map(|_| ()), + Err(GitReadError::FilterSelectionProbeLimitExceeded { max_probes }) + ); + let probe_count = std::fs::read_to_string(log) + .expect("read wrapper log") + .lines() + .filter(|line| line.contains(" hash-object --stdin --path ")) + .count(); + assert_eq!(probe_count, max_probes); + assert!(!filter_marker_is_set(&repo, "codex.budget-filter-ran").await); +} + +#[tokio::test] +async fn ordinary_driver_uses_one_bulk_path_and_attribute_probe() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, 24).await; + run_git( + &repo, + &[ + "config", + "filter.ordinary.clean", + "git config codex.ordinary-filter-ran true && git hash-object --stdin", + ], + ) + .await; + + let wrapper = temp_dir.path().join("git-wrapper"); + let log = temp_dir.path().join("git-wrapper.log"); + let real_git = shell_quote(&real_git()); + write_wrapper( + &wrapper, + &format!( + "#!/bin/sh\nprintf '%s\\n' \"$*\" >>{}\nexec {real_git} \"$@\"\n", + shell_quote(&log) + ), + ); + let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner"); + + prepare_status_filter_guard(&git, &repo) + .await + .expect("prepare ordinary-driver guard"); + let lines = std::fs::read_to_string(log).expect("read wrapper log"); + assert_eq!( + lines + .lines() + .filter(|line| line.contains(" ls-files -z --cached")) + .count(), + 1 + ); + assert_eq!( + lines + .lines() + .filter(|line| line.contains(" check-attr --stdin -z filter")) + .count(), + 1 + ); + assert_eq!( + lines + .lines() + .filter(|line| line.contains(" hash-object --stdin --path ")) + .count(), + 0 + ); + assert!(!filter_marker_is_set(&repo, "codex.ordinary-filter-ran").await); +}