diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index d572f68f21..3356b66c14 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -804,7 +804,7 @@ "critical-section_1.2.0": "{\"dependencies\":[],\"features\":{\"restore-state-bool\":[],\"restore-state-none\":[],\"restore-state-u16\":[],\"restore-state-u32\":[],\"restore-state-u64\":[],\"restore-state-u8\":[],\"restore-state-usize\":[],\"std\":[\"restore-state-bool\"]}}", "crossbeam-channel_0.5.15": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.13.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"signal-hook\",\"req\":\"^0.3\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"crossbeam-utils/std\"]}}", "crossbeam-deque_0.8.6": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-epoch\",\"req\":\"^0.9.17\"},{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"crossbeam-epoch/std\",\"crossbeam-utils/std\"]}}", - "crossbeam-epoch_0.9.18": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"name\":\"loom-crate\",\"optional\":true,\"package\":\"loom\",\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"loom\":[\"loom-crate\",\"crossbeam-utils/loom\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", + "crossbeam-epoch_0.9.20": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"name\":\"loom-crate\",\"optional\":true,\"package\":\"loom\",\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"loom\":[\"loom-crate\",\"crossbeam-utils/loom\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", "crossbeam-queue_0.3.12": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", "crossbeam-utils_0.8.21": "{\"dependencies\":[{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"nightly\":[],\"std\":[]}}", "crossterm_winapi_0.9.1": "{\"dependencies\":[{\"features\":[\"winbase\",\"consoleapi\",\"processenv\",\"handleapi\",\"synchapi\",\"impl-default\"],\"name\":\"winapi\",\"req\":\"^0.3.8\",\"target\":\"cfg(windows)\"}],\"features\":{}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 3ba4ea8a25..d3bfac6e66 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3134,9 +3134,11 @@ dependencies = [ "codex-utils-path-uri", "futures", "gix", + "libc", "once_cell", "pretty_assertions", "regex", + "rustix 1.1.4", "same-file", "schemars 0.8.22", "serde", @@ -3146,6 +3148,7 @@ dependencies = [ "tokio", "ts-rs", "walkdir", + "windows-sys 0.52.0", ] [[package]] @@ -4821,9 +4824,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" dependencies = [ "crossbeam-utils", ] diff --git a/codex-rs/chatgpt/tests/suite/apply_command_e2e.rs b/codex-rs/chatgpt/tests/suite/apply_command_e2e.rs index c2d570528c..ed342d9aad 100644 --- a/codex-rs/chatgpt/tests/suite/apply_command_e2e.rs +++ b/codex-rs/chatgpt/tests/suite/apply_command_e2e.rs @@ -172,10 +172,7 @@ console.log(fib(10)); let apply_result = apply_diff_from_task(task_response, Some(repo_path.to_path_buf())).await; - assert!( - apply_result.is_err(), - "Expected apply to fail due to merge conflicts" - ); + let apply_error = apply_result.expect_err("Expected apply to fail due to merge conflicts"); let contents = std::fs::read_to_string(&fibonacci_path).expect("Failed to read fibonacci.js"); @@ -183,6 +180,6 @@ console.log(fib(10)); contents.contains("<<<<<<< HEAD") || contents.contains("=======") || contents.contains(">>>>>>> "), - "fibonacci.js should contain merge conflict markers, got: {contents}", + "fibonacci.js should contain merge conflict markers, got: {contents}\napply error: {apply_error:#}", ); } diff --git a/codex-rs/git-utils/Cargo.toml b/codex-rs/git-utils/Cargo.toml index 7d137de8f6..e79b845fb9 100644 --- a/codex-rs/git-utils/Cargo.toml +++ b/codex-rs/git-utils/Cargo.toml @@ -15,7 +15,7 @@ codex-file-system = { workspace = true } codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-path-uri = { workspace = true } -futures = { workspace = true, features = ["alloc", "executor"] } +futures = { workspace = true, features = ["alloc"] } gix = { workspace = true } once_cell = { workspace = true } regex = "1" @@ -33,7 +33,17 @@ ts-rs = { workspace = true, features = [ ] } walkdir = { workspace = true } +[target.'cfg(unix)'.dependencies] +libc = { workspace = true } + +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { version = "1.1.4", features = ["fs"] } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.52", features = ["Win32_Storage_FileSystem"] } + [dev-dependencies] +futures = { workspace = true, features = ["executor"] } pretty_assertions = { workspace = true } tokio = { workspace = true, features = ["test-util"] } diff --git a/codex-rs/git-utils/src/apply.rs b/codex-rs/git-utils/src/apply.rs index e01903aa16..373aa6ad64 100644 --- a/codex-rs/git-utils/src/apply.rs +++ b/codex-rs/git-utils/src/apply.rs @@ -10,15 +10,16 @@ use std::io; use std::path::Path; use std::path::PathBuf; -#[cfg(test)] -use crate::FsmonitorOverride; use crate::apply_output::parse_git_apply_output; use crate::git_command::GitRunner; use crate::guarded_config::GuardedGitConfig; use crate::patch_paths::extract_patch_path_inventory_guarded; -use crate::reverse_staging::stage_effective_paths_for_reverse; -#[cfg(test)] -use crate::safe_git::DISABLED_HOOKS_PATH; +use crate::reverse_staging::ReverseApplyMode; +use crate::reverse_staging::execute_reverse_staging_plan; +use crate::reverse_staging::execute_reverse_staging_plan_in_scratch; +use crate::reverse_staging::prepare_reverse_staging_plan; +use crate::reverse_staging::seal_reverse_staging_plan; +use crate::reverse_staging::validate_effective_paths_for_reverse; #[cfg(test)] use crate::safe_git::isolate_git_command_environment; @@ -43,6 +44,47 @@ pub struct ApplyGitResult { pub cmd_for_log: String, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ApplyStrategy { + Direct, + ThreeWay, +} + +#[cfg(test)] +thread_local! { + static AFTER_REVERSE_STAGING_HOOK: std::cell::RefCell>> = + std::cell::RefCell::new(None); +} + +#[cfg(test)] +fn install_after_reverse_staging_hook(hook: impl FnOnce() + 'static) { + AFTER_REVERSE_STAGING_HOOK.with(|slot| { + let previous = slot.borrow_mut().replace(Box::new(hook)); + assert!( + previous.is_none(), + "reverse staging test hook already installed" + ); + }); +} + +#[cfg(test)] +fn run_after_reverse_staging_hook() { + AFTER_REVERSE_STAGING_HOOK.with(|slot| { + if let Some(hook) = slot.borrow_mut().take() { + hook(); + } + }); +} + +impl ApplyStrategy { + fn reverse_mode(self) -> ReverseApplyMode { + match self { + Self::Direct => ReverseApplyMode::Direct, + Self::ThreeWay => ReverseApplyMode::ThreeWay, + } + } +} + /// Apply a unified diff to the target repository by shelling out to `git apply`. /// /// When [`ApplyGitRequest::preflight`] is `true`, this behaves like `git apply --check` and @@ -58,6 +100,7 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result { .and_then(std::fs::canonicalize)?; let mut config = GuardedGitConfig::authorize(&git, &expected_root, cfg_parts)?; resolve_git_root(&config, &requested_cwd)?; + config.freeze_apply_policy()?; // Write unified diff into a temporary file let (tmpdir, patch_path) = write_temp_patch(&req.diff)?; @@ -69,15 +112,38 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result { config.authorize_filter_paths(patch_paths)?; let patch_arg = patch_path.to_string_lossy().to_string(); + // Applicability checks conflate content conflicts with fatal whitespace + // policy. Parse the requested orientation independently first: numstat + // enforces the frozen whitespace policy without consulting or changing + // the index/worktree. This ordering makes a mixed conflict + policy error + // fail before merge-policy reads or reverse staging. + let (policy_rendered, policy_output) = config.run_apply_policy_gate(req.revert, &patch_arg)?; + let policy_code = policy_output.status.code().unwrap_or(-1); + let policy_stdout = String::from_utf8_lossy(&policy_output.stdout).into_owned(); + let policy_stderr = String::from_utf8_lossy(&policy_output.stderr).into_owned(); + if policy_code != 0 { + return Ok(structured_apply_result( + policy_code, + policy_stdout, + policy_stderr, + policy_rendered, + )); + } + // Optional preflight: dry-run only; do not modify working tree if req.preflight { - let mut check_args = vec!["apply".to_string(), "--check".to_string()]; + let (rendered, output) = config.run_apply_preflight_check(req.revert, &patch_arg)?; + let c_code = output.status.code().unwrap_or(-1); + let c_out = String::from_utf8_lossy(&output.stdout).into_owned(); + let c_err = String::from_utf8_lossy(&output.stderr).into_owned(); if req.revert { - check_args.push("-R".to_string()); + let mode = if c_code == 0 { + ReverseApplyMode::Direct + } else { + ReverseApplyMode::ThreeWay + }; + validate_effective_paths_for_reverse(&config, patch_paths, mode)?; } - check_args.push(patch_arg); - let rendered = config.render_command_for_log(&check_args)?; - let (c_code, c_out, c_err) = run_guarded_apply(&config, &check_args)?; let (mut applied_paths, mut skipped_paths, mut conflicted_paths) = parse_git_apply_output(&c_out, &c_err); applied_paths.sort(); @@ -101,35 +167,71 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result { // reverse check must inspect the working tree before staging: requiring // the old index to match would misclassify a clean undo as a three-way // fallback. Forward direct application still requires index agreement. - let mut plain_check_args = vec!["apply".to_string(), "--check".to_string()]; - if !req.revert { - plain_check_args.push("--index".to_string()); - } - if req.revert { - plain_check_args.push("-R".to_string()); - } - plain_check_args.push(patch_arg.clone()); - let (plain_check_code, _, _) = run_guarded_apply(&config, &plain_check_args)?; + let plain_check = config.run_apply_strategy_check(req.revert, &patch_arg)?; + let plain_check_code = plain_check.status.code().unwrap_or(-1); - let mut args = vec!["apply".to_string()]; - if plain_check_code != 0 { - config.install_three_way_merge_policy()?; - args.push("--3way".to_string()); + let strategy = if plain_check_code != 0 { + ApplyStrategy::ThreeWay } else { - args.push("--index".to_string()); - } - if req.revert { - // Stage only after the worktree-only applicability decision. The - // guarded config is shared with the final Git command. - stage_effective_paths_for_reverse(&mut config, patch_paths)?; - } - if req.revert { - args.push("-R".to_string()); - } - args.push(patch_arg); + ApplyStrategy::Direct + }; + let reverse_plan = req + .revert + .then(|| prepare_reverse_staging_plan(&config, patch_paths, strategy.reverse_mode())) + .transpose()?; - let cmd_for_log = config.render_command_for_log(&args)?; - let (code, stdout, stderr) = run_guarded_apply(&config, &args)?; + if strategy == ApplyStrategy::ThreeWay { + config.install_three_way_merge_policy(&patch_path_inventory.primary_records)?; + } + let mut reverse_plan = reverse_plan + .map(|plan| seal_reverse_staging_plan(&mut config, plan)) + .transpose()?; + + if strategy == ApplyStrategy::ThreeWay && config.three_way_requires_merge_policy_proof()? { + let scratch = config.create_three_way_scratch_storage()?; + if let Some(plan) = &mut reverse_plan { + execute_reverse_staging_plan_in_scratch(&config, plan, &scratch)?; + } + config.prove_three_way_merge_policy_safety(&scratch, req.revert, &patch_arg)?; + } + + if let Some(plan) = reverse_plan { + // The same sealed plan was modeled in scratch before any merge-policy + // refusal could mutate the real index. + execute_reverse_staging_plan(&config, plan)?; + #[cfg(test)] + run_after_reverse_staging_hook(); + } + + let (cmd_for_log, output) = match strategy { + ApplyStrategy::Direct => { + // The fixed helper requires proof that the successful frozen- + // policy gate covered this exact patch and orientation. + let rendered = config.render_direct_apply_for_log(req.revert, &patch_arg)?; + let output = config.run_direct_apply(req.revert, &patch_arg)?; + ( + rendered, + ( + output.status.code().unwrap_or(-1), + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + ), + ) + } + ApplyStrategy::ThreeWay => { + let rendered = config.render_three_way_apply_for_log(req.revert, &patch_arg)?; + let output = config.run_three_way_apply(req.revert, &patch_arg)?; + ( + rendered, + ( + output.status.code().unwrap_or(-1), + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + ), + ) + } + }; + let (code, stdout, stderr) = output; let (mut applied_paths, mut skipped_paths, mut conflicted_paths) = if code == 0 { (patch_path_inventory.primary_paths, Vec::new(), Vec::new()) @@ -154,6 +256,31 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result { }) } +fn structured_apply_result( + exit_code: i32, + stdout: String, + stderr: String, + cmd_for_log: String, +) -> ApplyGitResult { + let (mut applied_paths, mut skipped_paths, mut conflicted_paths) = + parse_git_apply_output(&stdout, &stderr); + applied_paths.sort(); + applied_paths.dedup(); + skipped_paths.sort(); + skipped_paths.dedup(); + conflicted_paths.sort(); + conflicted_paths.dedup(); + ApplyGitResult { + exit_code, + applied_paths, + skipped_paths, + conflicted_paths, + stdout, + stderr, + cmd_for_log, + } +} + fn resolve_git_root(config: &GuardedGitConfig<'_>, requested_cwd: &Path) -> io::Result { let mut command = config.rev_parse_command()?; command.arg("--show-toplevel"); @@ -205,42 +332,6 @@ pub(crate) fn write_temp_patch(diff: &str) -> io::Result<(tempfile::TempDir, Pat Ok((dir, path)) } -fn run_guarded_apply( - config: &GuardedGitConfig<'_>, - args: &[String], -) -> io::Result<(i32, String, String)> { - let Some((subcommand, args)) = args.split_first() else { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "missing guarded Git subcommand", - )); - }; - if subcommand != "apply" { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "unexpected guarded Git subcommand", - )); - } - let mut command = config.apply_command()?; - command.args(args); - let output = command.output()?; - Ok(( - output.status.code().unwrap_or(-1), - String::from_utf8_lossy(&output.stdout).into_owned(), - String::from_utf8_lossy(&output.stderr).into_owned(), - )) -} - -#[cfg(test)] -pub(crate) fn safe_git_config_parts() -> Vec { - vec![ - "-c".to_string(), - format!("core.hooksPath={DISABLED_HOOKS_PATH}"), - "-c".to_string(), - FsmonitorOverride::Disabled.git_config_arg().to_string(), - ] -} - #[cfg(all(test, unix))] #[path = "apply_transport_tests.rs"] mod transport_tests; @@ -259,6 +350,7 @@ mod tests { use crate::guarded_config::config_source_authorization_count; use crate::guarded_config::merge_attribute_read_count; use crate::guarded_config::merge_config_read_count; + use crate::guarded_config::merge_overlay_count; use crate::guarded_config::reset_config_source_authorization_count; use crate::guarded_config::reset_merge_policy_counts; use crate::safe_git::filter_policy_overlay_count; @@ -326,57 +418,6 @@ mod tests { .replace("\r\n", "\n") } - fn commit_filter_attributes(root: &Path, tracked_path: &str) { - std::fs::write( - root.join(".gitattributes"), - format!("{tracked_path} filter=x=y\n"), - ) - .expect("write attributes"); - let (add_code, _, add_err) = run(root, &["git", "add", ".gitattributes"]); - assert_eq!(add_code, 0, "add attributes: {add_err}"); - let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "attributes"]); - assert_eq!(commit_code, 0, "commit attributes: {commit_err}"); - } - - fn configure_clean_filter(root: &Path, tracked_path: &str) { - commit_filter_attributes(root, tracked_path); - let (config_code, _, config_err) = run( - root, - &[ - "git", - "config", - "filter.x=y.clean", - "git config codex.filterran true && git hash-object --stdin", - ], - ); - assert_eq!(config_code, 0, "configure filter: {config_err}"); - } - - fn configure_worktree_clean_filter(root: &Path, tracked_path: &str) { - commit_filter_attributes(root, tracked_path); - let (extension_code, _, extension_err) = run( - root, - &["git", "config", "extensions.worktreeConfig", "true"], - ); - assert_eq!(extension_code, 0, "enable worktree config: {extension_err}"); - let (config_code, _, config_err) = run( - root, - &[ - "git", - "config", - "--worktree", - "filter.x=y.clean", - "git config codex.filterran true && git hash-object --stdin", - ], - ); - assert_eq!(config_code, 0, "configure worktree filter: {config_err}"); - } - - fn configured_filter_ran(root: &Path) -> bool { - let (code, _, _) = run(root, &["git", "config", "--get", "codex.filterran"]); - code == 0 - } - #[cfg(unix)] fn trusted_git_directory() -> PathBuf { std::env::split_paths(&std::env::var_os("PATH").expect("PATH")) @@ -440,6 +481,416 @@ mod tests { assert!(!root.join("preflight.txt").exists()); } + #[test] + fn apply_resolves_relative_primary_config_from_repository_root() { + let _g = env_lock().lock().unwrap(); + if std::env::var_os("CODEX_GIT_UTILS_APPLY_ENV_CHILD").is_none() { + run_isolated_test( + "apply::tests::apply_resolves_relative_primary_config_from_repository_root", + &[("GIT_CONFIG_GLOBAL", OsStr::new("../external/config"))], + ); + return; + } + + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let nested_cwd = root.join("nested"); + let external_config = fixture.path().join("external/config"); + let mismatched_nested_config = root.join("external/config"); + std::fs::create_dir_all(&nested_cwd).expect("nested cwd"); + std::fs::create_dir_all(external_config.parent().expect("config parent")) + .expect("external config directory"); + std::fs::create_dir_all( + mismatched_nested_config + .parent() + .expect("mismatched config parent"), + ) + .expect("mismatched config directory"); + std::fs::write(&external_config, "[codex]\n\tprobe = loaded\n").expect("external config"); + std::fs::write(&mismatched_nested_config, "[invalid\n") + .expect("mismatched nested-cwd config"); + let (init_code, _, init_err) = run(&root, &["git", "init"]); + assert_eq!(init_code, 0, "init repository: {init_err}"); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: nested_cwd, + diff: "diff --git a/hello.txt b/hello.txt\nnew file mode 100644\n--- /dev/null\n+++ b/hello.txt\n@@ -0,0 +1 @@\n+hello\n".to_string(), + revert: false, + preflight: false, + }) + .expect("apply with root-relative primary config"); + assert_eq!(result.exit_code, 0, "apply result: {result:?}"); + assert_eq!(read_file_normalized(&root.join("hello.txt")), "hello\n"); + } + + #[cfg(target_os = "linux")] + #[test] + fn apply_refuses_process_relative_primary_config_before_mutating_the_repository() { + const TEST_NAME: &str = "apply::tests::apply_refuses_process_relative_primary_config_before_mutating_the_repository"; + if std::env::var_os("CODEX_GIT_UTILS_APPLY_ENV_CHILD").is_none() { + run_isolated_test( + TEST_NAME, + &[ + ( + "GIT_CONFIG_GLOBAL", + OsStr::new("/proc/self/cwd/codex-process-relative.gitconfig"), + ), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + ); + return; + } + + let repo = init_repo(); + let root = repo.path(); + std::fs::write( + root.join("codex-process-relative.gitconfig"), + "[filter \"unsafe\"]\nclean = false\n", + ) + .expect("worktree config"); + let before_index = run(root, &["git", "ls-files", "--stage", "-z"]).1; + let request = ApplyGitRequest { + cwd: root.to_path_buf(), + diff: "diff --git a/hello.txt b/hello.txt\nnew file mode 100644\n--- /dev/null\n+++ b/hello.txt\n@@ -0,0 +1 @@\n+hello\n".to_string(), + revert: false, + preflight: false, + }; + + let error = apply_git_patch(&request).expect_err("process-relative primary config"); + + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("process-relative"), "{error}"); + assert!(!root.join("hello.txt").exists()); + assert_eq!( + run(root, &["git", "ls-files", "--stage", "-z"]).1, + before_index + ); + } + + #[test] + fn numstat_path_discovery_does_not_preempt_apply_whitespace_result() { + let _g = env_lock().lock().unwrap(); + let repo = init_repo(); + let root = repo.path(); + let (config_code, _, config_err) = + run(root, &["git", "config", "apply.whitespace", "error"]); + assert_eq!(config_code, 0, "configure whitespace policy: {config_err}"); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: "diff --git a/trailing.txt b/trailing.txt\nnew file mode 100644\n--- /dev/null\n+++ b/trailing.txt\n@@ -0,0 +1 @@\n+trailing \n".to_string(), + revert: false, + preflight: false, + }) + .expect("path discovery must leave apply failure in the structured result"); + assert_ne!(result.exit_code, 0); + assert!( + result.stderr.contains("trailing whitespace"), + "apply result: {result:?}" + ); + assert!(!root.join("trailing.txt").exists()); + } + + #[test] + fn fatal_whitespace_policy_precedes_selected_merge_driver_without_mutation() { + let _g = env_lock().lock().unwrap(); + for policy in ["error", "error-all"] { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt merge=selected\n") + .expect("write attributes"); + std::fs::write(root.join("file.txt"), "old\n").expect("write file"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + assert_eq!( + run( + root, + &[ + "git", + "config", + "merge.selected.driver", + "git config --file .git/config codex.mergeran true && false", + ], + ) + .0, + 0 + ); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", policy]).0, + 0 + ); + let index_before = std::fs::read(root.join(".git/index")).expect("read index"); + + reset_merge_policy_counts(); + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new \n".to_string(), + revert: false, + preflight: false, + }) + .expect("return structured whitespace failure"); + + assert_ne!(result.exit_code, 0, "{policy}: {result:?}"); + assert!( + result.stderr.contains("trailing whitespace"), + "{policy}: {result:?}" + ); + assert!(result.cmd_for_log.contains("--numstat"), "{result:?}"); + assert_eq!(merge_config_read_count(), 0, "{policy}"); + assert_eq!(merge_attribute_read_count(), 0, "{policy}"); + assert_eq!(merge_overlay_count(), 0, "{policy}"); + assert_eq!(read_file_normalized(&root.join("file.txt")), "old\n"); + assert_eq!( + std::fs::read(root.join(".git/index")).expect("reread index"), + index_before, + "{policy}" + ); + assert_ne!( + run(root, &["git", "config", "--get", "codex.mergeran"]).0, + 0, + "{policy}: merge driver must not run" + ); + } + } + + #[test] + fn nonfatal_whitespace_policies_reach_the_final_apply() { + let _g = env_lock().lock().unwrap(); + for (policy, expected) in [("warn", "new \n"), ("fix", "new\n")] { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("file.txt"), "old\n").expect("write file"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", policy]).0, + 0 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new \n".to_string(), + revert: false, + preflight: false, + }) + .expect("apply with nonfatal whitespace policy"); + + assert_eq!(result.exit_code, 0, "{policy}: {result:?}"); + assert_eq!(read_file_normalized(&root.join("file.txt")), expected); + } + } + + #[test] + fn fatal_whitespace_gate_remains_authoritative_after_reverse_staging() { + let _g = env_lock().lock().unwrap(); + for policy in ["error", "error-all"] { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt -whitespace\n") + .expect("write permissive attributes"); + std::fs::write(root.join("file.txt"), "bad \n").expect("write base file"); + assert_eq!( + run(root, &["git", "add", ".gitattributes", "file.txt"]).0, + 0 + ); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + std::fs::write(root.join("file.txt"), "good\n").expect("write patched file"); + let patch = run(root, &["git", "diff", "--full-index", "--", "file.txt"]); + assert_eq!(patch.0, 0, "create patch: {}", patch.2); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", policy]).0, + 0 + ); + + let attributes = root.join(".gitattributes"); + install_after_reverse_staging_hook(move || { + std::fs::write(attributes, "file.txt whitespace\n") + .expect("tighten whitespace attributes after staging"); + }); + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: patch.1, + revert: true, + preflight: false, + }) + .expect("reverse apply after attribute mutation"); + + assert_eq!(result.exit_code, 0, "{policy}: {result:?}"); + assert!( + result.cmd_for_log.contains("--whitespace=nowarn"), + "{policy}: {}", + result.cmd_for_log + ); + assert_eq!( + read_file_normalized(&root.join(".gitattributes")), + "file.txt whitespace\n", + "{policy}: race hook did not tighten the attribute" + ); + assert_eq!(read_file_normalized(&root.join("file.txt")), "bad \n"); + let cached = run( + root, + &["git", "diff", "--cached", "--quiet", "--", "file.txt"], + ); + assert_eq!(cached.0, 0, "{policy}: index retained staged data"); + } + } + + #[test] + fn fatal_whitespace_gate_and_projection_cover_reverse_three_way_staging() { + let _g = env_lock().lock().unwrap(); + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt -whitespace\n") + .expect("write permissive attributes"); + let base_contents = "01\n02\n03\n04\n05\n06\n07\n08\n09\nbad \n11\n12\n13\n14\n15\n"; + let patched_contents = "01\n02\n03\n04\n05\n06\n07\n08\n09\ngood\n11\n12\n13\n14\n15\n"; + let independent_contents = + "01\n02\n03\n04\n05\n06\nSEVEN\n08\n09\ngood\n11\n12\n13\n14\n15\n"; + let expected_contents = "01\n02\n03\n04\n05\n06\nSEVEN\n08\n09\nbad \n11\n12\n13\n14\n15\n"; + std::fs::write(root.join("file.txt"), base_contents).expect("write base"); + assert_eq!( + run(root, &["git", "add", ".gitattributes", "file.txt"]).0, + 0 + ); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + let base = run(root, &["git", "rev-parse", "HEAD"]).1; + std::fs::write(root.join("file.txt"), patched_contents).expect("write patch side"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "patched"]).0, 0); + let patch = run( + root, + &[ + "git", + "diff", + "--full-index", + base.trim(), + "HEAD", + "--", + "file.txt", + ], + ); + assert_eq!(patch.0, 0, "create patch: {}", patch.2); + std::fs::write(root.join("file.txt"), independent_contents) + .expect("write independent worktree edit"); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", "error"]).0, + 0 + ); + + let attributes = root.join(".gitattributes"); + install_after_reverse_staging_hook(move || { + std::fs::write(attributes, "file.txt whitespace\n") + .expect("tighten whitespace attributes after staging"); + }); + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: patch.1, + revert: true, + preflight: false, + }) + .expect("reverse three-way after attribute mutation"); + + assert_eq!(result.exit_code, 0, "{result:?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + assert!(result.cmd_for_log.contains("--3way")); + assert!(result.cmd_for_log.contains("--whitespace=nowarn")); + assert_eq!( + read_file_normalized(&root.join(".gitattributes")), + "file.txt whitespace\n", + "race hook did not tighten the attribute" + ); + assert_eq!( + read_file_normalized(&root.join("file.txt")), + expected_contents + ); + assert_eq!( + run(root, &["git", "diff", "--quiet", "--", "file.txt"]).0, + 0, + "final index and worktree differ" + ); + } + + #[test] + fn mixed_reverse_conflict_and_whitespace_error_does_not_mutate() { + let _g = env_lock().lock().unwrap(); + let repo = init_repo(); + let root = repo.path(); + let base = "01\n02\n03\n04\n05\n06\n07\n08\n09\n10\nbase \n12\n13\n14\n15\n"; + let theirs = "01\n02\n03\n04\n05\n06\n07\n08\n09\n10\ntheirs\n12\n13\n14\n15\n"; + let independently_edited = + "01\n02\n03\n04\n05\n06\n07\nEIGHT\n09\n10\ntheirs\n12\n13\n14\n15\n"; + std::fs::write(root.join("file.txt"), base).expect("write base"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + let base_oid = run(root, &["git", "rev-parse", "HEAD"]).1; + std::fs::write(root.join("file.txt"), theirs).expect("write theirs"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "theirs"]).0, 0); + let patch = run( + root, + &[ + "git", + "diff", + "--full-index", + base_oid.trim(), + "HEAD", + "--", + "file.txt", + ], + ); + assert_eq!(patch.0, 0, "create patch: {}", patch.2); + std::fs::write(root.join("file.txt"), independently_edited) + .expect("write independent edit"); + let patch_dir = tempfile::tempdir().expect("patch directory"); + let patch_path = patch_dir.path().join("mixed.diff"); + std::fs::write(&patch_path, &patch.1).expect("write patch"); + let patch_path = patch_path.to_str().expect("UTF-8 patch path"); + let structural = run( + root, + &[ + "git", + "apply", + "--check", + "--whitespace=nowarn", + "-R", + patch_path, + ], + ); + assert_ne!( + structural.0, 0, + "fixture must retain a structural reverse conflict" + ); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", "error"]).0, + 0 + ); + let index_before = std::fs::read(root.join(".git/index")).expect("read index"); + let worktree_before = std::fs::read(root.join("file.txt")).expect("read worktree"); + + reset_merge_policy_counts(); + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: patch.1, + revert: true, + preflight: false, + }) + .expect("return mixed policy failure"); + + assert_ne!(result.exit_code, 0, "{result:?}"); + assert!(result.stderr.contains("trailing whitespace"), "{result:?}"); + assert_eq!(merge_config_read_count(), 0); + assert_eq!(merge_attribute_read_count(), 0); + assert_eq!(merge_overlay_count(), 0); + assert_eq!( + std::fs::read(root.join(".git/index")).expect("reread index"), + index_before + ); + assert_eq!( + std::fs::read(root.join("file.txt")).expect("reread worktree"), + worktree_before + ); + } + #[test] fn apply_uses_cwd_repo_despite_inherited_repository_selectors() { let _g = env_lock().lock().unwrap(); @@ -794,101 +1245,6 @@ diff --git a/ghost.txt b/ghost.txt\n--- a/ghost.txt\n+++ b/ghost.txt\n@@ -1,1 +1 ); } - #[test] - fn apply_rejects_configured_clean_filter_without_running_it() { - let _g = env_lock().lock().unwrap(); - let repo = init_repo(); - let root = repo.path(); - std::fs::write(root.join("file.txt"), "orig\n").expect("write file"); - let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]); - assert_eq!(add_code, 0, "add file: {add_err}"); - let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "seed"]); - assert_eq!(commit_code, 0, "commit file: {commit_err}"); - configure_clean_filter(root, "file.txt"); - - let diff = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n-orig\n+next\n"; - for (revert, preflight) in [(false, false), (false, true), (true, false), (true, true)] { - let request = ApplyGitRequest { - cwd: root.to_path_buf(), - diff: diff.to_string(), - revert, - preflight, - }; - reset_config_source_authorization_count(); - let error = apply_git_patch(&request).expect_err("reject configured filter"); - assert_eq!( - config_source_authorization_count(), - 1, - "{revert} {preflight}" - ); - assert_eq!(error.kind(), io::ErrorKind::Unsupported); - assert!(!configured_filter_ran(root)); - assert_eq!(read_file_normalized(&root.join("file.txt")), "orig\n"); - } - } - - #[test] - fn apply_rejects_worktree_scoped_clean_filter_without_running_it() { - let _g = env_lock().lock().unwrap(); - let repo = init_repo(); - let root = repo.path(); - std::fs::write(root.join("file.txt"), "orig\n").expect("write file"); - let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]); - assert_eq!(add_code, 0, "add file: {add_err}"); - let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "seed"]); - assert_eq!(commit_code, 0, "commit file: {commit_err}"); - configure_worktree_clean_filter(root, "file.txt"); - - let request = ApplyGitRequest { - cwd: root.to_path_buf(), - diff: "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n-orig\n+next\n".to_string(), - revert: false, - preflight: true, - }; - let error = apply_git_patch(&request).expect_err("reject worktree filter"); - assert_eq!(error.kind(), io::ErrorKind::Unsupported); - assert!(!configured_filter_ran(root)); - assert_eq!(read_file_normalized(&root.join("file.txt")), "orig\n"); - } - - #[test] - fn apply_probe_rejects_command_scoped_clean_filter() { - let _g = env_lock().lock().unwrap(); - if std::env::var_os("CODEX_GIT_UTILS_APPLY_ENV_CHILD").is_none() { - run_isolated_test( - "apply::tests::apply_probe_rejects_command_scoped_clean_filter", - &[( - "CODEX_APPLY_GIT_CFG", - OsStr::new( - "filter.codex-test.clean=git config codex.filterran true && git hash-object --stdin", - ), - )], - ); - return; - } - - let repo = init_repo(); - let root = repo.path(); - std::fs::write(root.join("test.txt"), "orig\n").expect("write file"); - let (add_code, _, add_err) = run(root, &["git", "add", "test.txt"]); - assert_eq!(add_code, 0, "add file: {add_err}"); - let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "seed"]); - assert_eq!(commit_code, 0, "commit file: {commit_err}"); - std::fs::write(root.join(".gitattributes"), "test.txt filter=codex-test\n") - .expect("attributes"); - - let request = ApplyGitRequest { - cwd: root.to_path_buf(), - diff: "diff --git a/test.txt b/test.txt\n--- a/test.txt\n+++ b/test.txt\n@@ -1 +1 @@\n-orig\n+next\n".to_string(), - revert: false, - preflight: true, - }; - let error = apply_git_patch(&request).expect_err("reject command-scoped filter"); - assert_eq!(error.kind(), io::ErrorKind::Unsupported); - assert!(!configured_filter_ran(root)); - assert_eq!(read_file_normalized(&root.join("test.txt")), "orig\n"); - } - #[test] fn resolve_git_root_rejects_core_worktree_redirection() { let temp = tempfile::tempdir().expect("tempdir"); diff --git a/codex-rs/git-utils/src/exact_index_policy.rs b/codex-rs/git-utils/src/exact_index_policy.rs index e7c2b6947f..ae9f4abce7 100644 --- a/codex-rs/git-utils/src/exact_index_policy.rs +++ b/codex-rs/git-utils/src/exact_index_policy.rs @@ -14,6 +14,12 @@ pub(crate) enum ExactIndexPolicy { paths: Vec, content_filter_paths: Vec, }, + Flagged { + paths: Vec, + content_filter_paths: Vec, + skip_worktree: BTreeSet, + assume_unchanged: BTreeSet, + }, Refuse { stderr: String, }, @@ -154,18 +160,11 @@ pub(crate) fn resolve_exact_index_policy( }); } - let mut reasons = Vec::new(); - if !skipped.is_empty() { - reasons.push(format!("skip-worktree path(s): {}", quote_paths(&skipped))); - } - if !assumed_unchanged.is_empty() { - reasons.push(format!( - "assume-unchanged path(s): {}", - quote_paths(&assumed_unchanged) - )); - } - Ok(ExactIndexPolicy::Refuse { - stderr: format!("refusing to stage {}", reasons.join("; ")), + Ok(ExactIndexPolicy::Flagged { + paths, + content_filter_paths, + skip_worktree: skipped, + assume_unchanged: assumed_unchanged, }) } diff --git a/codex-rs/git-utils/src/exact_staging.rs b/codex-rs/git-utils/src/exact_staging.rs index 8ff94ae796..fd33c6f1ba 100644 --- a/codex-rs/git-utils/src/exact_staging.rs +++ b/codex-rs/git-utils/src/exact_staging.rs @@ -8,6 +8,7 @@ use std::process::Stdio; use crate::exact_index_policy::ExactIndexPolicy; use crate::exact_index_policy::resolve_exact_index_policy; +use crate::git_command::IsolatedGitStorage; use crate::guarded_config::GuardedGitConfig; use crate::patch_paths::validate_patch_path; @@ -17,35 +18,124 @@ pub(crate) struct StagePathsResult { pub(crate) stderr: String, } -#[derive(Clone, Copy)] -enum StagingProvenance { - FromApply, - Standalone, +enum SparseCheckoutPolicy { + Verified { excluded: BTreeSet }, + Refuse { result: StagePathsResult }, } -/// Stage only the literal paths supplied by a caller that has already applied -/// the operation-specific containment and filesystem policy. -/// -/// Unlike `git add`, `update-index` never treats a path that races from a leaf -/// to a directory as a recursive request. Callers that require staging to -/// succeed can inspect the returned status; the public forward helper retains -/// its historical best-effort handling of a non-zero Git command. -/// -/// This is not a transactional filesystem-confinement primitive. A concurrent -/// strict-ancestor swap to a symlink or Windows junction can still redirect the -/// bytes read for an already-confined index pathname. It cannot make this -/// exact command recurse into, or create index entries for, descendant paths; -/// the filter neutralizer also remains in force for the entire command. -pub(crate) fn update_index_exact_paths_from_apply( +pub(crate) struct PreparedReverseIndexUpdate { + paths: Vec, +} + +pub(crate) fn prepare_index_exact_paths_for_reverse_apply( config: &mut GuardedGitConfig<'_>, paths: &[String], content_filter_paths: &[String], +) -> io::Result { + validate_exact_staging_inputs(paths, content_filter_paths)?; + config.ensure_apply_filter_path_subset(content_filter_paths)?; + if paths.is_empty() { + return Ok(PreparedReverseIndexUpdate { paths: Vec::new() }); + } + + let (paths, content_filter_paths, skip_worktree, assume_unchanged) = + match resolve_exact_index_policy(config, paths, content_filter_paths)? { + ExactIndexPolicy::Proceed { + paths, + content_filter_paths, + } => ( + paths, + content_filter_paths, + BTreeSet::new(), + BTreeSet::new(), + ), + ExactIndexPolicy::Flagged { + paths, + content_filter_paths, + skip_worktree, + assume_unchanged, + } => (paths, content_filter_paths, skip_worktree, assume_unchanged), + ExactIndexPolicy::Refuse { stderr } => return Err(reverse_prepare_error(stderr)), + }; + config.ensure_apply_filter_path_subset(&content_filter_paths)?; + if !assume_unchanged.is_empty() { + return Err(reverse_prepare_error(format!( + "refusing to stage assume-unchanged path(s): {}", + quote_paths(&assume_unchanged) + ))); + } + + let ignored = ignored_untracked_paths(config, &paths)?; + let sparse_excluded = match sparse_checkout_policy(config, &paths)? { + SparseCheckoutPolicy::Verified { excluded } => excluded, + SparseCheckoutPolicy::Refuse { result } => { + return Err(reverse_prepare_error(result.stderr)); + } + }; + let non_sparse_skip_worktree = skip_worktree + .difference(&sparse_excluded) + .cloned() + .collect::>(); + if !non_sparse_skip_worktree.is_empty() { + return Err(reverse_prepare_error(format!( + "refusing to stage skip-worktree path(s): {}", + quote_paths(&non_sparse_skip_worktree) + ))); + } + let mut reasons = Vec::new(); + if !ignored.is_empty() { + reasons.push(format!( + "refusing to stage ignored untracked path(s): {}", + quote_paths(&ignored) + )); + } + if !sparse_excluded.is_empty() { + reasons.push(format!( + "refusing to stage path(s) outside the sparse-checkout definition: {}", + quote_paths(&sparse_excluded) + )); + } + if !reasons.is_empty() { + return Err(reverse_prepare_error(reasons.join("; "))); + } + + // Attach the one Git-add filter snapshot while the plan is prepared. + // Scratch and real executors below perform no policy/config reads. + config.authorize_git_add_filter_paths(&content_filter_paths)?; + Ok(PreparedReverseIndexUpdate { paths }) +} + +pub(crate) fn execute_prepared_reverse_index_update( + config: &GuardedGitConfig<'_>, + prepared: &PreparedReverseIndexUpdate, + scratch: Option<&IsolatedGitStorage>, ) -> io::Result { - update_index_exact_paths_common( - config, - paths, - content_filter_paths, - StagingProvenance::FromApply, + if prepared.paths.is_empty() { + return Ok(StagePathsResult { + exit_code: 0, + stderr: String::new(), + }); + } + let mut command = config.update_index_literal_pathspecs_command()?; + command + .disable_optional_locks() + .args(["--add", "--remove", "--"]) + .args(&prepared.paths); + let output = if let Some(storage) = scratch { + command.output_in_merge_scratch(storage)? + } else { + command.output()? + }; + Ok(StagePathsResult { + exit_code: output.status.code().unwrap_or(-1), + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + }) +} + +fn reverse_prepare_error(message: String) -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + format!("failed to prepare reverse patch staging: {message}"), ) } @@ -54,20 +144,13 @@ pub(crate) fn update_index_exact_paths_standalone( paths: &[String], content_filter_paths: &[String], ) -> io::Result { - update_index_exact_paths_common( - config, - paths, - content_filter_paths, - StagingProvenance::Standalone, - ) + update_index_exact_paths(config, paths, content_filter_paths) } -fn update_index_exact_paths_common( - config: &mut GuardedGitConfig<'_>, +fn validate_exact_staging_inputs( paths: &[String], content_filter_paths: &[String], - provenance: StagingProvenance, -) -> io::Result { +) -> io::Result<()> { for path in paths { if path.as_bytes().contains(&0) { return Err(io::Error::new( @@ -87,9 +170,25 @@ fn update_index_exact_paths_common( "content-filter staging path is not in the exact staging set", )); } - if matches!(provenance, StagingProvenance::FromApply) { - config.ensure_apply_filter_path_subset(content_filter_paths)?; - } + Ok(()) +} + +/// Stage only the literal paths supplied by a standalone caller that has +/// already applied the operation-specific containment and filesystem policy. +/// +/// Unlike `git add`, `update-index` never treats a path that races from a leaf +/// to a directory as a recursive request. This is not a transactional +/// filesystem-confinement primitive: a concurrent strict-ancestor swap to a +/// symlink or Windows junction can still redirect the bytes read for an +/// already-confined index pathname. It cannot make this exact command recurse +/// into, or create index entries for, descendant paths; the filter neutralizer +/// also remains in force for the entire command. +fn update_index_exact_paths( + config: &mut GuardedGitConfig<'_>, + paths: &[String], + content_filter_paths: &[String], +) -> io::Result { + validate_exact_staging_inputs(paths, content_filter_paths)?; if paths.is_empty() { return Ok(StagePathsResult { exit_code: 0, @@ -97,12 +196,23 @@ fn update_index_exact_paths_common( }); } - let (paths, content_filter_paths) = + let (paths, content_filter_paths, skip_worktree, assume_unchanged) = match resolve_exact_index_policy(config, paths, content_filter_paths)? { ExactIndexPolicy::Proceed { paths, content_filter_paths, - } => (paths, content_filter_paths), + } => ( + paths, + content_filter_paths, + BTreeSet::new(), + BTreeSet::new(), + ), + ExactIndexPolicy::Flagged { + paths, + content_filter_paths, + skip_worktree, + assume_unchanged, + } => (paths, content_filter_paths, skip_worktree, assume_unchanged), ExactIndexPolicy::Refuse { stderr } => { return Ok(StagePathsResult { exit_code: 1, @@ -110,23 +220,50 @@ fn update_index_exact_paths_common( }); } }; - if matches!(provenance, StagingProvenance::FromApply) { - config.ensure_apply_filter_path_subset(&content_filter_paths)?; + if !skip_worktree.is_empty() || !assume_unchanged.is_empty() { + let mut reasons = Vec::new(); + if !skip_worktree.is_empty() { + reasons.push(format!( + "skip-worktree path(s): {}", + quote_paths(&skip_worktree) + )); + } + if !assume_unchanged.is_empty() { + reasons.push(format!( + "assume-unchanged path(s): {}", + quote_paths(&assume_unchanged) + )); + } + return Ok(StagePathsResult { + exit_code: 1, + stderr: format!("refusing to stage {}", reasons.join("; ")), + }); } let ignored = ignored_untracked_paths(config, &paths)?; + let sparse_excluded = match sparse_checkout_policy(config, &paths)? { + SparseCheckoutPolicy::Verified { excluded } => excluded, + SparseCheckoutPolicy::Refuse { result } => return Ok(result), + }; + let mut exclusion_reasons = Vec::new(); if !ignored.is_empty() { + exclusion_reasons.push(format!( + "refusing to stage ignored untracked path(s): {}", + quote_paths(&ignored) + )); + } + if !sparse_excluded.is_empty() { + exclusion_reasons.push(format!( + "refusing to stage path(s) outside the sparse-checkout definition: {}", + quote_paths(&sparse_excluded) + )); + } + if !exclusion_reasons.is_empty() { return Ok(StagePathsResult { exit_code: 1, - stderr: format!( - "refusing to stage ignored untracked path(s): {}", - quote_paths(&ignored) - ), + stderr: exclusion_reasons.join("; "), }); } - if let Some(result) = sparse_checkout_policy(config, &paths)? { - return Ok(result); - } config.authorize_git_add_filter_paths(&content_filter_paths)?; let mut command = config.update_index_literal_pathspecs_command()?; @@ -135,10 +272,9 @@ fn update_index_exact_paths_common( .args(["--add", "--remove", "--"]) .args(&paths); let output = command.output()?; - Ok(StagePathsResult { - exit_code: output.status.code().unwrap_or(-1), - stderr: String::from_utf8_lossy(&output.stderr).into_owned(), - }) + let exit_code = output.status.code().unwrap_or(-1); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + Ok(StagePathsResult { exit_code, stderr }) } fn ignored_untracked_paths( @@ -191,9 +327,11 @@ fn ignored_untracked_paths( fn sparse_checkout_policy( config: &GuardedGitConfig<'_>, paths: &[String], -) -> io::Result> { +) -> io::Result { if !config.read_bool("core.sparseCheckout")?.unwrap_or(false) { - return Ok(None); + return Ok(SparseCheckoutPolicy::Verified { + excluded: BTreeSet::new(), + }); } // Do not let an older Git fall back to a PATH-resolved @@ -205,11 +343,14 @@ fn sparse_checkout_policy( && std::str::from_utf8(&builtins.stdout) .is_ok_and(|output| output.lines().any(|command| command == "sparse-checkout")); if !sparse_checkout_is_builtin { - return Ok(Some(StagePathsResult { - exit_code: builtins.status.code().unwrap_or(-1).max(1), - stderr: "unable to verify sparse-checkout staging policy with a built-in Git command" - .to_string(), - })); + return Ok(SparseCheckoutPolicy::Refuse { + result: StagePathsResult { + exit_code: builtins.status.code().unwrap_or(-1).max(1), + stderr: + "unable to verify sparse-checkout staging policy with a built-in Git command" + .to_string(), + }, + }); } let input = nul_path_input(paths)?; @@ -220,13 +361,15 @@ fn sparse_checkout_policy( .stdin(Stdio::from(input)); let output = command.output()?; if !output.status.success() { - return Ok(Some(StagePathsResult { - exit_code: output.status.code().unwrap_or(-1), - stderr: format!( - "unable to verify sparse-checkout staging policy: {}", - String::from_utf8_lossy(&output.stderr).trim() - ), - })); + return Ok(SparseCheckoutPolicy::Refuse { + result: StagePathsResult { + exit_code: output.status.code().unwrap_or(-1), + stderr: format!( + "unable to verify sparse-checkout staging policy: {}", + String::from_utf8_lossy(&output.stderr).trim() + ), + }, + }); } let included = parse_reported_paths(&output.stdout, paths, "sparse-checkout")?; let excluded = paths @@ -234,17 +377,7 @@ fn sparse_checkout_policy( .filter(|path| !included.contains(path.as_str())) .cloned() .collect::>(); - if excluded.is_empty() { - Ok(None) - } else { - Ok(Some(StagePathsResult { - exit_code: 1, - stderr: format!( - "refusing to stage path(s) outside the sparse-checkout definition: {}", - quote_paths(&excluded) - ), - })) - } + Ok(SparseCheckoutPolicy::Verified { excluded }) } fn nul_path_input(paths: &[String]) -> io::Result { diff --git a/codex-rs/git-utils/src/git_command.rs b/codex-rs/git-utils/src/git_command.rs index ca232e8704..bd6adbf216 100644 --- a/codex-rs/git-utils/src/git_command.rs +++ b/codex-rs/git-utils/src/git_command.rs @@ -1,15 +1,20 @@ use std::ffi::OsStr; +use std::ffi::OsString; use std::io; use std::path::Path; use std::path::PathBuf; use std::process::Command; use std::process::Stdio; +use std::sync::Arc; +#[cfg(windows)] +use same_file::Handle; use tokio::io::AsyncRead; use tokio::io::AsyncReadExt; use crate::errors::GitReadError; use crate::git_config_environment::GitConfigEnvironmentSnapshot; +use crate::guarded_config::GuardedOperationIdentity; #[cfg(test)] use crate::git_executable::git_executable_name; use crate::git_executable::harden_git_launch_environment; @@ -38,8 +43,16 @@ pub(crate) struct GitRunner { safe_path: std::ffi::OsString, authority: RepositoryAuthority, config_environment: GitConfigEnvironmentSnapshot, + replace_ref_base: Option, + no_replace_objects: Option, + attr_source: Option, + attr_nosystem: Option, + identity: Arc, } +#[derive(Debug)] +struct GitRunnerIdentity; + /// 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 { @@ -54,6 +67,188 @@ pub(crate) struct GitAsyncCommand { stdin_configured: bool, } +/// App-owned common repository metadata for one final three-way apply. +/// +/// The real per-worktree Git directory remains selected for HEAD and index +/// state, while this directory replaces every common config and attribute +/// source that could define a repository-selected executable helper. +pub(crate) struct IsolatedGitCommonDir { + root: tempfile::TempDir, +} + +/// Operation-owned writable state for a nonmutating merge-classification +/// probe. The active index is copied here, generated blobs are written only +/// to this object directory, and the real object database is attached as one +/// read-only, authority-derived alternate by `GitRunner`. +pub(crate) struct IsolatedGitStorage { + root: tempfile::TempDir, +} + +/// Operation-owned repository view for read-only status children. +/// +/// HEAD, config, and attributes are frozen into owned files. The live index +/// remains selected through the authority-pinned per-worktree Git directory, +/// and the active object database is attached only as an authority-derived +/// alternate. The owned common directory supplies the complete config and +/// attribute view, so a final child cannot reload a late +/// repository-selected helper namespace. +pub(crate) struct IsolatedGitReadContext { + common: IsolatedGitCommonDir, + head_contents: Box<[u8]>, + runner_identity: Arc, + operation_identity: GuardedOperationIdentity, + config_contents: Option>, + attributes_contents: Option>, +} + +impl IsolatedGitStorage { + fn index_path(&self) -> PathBuf { + self.root.path().join("index") + } + + fn objects_path(&self) -> PathBuf { + self.root.path().join("objects") + } + + fn validate(&self) -> io::Result<()> { + let index = self.index_path(); + let metadata = std::fs::symlink_metadata(&index)?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("isolated Git scratch index changed at {}", index.display()), + )); + } + let objects = self.objects_path(); + let metadata = std::fs::symlink_metadata(&objects)?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!( + "isolated Git scratch object directory changed at {}", + objects.display() + ), + )); + } + Ok(()) + } +} + +impl IsolatedGitReadContext { + pub(crate) fn config_path(&self) -> PathBuf { + self.common.config_path() + } + + pub(crate) fn attributes_path(&self) -> PathBuf { + self.common.attributes_path() + } + + pub(crate) fn seal_projected_files(mut self) -> io::Result { + self.config_contents = Some(std::fs::read(self.config_path())?.into_boxed_slice()); + self.attributes_contents = + Some(std::fs::read(self.attributes_path())?.into_boxed_slice()); + self.validate()?; + Ok(self) + } + + fn validate(&self) -> io::Result<()> { + self.common.validate()?; + let head_path = self.common.root.path().join("HEAD"); + let metadata = std::fs::symlink_metadata(&head_path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("isolated Git HEAD changed at {}", head_path.display()), + )); + } + if std::fs::read(&head_path)? != self.head_contents.as_ref() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated Git HEAD contents changed", + )); + } + if let Some(expected) = &self.config_contents + && std::fs::read(self.config_path())? != expected.as_ref() + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated Git config contents changed", + )); + } + if let Some(expected) = &self.attributes_contents + && std::fs::read(self.attributes_path())? != expected.as_ref() + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated Git attributes contents changed", + )); + } + Ok(()) + } +} + +impl IsolatedGitCommonDir { + pub(crate) fn config_path(&self) -> PathBuf { + self.root.path().join("config") + } + + pub(crate) fn attributes_path(&self) -> PathBuf { + self.root.path().join("info/attributes") + } + + fn system_config_path(&self) -> PathBuf { + self.root.path().join("system.gitconfig") + } + + fn global_config_path(&self) -> PathBuf { + self.root.path().join("global.gitconfig") + } + + fn home_path(&self) -> PathBuf { + self.root.path().join("home") + } + + fn xdg_config_home(&self) -> PathBuf { + self.root.path().join("xdg") + } + + fn validate(&self) -> io::Result<()> { + for path in [ + self.config_path(), + self.system_config_path(), + self.global_config_path(), + self.root.path().join("info/attributes"), + ] { + let metadata = std::fs::symlink_metadata(&path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("isolated Git metadata file changed at {}", path.display()), + )); + } + } + for path in [ + self.root.path().join("objects"), + self.root.path().join("refs"), + self.root.path().join("info"), + self.home_path(), + self.xdg_config_home(), + ] { + let metadata = std::fs::symlink_metadata(&path)?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!( + "isolated Git metadata directory changed at {}", + path.display() + ), + )); + } + } + Ok(()) + } +} + impl GitCommand { pub(crate) fn arg(&mut self, arg: impl AsRef) -> &mut Self { self.inner.arg(arg); @@ -143,6 +338,22 @@ impl GitRunner { } harden_git_launch_environment(&mut command, &self.safe_path); self.config_environment.apply_to(&mut command); + match &self.replace_ref_base { + Some(value) => command.env("GIT_REPLACE_REF_BASE", value), + None => command.env_remove("GIT_REPLACE_REF_BASE"), + }; + match &self.no_replace_objects { + Some(value) => command.env("GIT_NO_REPLACE_OBJECTS", value), + None => command.env_remove("GIT_NO_REPLACE_OBJECTS"), + }; + match &self.attr_source { + Some(value) => command.env("GIT_ATTR_SOURCE", value), + None => command.env_remove("GIT_ATTR_SOURCE"), + }; + match &self.attr_nosystem { + Some(value) => command.env("GIT_ATTR_NOSYSTEM", value), + None => command.env_remove("GIT_ATTR_NOSYSTEM"), + }; GitCommand { inner: command } } @@ -153,14 +364,32 @@ impl GitRunner { Ok(command) } + fn async_command(&self) -> GitAsyncCommand { + GitAsyncCommand { + inner: tokio::process::Command::from(self.command().inner), + stdin_configured: false, + } + } + 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); + let mut command = self.async_command(); command.arg("-C").arg(cwd); - Ok(GitAsyncCommand { - inner: command, - stdin_configured: false, - }) + Ok(command) + } + + pub(crate) fn async_config_file_write_command( + &self, + config_path: &Path, + ) -> GitAsyncCommand { + let mut command = self.async_command(); + scrub_repository_and_config_environment(command.inner.as_std_mut()); + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(["config", "--file"]) + .arg(config_path) + .arg("--add"); + command } fn canonical_command_cwd(&self, cwd: &Path) -> io::Result { @@ -197,11 +426,345 @@ impl GitRunner { self.config_environment.value(name) } + pub(crate) fn replacement_ref_base_is_custom(&self) -> bool { + self.replace_ref_base.is_some() + } + + pub(crate) fn replacement_refs_are_disabled(&self) -> bool { + self.no_replace_objects.is_some() + } + + pub(crate) fn attribute_source_is_custom(&self) -> bool { + self.attr_source.is_some() + } + + /// Read repository-format keys from the authority-bound common config. + /// The common-directory identity remains pinned through the fixed + /// `--file --no-includes` child and is revalidated after it exits. + pub(crate) fn read_active_common_config_without_includes( + &self, + pattern: &str, + show_scope: bool, + ) -> io::Result<(std::process::Output, PathBuf)> { + self.authority.revalidate_active_repository_metadata()?; + let common_dir = self.authority.active_common_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common config is unavailable", + ) + })?; + let pinned_common = git_child_directory(common_dir, "active Git common directory")?; + let config_path = pinned_common.join("config"); + // The absolute --file selector needs no repository cwd. Avoiding one + // also prevents Git setup from interpreting unrelated repository + // config before the fixed, no-includes query runs. + let mut command = self.command(); + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(["config", "--file"]) + .arg(&config_path) + .args(["--null", "--show-origin", "--no-includes"]); + if show_scope { + command.arg("--show-scope"); + } + command.args(["--get-regexp", pattern]); + let output = self.output(command)?; + self.authority.revalidate_active_repository_metadata()?; + let _post_read_identity = pinned_common.revalidate()?; + Ok((output, config_path)) + } + + pub(crate) async fn read_active_common_config_without_includes_async( + &self, + pattern: &str, + show_scope: bool, + ) -> io::Result<(std::process::Output, PathBuf)> { + self.authority.revalidate_active_repository_metadata()?; + let common_dir = self.authority.active_common_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common config is unavailable", + ) + })?; + let pinned_common = git_child_directory(common_dir, "active Git common directory")?; + let config_path = pinned_common.join("config"); + let mut command = self.async_command(); + scrub_repository_and_config_environment(command.inner.as_std_mut()); + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(["config", "--file"]) + .arg(&config_path) + .args(["--null", "--show-origin", "--no-includes"]); + if show_scope { + command.arg("--show-scope"); + } + command.args(["--get-regexp", pattern]); + let output = self + .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await?; + self.authority.revalidate_active_repository_metadata()?; + let _post_read_identity = pinned_common.revalidate()?; + Ok((output, config_path)) + } + + pub(crate) async fn read_active_info_attributes_bounded_async( + &self, + max_bytes: usize, + ) -> io::Result> { + self.revalidate_active_repository_metadata()?; + let common_dir = self.authority.active_common_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common attributes are unavailable", + ) + })?; + let contents = read_common_info_attributes_bounded_async(common_dir, max_bytes).await?; + self.revalidate_active_repository_metadata()?; + Ok(contents) + } + + pub(crate) fn create_isolated_common_dir(&self) -> io::Result { + let root = tempfile::tempdir()?; + self.authority + .ensure_config_source_is_not_worktree_controlled( + root.path(), + "owned isolated Git common directory", + )?; + for path in ["objects", "refs", "info", "home", "xdg"] { + std::fs::create_dir_all(root.path().join(path))?; + } + for path in [ + "config", + "system.gitconfig", + "global.gitconfig", + "info/attributes", + ] { + std::fs::write(root.path().join(path), [])?; + } + let isolated = IsolatedGitCommonDir { root }; + isolated.validate()?; + Ok(isolated) + } + + pub(crate) fn create_isolated_git_storage(&self) -> io::Result { + self.revalidate_active_repository_metadata()?; + let canonical_git_dir = self.authority.active_git_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git directory is unavailable for scratch index creation", + ) + })?; + let git_dir = git_child_directory(canonical_git_dir, "active Git directory")?; + let canonical_common_dir = self.authority.active_common_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common directory is unavailable for scratch index creation", + ) + })?; + let common_dir = git_child_directory(canonical_common_dir, "active Git common directory")?; + let source_index = git_dir.join("index"); + let root = tempfile::tempdir()?; + self.authority + .ensure_config_source_is_not_worktree_controlled( + root.path(), + "owned isolated Git scratch storage", + )?; + std::fs::create_dir(root.path().join("objects"))?; + copy_regular_file_without_follow(&source_index, &root.path().join("index"))?; + // A copied split index resolves its content-addressed base beside the + // active per-worktree index, not in a distinct common directory. Copy + // only well-formed names from that authoritative Git directory; Git + // will still verify the base object ID from the link extension. + copy_shared_indexes(git_dir.as_path(), root.path())?; + self.revalidate_active_repository_metadata()?; + let _post_copy_identity = git_dir.revalidate()?; + let _post_copy_common_identity = common_dir.revalidate()?; + let storage = IsolatedGitStorage { root }; + storage.validate()?; + Ok(storage) + } + + pub(crate) fn create_isolated_read_context( + &self, + head_oid: Option<&str>, + operation_identity: &GuardedOperationIdentity, + ) -> io::Result { + if head_oid.is_some_and(|oid| { + !matches!(oid.len(), 40 | 64) || !oid.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "isolated Git read context requires a full commit object ID", + )); + } + let common = self.create_isolated_common_dir()?; + let head_contents = head_oid + .map(|oid| format!("{}\n", oid.to_ascii_lowercase()).into_bytes()) + .unwrap_or_else(|| b"ref: refs/heads/codex-unborn\n".to_vec()) + .into_boxed_slice(); + std::fs::write(common.root.path().join("HEAD"), &head_contents)?; + let context = IsolatedGitReadContext { + common, + head_contents, + runner_identity: Arc::clone(&self.identity), + operation_identity: operation_identity.clone(), + config_contents: None, + attributes_contents: None, + }; + context.validate()?; + Ok(context) + } + pub(crate) fn output(&self, mut command: GitCommand) -> io::Result { self.prepare_command_for_launch(&mut command.inner)?; command.inner.output() } + pub(crate) fn output_in_isolated_common_dir( + &self, + command: GitCommand, + isolated: &IsolatedGitCommonDir, + ) -> io::Result { + self.output_in_isolated_common_dir_with_storage(command, isolated, None) + } + + pub(crate) fn output_in_isolated_scratch( + &self, + command: GitCommand, + isolated: &IsolatedGitCommonDir, + storage: &IsolatedGitStorage, + ) -> io::Result { + self.output_in_isolated_common_dir_with_storage(command, isolated, Some(storage)) + } + + fn output_in_isolated_common_dir_with_storage( + &self, + mut command: GitCommand, + isolated: &IsolatedGitCommonDir, + storage: Option<&IsolatedGitStorage>, + ) -> io::Result { + self.revalidate_active_repository_metadata()?; + isolated.validate()?; + if let Some(storage) = storage { + storage.validate()?; + } + self.authority + .ensure_config_source_is_not_worktree_controlled( + isolated.root.path(), + "owned isolated Git common directory", + )?; + isolate_git_command_environment(&mut command.inner); + scrub_repository_and_config_environment(&mut command.inner); + + let canonical_git_dir = self.authority.active_git_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git directory is unavailable for isolated three-way apply", + ) + })?; + let canonical_common_dir = self.authority.active_common_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common directory is unavailable for isolated three-way apply", + ) + })?; + let canonical_worktree = self.authority.active_worktree_root().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git worktree is unavailable for isolated three-way apply", + ) + })?; + + // Repository authority retains canonical paths for identity and route + // validation. Git for Windows does not recognize the verbatim + // `\\?\` spellings returned by `std::fs::canonicalize` in these + // environment variables, so simplify only the child-facing spelling + // after proving that it names the same existing directory. + let git_dir = git_child_directory(canonical_git_dir, "active Git directory")?; + let common_dir = git_child_directory(canonical_common_dir, "active Git common directory")?; + let worktree = git_child_directory(canonical_worktree, "active Git worktree")?; + #[cfg(windows)] + let isolated_root_base = std::fs::canonicalize(isolated.root.path())?; + #[cfg(not(windows))] + let isolated_root_base = isolated.root.path().to_path_buf(); + let isolated_root = + git_child_directory(&isolated_root_base, "owned isolated Git common directory")?; + let real_object_directory = common_dir.join("objects"); + let index_file = storage + .map(IsolatedGitStorage::index_path) + .unwrap_or_else(|| git_dir.join("index")); + let object_directory = storage + .map(IsolatedGitStorage::objects_path) + .unwrap_or_else(|| real_object_directory.clone()); + let alternate_object_directories = storage + .map(|_| { + std::env::join_paths([&real_object_directory]).map_err(|error| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("cannot encode isolated Git object alternate: {error}"), + ) + }) + }) + .transpose()?; + let system_config = isolated_root.join("system.gitconfig"); + let global_config = isolated_root.join("global.gitconfig"); + let home = isolated_root.join("home"); + let xdg_config_home = isolated_root.join("xdg"); + command + .inner + .env("GIT_DIR", git_dir.as_path()) + .env("GIT_COMMON_DIR", isolated_root.as_path()) + .env("GIT_WORK_TREE", worktree.as_path()) + .env("GIT_INDEX_FILE", index_file) + .env("GIT_OBJECT_DIRECTORY", object_directory) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_SYSTEM", system_config) + .env("GIT_CONFIG_GLOBAL", global_config) + .env("GIT_CONFIG_COUNT", "0") + .env("GIT_ATTR_NOSYSTEM", "1") + .env("GIT_NO_REPLACE_OBJECTS", "1") + .env("HOME", &home) + .env("XDG_CONFIG_HOME", &xdg_config_home); + if let Some(alternates) = alternate_object_directories { + command + .inner + .env("GIT_ALTERNATE_OBJECT_DIRECTORIES", alternates); + } + #[cfg(windows)] + command + .inner + .env("APPDATA", &home) + .env("PROGRAMDATA", &home) + .env("USERPROFILE", &home); + command.inner.envs(crate::local_only_git_env()); + harden_git_launch_environment(&mut command.inner, &self.safe_path); + self.output_after_isolated_child_validation( + &mut command.inner, + isolated, + storage, + [&git_dir, &common_dir, &worktree, &isolated_root], + ) + } + + fn output_after_isolated_child_validation( + &self, + command: &mut Command, + isolated: &IsolatedGitCommonDir, + storage: Option<&IsolatedGitStorage>, + child_directories: [&GitChildDirectory; 4], + ) -> io::Result { + self.revalidate_active_repository_metadata()?; + isolated.validate()?; + if let Some(storage) = storage { + storage.validate()?; + } + let _child_directory_validations = child_directories + .into_iter() + .map(GitChildDirectory::revalidate) + .collect::>>()?; + command.output() + } + fn revalidate_active_repository_metadata(&self) -> io::Result<()> { self.authority.revalidate_active_repository_metadata() } @@ -232,6 +795,203 @@ impl GitRunner { max_bytes_per_stream: usize, ) -> io::Result { self.prepare_command_for_launch(command.inner.as_std_mut())?; + output_async_bounded_inner(command, max_bytes_per_stream).await + } + + pub(crate) async fn output_async_in_isolated_read_context( + &self, + mut command: GitAsyncCommand, + context: &IsolatedGitReadContext, + operation_identity: &GuardedOperationIdentity, + max_bytes_per_stream: usize, + ) -> io::Result { + if !Arc::ptr_eq(&self.identity, &context.runner_identity) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated Git read context belongs to another runner", + )); + } + if !context + .operation_identity + .same_operation(operation_identity) + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated Git read context belongs to another operation", + )); + } + if context.config_contents.is_none() || context.attributes_contents.is_none() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated Git read context is not sealed", + )); + } + self.revalidate_active_repository_metadata()?; + context.validate()?; + self.authority + .ensure_config_source_is_not_worktree_controlled( + context.common.root.path(), + "owned isolated Git read context", + )?; + isolate_git_command_environment(command.inner.as_std_mut()); + scrub_repository_and_config_environment(command.inner.as_std_mut()); + + let canonical_common_dir = self.authority.active_common_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common directory is unavailable for isolated read", + ) + })?; + let canonical_worktree = self.authority.active_worktree_root().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git worktree is unavailable for isolated read", + ) + })?; + let common_dir = git_child_directory(canonical_common_dir, "active Git common directory")?; + let worktree = git_child_directory(canonical_worktree, "active Git worktree")?; + #[cfg(windows)] + let isolated_root_base = std::fs::canonicalize(context.common.root.path())?; + #[cfg(not(windows))] + let isolated_root_base = context.common.root.path().to_path_buf(); + let isolated_root = + git_child_directory(&isolated_root_base, "owned isolated Git read directory")?; + let canonical_git_dir = self.authority.active_git_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git directory is unavailable for isolated read", + ) + })?; + let git_dir = git_child_directory(canonical_git_dir, "active Git directory")?; + + let real_object_directory = common_dir.join("objects"); + let alternate_object_directories = + std::env::join_paths([&real_object_directory]).map_err(|error| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("cannot encode isolated Git object alternate: {error}"), + ) + })?; + let system_config = isolated_root.join("system.gitconfig"); + let global_config = isolated_root.join("global.gitconfig"); + command + .inner + .env("GIT_DIR", isolated_root.as_path()) + .env("GIT_COMMON_DIR", isolated_root.as_path()) + .env("GIT_WORK_TREE", worktree.as_path()) + .env("GIT_INDEX_FILE", git_dir.join("index")) + .env("GIT_OBJECT_DIRECTORY", isolated_root.join("objects")) + .env( + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + alternate_object_directories, + ) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_SYSTEM", system_config) + .env("GIT_CONFIG_GLOBAL", global_config) + .env("GIT_CONFIG_COUNT", "0") + .env_remove("GIT_ATTR_SOURCE") + .env("GIT_NO_REPLACE_OBJECTS", "1"); + self.apply_captured_attribute_environment(command.inner.as_std_mut()); + command.inner.envs(crate::local_only_git_env()); + harden_git_launch_environment(command.inner.as_std_mut(), &self.safe_path); + + self.revalidate_active_repository_metadata()?; + context.validate()?; + let _child_directory_validations = [&git_dir, &common_dir, &worktree, &isolated_root] + .into_iter() + .map(GitChildDirectory::revalidate) + .collect::>>()?; + output_async_bounded_inner(command, max_bytes_per_stream).await + } + + /// Restore only the runner-captured selectors that choose default global + /// and system attribute files. Config remains pinned to owned empty files; + /// `GIT_ATTR_SOURCE` remains removed so it cannot replace worktree + /// attributes in the synthetic repository view. + fn apply_captured_attribute_environment(&self, command: &mut Command) { + for name in ["HOME", "XDG_CONFIG_HOME"] { + match self.config_environment.value(name) { + Some(value) => command.env(name, value), + None => command.env_remove(name), + }; + } + #[cfg(windows)] + for name in [ + "APPDATA", + "PROGRAMDATA", + "USERPROFILE", + "HOMEDRIVE", + "HOMEPATH", + ] { + match self.config_environment.value(name) { + Some(value) => command.env(name, value), + None => command.env_remove(name), + }; + } + match &self.attr_nosystem { + Some(value) => command.env("GIT_ATTR_NOSYSTEM", value), + None => command.env_remove("GIT_ATTR_NOSYSTEM"), + }; + command.env_remove("GIT_ATTR_SOURCE"); + } + + fn from_search_path( + authority: RepositoryAuthority, + search_path: &OsStr, + ) -> Result { + authority.ensure_primary_authority()?; + let selected = select_git_executable(&authority, search_path)?; + let config_environment = GitConfigEnvironmentSnapshot::capture().map_err(|error| { + GitReadError::InvalidConfigEnvironment { + reason: error.to_string(), + } + })?; + Ok(Self { + executable: selected.executable, + #[cfg(any(unix, test))] + argv0: selected.argv0, + safe_path: selected.safe_path, + authority, + config_environment, + replace_ref_base: std::env::var_os("GIT_REPLACE_REF_BASE"), + no_replace_objects: std::env::var_os("GIT_NO_REPLACE_OBJECTS"), + attr_source: std::env::var_os("GIT_ATTR_SOURCE"), + attr_nosystem: std::env::var_os("GIT_ATTR_NOSYSTEM"), + identity: Arc::new(GitRunnerIdentity), + }) + } + + #[cfg(all(test, unix))] + 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)?; + let config_environment = GitConfigEnvironmentSnapshot::capture().map_err(|error| { + GitReadError::InvalidConfigEnvironment { + reason: error.to_string(), + } + })?; + Ok(Self { + argv0: executable.clone(), + executable, + safe_path, + authority, + config_environment, + replace_ref_base: std::env::var_os("GIT_REPLACE_REF_BASE"), + no_replace_objects: std::env::var_os("GIT_NO_REPLACE_OBJECTS"), + attr_source: std::env::var_os("GIT_ATTR_SOURCE"), + attr_nosystem: std::env::var_os("GIT_ATTR_NOSYSTEM"), + identity: Arc::new(GitRunnerIdentity), + }) + } +} + +async fn output_async_bounded_inner( + mut command: GitAsyncCommand, + max_bytes_per_stream: usize, +) -> io::Result { command.inner.kill_on_drop(true); if !command.stdin_configured { command.inner.stdin(Stdio::null()); @@ -268,49 +1028,6 @@ impl GitRunner { stdout, stderr, }) - } - - fn from_search_path( - authority: RepositoryAuthority, - search_path: &OsStr, - ) -> Result { - authority.ensure_primary_authority()?; - let selected = select_git_executable(&authority, search_path)?; - let config_environment = GitConfigEnvironmentSnapshot::capture().map_err(|error| { - GitReadError::InvalidConfigEnvironment { - reason: error.to_string(), - } - })?; - Ok(Self { - executable: selected.executable, - #[cfg(any(unix, test))] - argv0: selected.argv0, - safe_path: selected.safe_path, - authority, - config_environment, - }) - } - - #[cfg(all(test, unix))] - 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)?; - let config_environment = GitConfigEnvironmentSnapshot::capture().map_err(|error| { - GitReadError::InvalidConfigEnvironment { - reason: error.to_string(), - } - })?; - Ok(Self { - argv0: executable.clone(), - executable, - safe_path, - authority, - config_environment, - }) - } } async fn read_bounded_output( @@ -334,6 +1051,524 @@ async fn read_bounded_output( } } +#[cfg(unix)] +async fn read_common_info_attributes_bounded_async( + root: &Path, + max_bytes: usize, +) -> io::Result> { + use std::ffi::CString; + use std::os::fd::AsRawFd; + use std::os::fd::FromRawFd; + use std::os::unix::fs::OpenOptionsExt; + + fn openat(directory: &std::fs::File, name: &str, flags: i32) -> io::Result { + let name = CString::new(name).expect("fixed path component"); + // SAFETY: the directory descriptor is live and the fixed component is + // NUL-free. The returned descriptor is immediately owned by File. + let descriptor = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) }; + if descriptor < 0 { + Err(io::Error::last_os_error()) + } else { + // SAFETY: openat returned a fresh owned descriptor. + Ok(unsafe { std::fs::File::from_raw_fd(descriptor) }) + } + } + + let root = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) + .open(root)?; + let info = match openat( + &root, + "info", + libc::O_RDONLY + | libc::O_DIRECTORY + | libc::O_NOFOLLOW + | libc::O_NONBLOCK + | libc::O_CLOEXEC, + ) { + Ok(info) => info, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error), + }; + let attributes = match openat( + &info, + "attributes", + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC, + ) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error), + }; + let _pins = (root, info); + read_regular_file_bounded_async(attributes, max_bytes, "Git info attributes").await +} + +#[cfg(windows)] +async fn read_common_info_attributes_bounded_async( + root: &Path, + max_bytes: usize, +) -> io::Result> { + use std::fs::OpenOptions; + use std::os::windows::fs::MetadataExt; + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT; + use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS; + use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE; + + let open = |path: &Path, directory: bool| { + let mut options = OpenOptions::new(); + options + .read(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .custom_flags( + FILE_FLAG_OPEN_REPARSE_POINT + | if directory { + FILE_FLAG_BACKUP_SEMANTICS + } else { + 0 + }, + ); + options.open(path) + }; + let root_pin = open(root, true)?; + if root_pin.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Git common directory is a reparse point", + )); + } + let info_path = root.join("info"); + let info_pin = match open(&info_path, true) { + Ok(info) => info, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error), + }; + if info_pin.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Git info directory is a reparse point", + )); + } + let attributes = match open(&info_path.join("attributes"), false) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error), + }; + if attributes.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Git info attributes are a reparse point", + )); + } + let _pins = (root_pin, info_pin); + read_regular_file_bounded_async(attributes, max_bytes, "Git info attributes").await +} + +#[cfg(not(any(unix, windows)))] +async fn read_common_info_attributes_bounded_async( + root: &Path, + max_bytes: usize, +) -> io::Result> { + let file = match std::fs::OpenOptions::new() + .read(true) + .open(root.join("info/attributes")) + { + Ok(file) => file, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(Vec::new()); + } + Err(error) => return Err(error), + }; + read_regular_file_bounded_async(file, max_bytes, "Git info attributes").await +} + +async fn read_regular_file_bounded_async( + file: std::fs::File, + max_bytes: usize, + description: &str, +) -> io::Result> { + let file = tokio::fs::File::from_std(file); + let metadata = file.metadata().await?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("{description} are not a regular file"), + )); + } + if metadata.len() > max_bytes as u64 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("{description} exceed their byte limit"), + )); + } + let mut contents = Vec::with_capacity(metadata.len() as usize); + file.take(max_bytes as u64 + 1) + .read_to_end(&mut contents) + .await?; + if contents.len() > max_bytes { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("{description} grew beyond their byte limit"), + )); + } + Ok(contents) +} + +fn copy_shared_indexes(source_dir: &Path, destination_dir: &Path) -> io::Result<()> { + for entry in std::fs::read_dir(source_dir)? { + let entry = entry?; + let Some(name) = entry.file_name().to_str().map(str::to_string) else { + continue; + }; + let Some(suffix) = name.strip_prefix("sharedindex.") else { + continue; + }; + if !matches!(suffix.len(), 40 | 64) + || !suffix + .bytes() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) + { + continue; + } + copy_regular_file_without_follow(&entry.path(), &destination_dir.join(name))?; + } + Ok(()) +} + +fn copy_regular_file_without_follow(source: &Path, destination: &Path) -> io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + + options.custom_flags(libc::O_NOFOLLOW); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE; + + // Keep the opened index entry from being deleted/replaced while its + // bytes are copied, and open a reparse point itself so it can be + // rejected rather than followed. + options + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut input = options.open(source).map_err(|error| { + io::Error::new( + error.kind(), + format!("active Git index is unavailable for scratch classification: {error}"), + ) + })?; + let metadata = input.metadata()?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git index is not a regular file", + )); + } + let mut output = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(destination)?; + std::io::copy(&mut input, &mut output)?; + Ok(()) +} + +struct GitChildDirectory { + child_path: PathBuf, + #[cfg(windows)] + canonical_path: PathBuf, + #[cfg(windows)] + canonical_identity: Handle, + #[cfg(windows)] + child_identity: Handle, + #[cfg(windows)] + description: &'static str, +} + +struct GitChildDirectoryValidation { + #[cfg(windows)] + _canonical_identity: Handle, + #[cfg(windows)] + _child_identity: Handle, +} + +#[cfg(windows)] +fn open_git_child_directory_identity(path: &Path) -> io::Result { + use std::fs::OpenOptions; + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE; + + // Keep the selected directory entry pinned until the Git child exits. + // Deliberately omit FILE_SHARE_DELETE so it cannot be renamed or replaced + // between final identity validation and process creation. + let directory = OpenOptions::new() + .read(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) + .open(path)?; + Handle::from_file(directory) +} + +impl GitChildDirectory { + fn as_path(&self) -> &Path { + &self.child_path + } + + fn join(&self, path: impl AsRef) -> PathBuf { + self.child_path.join(path) + } + + #[cfg(windows)] + fn new( + canonical_path: PathBuf, + child_path: PathBuf, + description: &'static str, + ) -> io::Result { + let canonical_metadata = std::fs::metadata(&canonical_path)?; + let child_metadata = std::fs::metadata(&child_path)?; + if !canonical_metadata.is_dir() || !child_metadata.is_dir() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("{description} is not an existing directory"), + )); + } + let canonical_identity = open_git_child_directory_identity(&canonical_path)?; + let child_identity = open_git_child_directory_identity(&child_path)?; + if canonical_identity != child_identity { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("Git-compatible spelling changed the identity of {description}"), + )); + } + Ok(Self { + child_path, + canonical_path, + canonical_identity, + child_identity, + description, + }) + } + + #[cfg(windows)] + fn revalidate(&self) -> io::Result { + let canonical_metadata = std::fs::metadata(&self.canonical_path)?; + let child_metadata = std::fs::metadata(&self.child_path)?; + if !canonical_metadata.is_dir() || !child_metadata.is_dir() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("{} is no longer an existing directory", self.description), + )); + } + let canonical_identity = open_git_child_directory_identity(&self.canonical_path)?; + let child_identity = open_git_child_directory_identity(&self.child_path)?; + if canonical_identity != self.canonical_identity + || child_identity != self.child_identity + || canonical_identity != child_identity + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!( + "Git-compatible spelling no longer identifies the original {}", + self.description + ), + )); + } + Ok(GitChildDirectoryValidation { + _canonical_identity: canonical_identity, + _child_identity: child_identity, + }) + } + + #[cfg(not(windows))] + fn revalidate(&self) -> io::Result { + Ok(GitChildDirectoryValidation {}) + } +} + +#[cfg(windows)] +fn git_child_directory(path: &Path, description: &'static str) -> io::Result { + let child_path = git_compatible_windows_path(path, description)?; + GitChildDirectory::new(path.to_path_buf(), child_path, description) +} + +#[cfg(not(windows))] +fn git_child_directory(path: &Path, _description: &'static str) -> io::Result { + Ok(GitChildDirectory { + child_path: path.to_path_buf(), + }) +} + +#[cfg(windows)] +fn git_compatible_windows_path(path: &Path, description: &'static str) -> io::Result { + use std::ffi::OsString; + use std::os::windows::ffi::OsStrExt; + use std::os::windows::ffi::OsStringExt; + + let units = path.as_os_str().encode_wide().collect::>(); + match classify_windows_git_path_units(&units) { + WindowsGitPathUnits::Unchanged => Ok(path.to_path_buf()), + WindowsGitPathUnits::Converted(simplified) => { + Ok(PathBuf::from(OsString::from_wide(&simplified))) + } + WindowsGitPathUnits::Rejected => Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("refusing unsupported Windows namespace for {description}"), + )), + } +} + +#[cfg(any(windows, test))] +#[derive(Debug, Eq, PartialEq)] +enum WindowsGitPathUnits { + Unchanged, + Converted(Vec), + Rejected, +} + +#[cfg(any(windows, test))] +fn classify_windows_git_path_units(path: &[u16]) -> WindowsGitPathUnits { + const BACKSLASH: u16 = b'\\' as u16; + const VERBATIM_PREFIX: [u16; 4] = [BACKSLASH, BACKSLASH, b'?' as u16, BACKSLASH]; + const DEVICE_PREFIX: [u16; 4] = [BACKSLASH, BACKSLASH, b'.' as u16, BACKSLASH]; + const NT_PREFIX: [u16; 4] = [BACKSLASH, b'?' as u16, b'?' as u16, BACKSLASH]; + const FORWARD_VERBATIM_PREFIX: [u16; 4] = [b'/' as u16, b'/' as u16, b'?' as u16, b'/' as u16]; + const FORWARD_DEVICE_PREFIX: [u16; 4] = [b'/' as u16, b'/' as u16, b'.' as u16, b'/' as u16]; + + if path.contains(&0) { + return WindowsGitPathUnits::Rejected; + } + if path.starts_with(&DEVICE_PREFIX) + || path.starts_with(&NT_PREFIX) + || path.starts_with(&FORWARD_VERBATIM_PREFIX) + || path.starts_with(&FORWARD_DEVICE_PREFIX) + { + return WindowsGitPathUnits::Rejected; + } + let Some(path) = path.strip_prefix(&VERBATIM_PREFIX) else { + return WindowsGitPathUnits::Unchanged; + }; + + if path.len() >= 3 + && ascii_u16_is_alphabetic(path[0]) + && path[1] == b':' as u16 + && path[2] == BACKSLASH + { + return WindowsGitPathUnits::Converted(path.to_vec()); + } + + if path.len() < 4 + || !ascii_u16_eq_ignore_case(path[0], /*ascii*/ b'U') + || !ascii_u16_eq_ignore_case(path[1], /*ascii*/ b'N') + || !ascii_u16_eq_ignore_case(path[2], /*ascii*/ b'C') + || path[3] != BACKSLASH + { + return WindowsGitPathUnits::Rejected; + } + let unc_path = &path[4..]; + let Some(server_end) = unc_path.iter().position(|unit| *unit == BACKSLASH) else { + return WindowsGitPathUnits::Rejected; + }; + if server_end == 0 { + return WindowsGitPathUnits::Rejected; + } + let share = &unc_path[server_end + 1..]; + let share_end = share + .iter() + .position(|unit| *unit == BACKSLASH) + .unwrap_or(share.len()); + if share_end == 0 { + return WindowsGitPathUnits::Rejected; + } + + let mut simplified = Vec::with_capacity(unc_path.len() + 2); + simplified.extend([BACKSLASH, BACKSLASH]); + simplified.extend_from_slice(unc_path); + WindowsGitPathUnits::Converted(simplified) +} + +#[cfg(any(windows, test))] +fn ascii_u16_is_alphabetic(unit: u16) -> bool { + (b'A' as u16..=b'Z' as u16).contains(&unit) || (b'a' as u16..=b'z' as u16).contains(&unit) +} + +#[cfg(any(windows, test))] +fn ascii_u16_eq_ignore_case(unit: u16, ascii: u8) -> bool { + unit == ascii.to_ascii_lowercase() as u16 || unit == ascii.to_ascii_uppercase() as u16 +} + +fn scrub_repository_and_config_environment(command: &mut Command) { + let mut names = std::env::vars_os() + .map(|(name, _)| name) + .filter(|name| isolated_launch_variable(name)) + .collect::>(); + names.extend( + command + .get_envs() + .filter(|&(name, _)| isolated_launch_variable(name)) + .map(|(name, _)| name.to_os_string()), + ); + names.sort(); + names.dedup(); + for name in names { + command.env_remove(name); + } +} + +fn isolated_launch_variable(name: &OsStr) -> bool { + let name = name.to_string_lossy().to_ascii_uppercase(); + matches!( + name.as_str(), + "GIT_DIR" + | "GIT_COMMON_DIR" + | "GIT_WORK_TREE" + | "GIT_INDEX_FILE" + | "GIT_INDEX_VERSION" + | "GIT_OBJECT_DIRECTORY" + | "GIT_ALTERNATE_OBJECT_DIRECTORIES" + | "GIT_NAMESPACE" + | "GIT_QUARANTINE_PATH" + | "GIT_GRAFT_FILE" + | "GIT_SHALLOW_FILE" + | "GIT_REPLACE_REF_BASE" + | "GIT_NO_REPLACE_OBJECTS" + | "GIT_ATTR_SOURCE" + | "GIT_ATTR_NOSYSTEM" + | "GIT_CONFIG" + | "GIT_CONFIG_GLOBAL" + | "GIT_CONFIG_SYSTEM" + | "GIT_CONFIG_NOSYSTEM" + | "GIT_CONFIG_COUNT" + | "GIT_CONFIG_PARAMETERS" + | "GIT_DEFAULT_HASH" + | "GIT_DEFAULT_REF_FORMAT" + | "GIT_REFERENCE_BACKEND" + | "HOME" + | "XDG_CONFIG_HOME" + | "APPDATA" + | "PROGRAMDATA" + | "USERPROFILE" + | "HOMEDRIVE" + | "HOMEPATH" + ) || name.starts_with("GIT_CONFIG_KEY_") + || name.starts_with("GIT_CONFIG_VALUE_") +} + #[cfg(test)] thread_local! { static GIT_RUNNER_CONSTRUCTION_COUNT: std::cell::Cell = const { std::cell::Cell::new(0) }; diff --git a/codex-rs/git-utils/src/git_command_tests.rs b/codex-rs/git-utils/src/git_command_tests.rs index b407d64e87..b51e4ee4e4 100644 --- a/codex-rs/git-utils/src/git_command_tests.rs +++ b/codex-rs/git-utils/src/git_command_tests.rs @@ -48,6 +48,36 @@ async fn bounded_async_output_rejects_the_first_byte_over_limit() { assert_eq!(error.kind(), io::ErrorKind::InvalidData); } +#[tokio::test] +async fn common_info_attributes_treat_a_missing_info_directory_as_empty_and_bound_bytes() { + let fixture = tempfile::tempdir().expect("fixture"); + assert_eq!( + read_common_info_attributes_bounded_async(fixture.path(), 4) + .await + .expect("missing info directory is an empty source"), + Vec::::new() + ); + + std::fs::create_dir(fixture.path().join("info")).expect("create info directory"); + std::fs::write(fixture.path().join("info/attributes"), b"1234") + .expect("write exact-limit attributes"); + assert_eq!( + read_common_info_attributes_bounded_async(fixture.path(), 4) + .await + .expect("exact-limit attributes"), + b"1234" + ); + std::fs::write(fixture.path().join("info/attributes"), b"12345") + .expect("write over-limit attributes"); + assert_eq!( + read_common_info_attributes_bounded_async(fixture.path(), 4) + .await + .expect_err("over-limit attributes must fail") + .kind(), + io::ErrorKind::InvalidData + ); +} + #[cfg(unix)] #[tokio::test] async fn bounded_async_output_closes_an_unowned_piped_stdin() { @@ -346,6 +376,92 @@ fn git_config_path(path: &Path) -> String { format!("\"{}\"", path.replace('\\', "\\\\").replace('"', "\\\"")) } +#[test] +fn isolated_storage_uses_linked_worktree_shared_index_over_common_decoy() { + let fixture = tempdir_for_native_git(); + 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, &["config", "user.email", "codex@example.com"]); + run_git(&main, &["config", "user.name", "Codex"]); + std::fs::write(main.join("tracked.txt"), "tracked\n").expect("write tracked file"); + run_git(&main, &["add", "tracked.txt"]); + run_git(&main, &["commit", "-m", "base"]); + run_git( + &main, + &["worktree", "add", "-b", "linked", path_text(&linked)], + ); + run_git(&linked, &["update-index", "--split-index"]); + + let git_dir = PathBuf::from(run_git_stdout( + &linked, + &["rev-parse", "--absolute-git-dir"], + )); + let common_dir = PathBuf::from(run_git_stdout(&linked, &["rev-parse", "--git-common-dir"])); + let common_dir = if common_dir.is_absolute() { + common_dir + } else { + linked.join(common_dir) + }; + let common_dir = std::fs::canonicalize(common_dir).expect("canonical common directory"); + assert_ne!( + git_dir, common_dir, + "fixture must use distinct Git directories" + ); + + let shared_name = std::fs::read_dir(&git_dir) + .expect("read per-worktree Git directory") + .filter_map(Result::ok) + .map(|entry| entry.file_name()) + .find(|name| { + let Some(name) = name.to_str() else { + return false; + }; + let Some(suffix) = name.strip_prefix("sharedindex.") else { + return false; + }; + matches!(suffix.len(), 40 | 64) + && suffix + .bytes() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) + }) + .expect("linked worktree split-index base"); + let active_shared = git_dir.join(&shared_name); + let active_bytes = std::fs::read(&active_shared).expect("read active shared index"); + let common_decoy = common_dir.join(&shared_name); + std::fs::write(&common_decoy, b"stale common shared-index decoy") + .expect("write stale common decoy"); + + let runner = GitRunner::for_cwd(&linked).expect("runner"); + let storage = runner + .create_isolated_git_storage() + .expect("copy authoritative split index"); + assert_eq!( + std::fs::read(storage.root.path().join(&shared_name)).expect("read scratch shared index"), + active_bytes, + "distinct common-directory decoy must not replace the active per-worktree base" + ); + + let isolated = runner + .create_isolated_common_dir() + .expect("isolated common directory"); + let mut command = runner.command_for_cwd(&linked).expect("ls-files command"); + command.args(["ls-files", "--stage", "--", "tracked.txt"]); + let output = runner + .output_in_isolated_scratch(command, &isolated, &storage) + .expect("read copied split index"); + assert!( + output.status.success(), + "copied split index must resolve its active base: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + String::from_utf8_lossy(&output.stdout).contains("\ttracked.txt"), + "copied index did not retain tracked entry" + ); +} + struct OverlappingRegisteredRoute { main: PathBuf, nested: PathBuf, @@ -493,6 +609,39 @@ fn config_source_authority_preserves_and_rejects_a_worktree_crossing_spelling() ); } +#[cfg(target_os = "linux")] +#[test] +fn config_source_authority_rejects_direct_and_aliased_procfs_symlinks() { + use std::os::unix::fs::symlink; + + let fixture = tempdir_for_native_git(); + let root = fixture.path().join("repo"); + let alias = fixture.path().join("config-alias"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git(&root, &["init", "-q"]); + symlink("/proc/self/cwd", &alias).expect("create procfs alias"); + let authority = config_authority_for_root(&root); + + for path in [ + PathBuf::from("/proc/self/cwd/config"), + PathBuf::from("/proc/thread-self/cwd/config"), + PathBuf::from("/proc/self/fd/1048575/config"), + PathBuf::from("/proc/4294967295/cwd/config"), + alias.join("config"), + ] { + let error = authority + .ensure_config_source_is_not_worktree_controlled(&path, "test config") + .expect_err("process-relative config source"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("process-relative"), "{error}"); + assert!(error.to_string().contains("test config"), "{error}"); + assert!( + error.to_string().contains(&path.display().to_string()), + "{error}" + ); + } +} + #[test] fn config_source_authority_allows_protected_metadata_and_unrelated_external_paths() { let fixture = tempdir_for_native_git(); @@ -1456,6 +1605,238 @@ fn command_for_cwd_executes_from_a_canonical_windows_path() { ); } +#[test] +fn windows_verbatim_git_path_conversion_is_narrow_and_non_lossy() { + fn units(value: &str) -> Vec { + value.encode_utf16().collect() + } + + assert_eq!( + classify_windows_git_path_units(&units(r"\\?\C:\Users\alice\repo")), + WindowsGitPathUnits::Converted(units(r"C:\Users\alice\repo")) + ); + assert_eq!( + classify_windows_git_path_units(&units(r"\\?\UNC\server\share\repo")), + WindowsGitPathUnits::Converted(units(r"\\server\share\repo")) + ); + assert_eq!( + classify_windows_git_path_units(&units(r"\\?\unc\server\share")), + WindowsGitPathUnits::Converted(units(r"\\server\share")) + ); + + for unchanged in [r"C:\Users\alice\repo", r"\\server\share\repo"] { + assert_eq!( + classify_windows_git_path_units(&units(unchanged)), + WindowsGitPathUnits::Unchanged, + "unexpected conversion for {unchanged:?}" + ); + } + + for rejected in [ + r"\\.\C:\device-path", + r"\??\C:\nt-path", + r"//?/C:/forward-verbatim", + r"//./C:/forward-device", + r"\\?\C:relative", + r"\\?\C:/forward-tail", + r"\\?\GLOBALROOT\Device\HarddiskVolume1", + r"\\?\Volume{12345678-1234-1234-1234-123456789abc}\repo", + r"\\?\UNC\\share", + r"\\?\UNC\server\", + ] { + assert_eq!( + classify_windows_git_path_units(&units(rejected)), + WindowsGitPathUnits::Rejected, + "unexpected acceptance for {rejected:?}" + ); + } + + let mut unpaired_surrogate = units(r"\\?\C:\repo\"); + unpaired_surrogate.push(0xD800); + let mut expected = units(r"C:\repo\"); + expected.push(0xD800); + assert_eq!( + classify_windows_git_path_units(&unpaired_surrogate), + WindowsGitPathUnits::Converted(expected) + ); + + assert_eq!( + classify_windows_git_path_units(&units(r"\\?\C:\repo\😀")), + WindowsGitPathUnits::Converted(units(r"C:\repo\😀")) + ); + let mut unpaired_low_surrogate = units(r"\\?\C:\repo\"); + unpaired_low_surrogate.push(0xDC00); + let mut expected = units(r"C:\repo\"); + expected.push(0xDC00); + assert_eq!( + classify_windows_git_path_units(&unpaired_low_surrogate), + WindowsGitPathUnits::Converted(expected) + ); + + let mut nul = units(r"\\?\C:\repo\"); + nul.push(0); + assert_eq!( + classify_windows_git_path_units(&nul), + WindowsGitPathUnits::Rejected + ); +} + +#[cfg(windows)] +#[test] +fn git_child_directory_simplifies_canonical_path_without_changing_identity() { + use std::os::windows::ffi::OsStrExt; + + let directory = tempfile::tempdir().expect("fixture"); + let canonical = std::fs::canonicalize(directory.path()).expect("canonical fixture"); + let child = git_child_directory(&canonical, "test directory").expect("child spelling"); + assert_eq!( + same_file::Handle::from_path(&canonical).expect("canonical identity"), + same_file::Handle::from_path(child.as_path()).expect("child identity") + ); + child.revalidate().expect("revalidate child spelling"); + let child_units = child + .as_path() + .as_os_str() + .encode_wide() + .collect::>(); + assert!(!child_units.starts_with(&[b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16,])); +} + +#[cfg(windows)] +#[test] +fn git_child_directory_pins_git_paths_against_rename_and_replacement() { + const WINDOWS_ERROR_SHARING_VIOLATION: i32 = 32; + + let fixture = tempfile::tempdir().expect("fixture"); + let git_dir_path = fixture.path().join("git-dir"); + let common_dir_path = fixture.path().join("common-dir"); + std::fs::create_dir_all(&git_dir_path).expect("create Git directory"); + std::fs::create_dir_all(&common_dir_path).expect("create common directory"); + + let canonical_git_dir = std::fs::canonicalize(&git_dir_path).expect("canonical Git directory"); + let canonical_common_dir = + std::fs::canonicalize(&common_dir_path).expect("canonical common directory"); + let git_dir = + git_child_directory(&canonical_git_dir, "active Git directory").expect("pin Git directory"); + let common_dir = git_child_directory(&canonical_common_dir, "active Git common directory") + .expect("pin common directory"); + assert_ne!( + git_dir.as_path(), + canonical_git_dir, + "test must exercise the simplified Git-compatible spelling" + ); + + let moved_git_dir = fixture.path().join("git-dir-moved"); + let error = std::fs::rename(&canonical_git_dir, &moved_git_dir) + .expect_err("canonical Git directory pin must block rename"); + assert_eq!( + error.raw_os_error(), + Some(WINDOWS_ERROR_SHARING_VIOLATION), + "{error}" + ); + + let error = std::fs::remove_dir(&canonical_common_dir) + .expect_err("common directory pin must block replacement"); + assert_eq!( + error.raw_os_error(), + Some(WINDOWS_ERROR_SHARING_VIOLATION), + "{error}" + ); + + let moved_child_spelling = fixture.path().join("git-dir-child-spelling-moved"); + let error = std::fs::rename(git_dir.as_path(), &moved_child_spelling) + .expect_err("simplified Git-compatible spelling pin must block rename"); + assert_eq!( + error.raw_os_error(), + Some(WINDOWS_ERROR_SHARING_VIOLATION), + "{error}" + ); + + drop(git_dir); + std::fs::rename(&canonical_git_dir, &moved_git_dir) + .expect("released Git directory pins must allow rename"); + drop(common_dir); + std::fs::remove_dir(&canonical_common_dir) + .expect("released common directory pins must allow removal"); + std::fs::create_dir(&common_dir_path).expect("replace released common directory"); +} + +#[cfg(windows)] +#[test] +fn isolated_child_final_validation_rejects_retargeted_spelling_before_spawn() { + let fixture = tempfile::tempdir().expect("fixture"); + let repo = fixture.path().join("repo"); + let original = fixture.path().join("original"); + let attacker = fixture.path().join("attacker"); + let child_spelling = fixture.path().join("child-spelling"); + for directory in [&repo, &original, &attacker] { + std::fs::create_dir_all(directory).expect("create directory"); + } + run_git(&repo, &["init", "-q"]); + create_junction(&child_spelling, &original); + + let canonical = std::fs::canonicalize(&original).expect("canonical original"); + let child = GitChildDirectory::new( + canonical, + child_spelling.clone(), + "test Git child directory", + ) + .expect("initial child identity"); + // Keep identity snapshots that permit deletion, then release the guarded + // handles so this test can still exercise the defense-in-depth final + // revalidation after a child spelling has actually been retargeted. + let canonical_identity = + same_file::Handle::from_path(&child.canonical_path).expect("canonical identity snapshot"); + let child_identity = + same_file::Handle::from_path(&child.child_path).expect("child identity snapshot"); + let GitChildDirectory { + child_path, + canonical_path, + canonical_identity: pinned_canonical_identity, + child_identity: pinned_child_identity, + description, + } = child; + drop(pinned_canonical_identity); + drop(pinned_child_identity); + let child = GitChildDirectory { + child_path, + canonical_path, + canonical_identity, + child_identity, + description, + }; + let runner = GitRunner::for_cwd(&repo).expect("runner"); + let isolated = runner + .create_isolated_common_dir() + .expect("isolated common dir"); + let marker = fixture.path().join("child-ran.gitconfig"); + let mut command = runner.command_for_cwd(&repo).expect("marker command"); + command + .args(["config", "--file"]) + .arg(&marker) + .args(["codex.child-ran", "true"]); + + std::fs::remove_dir(&child_spelling).expect("remove original junction"); + create_junction(&child_spelling, &attacker); + + let error = runner + .output_after_isolated_child_validation( + &mut command.inner, + &isolated, + None, + [&child, &child, &child, &child], + ) + .expect_err("retargeted child spelling must fail closed"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!( + error + .to_string() + .contains("no longer identifies the original"), + "{error}" + ); + assert!(!marker.exists(), "child command ran despite stale identity"); +} + #[test] fn gitdir_terminal_worktree_root_is_never_promoted_to_metadata() { let fixture = tempfile::tempdir().expect("fixture"); @@ -1673,6 +2054,79 @@ fn active_commondir_route_is_revalidated_before_every_child() { ); } +#[cfg(unix)] +#[test] +fn active_worktree_identity_is_revalidated_before_every_child() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let moved_root = fixture.path().join("repo-moved"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git(&root, &["init", "-q"]); + let runner = GitRunner::for_cwd(&root).expect("runner for original repository"); + let sentinel = fixture.path().join("git-child-ran"); + let mut command = runner + .command_for_cwd(&root) + .expect("command for original repository"); + command + .args(["config", "--file"]) + .arg(&sentinel) + .args(["probe.value", "ran"]); + + std::fs::rename(&root, &moved_root).expect("move original repository"); + std::fs::create_dir_all(&root).expect("create replacement repository"); + run_git(&root, &["init", "-q"]); + assert!(moved_root.join(".git").is_dir()); + assert!(root.join(".git").is_dir()); + + let error = runner + .output(command) + .expect_err("same-path repository replacement must block Git child"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!( + error + .to_string() + .contains("guarded Git repository identity changed before Git launch"), + "{error}" + ); + assert!( + !sentinel.exists(), + "Git child executed after same-path repository replacement" + ); + assert_eq!( + crate::status_guard::map_io_error("status", error), + GitReadError::AuthorityRefused { + operation: "status".to_string(), + } + ); +} + +#[cfg(windows)] +#[test] +fn active_worktree_identity_pins_repository_for_runner_lifetime() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let moved_root = fixture.path().join("repo-moved"); + std::fs::create_dir_all(&root).expect("create repository"); + run_git(&root, &["init", "-q"]); + let runner = GitRunner::for_cwd(&root).expect("runner for original repository"); + + let error = std::fs::rename(&root, &moved_root) + .expect_err("live repository identity handle must block replacement"); + const WINDOWS_ERROR_SHARING_VIOLATION: i32 = 32; + assert_eq!( + error.raw_os_error(), + Some(WINDOWS_ERROR_SHARING_VIOLATION), + "{error}" + ); + assert!(root.join(".git").is_dir()); + assert!(!moved_root.exists()); + + drop(runner); + std::fs::rename(&root, &moved_root).expect("released identity handle must allow move"); + assert!(!root.exists()); + assert!(moved_root.join(".git").is_dir()); +} + #[cfg(unix)] #[test] fn direct_external_separate_git_dir_absolute_and_relative_routes_execute_git() { diff --git a/codex-rs/git-utils/src/git_config.rs b/codex-rs/git-utils/src/git_config.rs index b446e532e1..368d4140ef 100644 --- a/codex-rs/git-utils/src/git_config.rs +++ b/codex-rs/git-utils/src/git_config.rs @@ -6,6 +6,84 @@ use std::path::Path; use crate::git_command::GitRunner; use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; +pub(crate) fn parse_git_boolean(value: &[u8]) -> Option { + parse_git_boolean_with_minimum(value, i128::from(i32::MIN)) +} + +/// Parse the Git boolean grammar while excluding numeric `INT_MIN`. +/// +/// Older supported Git releases reject that one signed endpoint after unit +/// expansion, so environment gates that must succeed across versions use this +/// conservative variant. The accepted spellings otherwise share one parser. +pub(crate) fn parse_git_boolean_symmetric_i32(value: &[u8]) -> Option { + parse_git_boolean_with_minimum(value, -i128::from(i32::MAX)) +} + +fn parse_git_boolean_with_minimum(value: &[u8], minimum: i128) -> Option { + if value.eq_ignore_ascii_case(b"true") + || value.eq_ignore_ascii_case(b"yes") + || value.eq_ignore_ascii_case(b"on") + { + return Some(true); + } + if value.is_empty() + || value.eq_ignore_ascii_case(b"false") + || value.eq_ignore_ascii_case(b"no") + || value.eq_ignore_ascii_case(b"off") + { + return Some(false); + } + + // Git parses the remaining boolean spellings through `git_parse_int`: C + // base-0 syntax, an optional binary-unit suffix, and signed `int` bounds. + let value = std::str::from_utf8(value) + .ok()? + .trim_start_matches(|value: char| value.is_ascii_whitespace()); + let (negative, unsigned) = match value.as_bytes().first() { + Some(b'-') => (true, &value[1..]), + Some(b'+') => (false, &value[1..]), + Some(_) => (false, value), + None => return None, + }; + let (base, unsigned) = if unsigned.starts_with("0x") || unsigned.starts_with("0X") { + (16, &unsigned[2..]) + } else if unsigned.starts_with('0') { + (8, unsigned) + } else { + (10, unsigned) + }; + let digit_count = unsigned + .bytes() + .take_while(|byte| match base { + 8 => matches!(byte, b'0'..=b'7'), + 10 => byte.is_ascii_digit(), + 16 => byte.is_ascii_hexdigit(), + _ => false, + }) + .count(); + if digit_count == 0 { + return None; + } + let (digits, suffix) = unsigned.split_at(digit_count); + let factor = if suffix.is_empty() { + 1_i128 + } else if suffix.eq_ignore_ascii_case("k") { + 1024 + } else if suffix.eq_ignore_ascii_case("m") { + 1024 * 1024 + } else if suffix.eq_ignore_ascii_case("g") { + 1024 * 1024 * 1024 + } else { + return None; + }; + let magnitude = i128::from_str_radix(digits, base).ok()?; + let signed = if negative { -magnitude } else { magnitude }; + let value = signed.checked_mul(factor)?; + (minimum..=i128::from(i32::MAX)) + .contains(&value) + .then_some(value != 0) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum GitConfigScope { Unknown, @@ -24,6 +102,58 @@ pub(crate) struct GitConfigEntry { pub(crate) value: String, } +/// A value emitted by `git config --null --show-names`. +/// +/// Git deliberately omits the key/value delimiter for an implicit Boolean +/// (`key`) and retains it for an explicit empty value (`key =`). Keep that +/// distinction available to bounded fixed policy readers without widening +/// acceptance in ordinary config consumers. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum GitConfigValue { + Implicit, + Explicit(String), +} + +/// One ordered record from the fixed merge-policy config query. +/// +/// This deliberately exposes typed implicit-vs-explicit presence only for +/// merge policy. Existing executable- and path-valued config readers retain +/// their strict rejection of implicit values. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct MergeConfigRecord { + pub(crate) key: String, + pub(crate) value: GitConfigValue, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct GitConfigValueEntry { + scope: GitConfigScope, + origin: GitConfigOrigin, + key: String, + value: GitConfigValue, +} + +impl TryFrom for GitConfigEntry { + type Error = io::Error; + + fn try_from(entry: GitConfigValueEntry) -> Result { + let value = match entry.value { + GitConfigValue::Explicit(value) => value, + GitConfigValue::Implicit => { + return Err(invalid_config_output( + "Git config record has no key/value separator", + )); + } + }; + Ok(Self { + scope: entry.scope, + origin: entry.origin, + key: entry.key, + value, + }) + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum GitConfigOrigin { CommandLine, @@ -41,6 +171,13 @@ pub(crate) fn parse_effective_config( } pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result> { + parse_config_value_entries(output)? + .into_iter() + .map(GitConfigEntry::try_from) + .collect() +} + +fn parse_config_value_entries(output: &[u8]) -> io::Result> { if output.is_empty() { return Ok(Vec::new()); } @@ -57,19 +194,15 @@ pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result io::Result io::Result> { - Ok(parse_config_entries_with_origins(output)? +/// precedence, so duplicate include directives remain ordered. Scope is +/// retained as best-effort metadata only; command-line entries remain +/// distinguishable. +pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result> { + parse_config_value_entries_with_origins(output)? .into_iter() - .map(|entry| (entry.key.clone(), entry)) - .collect()) + .map(GitConfigEntry::try_from) + .collect() } -pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result> { +fn parse_config_value_entries_with_origins(output: &[u8]) -> io::Result> { if output.is_empty() { return Ok(Vec::new()); } @@ -106,11 +237,7 @@ pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result io::Result (&str, GitConfigValue) { + match entry.split_once('\n') { + Some((key, value)) => (key, GitConfigValue::Explicit(value.to_string())), + None => (entry, GitConfigValue::Implicit), + } +} + +#[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 read_effective_config_entries_with_fallback( git: &GitRunner, cwd: &Path, @@ -149,6 +293,68 @@ pub(crate) fn read_effective_config_entries_with_fallback( ) } +/// Read the one effective scalar whose implicit form has defined semantics. +/// +/// Existing config readers continue to reject implicit values through +/// [`GitConfigEntry::try_from`]. Keeping this query fixed prevents a caller +/// from using the permissive parser for executable or path-valued config. +pub(crate) fn read_effective_shared_repository_with_fallback( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], +) -> io::Result> { + const PATTERN: &str = r"^core\.sharedrepository$"; + let entries = read_config_value_entries_with_fallback( + git, + cwd, + git_config_args, + PATTERN, + "shared repository", + /*follow_includes*/ true, + /*config_file*/ None, + )?; + let mut effective = None; + for entry in entries { + if entry.key != "core.sharedrepository" { + return Err(invalid_config_output( + "unexpected key in shared-repository config output", + )); + } + effective = Some(entry.value); + } + Ok(effective) +} + +/// Read the complete ordered merge-driver namespace inventory. +/// +/// Git 2.54 creates a user-driver namespace for any key with a subsection, +/// including an empty or dotted subsection. A top-level `merge.*` scalar has +/// no subsection and is ignored, except for the separately handled +/// `merge.default`. Keep the query fixed so permissive typed values cannot be +/// requested for unrelated executable or path config. +pub(crate) fn read_merge_config_records_with_fallback( + git: &GitRunner, + cwd: &Path, + git_config_args: &[String], +) -> io::Result> { + const PATTERN: &str = r"^(merge\.default|merge\..*\..+)$"; + Ok(read_config_value_entries_with_fallback( + git, + cwd, + git_config_args, + PATTERN, + "merge", + /*follow_includes*/ true, + /*config_file*/ None, + )? + .into_iter() + .map(|entry| MergeConfigRecord { + key: entry.key, + value: entry.value, + }) + .collect()) +} + pub(crate) fn read_config_entries_without_includes( git: &GitRunner, cwd: &Path, @@ -197,6 +403,29 @@ fn read_config_entries_with_fallback( follow_includes: bool, config_file: Option<&Path>, ) -> io::Result> { + read_config_value_entries_with_fallback( + git, + cwd, + git_config_args, + pattern, + probe, + follow_includes, + config_file, + )? + .into_iter() + .map(GitConfigEntry::try_from) + .collect() +} + +fn read_config_value_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, @@ -211,7 +440,7 @@ fn read_config_entries_with_fallback( .code() .is_some_and(|code| code == 0 || code == 1) { - return parse_config_entries(&scoped.stdout); + return parse_config_value_entries(&scoped.stdout); } let legacy = run_effective_config_query( @@ -234,7 +463,7 @@ fn read_config_entries_with_fallback( String::from_utf8_lossy(&legacy.stderr).trim() ))); } - parse_config_entries_with_origins(&legacy.stdout) + parse_config_value_entries_with_origins(&legacy.stdout) } async fn read_config_entries_with_fallback_async( diff --git a/codex-rs/git-utils/src/git_config_environment.rs b/codex-rs/git-utils/src/git_config_environment.rs index 43d80a3afd..1cd718c13e 100644 --- a/codex-rs/git-utils/src/git_config_environment.rs +++ b/codex-rs/git-utils/src/git_config_environment.rs @@ -61,11 +61,16 @@ impl GitConfigEnvironmentSnapshot { .collect::>(); if let Some(raw_count) = value_for(OsStr::new("GIT_CONFIG_COUNT")) { - let count = raw_count + let raw_count = raw_count .to_str() - .ok_or_else(|| invalid_environment("non-UTF-8 GIT_CONFIG_COUNT"))? - .parse::() - .map_err(|_| invalid_environment("invalid GIT_CONFIG_COUNT"))?; + .ok_or_else(|| invalid_environment("non-UTF-8 GIT_CONFIG_COUNT"))?; + let count = if raw_count.is_empty() { + 0 + } else { + raw_count + .parse::() + .map_err(|_| invalid_environment("invalid GIT_CONFIG_COUNT"))? + }; if count > MAX_CONFIG_ENVIRONMENT_ENTRIES { return Err(invalid_environment( "GIT_CONFIG_COUNT exceeds the supported safety bound", @@ -98,6 +103,7 @@ impl GitConfigEnvironmentSnapshot { } } + #[cfg_attr(not(test), allow(dead_code))] pub(crate) fn value(&self, name: &str) -> Option<&OsStr> { self.entries .iter() diff --git a/codex-rs/git-utils/src/git_config_environment_tests.rs b/codex-rs/git-utils/src/git_config_environment_tests.rs index 3cdec9a790..54e4cd5766 100644 --- a/codex-rs/git-utils/src/git_config_environment_tests.rs +++ b/codex-rs/git-utils/src/git_config_environment_tests.rs @@ -40,10 +40,15 @@ fn snapshot_binds_present_empty_and_absent_fixed_and_indexed_values() { snapshot.value("GIT_CONFIG_PARAMETERS"), Some(OsStr::new("'safe.parameter'='present'")) ); + assert_eq!(snapshot.value("GIT_CONFIG_COUNT"), Some(OsStr::new("2"))); assert_eq!( snapshot.value("GIT_CONFIG_KEY_0"), Some(OsStr::new("safe.one")) ); + assert_eq!( + snapshot.value("GIT_CONFIG_VALUE_0"), + Some(OsStr::new("present")) + ); assert_eq!(snapshot.value("GIT_CONFIG_VALUE_1"), None); let mut command = Command::new("git"); @@ -80,6 +85,39 @@ fn snapshot_rejects_malformed_or_unbounded_command_config_count() { } } +#[test] +fn snapshot_treats_empty_command_config_count_as_zero() { + let values = BTreeMap::from([ + (OsString::from("GIT_CONFIG_COUNT"), OsString::from("")), + ( + OsString::from("GIT_CONFIG_KEY_0"), + OsString::from("untrusted.key"), + ), + ( + OsString::from("GIT_CONFIG_VALUE_0"), + OsString::from("untrusted-value"), + ), + ]); + let snapshot = GitConfigEnvironmentSnapshot::capture_from(|name| values.get(name).cloned()) + .expect("capture empty count"); + + assert_eq!(snapshot.value("GIT_CONFIG_COUNT"), Some(OsStr::new(""))); + assert_eq!(snapshot.value("GIT_CONFIG_KEY_0"), None); + assert_eq!(snapshot.value("GIT_CONFIG_VALUE_0"), None); + + let mut command = Command::new("git"); + command.env("GIT_CONFIG_COUNT", "1"); + snapshot.apply_to(&mut command); + let child_environment = command + .get_envs() + .map(|(name, value)| (name.to_owned(), value.map(OsStr::to_owned))) + .collect::>(); + assert_eq!( + child_environment.get(OsStr::new("GIT_CONFIG_COUNT")), + Some(&Some(OsString::from(""))) + ); +} + #[cfg(unix)] #[test] fn snapshot_preserves_non_utf8_config_path_bytes() { diff --git a/codex-rs/git-utils/src/git_config_sources.rs b/codex-rs/git-utils/src/git_config_sources.rs index 1eb3abcdec..035f5d70af 100644 --- a/codex-rs/git-utils/src/git_config_sources.rs +++ b/codex-rs/git-utils/src/git_config_sources.rs @@ -121,11 +121,7 @@ pub(crate) fn ensure_no_worktree_config_sources( 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, - )) + ensure_no_worktree_config_sources_blocking_impl(git, git_root, git_config_args) } /// Async counterpart to [`ensure_no_worktree_config_sources`] for bounded @@ -137,102 +133,88 @@ pub(crate) async fn ensure_no_worktree_config_sources_async( git_root: &Path, git_config_args: &[String], ) -> io::Result<()> { - ensure_no_worktree_config_sources_impl(SourceExecution::Async(git), git_root, git_config_args) - .await + ensure_no_worktree_config_sources_async_impl(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<'_>, +fn ensure_no_worktree_config_sources_blocking_impl( + git: &GitRunner, + git_root: &Path, + git_config_args: &[String], +) -> io::Result<()> { + let git_root = normalize_absolute_path(std::fs::canonicalize(git_root)?)?; + + for (description, candidate) in legacy_primary_config_source_candidates(git)? { + if !is_disabled_primary_config_path(&candidate) { + reject_source(git, &git_root, &candidate, description)?; + } + } + for candidate in selected_git_home_config_candidates(git, &git_root)? { + reject_source(git, &git_root, &candidate, "selected Git HOME config")?; + } + if let Some(candidate) = selected_git_prefix_system_candidate(git, &git_root)? { + reject_source( + git, + &git_root, + &candidate, + "selected Git prefix system config", + )?; + } + let entries = read_config_entries_without_includes( + git, + &git_root, + git_config_args, + INCLUDE_CONFIG_PATTERN, + "include", + /*config_file*/ None, + )?; + #[cfg(test)] + signal_blocking_no_includes_query_phase(); + let mut pending = Vec::new(); + let mut include_budget = IncludeGraphBudget::default(); + validate_include_entries( + git, + &git_root, + entries, + /*depth*/ 1, + &mut pending, + &mut include_budget, + )?; + let mut visited = BTreeSet::new(); + while let Some((config_path, depth)) = pending.pop() { + if !pending_include_is_new(&config_path, depth, &mut visited)? { + continue; + } + let entries = read_config_entries_without_includes( + git, + &git_root, + &[], + INCLUDE_CONFIG_PATTERN, + "include", + Some(&config_path), + )?; + validate_include_entries( + git, + &git_root, + entries, + depth + 1, + &mut pending, + &mut include_budget, + )?; + } + for (description, candidate) in default_system_config_source_candidates(git, &git_root)? { + if !is_disabled_primary_config_path(&candidate) { + reject_source(git, &git_root, &candidate, description)?; + } + } + Ok(()) +} + +async fn ensure_no_worktree_config_sources_async_impl( + git: &GitRunner, 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 @@ -242,10 +224,10 @@ async fn ensure_no_worktree_config_sources_impl( reject_source(git, &git_root, &candidate, description)?; } } - for candidate in execution.selected_home_candidates(&git_root).await? { + for candidate in selected_git_home_config_candidates_async(git, &git_root).await? { reject_source(git, &git_root, &candidate, "selected Git HOME config")?; } - if let Some(candidate) = execution.selected_prefix_candidate(&git_root).await? { + if let Some(candidate) = selected_git_prefix_system_candidate_async(git, &git_root).await? { reject_source( git, &git_root, @@ -253,71 +235,59 @@ async fn ensure_no_worktree_config_sources_impl( "selected Git prefix system config", )?; } - let entries = execution - .read_include_entries(&git_root, git_config_args, /*config_file*/ None) - .await?; - #[cfg(test)] - if matches!(execution, SourceExecution::Blocking(_)) { - signal_blocking_no_includes_query_phase(); - } + let entries = read_config_entries_without_includes_async( + git, + &git_root, + git_config_args, + INCLUDE_CONFIG_PATTERN, + "include", + /*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?; + validate_include_entries_async( + git, + &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()) { + if !pending_include_is_new(&config_path, depth, &mut visited)? { 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?; + let entries = read_config_entries_without_includes_async( + git, + &git_root, + &[], + INCLUDE_CONFIG_PATTERN, + "include", + Some(&config_path), + ) + .await?; + validate_include_entries_async( + git, + &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? { + for (description, candidate) in + default_system_config_source_candidates_async(git, &git_root).await? + { if !is_disabled_primary_config_path(&candidate) { reject_source(git, &git_root, &candidate, description)?; } @@ -325,6 +295,39 @@ async fn ensure_no_worktree_config_sources_impl( Ok(()) } +fn pending_include_is_new( + config_path: &Path, + depth: usize, + visited: &mut BTreeSet, +) -> io::Result { + 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 + ) => + { + return Ok(false); + } + Err(error) => return Err(error), + } + if !visited.insert(config_path.to_path_buf()) { + return Ok(false); + } + if visited.len() > MAX_CONFIG_INCLUDE_FILES { + return Err(path_safety::invalid_config_source( + "too many Git config include files", + )); + } + Ok(true) +} + fn reject_source( git: &GitRunner, cwd: &Path, 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 index 4bccb0011a..73623e4194 100644 --- a/codex-rs/git-utils/src/git_config_sources/primary_sources.rs +++ b/codex-rs/git-utils/src/git_config_sources/primary_sources.rs @@ -8,6 +8,7 @@ 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; +use crate::git_config::parse_git_boolean_symmetric_i32; pub(super) fn default_system_config_source_candidates( git: &GitRunner, @@ -379,19 +380,8 @@ fn git_env_bool(git: &GitRunner, name: &str) -> io::Result { 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")), - } + parse_git_boolean_symmetric_i32(value.as_bytes()) + .ok_or_else(|| invalid_config_source("invalid Git boolean environment value")) } #[cfg(windows)] diff --git a/codex-rs/git-utils/src/git_config_sources_tests.rs b/codex-rs/git-utils/src/git_config_sources_tests.rs index ed4727b422..882fbc2ea0 100644 --- a/codex-rs/git-utils/src/git_config_sources_tests.rs +++ b/codex-rs/git-utils/src/git_config_sources_tests.rs @@ -40,6 +40,7 @@ fn init_repo_at(root: &Path) { } #[cfg(windows)] +#[allow(dead_code)] 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 @@ -65,6 +66,17 @@ fn guard(root: &Path) -> io::Result<()> { ensure_no_worktree_config_sources(&git, root, &[]) } +#[test] +fn blocking_source_authorization_is_safe_inside_futures_local_pool() { + let repo = init_repo(); + let git = GitRunner::for_cwd_io(repo.path()).expect("Git runner"); + + futures::executor::block_on(async { + ensure_no_worktree_config_sources(&git, repo.path(), &[]) + .expect("blocking traversal must not enter a nested executor"); + }); +} + fn add_include(root: &Path, key: &str, value: &str) { run_success(root, &["config", "--add", key, value]); } @@ -74,7 +86,28 @@ fn assert_worktree_rejection(error: io::Error) { assert!(error.to_string().contains("worktree-controlled"), "{error}"); } +#[cfg(target_os = "linux")] +fn assert_process_relative_include_rejection(error: io::Error) { + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!( + error + .to_string() + .contains("process-relative Git config include"), + "{error}" + ); +} + fn run_isolated_source_test(test_name: &str, env: &[(&str, &OsStr)], removed: &[&str]) { + let cwd = std::env::current_dir().expect("current directory"); + run_isolated_source_test_from(test_name, env, removed, &cwd); +} + +fn run_isolated_source_test_from( + test_name: &str, + env: &[(&str, &OsStr)], + removed: &[&str], + cwd: &Path, +) { let mut command = std::process::Command::new(std::env::current_exe().expect("test binary")); crate::safe_git::isolate_git_command_environment(&mut command); command @@ -82,7 +115,8 @@ fn run_isolated_source_test(test_name: &str, env: &[(&str, &OsStr)], removed: &[ .arg("--exact") .arg("--nocapture") .env("CODEX_GIT_CONFIG_SOURCE_CHILD", "1") - .env("RUST_TEST_THREADS", "1"); + .env("RUST_TEST_THREADS", "1") + .current_dir(cwd); for (name, value) in env { command.env(name, value); } @@ -98,6 +132,90 @@ fn run_isolated_source_test(test_name: &str, env: &[(&str, &OsStr)], removed: &[ ); } +#[cfg(target_os = "linux")] +#[test] +fn rejects_process_relative_primary_config_sources_before_git_changes_cwd() { + use std::os::unix::fs::symlink; + + const TEST_NAME: &str = "git_config_sources::tests::rejects_process_relative_primary_config_sources_before_git_changes_cwd"; + if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("repo"); + let external = fixture.path().join("external"); + let alias = fixture.path().join("config-alias"); + let chained_alias = fixture.path().join("chained-alias"); + init_repo_at(&root); + std::fs::create_dir(&external).expect("external directory"); + std::fs::write( + external.join("decoy.gitconfig"), + "[safe]\nvalue = external\n", + ) + .expect("external decoy"); + std::fs::write( + external.join(".gitconfig"), + "[safe]\nvalue = external-home\n", + ) + .expect("external HOME config"); + for leaf in ["decoy.gitconfig", "missing-parent.gitconfig"] { + std::fs::write(root.join(leaf), "[unsafe]\nhelper = worktree\n") + .expect("worktree config"); + } + symlink("/proc/self/cwd", &alias).expect("procfs alias"); + symlink("config-alias", &chained_alias).expect("chained procfs alias"); + + let candidates = [ + PathBuf::from("/proc/self/cwd/decoy.gitconfig"), + PathBuf::from("/proc/thread-self/cwd/decoy.gitconfig"), + PathBuf::from("/proc/self/cwd/missing-parent.gitconfig"), + alias.join("decoy.gitconfig"), + chained_alias.join("decoy.gitconfig"), + ]; + for candidate in &candidates { + run_isolated_source_test_from( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("GIT_CONFIG_GLOBAL", candidate.as_os_str()), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + &["GIT_CONFIG_SYSTEM"], + &external, + ); + } + run_isolated_source_test_from( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("GIT_CONFIG_GLOBAL", OsStr::new("")), + ( + "GIT_CONFIG_SYSTEM", + OsStr::new("/proc/self/cwd/decoy.gitconfig"), + ), + ], + &["GIT_CONFIG_NOSYSTEM"], + &external, + ); + run_isolated_source_test_from( + TEST_NAME, + &[ + ("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()), + ("HOME", OsStr::new("/proc/self/cwd")), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + &["GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "XDG_CONFIG_HOME"], + &external, + ); + return; + } + + let root = PathBuf::from( + std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"), + ); + let error = guard(&root).expect_err("process-relative primary config source"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("process-relative"), "{error}"); +} + #[test] fn allows_protected_metadata_and_external_config_sources() { let repo = init_repo(); @@ -402,9 +520,8 @@ fn rejects_worktree_fifo_primary_source_without_opening_it() { } #[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"; +fn git_config_nosystem_uses_the_shared_parser_with_a_cross_version_numeric_subset() { + const TEST_NAME: &str = "git_config_sources::tests::git_config_nosystem_uses_the_shared_parser_with_a_cross_version_numeric_subset"; if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() { let repo = init_repo(); let unsafe_system = repo.path().join("system.gitconfig"); @@ -415,6 +532,11 @@ fn git_config_nosystem_accepts_cross_version_boolean_values() { ("-1", "ignored"), ("01", "ignored"), ("+1", "ignored"), + ("0x1", "ignored"), + ("010", "ignored"), + ("1k", "ignored"), + ("-1g", "ignored"), + (" 1", "ignored"), ("2147483647", "ignored"), ("-2147483647", "ignored"), ("true", "ignored"), @@ -427,9 +549,17 @@ fn git_config_nosystem_accepts_cross_version_boolean_values() { ("no", "rejected"), ("off", "rejected"), ("not-a-bool", "invalid"), + ("08", "invalid"), ("2147483648", "invalid"), ("-2147483648", "invalid"), + ("-0x80000000", "invalid"), + ("-020000000000", "invalid"), + ("-2097152k", "invalid"), + ("-2048m", "invalid"), + ("-2g", "invalid"), + (" -2G", "invalid"), ("-2147483649", "invalid"), + ("2g", "invalid"), ] { run_isolated_source_test( TEST_NAME, @@ -838,6 +968,73 @@ async fn blocking_and_async_source_authorization_share_the_same_include_policy() assert_eq!(asynchronous.kind(), blocking.kind()); } +#[cfg(target_os = "linux")] +#[test] +fn rejects_process_relative_procfs_includes_across_the_include_graph() { + use std::os::unix::fs::symlink; + + for (key, value, leaf) in [ + ( + "include.path", + "/proc/self/cwd/direct.gitconfig", + "direct.gitconfig", + ), + ( + "includeIf.gitdir:/definitely/not/this/repository/**.path", + "/proc/thread-self/cwd/conditional.gitconfig", + "conditional.gitconfig", + ), + ] { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(leaf), "[unsafe]\nhelper = worktree\n") + .expect("write process-relative include target"); + add_include(root, key, value); + assert_process_relative_include_rejection( + guard(root).expect_err("process-relative repository include"), + ); + } + + let repo = init_repo(); + let root = repo.path(); + std::fs::write( + root.join("command.gitconfig"), + "[unsafe]\nhelper = worktree\n", + ) + .expect("write command include target"); + let git = GitRunner::for_cwd_io(root).expect("Git runner"); + let args = vec![ + "-c".to_string(), + "include.path=/proc/self/cwd/command.gitconfig".to_string(), + ]; + assert_process_relative_include_rejection( + ensure_no_worktree_config_sources(&git, root, &args) + .expect_err("process-relative command-scoped include"), + ); + + let repo = init_repo(); + let root = repo.path(); + std::fs::write( + root.join("nested.gitconfig"), + "[unsafe]\nhelper = worktree\n", + ) + .expect("write nested include target"); + let external = tempfile::tempdir().expect("external include directory"); + let parent = external.path().join("parent.gitconfig"); + let alias = external.path().join("procfs-alias"); + symlink("/proc/self/cwd", &alias).expect("create procfs alias"); + std::fs::write(&parent, "[include]\npath = procfs-alias/nested.gitconfig\n") + .expect("write external parent config"); + add_include( + root, + "include.path", + parent.to_str().expect("UTF-8 parent config path"), + ); + assert_process_relative_include_rejection( + guard(root).expect_err("nested aliased process-relative include"), + ); +} + #[test] fn rejects_every_duplicate_and_nested_include_target() { for unsafe_first in [true, false] { diff --git a/codex-rs/git-utils/src/git_config_tests.rs b/codex-rs/git-utils/src/git_config_tests.rs index 77a055997a..151ee0832f 100644 --- a/codex-rs/git-utils/src/git_config_tests.rs +++ b/codex-rs/git-utils/src/git_config_tests.rs @@ -28,6 +28,256 @@ command\0command line:\0merge.Name.driver\nhelper %A %B\0"; ); } +#[test] +fn typed_config_parser_distinguishes_implicit_from_explicit_empty() { + let scoped = b"local\0file:/repo/.git/config\0core.sharedrepository\0\ +local\0file:/repo/.git/config\0core.other\n\0"; + let parsed = parse_config_value_entries(scoped).expect("parse typed scoped config"); + assert_eq!(parsed[0].key, "core.sharedrepository"); + assert_eq!(parsed[0].value, GitConfigValue::Implicit); + assert_eq!(parsed[1].key, "core.other"); + assert_eq!(parsed[1].value, GitConfigValue::Explicit(String::new())); + + let legacy = b"file:/repo/.git/config\0core.sharedrepository\0\ +file:/repo/.git/config\0core.other\n\0"; + let parsed = + parse_config_value_entries_with_origins(legacy).expect("parse typed legacy config"); + assert_eq!(parsed[0].value, GitConfigValue::Implicit); + assert_eq!(parsed[1].value, GitConfigValue::Explicit(String::new())); +} + +#[test] +fn ordinary_config_parser_still_rejects_implicit_values() { + for output in [ + b"local\0file:/repo/.git/config\0filter.demo.clean\0".as_slice(), + b"file:/repo/.git/config\0include.path\0".as_slice(), + ] { + let result = if output.starts_with(b"local\0") { + parse_config_entries(output) + } else { + parse_config_entries_with_origins(output) + }; + assert!(result.is_err(), "implicit value unexpectedly accepted"); + } +} + +#[test] +fn typed_config_parser_splits_only_the_first_value_delimiter() { + let output = b"local\0file:/repo/.git/config\0core.demo\nfirst\nsecond\0"; + let parsed = parse_config_value_entries(output).expect("parse multiline explicit value"); + assert_eq!( + parsed[0].value, + GitConfigValue::Explicit("first\nsecond".to_string()) + ); +} + +#[test] +fn fixed_merge_config_reader_preserves_ordered_typed_records() { + use std::io::Write as _; + + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + let mut init = std::process::Command::new("git"); + crate::safe_git::isolate_git_command_environment(&mut init); + let output = init + .args(["init", "-q"]) + .current_dir(root) + .output() + .expect("initialize repo"); + assert!(output.status.success()); + let mut config = std::fs::OpenOptions::new() + .append(true) + .open(root.join(".git/config")) + .expect("open local config"); + write!( + config, + "\n[merge \"codex-reader\"]\n\tname\n\tname = later\n\tarbitrary\n\ + [merge \"codex.reader.dotted\"]\n\tunknown\n\ + [merge]\n\tcodexscalar = ignored\n" + ) + .expect("append merge config records"); + drop(config); + + let git = GitRunner::for_cwd_io(root).expect("runner"); + let all_records = read_merge_config_records_with_fallback(&git, root, &[]) + .expect("read fixed merge config records"); + assert!( + all_records + .iter() + .all(|record| record.key != "merge.codexscalar"), + "top-level merge scalar must not be returned as a user namespace" + ); + let records = all_records + .into_iter() + .filter(|record| { + record.key.starts_with("merge.codex-reader.") + || record.key.starts_with("merge.codex.reader.dotted.") + }) + .collect::>(); + assert_eq!( + records, + vec![ + MergeConfigRecord { + key: "merge.codex-reader.name".to_string(), + value: GitConfigValue::Implicit, + }, + MergeConfigRecord { + key: "merge.codex-reader.name".to_string(), + value: GitConfigValue::Explicit("later".to_string()), + }, + MergeConfigRecord { + key: "merge.codex-reader.arbitrary".to_string(), + value: GitConfigValue::Implicit, + }, + MergeConfigRecord { + key: "merge.codex.reader.dotted.unknown".to_string(), + value: GitConfigValue::Implicit, + }, + ] + ); +} + +#[test] +fn effective_shared_repository_reader_preserves_implicit_and_empty_values() { + use std::io::Write as _; + + for (line, expected) in [ + ("\tsharedRepository\n", GitConfigValue::Implicit), + ( + "\tsharedRepository =\n", + GitConfigValue::Explicit(String::new()), + ), + ] { + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + let mut init = std::process::Command::new("git"); + crate::safe_git::isolate_git_command_environment(&mut init); + let initialized = init + .args(["init", "-q"]) + .current_dir(root) + .output() + .expect("initialize repo"); + assert!( + initialized.status.success(), + "initialize repo: {}", + String::from_utf8_lossy(&initialized.stderr) + ); + let mut config = std::fs::OpenOptions::new() + .append(true) + .open(root.join(".git/config")) + .expect("open local config"); + write!(config, "\n[core]\n{line}").expect("append shared-repository value"); + drop(config); + + let git = GitRunner::for_cwd_io(root).expect("Git runner"); + assert_eq!( + read_effective_shared_repository_with_fallback(&git, root, &[]) + .expect("read shared repository"), + Some(expected), + "config line {line:?}" + ); + } +} + +#[test] +fn git_boolean_accepts_native_git_spellings() { + for (value, expected) in [ + (b"true".as_slice(), true), + (b"TRUE".as_slice(), true), + (b"yes".as_slice(), true), + (b"On".as_slice(), true), + (b"1".as_slice(), true), + (b"2".as_slice(), true), + (b"-1".as_slice(), true), + (b"+1".as_slice(), true), + (b"01".as_slice(), true), + (b"0x1".as_slice(), true), + (b"0Xf".as_slice(), true), + (b"010".as_slice(), true), + (b"1k".as_slice(), true), + (b"1M".as_slice(), true), + (b"1g".as_slice(), true), + (b" 1".as_slice(), true), + (b"2147483647".as_slice(), true), + (b"-2147483648".as_slice(), true), + (b"-2g".as_slice(), true), + (b"false".as_slice(), false), + (b"FALSE".as_slice(), false), + (b"no".as_slice(), false), + (b"Off".as_slice(), false), + (b"".as_slice(), false), + (b"0".as_slice(), false), + (b"-0".as_slice(), false), + (b"+0".as_slice(), false), + (b"00".as_slice(), false), + (b"0x0".as_slice(), false), + (b"0k".as_slice(), false), + ] { + assert_eq!(parse_git_boolean(value), Some(expected), "value {value:?}"); + } +} + +#[test] +fn git_boolean_rejects_values_native_git_rejects() { + for value in [ + b"08".as_slice(), + b"-08".as_slice(), + b"2147483648".as_slice(), + b"-2147483649".as_slice(), + b"9223372036854775807".as_slice(), + b"2g".as_slice(), + b"-3g".as_slice(), + b"0x".as_slice(), + b"0b1".as_slice(), + b"1kb".as_slice(), + b"1foo".as_slice(), + b"1_0".as_slice(), + b"1 ".as_slice(), + b" ".as_slice(), + b"+".as_slice(), + b"-".as_slice(), + b"not-a-bool".as_slice(), + b"\xff".as_slice(), + ] { + assert_eq!(parse_git_boolean(value), None, "value {value:?}"); + } +} + +#[test] +fn symmetric_git_boolean_parser_excludes_only_int_min_spellings() { + for value in [ + b"-2147483648".as_slice(), + b"-0x80000000".as_slice(), + b"-020000000000".as_slice(), + b"-2097152k".as_slice(), + b"-2048m".as_slice(), + b"-2g".as_slice(), + b" -2G".as_slice(), + ] { + assert_eq!(parse_git_boolean(value), Some(true), "value {value:?}"); + assert_eq!( + parse_git_boolean_symmetric_i32(value), + None, + "value {value:?}" + ); + } + + for value in [ + b"0x1".as_slice(), + b"010".as_slice(), + b"1k".as_slice(), + b"-1g".as_slice(), + b" 1".as_slice(), + b"-2147483647".as_slice(), + ] { + assert_eq!( + parse_git_boolean_symmetric_i32(value), + parse_git_boolean(value), + "value {value:?}" + ); + } +} + #[test] fn entry_parsers_preserve_duplicate_include_directives_in_order() { let scoped = b"local\0file:.git/config\0include.path\n../unsafe.gitconfig\0\ @@ -80,7 +330,7 @@ fn rejects_malformed_config_records() { b"global\0\0key\nvalue\0".as_slice(), b"global\0file:/tmp/config\0\nvalue\0".as_slice(), ] { - assert!(parse_effective_config(output).is_err(), "{output:?}"); + assert!(parse_config_entries(output).is_err(), "{output:?}"); } } diff --git a/codex-rs/git-utils/src/guarded_config.rs b/codex-rs/git-utils/src/guarded_config.rs index 70d2cfb8cb..6a9ad21c9a 100644 --- a/codex-rs/git-utils/src/guarded_config.rs +++ b/codex-rs/git-utils/src/guarded_config.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::ffi::OsStr; use std::io; use std::io::Seek; @@ -8,14 +9,21 @@ use std::process::Stdio; use std::sync::Arc; use crate::FsmonitorOverride; -use crate::FsmonitorProbeRunner; use crate::git_command::GitAsyncCommand; use crate::git_command::GitCommand; use crate::git_command::GitRunner; +use crate::git_command::IsolatedGitStorage; use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; use crate::git_config::GitConfigEntry; +use crate::git_config::GitConfigOrigin; +use crate::git_config::GitConfigValue; +use crate::git_config::MergeConfigRecord; +use crate::git_config::parse_config_entries; +use crate::git_config::parse_config_entries_with_origins; use crate::git_config::read_effective_config_with_fallback; use crate::git_config::read_effective_config_with_fallback_async; +use crate::git_config::read_effective_shared_repository_with_fallback; +use crate::git_config::read_merge_config_records_with_fallback; use crate::git_config_sources::ensure_no_worktree_config_sources; use crate::git_config_sources::ensure_no_worktree_config_sources_async; use crate::safe_git::DISABLED_HOOKS_PATH; @@ -31,7 +39,7 @@ use crate::safe_git::SentinelFilterProbeResolution; use crate::safe_git::build_filter_policy_snapshot; use crate::safe_git::classify_selected_filter; use crate::safe_git::classify_sentinel_filter_probes; -use crate::safe_git::executable_filter_drivers; +use crate::safe_git::status_policy_filter_drivers; use crate::safe_git::git_path_argument; use crate::safe_git::parse_filter_attributes; use crate::safe_git::parse_nul_paths; @@ -57,6 +65,8 @@ pub(crate) use merge_overlay::merge_overlay_count; #[cfg(test)] pub(crate) use merge_overlay::reset_merge_policy_counts; mod reverse_probe; +mod status_context; +use status_context::SealedStatusReadContext; /// Proof that one exact Git config invocation has no worktree-controlled /// source routes for one runner and canonical repository root. @@ -122,6 +132,141 @@ impl<'git> ValidatedConfigSources<'git> { ) } + fn read_shared_repository(&self) -> io::Result> { + read_effective_shared_repository_with_fallback( + self.git, + &self.canonical_root, + &self.base_config_args, + ) + } + + fn read_merge_config(&self) -> io::Result> { + read_merge_config_records_with_fallback( + self.git, + &self.canonical_root, + &self.base_config_args, + ) + } + + fn read_direct_common_config( + &self, + pattern: &str, + probe: &str, + ) -> io::Result> { + let (scoped, scoped_path) = self + .git + .read_active_common_config_without_includes(pattern, /*show_scope*/ true)?; + let entries = if scoped + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + parse_config_entries(&scoped.stdout)? + } else { + let (legacy, legacy_path) = self + .git + .read_active_common_config_without_includes(pattern, /*show_scope*/ false)?; + if legacy_path != scoped_path { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common config changed during format fallback", + )); + } + if !legacy + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + return Err(io::Error::other(format!( + "git {probe} direct common config probe failed with status {}: {}", + legacy.status, + String::from_utf8_lossy(&legacy.stderr).trim() + ))); + } + parse_config_entries_with_origins(&legacy.stdout)? + }; + for entry in &entries { + let expected_origin = match &entry.origin { + GitConfigOrigin::File(origin) => { + same_file::is_same_file(origin, &scoped_path).unwrap_or(false) + } + GitConfigOrigin::CommandLine => false, + }; + if !expected_origin { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("git {probe} direct common config probe returned an unexpected origin"), + )); + } + } + Ok(entries + .into_iter() + .map(|entry| (entry.key.clone(), entry)) + .collect()) + } + + async fn read_direct_common_config_async( + &self, + pattern: &str, + probe: &str, + ) -> io::Result> { + let (scoped, scoped_path) = self + .git + .read_active_common_config_without_includes_async(pattern, /*show_scope*/ true) + .await?; + let entries = if scoped + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + parse_config_entries(&scoped.stdout)? + } else { + let (legacy, legacy_path) = self + .git + .read_active_common_config_without_includes_async( + pattern, + /*show_scope*/ false, + ) + .await?; + if legacy_path != scoped_path { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git common config changed during format fallback", + )); + } + if !legacy + .status + .code() + .is_some_and(|code| code == 0 || code == 1) + { + return Err(io::Error::other(format!( + "git {probe} direct common config probe failed with status {}: {}", + legacy.status, + String::from_utf8_lossy(&legacy.stderr).trim() + ))); + } + parse_config_entries_with_origins(&legacy.stdout)? + }; + for entry in &entries { + let expected_origin = match &entry.origin { + GitConfigOrigin::File(origin) => { + same_file::is_same_file(origin, &scoped_path).unwrap_or(false) + } + GitConfigOrigin::CommandLine => false, + }; + if !expected_origin { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("git {probe} direct common config probe returned an unexpected origin"), + )); + } + } + Ok(entries + .into_iter() + .map(|entry| (entry.key.clone(), entry)) + .collect()) + } + fn read_bool(&self, key: &str) -> io::Result> { let mut command = self.git.command_for_cwd(&self.canonical_root)?; command @@ -216,6 +361,14 @@ fn invalid_base_config_args() -> io::Error { pub(crate) struct GuardedGitConfig<'git> { sources: ValidatedConfigSources<'git>, identity: Arc, + // Captured once for an apply operation and appended after every mutable + // config source/overlay so these scalar inputs cannot change between a + // nonmutating gate and a later index/worktree mutation. + apply_policy: Option, + // Set only by the fixed real-policy numstat gate. Fatal whitespace modes + // may be neutralized for a later mutating child only after this proof is + // recorded on the same operation capability. + apply_policy_gate: ApplyPolicyGateState, // Ordered, typed snapshots keep each sealed filter overlay alive through // every later child. Downstream staging may attach a fresh Git-add policy // without rebuilding or weakening the source authorization. @@ -226,13 +379,17 @@ pub(crate) struct GuardedGitConfig<'git> { merge: Option, merge_policy_installed: bool, // Status is a mutually exclusive operation state rather than another - // mutation overlay. `Some` with no neutralizer records the zero-driver - // case and is still required before the final status sink can run. - status: Option, + // mutation overlay. The retained context freezes helper selection, HEAD, + // and untracked presence for the final tracked-only Status sink. + status: Option, + // Set only after proving the effective replacement-ref namespace empty + // (or already disabled). Every later snapshot command then forces + // replacements off so a late ref cannot affect the frozen context. + status_replacements_disabled: bool, } -struct StatusFilterPolicySnapshot { - neutralizer: Option, +struct StatusPolicySnapshot { + context: SealedStatusReadContext, fsmonitor: Option, } @@ -301,6 +458,105 @@ impl StatusRootMismatch { struct CapabilityIdentity; +/// Opaque operation identity for sealed plans implemented in sibling modules. +/// Its inner capability cannot be forged or rebound outside this module. +#[derive(Clone)] +pub(crate) struct GuardedOperationIdentity(Arc); + +impl GuardedOperationIdentity { + pub(crate) fn same_operation(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +enum ApplyPolicyGateState { + NotRun, + Failed, + Succeeded { revert: bool, patch_path: String }, +} + +const APPLY_POLICY_CONFIG_PATTERN: &str = + r"^(apply\.(whitespace|ignorewhitespace)|core\.whitespace)$"; +const DEFAULT_APPLY_WHITESPACE: &str = "warn"; +const DEFAULT_APPLY_IGNORE_WHITESPACE: &str = "false"; +const DEFAULT_CORE_WHITESPACE: &str = "blank-at-eol,blank-at-eof,space-before-tab"; + +struct ApplyPolicySnapshot { + config_args: Box<[String]>, + whitespace_mode: ApplyWhitespaceMode, +} + +/// Normalized `apply.whitespace` behavior frozen for one apply operation. +/// +/// Unknown or case-mismatched values stay invalid here and are left for Git's +/// authoritative policy gate to reject. The `strip` alias has the same byte- +/// correcting behavior as `fix`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ApplyWhitespaceMode { + Warn, + Nowarn, + Error, + ErrorAll, + Fix, + Invalid, +} + +impl ApplyWhitespaceMode { + fn normalize(value: &str) -> Self { + match value { + "warn" => Self::Warn, + "nowarn" => Self::Nowarn, + "error" => Self::Error, + "error-all" => Self::ErrorAll, + "fix" | "strip" => Self::Fix, + _ => Self::Invalid, + } + } + + pub(crate) fn is_fatal(self) -> bool { + matches!(self, Self::Error | Self::ErrorAll) + } +} + +impl ApplyPolicySnapshot { + fn capture(sources: &ValidatedConfigSources<'_>) -> io::Result { + let entries = sources.read_effective(APPLY_POLICY_CONFIG_PATTERN, "apply policy")?; + let value = |key: &str, default: &str| { + entries + .get(key) + .map(|entry| entry.value.clone()) + .unwrap_or_else(|| default.to_string()) + }; + let apply_whitespace = value("apply.whitespace", DEFAULT_APPLY_WHITESPACE); + Ok(Self { + config_args: vec![ + "-c".to_string(), + format!("apply.whitespace={apply_whitespace}"), + "-c".to_string(), + format!( + "apply.ignoreWhitespace={}", + value("apply.ignorewhitespace", DEFAULT_APPLY_IGNORE_WHITESPACE) + ), + "-c".to_string(), + format!( + "core.whitespace={}", + value("core.whitespace", DEFAULT_CORE_WHITESPACE) + ), + ] + .into_boxed_slice(), + whitespace_mode: ApplyWhitespaceMode::normalize(&apply_whitespace), + }) + } + + fn append_to(&self, command: &mut GitCommand) { + command.args(&self.config_args); + } + + fn append_rendered(&self, parts: &mut Vec) { + parts.extend(self.config_args.iter().cloned()); + } +} + #[derive(Clone, Copy)] enum BoundSubcommand { Apply, @@ -388,6 +644,24 @@ impl GuardedAsyncGitCommand<'_, '_> { .output_async_bounded(self.inner, MAX_INTERNAL_GIT_OUTPUT_BYTES) .await } + + async fn output_in_status_context( + self, + context: &SealedStatusReadContext, + ) -> io::Result { + let isolated = context.context(&self.operation.identity)?; + let operation_identity = self.operation.operation_identity(); + self.operation + .sources + .git + .output_async_in_isolated_read_context( + self.inner, + isolated, + &operation_identity, + MAX_INTERNAL_GIT_OUTPUT_BYTES, + ) + .await + } } /// A sealed filter-only include owned for the complete capability lifetime. @@ -467,6 +741,23 @@ impl GuardedGitCommand<'_, '_> { pub(crate) fn output(self) -> io::Result { self.operation.sources.git.output(self.inner) } + + pub(crate) fn output_in_merge_scratch( + self, + storage: &IsolatedGitStorage, + ) -> io::Result { + let merge = self.operation.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "scratch index command requires an installed merge policy", + ) + })?; + let isolated = merge.common_dir(&self.operation.identity)?; + self.operation + .sources + .git + .output_in_isolated_scratch(self.inner, isolated, storage) + } } impl<'git> GuardedGitConfig<'git> { @@ -478,10 +769,13 @@ impl<'git> GuardedGitConfig<'git> { Ok(Self { sources: ValidatedConfigSources::authorize(git, canonical_root, base_config_args)?, identity: Arc::new(CapabilityIdentity), + apply_policy: None, + apply_policy_gate: ApplyPolicyGateState::NotRun, filters: Vec::new(), merge: None, merge_policy_installed: false, status: None, + status_replacements_disabled: false, }) } @@ -493,10 +787,13 @@ impl<'git> GuardedGitConfig<'git> { Ok(Self { sources: ValidatedConfigSources::authorize_async(git, root, Vec::new()).await?, identity: Arc::new(CapabilityIdentity), + apply_policy: None, + apply_policy_gate: ApplyPolicyGateState::NotRun, filters: Vec::new(), merge: None, merge_policy_installed: false, status: None, + status_replacements_disabled: false, }) } @@ -504,8 +801,187 @@ impl<'git> GuardedGitConfig<'git> { &self.sources.canonical_root } - pub(crate) fn apply_command(&self) -> io::Result> { - self.guarded_command(BoundSubcommand::Apply) + pub(crate) fn operation_identity(&self) -> GuardedOperationIdentity { + GuardedOperationIdentity(Arc::clone(&self.identity)) + } + + pub(crate) fn ensure_operation_identity( + &self, + identity: &GuardedOperationIdentity, + ) -> io::Result<()> { + if Arc::ptr_eq(&self.identity, &identity.0) { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "sealed Git plan belongs to another operation", + )) + } + } + + pub(crate) fn freeze_apply_policy(&mut self) -> io::Result<()> { + if self.status.is_some() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "apply policy cannot coexist with status policy", + )); + } + if self.apply_policy.is_some() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "apply policy is already frozen for this operation", + )); + } + self.apply_policy = Some(ApplyPolicySnapshot::capture(&self.sources)?); + Ok(()) + } + + /// Parse the patch's path inventory without consulting or mutating the + /// index/worktree. The fixed whitespace override keeps path discovery from + /// preempting the later authoritative apply-policy result. + pub(crate) fn run_apply_numstat_path_inventory( + &self, + revert: bool, + patch_path: &Path, + ) -> io::Result { + let mut command = self.apply_command()?; + command.args(["--numstat", "--whitespace=nowarn", "-z"]); + if revert { + command.arg("-R"); + } + command.arg("--").arg(patch_path); + command.output() + } + + /// Run the one fixed, nonmutating policy gate and bind a successful result + /// to this operation. Keeping the proof here prevents a future caller from + /// suppressing a fatal final whitespace check without first executing the + /// authoritative frozen-policy gate. + pub(crate) fn run_apply_policy_gate( + &mut self, + revert: bool, + patch_path: &str, + ) -> io::Result<(String, std::process::Output)> { + if !matches!(self.apply_policy_gate, ApplyPolicyGateState::NotRun) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "apply policy gate may run only once per operation", + )); + } + if self.apply_policy.is_none() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "apply policy must be frozen before its gate runs", + )); + } + // Mark the one-shot gate consumed before any fallible launch step. + self.apply_policy_gate = ApplyPolicyGateState::Failed; + let mut args = vec![ + "apply".to_string(), + "--numstat".to_string(), + "-z".to_string(), + ]; + if revert { + args.push("-R".to_string()); + } + args.push(patch_path.to_string()); + let rendered = self.render_apply_command_for_log(&args)?; + let mut command = self.apply_command()?; + command.args(&args[1..]); + let output = command.output()?; + if output.status.success() { + self.apply_policy_gate = ApplyPolicyGateState::Succeeded { + revert, + patch_path: patch_path.to_string(), + }; + } + Ok((rendered, output)) + } + + /// Run the public preflight shape without exposing a generic `git apply` + /// command on which a caller could append mutating options. + pub(crate) fn run_apply_preflight_check( + &self, + revert: bool, + patch_path: &str, + ) -> io::Result<(String, std::process::Output)> { + let mut args = vec!["apply".to_string(), "--check".to_string()]; + if revert { + args.push("-R".to_string()); + } + args.push(patch_path.to_string()); + let rendered = self.render_apply_command_for_log(&args)?; + let mut command = self.apply_command()?; + command.args(&args[1..]); + Ok((rendered, command.output()?)) + } + + /// Check whether the final operation can use the direct strategy. This is + /// deliberately fixed to `--check`; callers receive only the output, never + /// the underlying apply command. + pub(crate) fn run_apply_strategy_check( + &self, + revert: bool, + patch_path: &str, + ) -> io::Result { + let mut command = self.apply_command()?; + command.args(["--check", "--whitespace=nowarn"]); + if !revert { + command.arg("--index"); + } + if revert { + command.arg("-R"); + } + command.arg(patch_path); + command.output() + } + + /// Return the typed frozen mode only after the authoritative gate has + /// succeeded for this operation. + pub(crate) fn final_apply_whitespace_mode( + &self, + revert: bool, + patch_path: &str, + ) -> io::Result { + match &self.apply_policy_gate { + ApplyPolicyGateState::Succeeded { + revert: gated_revert, + patch_path: gated_patch, + } if *gated_revert == revert && gated_patch == patch_path => {} + ApplyPolicyGateState::Succeeded { .. } => { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "final apply does not match its successful policy gate", + )); + } + ApplyPolicyGateState::NotRun | ApplyPolicyGateState::Failed => { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "final apply whitespace policy requires a successful policy gate", + )); + } + } + self.apply_policy + .as_ref() + .map(|policy| policy.whitespace_mode) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "final apply whitespace policy is not frozen", + ) + }) + } + + fn apply_command(&self) -> io::Result> { + let mut command = self.command_with_attached_overlays()?; + if let Some(policy) = &self.apply_policy { + policy.append_to(&mut command); + } + BoundSubcommand::Apply.append_to(&mut command); + Ok(GuardedGitCommand { + operation: self, + inner: command, + }) } pub(crate) fn rev_parse_command(&self) -> io::Result> { @@ -583,9 +1059,6 @@ impl<'git> GuardedGitConfig<'git> { if let Some(neutralizer) = apply.and_then(FilterPolicySnapshot::neutralizer) { neutralizer.append_rendered_args(&self.identity, &mut args)?; } - if let Some(merge) = &self.merge { - merge.append_rendered_args(&self.identity, &mut args)?; - } if let Some(neutralizer) = git_add.and_then(FilterPolicySnapshot::neutralizer) { neutralizer.append_rendered_args(&self.identity, &mut args)?; } @@ -612,10 +1085,15 @@ impl<'git> GuardedGitConfig<'git> { } fn ensure_status_exclusive_state(&self) -> io::Result<()> { - if !self.filters.is_empty() || self.merge.is_some() || self.merge_policy_installed { + if self.apply_policy.is_some() + || !matches!(self.apply_policy_gate, ApplyPolicyGateState::NotRun) + || !self.filters.is_empty() + || self.merge.is_some() + || self.merge_policy_installed + { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - "status policy cannot coexist with mutation filter or merge policy", + "status policy cannot coexist with apply, mutation filter, or merge policy", )); } Ok(()) @@ -737,21 +1215,23 @@ impl<'git> GuardedGitConfig<'git> { if !output.status.success() { return Err(command_failure("tracked-path probe", &output)); } - let paths = parse_nul_paths(&output.stdout)?; + let mut paths = parse_nul_paths(&output.stdout)?; if paths.len() > MAX_STATUS_TRACKED_PATHS { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( - "tracked path count {} exceeds the status limit {MAX_STATUS_TRACKED_PATHS}", + "tracked path record count {} exceeds the status limit {MAX_STATUS_TRACKED_PATHS}", paths.len() ), )); } + paths.sort(); + paths.dedup(); Ok(paths) } - /// Install the mutually exclusive Status filter policy. The common - /// zero-driver path occupies the slot without scanning tracked paths. + /// Install the mutually exclusive Status filter policy and publish one + /// operation-owned config, attribute, HEAD, and untracked-presence view. pub(crate) async fn install_status_policy_async(&mut self) -> io::Result<()> { self.ensure_status_exclusive_state()?; if self.status.is_some() { @@ -766,61 +1246,191 @@ impl<'git> GuardedGitConfig<'git> { .sources .read_effective_async(crate::safe_git::EXECUTABLE_FILTER_CONFIG_PATTERN, "filter") .await?; - let executable_drivers = executable_filter_drivers(&entries)?; + let executable_drivers = status_policy_filter_drivers(&entries)?; validate_executable_driver_count(&executable_drivers)?; - if executable_drivers.is_empty() { - self.status = Some(StatusFilterPolicySnapshot { - neutralizer: None, - fsmonitor: None, - }); - return Ok(()); - } - let paths = self.read_status_tracked_paths_async().await?; - let neutralizer = self - .build_filter_override_async(&executable_drivers) + let neutralizer = if executable_drivers.is_empty() { + None + } else { + Some( + self.build_filter_override_async(&executable_drivers) + .await?, + ) + }; + self.ensure_no_effective_replacement_refs_async(neutralizer.as_ref()) .await?; - let attributes = self - .read_status_filter_attributes_async(&paths, &executable_drivers, &neutralizer) - .await?; - let mut required_cache = BTreeMap::new(); - for (path, driver) in attributes { - if !executable_drivers.contains(&driver) { - continue; - } - let required = required_cache.get(&driver).copied(); - let mut policy = classify_selected_filter(&entries, &driver, required); - if policy == SelectedFilterPolicy::NeedsRequiredValue { - let required = self - .sources - .read_bool_async(&format!("filter.{driver}.required")) - .await - .map_err(|error| { - io::Error::new( - io::ErrorKind::Unsupported, - format!( - "refusing selected Git filter {driver:?} with malformed required value: {error}" - ), - ) - })? - .unwrap_or(false); - required_cache.insert(driver.clone(), required); - policy = classify_selected_filter(&entries, &driver, Some(required)); - } - if policy == SelectedFilterPolicy::Refused { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - SelectedStatusFilterRefusal { driver, path }, - )); + if let Some(neutralizer) = &neutralizer { + let attributes = self + .read_status_filter_attributes_async(&paths, &executable_drivers, neutralizer) + .await?; + let mut required_cache = BTreeMap::new(); + for (path, driver) in attributes { + if !executable_drivers.contains(&driver) { + continue; + } + let required = required_cache.get(&driver).copied(); + let mut policy = classify_selected_filter(&entries, &driver, required); + if policy == SelectedFilterPolicy::NeedsRequiredValue { + let required = self + .sources + .read_bool_async(&format!("filter.{driver}.required")) + .await + .map_err(|error| { + io::Error::new( + io::ErrorKind::Unsupported, + format!( + "refusing selected Git filter {driver:?} with malformed required value: {error}" + ), + ) + })? + .unwrap_or(false); + required_cache.insert(driver.clone(), required); + policy = classify_selected_filter(&entries, &driver, Some(required)); + } + if policy == SelectedFilterPolicy::Refused { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + SelectedStatusFilterRefusal { driver, path }, + )); + } } } - self.status = Some(StatusFilterPolicySnapshot { - neutralizer: Some(neutralizer), + let has_untracked = self + .read_status_untracked_presence_async(neutralizer.as_ref()) + .await?; + let head_oid = self + .read_status_head_oid_async(neutralizer.as_ref()) + .await?; + let context = self + .build_status_read_context_async( + head_oid.as_deref(), + has_untracked, + ) + .await?; + self.status = Some(StatusPolicySnapshot { + context, fsmonitor: None, }); Ok(()) } + async fn read_status_untracked_presence_async( + &self, + neutralizer: Option<&SealedFilterConfigOverride>, + ) -> io::Result { + let mut command = + self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?; + command.disable_optional_locks().args([ + "ls-files", + "-z", + "--others", + "--exclude-standard", + "--directory", + "--no-empty-directory", + "--", + ]); + let output = command.output().await?; + if !output.status.success() { + return Err(command_failure("status untracked-presence inventory", &output)); + } + let paths = parse_nul_paths(&output.stdout)?; + if paths.len() > MAX_STATUS_TRACKED_PATHS { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "status untracked-presence inventory exceeds its path limit", + )); + } + Ok(!paths.is_empty()) + } + + async fn read_status_head_oid_async( + &self, + neutralizer: Option<&SealedFilterConfigOverride>, + ) -> io::Result> { + let mut command = + self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?; + command + .disable_optional_locks() + .args(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]); + let output = command.output().await?; + if output.status.success() { + return parse_status_head_oid(&output.stdout).map(Some); + } + if output.status.code() != Some(1) + || !output.stdout.is_empty() + || !output.stderr.is_empty() + { + return Err(command_failure("status HEAD snapshot", &output)); + } + + let mut symbolic = + self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?; + symbolic + .disable_optional_locks() + .args(["symbolic-ref", "--quiet", "HEAD"]); + let symbolic = symbolic.output().await?; + if !symbolic.status.success() { + return Err(command_failure("status symbolic HEAD snapshot", &symbolic)); + } + let target = parse_status_symbolic_ref(&symbolic.stdout)?; + + let mut verify = self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?; + verify + .disable_optional_locks() + .args(["show-ref", "--verify", "--quiet", "--"]) + .arg(&target); + let verify = verify.output().await?; + if verify.status.code() == Some(1) + && verify.stdout.is_empty() + && verify.stderr.is_empty() + { + return Ok(None); + } + if verify.status.success() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Status HEAD target exists but does not resolve to a commit", + )); + } + Err(command_failure("status unborn HEAD verification", &verify)) + } + + async fn ensure_no_effective_replacement_refs_async( + &mut self, + neutralizer: Option<&SealedFilterConfigOverride>, + ) -> io::Result<()> { + if self.sources.git.replacement_refs_are_disabled() { + self.status_replacements_disabled = true; + return Ok(()); + } + if self.sources.git.replacement_ref_base_is_custom() { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "frozen Status is unavailable with a custom Git replacement-ref namespace", + )); + } + let mut command = + self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?; + command.disable_optional_locks().args([ + "for-each-ref", + "--format=%(refname)", + "refs/replace/", + ]); + let output = command.output().await?; + if !output.status.success() { + return Err(command_failure("status replacement-ref inventory", &output)); + } + if output.stdout.is_empty() { + self.status_replacements_disabled = true; + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "frozen Status is unavailable with active Git replacement refs", + )) + } + } + pub(crate) async fn detect_status_fsmonitor_async(&mut self) -> FsmonitorOverride { if self.status.is_none() || self.ensure_status_exclusive_state().is_err() { return FsmonitorOverride::Disabled; @@ -828,14 +1438,13 @@ impl<'git> GuardedGitConfig<'git> { if let Some(fsmonitor) = self.status.as_ref().and_then(|status| status.fsmonitor) { return fsmonitor; } - let fsmonitor = { - let mut runner = StatusFsmonitorProbeRunner { config: self }; - crate::detect_fsmonitor_override(&mut runner).await - }; if let Some(status) = &mut self.status { - status.fsmonitor = Some(fsmonitor); + // The synthetic owned Git directory has no stable fsmonitor daemon + // identity or socket lifecycle. Disabling it is a performance-only + // downgrade and avoids launching a daemon tied to temporary state. + status.fsmonitor = Some(FsmonitorOverride::Disabled); } - fsmonitor + FsmonitorOverride::Disabled } pub(crate) async fn status_output_async(&self) -> io::Result { @@ -851,13 +1460,51 @@ impl<'git> GuardedGitConfig<'git> { "status output requires a retained fsmonitor decision", ) })?; - let mut command = self.pending_status_command(fsmonitor, status.neutralizer.as_ref())?; + let mut command = self.pending_frozen_status_command(fsmonitor)?; command.disable_optional_locks().args([ "status", "--porcelain", "--ignore-submodules=dirty", + "--untracked-files=no", ]); - command.output().await + command.output_in_status_context(&status.context).await + } + + pub(crate) fn status_has_untracked_snapshot(&self) -> io::Result { + let status = self.status.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "untracked status requires an installed status filter policy", + ) + })?; + status.context.has_untracked(&self.identity) + } + + fn pending_frozen_status_command<'operation>( + &'operation self, + fsmonitor: FsmonitorOverride, + ) -> io::Result> { + self.ensure_status_exclusive_state()?; + if self.status.is_none() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "frozen Status command requires an installed context", + )); + } + let mut command = self + .sources + .git + .async_command_for_cwd(&self.sources.canonical_root)?; + command.args([ + "-c", + &format!("core.hooksPath={DISABLED_HOOKS_PATH}"), + "-c", + fsmonitor.git_config_arg(), + ]); + Ok(GuardedAsyncGitCommand { + operation: self, + inner: command, + }) } fn pending_status_command<'operation>( @@ -870,6 +1517,9 @@ impl<'git> GuardedGitConfig<'git> { .git .async_command_for_cwd(&self.sources.canonical_root)?; command.args(self.status_config_args(fsmonitor, neutralizer)?); + if self.status_replacements_disabled { + command.env("GIT_NO_REPLACE_OBJECTS", "1"); + } Ok(GuardedAsyncGitCommand { operation: self, inner: command, @@ -1154,13 +1804,13 @@ impl<'git> GuardedGitConfig<'git> { let [apply] = self.filters.as_slice() else { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - "composed exact staging requires exactly one apply filter snapshot", + "reverse exact staging requires exactly one apply filter snapshot", )); }; if apply.role() != FilterPolicyRole::Apply { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - "composed exact staging requires an apply filter snapshot", + "reverse exact staging requires an apply filter snapshot", )); } if let Some(path) = paths @@ -1193,11 +1843,151 @@ impl<'git> GuardedGitConfig<'git> { Ok(apply.checked_paths()) } + pub(crate) fn run_direct_apply( + &self, + revert: bool, + patch_path: &str, + ) -> io::Result { + let mode = self.final_apply_whitespace_mode(revert, patch_path)?; + let mut command = self.apply_command()?; + command.arg("--index"); + if mode.is_fatal() { + command.arg("--whitespace=nowarn"); + } + if revert { + command.arg("-R"); + } + command.arg(patch_path); + command.output() + } + + pub(crate) fn render_direct_apply_for_log( + &self, + revert: bool, + patch_path: &str, + ) -> io::Result { + let mode = self.final_apply_whitespace_mode(revert, patch_path)?; + let mut args = vec!["apply".to_string(), "--index".to_string()]; + if mode.is_fatal() { + args.push("--whitespace=nowarn".to_string()); + } + if revert { + args.push("-R".to_string()); + } + args.push(patch_path.to_string()); + self.render_apply_command_for_log(&args) + } + + pub(crate) fn run_three_way_apply( + &mut self, + revert: bool, + patch_path: &str, + ) -> io::Result { + let (apply, _git_add) = self.ordered_filter_snapshots()?; + if apply.is_none() || !self.merge_policy_installed { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "three-way apply policy is not installed", + )); + } + self.consume_three_way_merge_policy_proof(revert, patch_path)?; + let merge = self.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + let isolated = merge.common_dir(&self.identity)?; + let mut command = self + .sources + .git + .command_for_cwd(&self.sources.canonical_root)?; + append_safe_scalar_overrides(&mut command); + self.apply_policy + .as_ref() + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "three-way apply policy scalars are not frozen", + ) + })? + .append_to(&mut command); + BoundSubcommand::Apply.append_to(&mut command); + command.arg("--3way"); + if self + .final_apply_whitespace_mode(revert, patch_path)? + .is_fatal() + { + command.arg("--whitespace=nowarn"); + } + if revert { + command.arg("-R"); + } + command.arg(patch_path); + self.sources + .git + .output_in_isolated_common_dir(command, isolated) + } + + pub(crate) fn render_three_way_apply_for_log( + &self, + revert: bool, + patch_path: &str, + ) -> io::Result { + // Rendering may precede the final post-staging index revalidation, + // but it must never render a selected-custom operation with no proof. + self.ensure_three_way_merge_policy_proof_installed()?; + let merge = self.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + let _ = merge.common_dir(&self.identity)?; + let mut parts = vec![ + "env".to_string(), + "GIT_COMMON_DIR=".to_string(), + "git".to_string(), + ]; + parts.extend(safe_scalar_override_args()); + self.apply_policy + .as_ref() + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "three-way apply policy scalars are not frozen", + ) + })? + .append_rendered(&mut parts); + parts.push("apply".to_string()); + parts.push("--3way".to_string()); + if self + .final_apply_whitespace_mode(revert, patch_path)? + .is_fatal() + { + parts.push("--whitespace=nowarn".to_string()); + } + if revert { + parts.push("-R".to_string()); + } + parts.push(patch_path.to_string()); + Ok(format!( + "(cd {} && {})", + quote_shell(&self.sources.canonical_root.display().to_string()), + parts + .into_iter() + .map(|part| quote_shell(&part)) + .collect::>() + .join(" ") + )) + } + #[cfg(test)] - pub(crate) fn merge_include_arg(&self) -> Option<&str> { + pub(crate) fn merge_common_config_path(&self) -> Option { self.merge .as_ref() - .map(SealedMergeConfigOverride::include_arg) + .and_then(|merge| merge.common_dir(&self.identity).ok()) + .map(crate::git_command::IsolatedGitCommonDir::config_path) } pub(crate) fn authorize_git_add_filter_paths(&mut self, paths: &[String]) -> io::Result<()> { @@ -1210,6 +2000,14 @@ impl<'git> GuardedGitConfig<'git> { match self.filters.as_slice() { [] => {} [apply] if apply.role() == FilterPolicyRole::Apply => {} + [apply, git_add] + if apply.role() == FilterPolicyRole::Apply + && git_add.role() == FilterPolicyRole::GitAdd + && git_add.checked_paths().into_iter().collect::>() + == paths.iter().cloned().collect::>() => + { + return Ok(()); + } _ => { return Err(io::Error::new( io::ErrorKind::PermissionDenied, @@ -1222,6 +2020,7 @@ impl<'git> GuardedGitConfig<'git> { Ok(()) } + #[cfg(test)] pub(crate) fn render_command_for_log(&self, args: &[String]) -> io::Result { let mut parts = vec!["git".to_string()]; parts.extend(self.mutation_config_args()?); @@ -1236,51 +2035,31 @@ impl<'git> GuardedGitConfig<'git> { .join(" ") )) } -} -struct StatusFsmonitorProbeRunner<'a, 'git> { - config: &'a GuardedGitConfig<'git>, -} - -impl FsmonitorProbeRunner for StatusFsmonitorProbeRunner<'_, '_> { - async fn run_probe(&mut self, args: &[&str]) -> Option> { - let allowed = matches!( - args, - ["config", "--null", "--get", "core.fsmonitor"] - | [ - "config", - "--null", - "--type=bool", - "--fixed-value", - "--get", - "core.fsmonitor", - _, - ] - | ["version", "--build-options"] - ); - if !allowed { - return None; + pub(crate) fn render_apply_command_for_log(&self, args: &[String]) -> io::Result { + let mut parts = vec!["git".to_string()]; + parts.extend(self.sources.base_config_args.iter().cloned()); + parts.extend(safe_scalar_override_args()); + let (apply, git_add) = self.ordered_filter_snapshots()?; + if let Some(neutralizer) = apply.and_then(FilterPolicySnapshot::neutralizer) { + neutralizer.append_rendered_args(&self.identity, &mut parts)?; } - let mut command = self - .config - .sources - .git - .async_command_for_cwd(&self.config.sources.canonical_root) - .ok()?; - command - .env("GIT_OPTIONAL_LOCKS", "0") - .args(&self.config.sources.base_config_args) - .args(args); - match self - .config - .sources - .git - .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) - .await - { - Ok(output) if output.status.success() => Some(output.stdout), - Ok(_) | Err(_) => None, + if let Some(neutralizer) = git_add.and_then(FilterPolicySnapshot::neutralizer) { + neutralizer.append_rendered_args(&self.identity, &mut parts)?; } + if let Some(policy) = &self.apply_policy { + policy.append_rendered(&mut parts); + } + parts.extend(args.iter().cloned()); + Ok(format!( + "(cd {} && {})", + quote_shell(&self.sources.canonical_root.display().to_string()), + parts + .into_iter() + .map(|part| quote_shell(&part)) + .collect::>() + .join(" ") + )) } } @@ -1330,6 +2109,46 @@ fn safe_scalar_override_args() -> [String; 4] { ] } +fn parse_status_head_oid(output: &[u8]) -> io::Result { + let line = output.strip_suffix(b"\n").ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "unterminated Status HEAD output") + })?; + let line = line.strip_suffix(b"\r").unwrap_or(line); + if !matches!(line.len(), 40 | 64) || !line.iter().all(u8::is_ascii_hexdigit) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Status HEAD did not resolve to one full object ID", + )); + } + Ok(String::from_utf8(line.to_ascii_lowercase()).expect("ASCII object ID")) +} + +fn parse_status_symbolic_ref(output: &[u8]) -> io::Result { + let line = output.strip_suffix(b"\n").ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "unterminated Status symbolic HEAD output", + ) + })?; + let line = line.strip_suffix(b"\r").unwrap_or(line); + if !line.starts_with(b"refs/heads/") + || line.contains(&0) + || line + .iter() + .any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace()) + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Status HEAD did not resolve to a safe symbolic ref", + )); + } + git_path_argument(line) +} + +fn append_safe_scalar_overrides(command: &mut GitCommand) { + command.args(safe_scalar_override_args()); +} + fn quote_shell(value: &str) -> String { let simple = value .chars() diff --git a/codex-rs/git-utils/src/guarded_config/merge_overlay.rs b/codex-rs/git-utils/src/guarded_config/merge_overlay.rs index ac9f6e5309..4532facb47 100644 --- a/codex-rs/git-utils/src/guarded_config/merge_overlay.rs +++ b/codex-rs/git-utils/src/guarded_config/merge_overlay.rs @@ -1,5 +1,7 @@ use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::io; +use std::io::Write; use std::path::Path; use std::process::Stdio; use std::sync::Arc; @@ -7,9 +9,17 @@ use std::sync::Arc; use super::BoundSubcommand; use super::CapabilityIdentity; use super::GuardedGitConfig; +use crate::git_command::IsolatedGitCommonDir; +use crate::git_command::IsolatedGitStorage; use crate::git_config::GitConfigEntry; - -const MERGE_CONFIG_PATTERN: &str = r"^(merge\.default|merge\..*\.driver)$"; +use crate::git_config::GitConfigValue; +use crate::git_config::MergeConfigRecord; +use crate::git_config::parse_git_boolean_symmetric_i32; +const REPOSITORY_FORMAT_CONFIG_PATTERN: &str = + r"^(core\.repositoryformatversion|extensions\.(objectformat|compatobjectformat))$"; +const SANITIZED_CONFIG_PATTERN: &str = r"^(core\.(filemode|symlinks|ignorecase|precomposeunicode|protecthfs|protectntfs|trustctime|checkstat|longpaths|fscache|splitindex|sparsecheckout|sparsecheckoutcone|autocrlf|eol|safecrlf|checkroundtripencoding|bigfilethreshold)|index\.(sparse|version)|merge\.conflictstyle)$"; +// Git ignores an attribute line whose content length is at least this value. +const GIT_ATTRIBUTE_LINE_LENGTH_LIMIT: usize = 2048; /// A complete, fresh merge-config read bound to one authorized operation. /// @@ -17,12 +27,236 @@ const MERGE_CONFIG_PATTERN: &str = r"^(merge\.default|merge\..*\.driver)$"; /// and then ask the capability to treat its neutralizer as complete. struct MergeConfigSnapshot { owner: Arc, - entries: BTreeMap, + default: Option, + namespaces: BTreeSet, + conditional_invalid: bool, +} + +/// The helper-free merge behavior projected into the app-owned attribute +/// layer. A configured selected custom driver is retained as a distinct state +/// and quarantined as Git's built-in binary driver in both probe and final +/// children. +#[derive(Clone, Debug, Eq, PartialEq)] +enum MergeSelection { + Builtin(BuiltinMergeDriver), + QuarantinedCustom { name: String }, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum BuiltinMergeDriver { + Text, + Binary, + Union, +} + +impl BuiltinMergeDriver { + fn from_effective_attribute(attribute: &str, sanitized_default: &str) -> Self { + let selected = if attribute == "unspecified" { + sanitized_default + } else { + attribute + }; + match selected { + "unset" | "binary" => Self::Binary, + "union" => Self::Union, + // A set attribute, the explicit text driver, and an unconfigured + // name with no user-driver namespace fall back to Git's built-in + // text merge semantics. + _ => Self::Text, + } + } + + fn attribute_value(self) -> &'static str { + match self { + Self::Text => "text", + Self::Binary => "binary", + Self::Union => "union", + } + } +} + +/// Per-path apply semantics frozen at the strict `check-attr` probe. +/// +/// Git's public `check-attr` format conflates special states with the literal +/// values `set`, `unset`, and `unspecified`. This snapshot intentionally uses +/// Git's conventional rendering for those uncommon literal spellings. Every +/// other safely representable value is retained byte-for-byte. +struct MergeAttributeSnapshot { + owner: Arc, + paths: BTreeMap, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct FrozenPathApplyAttributes { + merge: MergeSelection, + safe: SafeApplyAttributes, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct ParsedPathApplyAttributes { + merge: String, + safe: SafeApplyAttributes, +} + +/// A helper-free attribute state that can be projected into an app-owned +/// `info/attributes` file without being reinterpreted as config or a command. +#[derive(Clone, Debug, Eq, PartialEq)] +enum ProjectedAttribute { + Set, + Unset, + Unspecified, + Value(Vec), +} + +impl ProjectedAttribute { + fn from_check_attr(value: &[u8]) -> io::Result { + // `git check-attr` deliberately renders both special states and the + // literal values `=set`, `=unset`, and `=unspecified` with the same + // sentinel text. Match Git's documented convention for this bounded + // PR while retaining all other raw values. + match value { + b"set" => Ok(Self::Set), + b"unset" => Ok(Self::Unset), + b"unspecified" => Ok(Self::Unspecified), + value => { + validate_projected_attribute_value(value)?; + Ok(Self::Value(value.to_vec())) + } + } + } + + fn projected_token(&self, name: &str) -> Vec { + match self { + Self::Set => name.as_bytes().to_vec(), + Self::Unset => format!("-{name}").into_bytes(), + Self::Unspecified => format!("!{name}").into_bytes(), + Self::Value(value) => { + let mut token = Vec::with_capacity(name.len() + 1 + value.len()); + token.extend_from_slice(name.as_bytes()); + token.push(b'='); + token.extend_from_slice(value); + token + } + } + } +} + +/// Safe in-process attributes consumed by Git 2.54's apply, low-level merge, +/// and checkout conversion paths. `filter` is captured only to make the fixed +/// query complete; projection always replaces it with `!filter`. +#[derive(Clone, Debug, Eq, PartialEq)] +struct SafeApplyAttributes { + whitespace: ProjectedAttribute, + conflict_marker_size: ProjectedAttribute, + text: ProjectedAttribute, + crlf: ProjectedAttribute, + eol: ProjectedAttribute, + ident: ProjectedAttribute, + working_tree_encoding: ProjectedAttribute, + _filter: ProjectedAttribute, +} + +impl MergeAttributeSnapshot { + fn from_effective( + owner: &Arc, + config: &MergeConfigSnapshot, + attributes: BTreeMap, + selected_custom: &BTreeMap, + ) -> io::Result { + config.ensure_owner(owner)?; + let sanitized_default = config.sanitized_default_driver(); + let paths = attributes + .into_iter() + .map(|(path, attributes)| { + let merge = selected_custom + .get(&path) + .map(|name| MergeSelection::QuarantinedCustom { name: name.clone() }) + .unwrap_or_else(|| { + MergeSelection::Builtin(BuiltinMergeDriver::from_effective_attribute( + &attributes.merge, + sanitized_default, + )) + }); + ( + path, + FrozenPathApplyAttributes { + merge, + safe: attributes.safe, + }, + ) + }) + .collect(); + Ok(Self { + owner: Arc::clone(owner), + paths, + }) + } + + fn ensure_owner(&self, owner: &Arc) -> io::Result<()> { + if !Arc::ptr_eq(&self.owner, owner) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "merge attribute snapshot belongs to another operation", + )); + } + Ok(()) + } } impl MergeConfigSnapshot { - fn entries(&self) -> &BTreeMap { - &self.entries + fn from_records( + owner: &Arc, + records: Vec, + ) -> io::Result { + let mut default = None; + let mut namespaces = BTreeSet::new(); + let mut conditional_invalid = false; + for record in records { + if record.key == "merge.default" { + match record.value { + GitConfigValue::Implicit => conditional_invalid = true, + GitConfigValue::Explicit(value) => default = Some(value), + } + continue; + } + let Some(namespace) = crate::merge_driver::merge_driver_subsection(&record.key)? else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "merge config record unexpectedly has no driver subsection", + )); + }; + namespaces.insert(namespace.to_string()); + let final_key = record + .key + .rsplit_once('.') + .map(|(_, key)| key) + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "malformed merge config record") + })?; + if matches!(&record.value, GitConfigValue::Implicit) + && matches!(final_key, "driver" | "name" | "recursive") + { + conditional_invalid = true; + } + } + Ok(Self { + owner: Arc::clone(owner), + default, + namespaces, + conditional_invalid, + }) + } + + fn namespaces(&self) -> &BTreeSet { + &self.namespaces + } + + fn default_driver(&self) -> Option<&str> { + self.default.as_deref() + } + + fn conditional_invalid(&self) -> bool { + self.conditional_invalid } fn ensure_owner(&self, owner: &Arc) -> io::Result<()> { @@ -35,50 +269,68 @@ impl MergeConfigSnapshot { Ok(()) } - fn nonempty_driver_keys(&self) -> io::Result> { - let mut keys = Vec::new(); - for entry in self.entries.values() { - if entry.key == "merge.default" { - continue; - } - let _driver = entry - .key - .strip_prefix("merge.") - .and_then(|key| key.strip_suffix(".driver")) - .ok_or_else(|| { - io::Error::new( - io::ErrorKind::InvalidData, - "malformed effective Git merge-driver key", - ) - })?; - if !entry.value.is_empty() { - keys.push(entry.key.as_str()); - } + fn sanitized_default_driver(&self) -> &str { + match self.default.as_deref() { + Some("binary") => "binary", + Some("union") => "union", + _ => "text", } - Ok(keys) } } -/// A sealed merge-driver-only include bound to one operation. +/// A sealed, helper-free common repository view bound to one operation. /// -/// Construction accepts only a complete `MergeConfigSnapshot`, and the type -/// exposes neither raw keys nor its include argument outside this module. +/// The real Git directory, index, worktree, and object store remain selected; +/// only common config and attributes are replaced for the final three-way +/// child. Construction accepts a complete merge snapshot so a caller cannot +/// attach an unreviewed or partial view. pub(super) struct SealedMergeConfigOverride { owner: Arc, - include_arg: String, - _config_dir: tempfile::TempDir, + common_dir: IsolatedGitCommonDir, + effective_paths: Vec, + selected_custom: BTreeMap, + custom_destinations: BTreeSet, + conditional_invalid: bool, + object_format: IndexObjectFormat, + proof: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct IndexStageEntry { + mode: u32, + object_id: IndexObjectId, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +enum IndexObjectId { + Sha1([u8; 20]), + Sha256([u8; 32]), +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum IndexObjectFormat { + Sha1, + Sha256, +} + +type IndexStageSnapshot = BTreeMap>; + +struct ThreeWayMergePolicyProof { + owner: Arc, + revert: bool, + patch_path: String, + custom_destinations: BTreeSet, + conditional_invalid: bool, + prospective_index: IndexStageSnapshot, } impl SealedMergeConfigOverride { - pub(super) fn append_rendered_args( + pub(super) fn common_dir( &self, owner: &Arc, - args: &mut Vec, - ) -> io::Result<()> { + ) -> io::Result<&IsolatedGitCommonDir> { self.ensure_owner(owner)?; - args.push("-c".to_string()); - args.push(self.include_arg.clone()); - Ok(()) + Ok(&self.common_dir) } fn ensure_owner(&self, owner: &Arc) -> io::Result<()> { @@ -91,9 +343,8 @@ impl SealedMergeConfigOverride { Ok(()) } - #[cfg(test)] - pub(super) fn include_arg(&self) -> &str { - &self.include_arg + fn proof_required(&self) -> bool { + self.conditional_invalid || !self.custom_destinations.is_empty() } } @@ -101,7 +352,10 @@ impl<'git> GuardedGitConfig<'git> { /// Install the complete fallback merge policy in one non-bypassable step. /// This is the only crate-visible merge-overlay API: callers cannot mark /// the policy complete without the fixed fresh config and attribute reads. - pub(crate) fn install_three_way_merge_policy(&mut self) -> io::Result<()> { + pub(crate) fn install_three_way_merge_policy( + &mut self, + primary_records: &[String], + ) -> io::Result<()> { let paths = self.apply_filter_paths()?; let snapshot = self.read_merge_config_snapshot()?; let input = merge_attribute_input(&paths)?; @@ -113,19 +367,41 @@ impl<'git> GuardedGitConfig<'git> { String::from_utf8_lossy(&output.stderr).trim() ))); } - let attributes = crate::merge_driver::parse_merge_attributes(&output.stdout, &paths)?; - if let Some((driver, path)) = - crate::merge_driver::untrusted_driver_selection(snapshot.entries(), &attributes)? - { - return Err(io::Error::new( - io::ErrorKind::Unsupported, - format!( - "refusing to run an internal Git three-way apply with merge driver {driver:?} selected for {path:?}" - ), - )); + let parsed_attributes = parse_three_way_attributes(&output.stdout, &paths)?; + let merge_attributes = parsed_attributes + .iter() + .map(|(path, attributes)| (path.clone(), attributes.merge.clone())) + .collect::>(); + let selected_custom = crate::merge_driver::untrusted_driver_selections( + snapshot.namespaces(), + snapshot.default_driver(), + &merge_attributes, + ); + let mut custom_destinations = BTreeSet::new(); + for path in primary_records { + if selected_custom.contains_key(path) && !custom_destinations.insert(path.clone()) { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + format!( + "refusing to classify repeated patch records for selected custom merge path {path:?}" + ), + )); + } } - let neutralizer = self.build_merge_override(&snapshot)?; - self.attach_merge_override(neutralizer) + let attributes = MergeAttributeSnapshot::from_effective( + &self.identity, + &snapshot, + parsed_attributes, + &selected_custom, + )?; + let isolated = self.build_merge_override( + &snapshot, + &attributes, + paths, + selected_custom, + custom_destinations, + )?; + self.attach_merge_override(isolated) } /// Read merge-driver policy from the frozen, authorized base invocation. @@ -141,15 +417,12 @@ impl<'git> GuardedGitConfig<'git> { } #[cfg(test)] MERGE_CONFIG_READ_COUNT.with(|count| count.set(count.get() + 1)); - Ok(MergeConfigSnapshot { - owner: Arc::clone(&self.identity), - entries: self.sources.read_effective(MERGE_CONFIG_PATTERN, "merge")?, - }) + MergeConfigSnapshot::from_records(&self.identity, self.sources.read_merge_config()?) } - /// Run the one fixed fresh merge-attribute query while the merge + /// Run the one fixed fresh apply-attribute query while the merge /// neutralizer is still absent. Existing apply-filter policy remains - /// attached, and callers cannot change the framing or attribute name. + /// attached, and callers cannot change the framing or attribute names. fn query_merge_attributes( &self, snapshot: &MergeConfigSnapshot, @@ -169,7 +442,19 @@ impl<'git> GuardedGitConfig<'git> { BoundSubcommand::CheckAttr.append_to(&mut command); command .env("GIT_OPTIONAL_LOCKS", "0") - .args(["--stdin", "-z", "merge"]) + .args([ + "--stdin", + "-z", + "merge", + "whitespace", + "conflict-marker-size", + "text", + "crlf", + "eol", + "ident", + "filter", + "working-tree-encoding", + ]) .stdin(Stdio::from(input)); self.sources.git.output(command) } @@ -177,48 +462,78 @@ impl<'git> GuardedGitConfig<'git> { fn build_merge_override( &self, snapshot: &MergeConfigSnapshot, - ) -> io::Result> { + attributes: &MergeAttributeSnapshot, + effective_paths: Vec, + selected_custom: BTreeMap, + custom_destinations: BTreeSet, + ) -> io::Result { snapshot.ensure_owner(&self.identity)?; + attributes.ensure_owner(&self.identity)?; if self.merge_policy_installed { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - "a merge neutralizer is already attached", + "an isolated three-way config is already attached", )); } - let driver_keys = snapshot.nonempty_driver_keys()?; - if driver_keys.is_empty() { - return Ok(None); - } - let config_dir = tempfile::tempdir()?; - let config_path = config_dir - .path() - .join("merge-driver-neutralization.gitconfig"); - self.ensure_owned_config_path(&config_path, "owned Git merge-driver neutralization")?; - std::fs::write(&config_path, [])?; - for key in driver_keys { - self.write_merge_override_value(&config_path, key)?; + let entries = self + .sources + .read_effective(SANITIZED_CONFIG_PATTERN, "three-way allowlist")?; + let shared_repository = self + .sources + .read_shared_repository()? + .as_ref() + .map(normalize_shared_repository) + .transpose()?; + let repository_format = self + .sources + .read_direct_common_config(REPOSITORY_FORMAT_CONFIG_PATTERN, "repository format")?; + let object_format = index_object_format(&repository_format)?; + let common_dir = self.sources.git.create_isolated_common_dir()?; + let config_path = common_dir.config_path(); + self.ensure_owned_config_path(&config_path, "owned isolated Git common config")?; + for entry in entries.values() { + self.write_sanitized_config_value(&config_path, &entry.key, &entry.value)?; } - let config_path = config_path.to_str().ok_or_else(|| { - io::Error::new(io::ErrorKind::InvalidData, "non-UTF-8 merge guard path") - })?; + if let Some(shared_repository) = shared_repository { + self.write_sanitized_config_value( + &config_path, + "core.sharedrepository", + &shared_repository, + )?; + } + for entry in repository_format.values() { + self.write_sanitized_config_value(&config_path, &entry.key, &entry.value)?; + } + self.write_sanitized_config_value(&config_path, "core.bare", "false")?; + self.write_sanitized_config_value( + &config_path, + "merge.default", + snapshot.sanitized_default_driver(), + )?; + if snapshot.conditional_invalid() { + append_conditional_invalid_merge_config(&config_path)?; + } + self.write_projected_merge_attributes(&common_dir, attributes)?; #[cfg(test)] MERGE_OVERLAY_COUNT.with(|count| count.set(count.get() + 1)); - Ok(Some(SealedMergeConfigOverride { + Ok(SealedMergeConfigOverride { owner: Arc::clone(&self.identity), - include_arg: format!("include.path={config_path}"), - _config_dir: config_dir, - })) + common_dir, + effective_paths, + selected_custom, + custom_destinations, + conditional_invalid: snapshot.conditional_invalid(), + object_format, + proof: None, + }) } - fn attach_merge_override( - &mut self, - neutralizer: Option, - ) -> io::Result<()> { + fn attach_merge_override(&mut self, isolated: SealedMergeConfigOverride) -> io::Result<()> { if self.merge_policy_installed { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - "a second merge neutralizer is not permitted", + "a second isolated three-way config is not permitted", )); } let [apply] = self.filters.as_slice() else { @@ -233,34 +548,873 @@ impl<'git> GuardedGitConfig<'git> { "merge policy requires an apply filter snapshot", )); } - if let Some(neutralizer) = &neutralizer { - neutralizer.ensure_owner(&self.identity)?; - } - self.merge = neutralizer; + isolated.ensure_owner(&self.identity)?; + self.merge = Some(isolated); self.merge_policy_installed = true; Ok(()) } - fn write_merge_override_value(&self, config_path: &Path, key: &str) -> io::Result<()> { - let mut command = self - .sources - .git - .command_for_cwd(&self.sources.canonical_root)?; + fn write_sanitized_config_value( + &self, + config_path: &Path, + key: &str, + value: &str, + ) -> io::Result<()> { + // The config path is absolute and operation-owned, so no repository + // cwd is needed. This keeps source repository values from being + // interpreted while serializing the already validated snapshot. + let mut command = self.sources.git.command(); command - .args(&self.sources.base_config_args) .args(["config", "--file"]) .arg(config_path) - .args(["--add", key, ""]); + .args(["--add", key, value]); let output = self.sources.git.output(command)?; if !output.status.success() { return Err(io::Error::other(format!( - "failed to write Git merge-driver neutralization for {key:?} (status {}): {}", + "failed to write isolated Git config value {key:?} (status {}): {}", output.status, String::from_utf8_lossy(&output.stderr).trim() ))); } Ok(()) } + + fn write_projected_merge_attributes( + &self, + common_dir: &IsolatedGitCommonDir, + attributes: &MergeAttributeSnapshot, + ) -> io::Result<()> { + attributes.ensure_owner(&self.identity)?; + let attributes_path = common_dir.attributes_path(); + self.ensure_owned_config_path(&attributes_path, "owned isolated Git merge attributes")?; + std::fs::write( + attributes_path, + projected_merge_attributes(&attributes.paths)?, + ) + } + + pub(crate) fn three_way_requires_merge_policy_proof(&self) -> io::Result { + let merge = self.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + merge.ensure_owner(&self.identity)?; + Ok(merge.proof_required()) + } + + pub(crate) fn create_three_way_scratch_storage(&self) -> io::Result { + if !self.three_way_requires_merge_policy_proof()? { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "three-way scratch storage requested without a merge-policy proof requirement", + )); + } + self.sources.git.create_isolated_git_storage() + } + + /// Prove that the frozen merge policy cannot reach repository-selected + /// helper dispatch or a conditionally invalid merge-config read for this + /// exact patch and prospective index. The caller may first model reverse + /// staging in `storage`. + pub(crate) fn prove_three_way_merge_policy_safety( + &mut self, + storage: &IsolatedGitStorage, + revert: bool, + patch_path: &str, + ) -> io::Result<()> { + let (effective_paths, custom_destinations, selected_custom, conditional_invalid) = { + let merge = self.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + merge.ensure_owner(&self.identity)?; + if !merge.proof_required() { + return Ok(()); + } + if merge.proof.is_some() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "merge-policy scratch proof may be installed only once", + )); + } + ( + merge.effective_paths.clone(), + merge.custom_destinations.clone(), + merge.selected_custom.clone(), + merge.conditional_invalid, + ) + }; + + // This also binds the scratch child to the successful real-policy + // gate for the exact patch and orientation. + let whitespace_mode = self.final_apply_whitespace_mode(revert, patch_path)?; + let prospective_index = + self.capture_merge_index_stage_snapshot(&effective_paths, Some(storage))?; + let output = self.run_scratch_three_way_apply( + storage, + revert, + patch_path, + whitespace_mode.is_fatal(), + )?; + let resulting_index = + self.capture_merge_index_stage_snapshot(&effective_paths, Some(storage))?; + + let completed = match output.status.code() { + Some(0) => true, + Some(1) => newly_unmerged_noncustom_path( + &prospective_index, + &resulting_index, + &custom_destinations, + ), + Some(_) | None => false, + }; + if !completed { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + format!( + "unable to prove helper-free merge-policy reachability (status {}): {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ), + )); + } + + if let Some(path) = custom_destinations.iter().find(|path| { + resulting_index + .get(*path) + .is_some_and(|entries| entries.keys().any(|stage| *stage != 0)) + }) { + let driver = selected_custom + .get(path) + .map(String::as_str) + .unwrap_or(""); + return Err(io::Error::new( + io::ErrorKind::Unsupported, + format!( + "refusing an internal Git three-way apply because merge driver {driver:?} is reachable for {path:?}" + ), + )); + } + + let merge = self.merge.as_mut().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config disappeared during classification", + ) + })?; + merge.proof = Some(ThreeWayMergePolicyProof { + owner: Arc::clone(&self.identity), + revert, + patch_path: patch_path.to_string(), + custom_destinations, + conditional_invalid, + prospective_index, + }); + Ok(()) + } + + pub(super) fn consume_three_way_merge_policy_proof( + &mut self, + revert: bool, + patch_path: &str, + ) -> io::Result<()> { + let (proof, effective_paths, custom_destinations, conditional_invalid) = { + let merge = self.merge.as_mut().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + merge.ensure_owner(&self.identity)?; + if !merge.proof_required() { + return Ok(()); + } + // Consume before every subsequent fallible validation. A failed + // query or mismatch must not leave a reusable proof behind. + let proof = merge.proof.take().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "the frozen merge policy requires an unused scratch proof", + ) + })?; + ( + proof, + merge.effective_paths.clone(), + merge.custom_destinations.clone(), + merge.conditional_invalid, + ) + }; + if !Arc::ptr_eq(&proof.owner, &self.identity) + || proof.revert != revert + || proof.patch_path != patch_path + || proof.custom_destinations != custom_destinations + || proof.conditional_invalid != conditional_invalid + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "merge-policy scratch proof does not match the final apply", + )); + } + let current_index = self.capture_merge_index_stage_snapshot(&effective_paths, None)?; + if current_index != proof.prospective_index { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Git index changed after merge-policy classification", + )); + } + Ok(()) + } + + pub(super) fn ensure_three_way_merge_policy_proof_installed(&self) -> io::Result<()> { + let merge = self.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + merge.ensure_owner(&self.identity)?; + if merge.proof_required() && merge.proof.is_none() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "the frozen merge policy requires a completed scratch proof", + )); + } + Ok(()) + } + + fn run_scratch_three_way_apply( + &self, + storage: &IsolatedGitStorage, + revert: bool, + patch_path: &str, + neutralize_fatal_whitespace: bool, + ) -> io::Result { + let merge = self.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + let isolated = merge.common_dir(&self.identity)?; + let mut command = self + .sources + .git + .command_for_cwd(&self.sources.canonical_root)?; + super::append_safe_scalar_overrides(&mut command); + self.apply_policy + .as_ref() + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "scratch apply policy scalars are not frozen", + ) + })? + .append_to(&mut command); + BoundSubcommand::Apply.append_to(&mut command); + command.args(["--cached", "--3way"]); + if neutralize_fatal_whitespace { + command.arg("--whitespace=nowarn"); + } + if revert { + command.arg("-R"); + } + command.arg("--").arg(patch_path); + self.sources + .git + .output_in_isolated_scratch(command, isolated, storage) + } + + fn capture_merge_index_stage_snapshot( + &self, + paths: &[String], + storage: Option<&IsolatedGitStorage>, + ) -> io::Result { + let merge = self.merge.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "isolated three-way config is unavailable", + ) + })?; + let isolated = merge.common_dir(&self.identity)?; + let mut command = self + .sources + .git + .command_for_cwd(&self.sources.canonical_root)?; + super::append_safe_scalar_overrides(&mut command); + command.arg("--literal-pathspecs"); + BoundSubcommand::LsFiles.append_to(&mut command); + command.args(["--stage", "-z", "--"]).args(paths); + let output = if let Some(storage) = storage { + self.sources + .git + .output_in_isolated_scratch(command, isolated, storage)? + } else { + self.sources + .git + .output_in_isolated_common_dir(command, isolated)? + }; + if !output.status.success() { + return Err(io::Error::other(format!( + "failed to inspect isolated Git index stages (status {}): {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + parse_index_stage_snapshot(&output.stdout, paths, merge.object_format) + } +} + +fn newly_unmerged_noncustom_path( + before: &IndexStageSnapshot, + after: &IndexStageSnapshot, + custom_destinations: &BTreeSet, +) -> bool { + after.iter().any(|(path, entries)| { + !custom_destinations.contains(path) + && before + .get(path) + .is_none_or(|prior| prior.keys().all(|stage| *stage == 0)) + && entries.keys().any(|stage| *stage != 0) + && before.get(path) != Some(entries) + }) +} + +fn parse_index_stage_snapshot( + output: &[u8], + expected_paths: &[String], + object_format: IndexObjectFormat, +) -> io::Result { + if output.is_empty() { + return Ok(IndexStageSnapshot::new()); + } + let body = output + .strip_suffix(&[0]) + .ok_or_else(|| invalid_stage_output("unterminated Git index stage output"))?; + if body.is_empty() { + return Err(invalid_stage_output("empty Git index stage record")); + } + if body.split(|byte| *byte == 0).any(<[u8]>::is_empty) { + return Err(invalid_stage_output("empty Git index stage record")); + } + if !output.ends_with(&[0]) { + return Err(invalid_stage_output("unterminated Git index stage output")); + } + let expected = expected_paths + .iter() + .map(String::as_str) + .collect::>(); + if expected.len() != expected_paths.len() || expected.iter().any(|path| path.is_empty()) { + return Err(invalid_stage_output("duplicate expected Git index path")); + } + let mut snapshot = IndexStageSnapshot::new(); + for record in body.split(|byte| *byte == 0) { + let separator = record + .iter() + .position(|byte| *byte == b'\t') + .ok_or_else(|| invalid_stage_output("missing Git index path separator"))?; + let (header, path) = record.split_at(separator); + let path = std::str::from_utf8(&path[1..]) + .map_err(|_| invalid_stage_output("non-UTF-8 Git index path"))?; + if !expected.contains(path) { + return Err(invalid_stage_output("unexpected Git index path")); + } + let fields = header.split(|byte| *byte == b' ').collect::>(); + let [mode, object_id, stage] = fields.as_slice() else { + return Err(invalid_stage_output("noncanonical Git index stage header")); + }; + let mode = std::str::from_utf8(mode) + .ok() + .filter(|mode| mode.len() == 6 && mode.bytes().all(|byte| matches!(byte, b'0'..=b'7'))) + .and_then(|mode| u32::from_str_radix(mode, 8).ok()) + .filter(|mode| matches!(*mode, 0o040000 | 0o100644 | 0o100755 | 0o120000 | 0o160000)) + .ok_or_else(|| invalid_stage_output("invalid Git index mode"))?; + let expected_oid_length = match object_format { + IndexObjectFormat::Sha1 => 40, + IndexObjectFormat::Sha256 => 64, + }; + if object_id.len() != expected_oid_length + || !object_id + .iter() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) + { + return Err(invalid_stage_output("invalid Git index object ID")); + } + let object_id = parse_index_object_id(object_id)?; + let stage = std::str::from_utf8(stage) + .ok() + .filter(|stage| stage.len() == 1) + .and_then(|stage| stage.parse::().ok()) + .filter(|stage| *stage <= 3) + .ok_or_else(|| invalid_stage_output("invalid Git index stage"))?; + let entries = snapshot.entry(path.to_string()).or_default(); + if entries.contains_key(&stage) { + return Err(invalid_stage_output("duplicate Git index stage")); + } + entries.insert(stage, IndexStageEntry { mode, object_id }); + } + if snapshot.values().any(|entries| { + entries + .get(&0) + .is_some_and(|entry| entry.object_id.is_zero()) + }) { + return Err(invalid_stage_output( + "Git index stage-zero entry has an intent-to-add object ID", + )); + } + if snapshot + .values() + .any(|entries| entries.contains_key(&0) && entries.keys().any(|stage| *stage != 0)) + { + return Err(invalid_stage_output( + "Git index path mixes stage zero with unmerged stages", + )); + } + if snapshot.values().any(|entries| { + !entries.contains_key(&0) && entries.keys().filter(|stage| **stage != 0).count() < 2 + }) { + return Err(invalid_stage_output( + "Git index path has an incomplete unmerged stage set", + )); + } + Ok(snapshot) +} + +impl IndexObjectId { + fn is_zero(&self) -> bool { + match self { + Self::Sha1(value) => value.iter().all(|byte| *byte == 0), + Self::Sha256(value) => value.iter().all(|byte| *byte == 0), + } + } +} + +fn parse_index_object_id(value: &[u8]) -> io::Result { + fn nibble(byte: u8) -> u8 { + match byte { + b'0'..=b'9' => byte - b'0', + b'a'..=b'f' => byte - b'a' + 10, + _ => unreachable!("caller validated lowercase hexadecimal"), + } + } + let mut decoded = [0_u8; 32]; + for (index, pair) in value.chunks_exact(2).enumerate() { + decoded[index] = (nibble(pair[0]) << 4) | nibble(pair[1]); + } + match value.len() { + 40 => { + let mut sha1 = [0_u8; 20]; + sha1.copy_from_slice(&decoded[..20]); + Ok(IndexObjectId::Sha1(sha1)) + } + 64 => Ok(IndexObjectId::Sha256(decoded)), + _ => Err(invalid_stage_output("invalid Git index object ID length")), + } +} + +fn invalid_stage_output(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +fn index_object_format( + repository_format: &BTreeMap, +) -> io::Result { + match repository_format + .get("extensions.objectformat") + .map(|entry| entry.value.as_str()) + { + None | Some("sha1") => Ok(IndexObjectFormat::Sha1), + Some("sha256") => Ok(IndexObjectFormat::Sha256), + Some(value) => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("unsupported Git repository object format {value:?}"), + )), + } +} + +/// Preserve Git's conditional failure for an implicit known merge value. +/// The fixed app-owned valueless key is accepted by the generic config parser +/// but rejected when low-level merge initialization reads its string value. +/// Trivial three-way equalities return before that initialization. +fn append_conditional_invalid_merge_config(config_path: &Path) -> io::Result<()> { + let mut config = std::fs::OpenOptions::new().append(true).open(config_path)?; + config.write_all(b"\n[merge \"codex-conditional-invalid\"]\n\tdriver\n")?; + config.flush() +} + +fn normalize_shared_repository(value: &GitConfigValue) -> io::Result { + let GitConfigValue::Explicit(value) = value else { + return Ok("group".to_string()); + }; + + match value.as_str() { + "umask" => return Ok("umask".to_string()), + "group" => return Ok("group".to_string()), + "all" | "world" | "everybody" => return Ok("all".to_string()), + _ => {} + } + + match parse_full_base8_i32(value) { + FullBase8I32::Value(0) => return Ok("umask".to_string()), + FullBase8I32::Value(1) => return Ok("group".to_string()), + FullBase8I32::Value(2) => return Ok("all".to_string()), + FullBase8I32::Value(mode) if mode & 0o600 == 0o600 => { + return Ok(format!("0{:03o}", mode & 0o666)); + } + FullBase8I32::Value(_) | FullBase8I32::Overflow => { + return Err(invalid_shared_repository(value)); + } + FullBase8I32::NotFull => {} + } + + match parse_git_boolean_symmetric_i32(value.as_bytes()) { + Some(true) => Ok("group".to_string()), + Some(false) => Ok("umask".to_string()), + None => Err(invalid_shared_repository(value)), + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum FullBase8I32 { + NotFull, + Value(i32), + Overflow, +} + +/// Reproduce the first numeric branch of Git's `git_config_perm`: a signed +/// base-8 `strtol` whose result is used only when it consumes the whole value. +/// Values outside `i32` are rejected because Git's subsequent `long` to `int` +/// narrowing is platform-dependent. +fn parse_full_base8_i32(value: &str) -> FullBase8I32 { + if value.is_empty() { + // `strtol("", &end, 8)` performs no conversion, but `end` still points + // at the terminating NUL. Git therefore takes its numeric-zero branch. + return FullBase8I32::Value(0); + } + + let trimmed = value.trim_start_matches(|character: char| character.is_ascii_whitespace()); + let (negative, digits) = match trimmed.as_bytes().first() { + Some(b'-') => (true, &trimmed[1..]), + Some(b'+') => (false, &trimmed[1..]), + Some(_) => (false, trimmed), + None => return FullBase8I32::NotFull, + }; + let digit_count = digits + .bytes() + .take_while(|byte| matches!(byte, b'0'..=b'7')) + .count(); + if digit_count == 0 || digit_count != digits.len() { + return FullBase8I32::NotFull; + } + + let limit = if negative { + i64::from(i32::MAX) + 1 + } else { + i64::from(i32::MAX) + }; + let mut magnitude = 0_i64; + for digit in digits.bytes() { + let Some(next) = magnitude + .checked_mul(8) + .and_then(|value| value.checked_add(i64::from(digit - b'0'))) + else { + return FullBase8I32::Overflow; + }; + if next > limit { + return FullBase8I32::Overflow; + } + magnitude = next; + } + + let signed = if negative { -magnitude } else { magnitude }; + match i32::try_from(signed) { + Ok(value) => FullBase8I32::Value(value), + Err(_) => FullBase8I32::Overflow, + } +} + +fn invalid_shared_repository(value: &str) -> io::Error { + io::Error::new( + io::ErrorKind::InvalidData, + format!("invalid core.sharedRepository value {value:?}"), + ) +} + +fn projected_merge_attributes( + paths: &BTreeMap, +) -> io::Result> { + if paths.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "refusing to project an empty merge attribute snapshot", + )); + } + let mut projection = Vec::new(); + for (path, attributes) in paths { + let pattern = literal_attribute_pattern(path)?; + let merge = match &attributes.merge { + MergeSelection::Builtin(driver) => { + format!("merge={}", driver.attribute_value()).into_bytes() + } + // Attribute-unset selects Git's built-in binary merge directly. + // It cannot be redirected by merge.default or by a driver named + // "binary", even if a later index/object race invalidates the + // trivial-merge proof. + MergeSelection::QuarantinedCustom { .. } => b"-merge".to_vec(), + }; + let tokens = [ + merge, + // Never retain an arbitrary filter selection in the final child. + // This highest-precedence reset also masks later worktree changes. + b"!filter".to_vec(), + attributes.safe.whitespace.projected_token("whitespace"), + attributes + .safe + .conflict_marker_size + .projected_token("conflict-marker-size"), + attributes.safe.text.projected_token("text"), + attributes.safe.crlf.projected_token("crlf"), + attributes.safe.eol.projected_token("eol"), + attributes.safe.ident.projected_token("ident"), + attributes + .safe + .working_tree_encoding + .projected_token("working-tree-encoding"), + ]; + append_projected_attribute_lines(&mut projection, pattern.as_bytes(), &tokens)?; + } + Ok(projection) +} + +fn append_projected_attribute_lines( + projection: &mut Vec, + pattern: &[u8], + tokens: &[Vec], +) -> io::Result<()> { + if tokens.is_empty() { + return Err(invalid_attribute_output( + "refusing to project an empty Git attribute token set", + )); + } + let mut line = pattern.to_vec(); + let mut tokens_on_line = 0_usize; + for token in tokens { + if token.is_empty() || token.iter().copied().any(is_git_attribute_token_separator) { + return Err(invalid_attribute_output( + "unrepresentable projected Git attribute token", + )); + } + let candidate_length = line.len() + 1 + token.len(); + if candidate_length >= GIT_ATTRIBUTE_LINE_LENGTH_LIMIT { + if tokens_on_line == 0 { + return Err(invalid_attribute_output( + "projected Git attribute line exceeds Git's length limit", + )); + } + projection.extend_from_slice(&line); + projection.push(b'\n'); + line.clear(); + line.extend_from_slice(pattern); + tokens_on_line = 0; + if line.len() + 1 + token.len() >= GIT_ATTRIBUTE_LINE_LENGTH_LIMIT { + return Err(invalid_attribute_output( + "projected Git attribute token exceeds Git's line length limit", + )); + } + } + line.push(b' '); + line.extend_from_slice(token); + tokens_on_line += 1; + } + projection.extend_from_slice(&line); + projection.push(b'\n'); + Ok(()) +} + +#[derive(Default)] +struct PendingPathApplyAttributes { + merge: Option, + whitespace: Option, + conflict_marker_size: Option, + text: Option, + crlf: Option, + eol: Option, + ident: Option, + filter: Option, + working_tree_encoding: Option, +} + +impl PendingPathApplyAttributes { + fn insert(&mut self, attribute: &[u8], value: &[u8]) -> io::Result<()> { + if attribute == b"merge" { + let value = std::str::from_utf8(value) + .map_err(|_| invalid_attribute_output("non-UTF-8 Git merge attribute value"))?; + if self.merge.replace(value.to_string()).is_some() { + return Err(invalid_attribute_output( + "duplicate Git merge attribute record", + )); + } + return Ok(()); + } + + let value = ProjectedAttribute::from_check_attr(value)?; + let slot = match attribute { + b"whitespace" => &mut self.whitespace, + b"conflict-marker-size" => &mut self.conflict_marker_size, + b"text" => &mut self.text, + b"crlf" => &mut self.crlf, + b"eol" => &mut self.eol, + b"ident" => &mut self.ident, + b"filter" => &mut self.filter, + b"working-tree-encoding" => &mut self.working_tree_encoding, + _ => { + return Err(invalid_attribute_output( + "unexpected Git attribute record name", + )); + } + }; + if slot.replace(value).is_some() { + return Err(invalid_attribute_output( + "duplicate Git apply attribute record", + )); + } + Ok(()) + } + + fn finish(self) -> io::Result { + Ok(ParsedPathApplyAttributes { + merge: required_attribute(self.merge, "merge")?, + safe: SafeApplyAttributes { + whitespace: required_attribute(self.whitespace, "whitespace")?, + conflict_marker_size: required_attribute( + self.conflict_marker_size, + "conflict-marker-size", + )?, + text: required_attribute(self.text, "text")?, + crlf: required_attribute(self.crlf, "crlf")?, + eol: required_attribute(self.eol, "eol")?, + ident: required_attribute(self.ident, "ident")?, + working_tree_encoding: required_attribute( + self.working_tree_encoding, + "working-tree-encoding", + )?, + _filter: required_attribute(self.filter, "filter")?, + }, + }) + } +} + +fn required_attribute(value: Option, name: &str) -> io::Result { + value.ok_or_else(|| invalid_attribute_output(&format!("missing Git {name} attribute record"))) +} + +/// Parse the strict NUL-framed output of the one fixed nine-attribute query. +/// Every authorized path must have exactly one record for every consumed name; +/// extra, duplicate, malformed, or unrepresentable data fails closed. +fn parse_three_way_attributes( + output: &[u8], + expected_paths: &[String], +) -> io::Result> { + let Some(body) = output.strip_suffix(&[0]) else { + return Err(invalid_attribute_output( + "unterminated Git attribute output", + )); + }; + let fields = body.split(|byte| *byte == 0).collect::>(); + if fields.len() % 3 != 0 { + return Err(invalid_attribute_output("incomplete Git attribute record")); + } + let expected = expected_paths + .iter() + .map(String::as_str) + .collect::>(); + if expected.len() != expected_paths.len() { + return Err(invalid_attribute_output( + "duplicate expected Git attribute path", + )); + } + let mut pending = expected_paths + .iter() + .cloned() + .map(|path| (path, PendingPathApplyAttributes::default())) + .collect::>(); + for record in fields.chunks_exact(3) { + let path = std::str::from_utf8(record[0]) + .map_err(|_| invalid_attribute_output("non-UTF-8 Git attribute path"))?; + if !expected.contains(path) { + return Err(invalid_attribute_output( + "unexpected Git attribute record path", + )); + } + pending + .get_mut(path) + .ok_or_else(|| invalid_attribute_output("missing expected Git attribute path"))? + .insert(record[1], record[2])?; + } + pending + .into_iter() + .map(|(path, attributes)| Ok((path, attributes.finish()?))) + .collect() +} + +fn validate_projected_attribute_value(value: &[u8]) -> io::Result<()> { + if value.iter().copied().any(is_git_attribute_token_separator) { + return Err(invalid_attribute_output( + "unrepresentable Git attribute value", + )); + } + Ok(()) +} + +fn is_git_attribute_token_separator(byte: u8) -> bool { + matches!(byte, 0 | b' ' | b'\t' | b'\r' | b'\n') +} + +fn invalid_attribute_output(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +/// Quote an exact repository-relative path as a root-anchored attributes +/// pattern. The first escaping layer protects Git wildmatch metacharacters; +/// the second is Git's C-style double-quoted attribute syntax. +fn literal_attribute_pattern(path: &str) -> io::Result { + if path.is_empty() || path.starts_with('/') || path.as_bytes().contains(&0) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "merge attribute path is not a repository-relative Git path", + )); + } + + let mut literal = String::with_capacity(path.len() + 1); + literal.push('/'); + for character in path.chars() { + if matches!(character, '*' | '?' | '[' | ']' | '\\') { + literal.push('\\'); + } + literal.push(character); + } + + let mut quoted = String::with_capacity(literal.len() + 2); + quoted.push('"'); + for character in literal.chars() { + match character { + '\\' => quoted.push_str("\\\\"), + '"' => quoted.push_str("\\\""), + '\n' => quoted.push_str("\\n"), + '\r' => quoted.push_str("\\r"), + '\t' => quoted.push_str("\\t"), + '\x07' => quoted.push_str("\\a"), + '\x08' => quoted.push_str("\\b"), + '\x0c' => quoted.push_str("\\f"), + '\x0b' => quoted.push_str("\\v"), + _ => quoted.push(character), + } + } + quoted.push('"'); + Ok(quoted) } fn merge_attribute_input(paths: &[String]) -> io::Result { diff --git a/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs b/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs index 069e4ff8c5..e902e18177 100644 --- a/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs +++ b/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs @@ -2,11 +2,10 @@ use super::*; use crate::git_command::GitRunner; use crate::safe_git::isolate_git_command_environment; use pretty_assertions::assert_eq; +use std::ffi::OsStr; fn run_git(cwd: &Path, args: &[&str]) { - let mut command = std::process::Command::new("git"); - isolate_git_command_environment(&mut command); - let output = command.current_dir(cwd).args(args).output().expect("Git"); + let output = git_output(cwd, args); assert!( output.status.success(), "git {args:?}: {}", @@ -14,6 +13,210 @@ fn run_git(cwd: &Path, args: &[&str]) { ); } +fn git_output(cwd: &Path, args: &[&str]) -> std::process::Output { + let mut command = std::process::Command::new("git"); + isolate_git_command_environment(&mut command); + command.current_dir(cwd).args(args).output().expect("Git") +} + +fn config_file_value(_cwd: &Path, config: &Path, key: &str) -> Option { + let mut command = std::process::Command::new("git"); + isolate_git_command_environment(&mut command); + let output = command + .current_dir(config.parent().expect("config parent")) + .args(["config", "--file"]) + .arg(config) + .args(["--get", key]) + .output() + .expect("read config file"); + if output.status.code() == Some(1) { + return None; + } + assert!( + output.status.success(), + "read {key:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + Some(String::from_utf8_lossy(&output.stdout).trim().to_string()) +} + +fn run_isolated_overlay_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); + command + .arg(test_name) + .arg("--exact") + .arg("--nocapture") + .env("CODEX_GIT_UTILS_MERGE_OVERLAY_CHILD", "1") + .env("RUST_TEST_THREADS", "1"); + for (name, value) in env { + command.env(name, value); + } + let output = command.output().expect("run isolated overlay 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) + ); +} + +fn unspecified_safe_attributes() -> SafeApplyAttributes { + SafeApplyAttributes { + whitespace: ProjectedAttribute::Unspecified, + conflict_marker_size: ProjectedAttribute::Unspecified, + text: ProjectedAttribute::Unspecified, + crlf: ProjectedAttribute::Unspecified, + eol: ProjectedAttribute::Unspecified, + ident: ProjectedAttribute::Unspecified, + working_tree_encoding: ProjectedAttribute::Unspecified, + _filter: ProjectedAttribute::Unspecified, + } +} + +fn frozen_path(merge: BuiltinMergeDriver) -> FrozenPathApplyAttributes { + FrozenPathApplyAttributes { + merge: MergeSelection::Builtin(merge), + safe: unspecified_safe_attributes(), + } +} + +fn complete_attribute_output(path: &str, overrides: &[(&str, &[u8])]) -> Vec { + let names = [ + "merge", + "whitespace", + "conflict-marker-size", + "text", + "crlf", + "eol", + "ident", + "filter", + "working-tree-encoding", + ]; + let mut output = Vec::new(); + for name in names { + let value = overrides + .iter() + .find_map(|(candidate, value)| (*candidate == name).then_some(*value)) + .unwrap_or(b"unspecified"); + output.extend_from_slice(path.as_bytes()); + output.push(0); + output.extend_from_slice(name.as_bytes()); + output.push(0); + output.extend_from_slice(value); + output.push(0); + } + output +} + +#[test] +fn index_stage_snapshot_parser_enforces_canonical_framing_and_format() { + let paths = ["file.txt".to_string()]; + let sha1 = "1".repeat(40); + let sha256 = "a".repeat(64); + let sha1_record = format!("100644 {sha1} 0\tfile.txt\0"); + let sha256_record = format!("100644 {sha256} 0\tfile.txt\0"); + + assert_eq!( + parse_index_stage_snapshot(&[], &paths, IndexObjectFormat::Sha1).expect("empty snapshot"), + IndexStageSnapshot::new() + ); + assert!( + parse_index_stage_snapshot(sha1_record.as_bytes(), &paths, IndexObjectFormat::Sha1).is_ok() + ); + assert!( + parse_index_stage_snapshot(sha256_record.as_bytes(), &paths, IndexObjectFormat::Sha256) + .is_ok() + ); + assert!( + parse_index_stage_snapshot(sha1_record.as_bytes(), &paths, IndexObjectFormat::Sha256) + .is_err() + ); + assert!( + parse_index_stage_snapshot(sha256_record.as_bytes(), &paths, IndexObjectFormat::Sha1) + .is_err() + ); + let tab_path = ["tab\tpath.txt".to_string()]; + let tab_record = format!("100644 {sha1} 0\ttab\tpath.txt\0"); + assert!( + parse_index_stage_snapshot(tab_record.as_bytes(), &tab_path, IndexObjectFormat::Sha1) + .is_ok() + ); + + let uppercase = format!("100644 {} 0\tfile.txt\0", "A".repeat(40)); + let zero_stage_zero = format!("100644 {} 0\tfile.txt\0", "0".repeat(40)); + let lone_unmerged = format!("100644 {sha1} 2\tfile.txt\0"); + let stage_zero_and_one = format!("100644 {sha1} 0\tfile.txt\0100644 {sha1} 1\tfile.txt\0"); + let malformed = [ + b"\0".to_vec(), + format!("\0{sha1_record}").into_bytes(), + format!("{sha1_record}\0").into_bytes(), + sha1_record.trim_end_matches('\0').as_bytes().to_vec(), + format!("100644 {sha1} 0\tfile.txt\0").into_bytes(), + format!("100644 {sha1} 0\tfile.txt\0").into_bytes(), + format!("10064 {sha1} 0\tfile.txt\0").into_bytes(), + format!("100600 {sha1} 0\tfile.txt\0").into_bytes(), + format!("100644 {sha1} 4\tfile.txt\0").into_bytes(), + format!("100644 {sha1} 0\tfile.txt\textra\0").into_bytes(), + uppercase.into_bytes(), + zero_stage_zero.into_bytes(), + lone_unmerged.into_bytes(), + stage_zero_and_one.into_bytes(), + ]; + for value in malformed { + assert!( + parse_index_stage_snapshot(&value, &paths, IndexObjectFormat::Sha1).is_err(), + "accepted malformed stage output {value:?}" + ); + } +} + +#[test] +fn exit_one_completion_witness_requires_new_noncustom_unmerged_state() { + fn entry(byte: u8) -> IndexStageEntry { + IndexStageEntry { + mode: 0o100644, + object_id: IndexObjectId::Sha1([byte; 20]), + } + } + + let custom = BTreeSet::from(["custom.txt".to_string()]); + let clean_before = BTreeMap::from([("peer.txt".to_string(), BTreeMap::from([(0, entry(1))]))]); + let newly_conflicted = BTreeMap::from([( + "peer.txt".to_string(), + BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]), + )]); + assert!(newly_unmerged_noncustom_path( + &clean_before, + &newly_conflicted, + &custom + )); + + let already_unmerged = BTreeMap::from([( + "peer.txt".to_string(), + BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]), + )]); + let changed_unmerged = BTreeMap::from([( + "peer.txt".to_string(), + BTreeMap::from([(1, entry(4)), (2, entry(5)), (3, entry(6))]), + )]); + assert!(!newly_unmerged_noncustom_path( + &already_unmerged, + &changed_unmerged, + &custom + )); + + let custom_conflict = BTreeMap::from([( + "custom.txt".to_string(), + BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]), + )]); + assert!(!newly_unmerged_noncustom_path( + &IndexStageSnapshot::new(), + &custom_conflict, + &custom + )); +} + #[test] fn sealed_merge_override_rejects_another_operation_identity() { let repo = tempfile::tempdir().expect("repo"); @@ -33,12 +236,769 @@ fn sealed_merge_override_rejects_another_operation_identity() { .expect("second apply snapshot"); let snapshot = first.read_merge_config_snapshot().expect("merge snapshot"); + let attributes = MergeAttributeSnapshot::from_effective( + &first.identity, + &snapshot, + BTreeMap::from([( + "file.txt".to_string(), + ParsedPathApplyAttributes { + merge: "unspecified".to_string(), + safe: unspecified_safe_attributes(), + }, + )]), + &BTreeMap::new(), + ) + .expect("merge attribute snapshot"); let neutralizer = first - .build_merge_override(&snapshot) - .expect("build merge override") - .expect("physical merge override"); + .build_merge_override( + &snapshot, + &attributes, + vec!["file.txt".to_string()], + BTreeMap::new(), + BTreeSet::new(), + ) + .expect("build isolated merge config"); let error = second - .attach_merge_override(Some(neutralizer)) + .attach_merge_override(neutralizer) .expect_err("cross-operation override must refuse"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); } + +#[test] +fn merge_config_snapshot_tracks_namespaces_and_sticky_conditional_invalidity() { + let owner = Arc::new(CapabilityIdentity); + let snapshot = MergeConfigSnapshot::from_records( + &owner, + vec![ + MergeConfigRecord { + key: "merge.default".to_string(), + value: GitConfigValue::Explicit("union".to_string()), + }, + MergeConfigRecord { + key: "merge.demo.name".to_string(), + value: GitConfigValue::Implicit, + }, + MergeConfigRecord { + key: "merge.demo.name".to_string(), + value: GitConfigValue::Explicit("later display name".to_string()), + }, + MergeConfigRecord { + key: "merge.dotted.name.unknown".to_string(), + value: GitConfigValue::Implicit, + }, + MergeConfigRecord { + key: "merge..unknown".to_string(), + value: GitConfigValue::Implicit, + }, + MergeConfigRecord { + key: "merge.default".to_string(), + value: GitConfigValue::Implicit, + }, + MergeConfigRecord { + key: "merge.default".to_string(), + value: GitConfigValue::Explicit("binary".to_string()), + }, + ], + ) + .expect("merge config snapshot"); + + assert_eq!(snapshot.default_driver(), Some("binary")); + assert_eq!( + snapshot.namespaces(), + &BTreeSet::from([String::new(), "demo".to_string(), "dotted.name".to_string(),]) + ); + assert!( + snapshot.conditional_invalid(), + "a later explicit value must not cure an earlier implicit known value" + ); + + let unknown_only = MergeConfigSnapshot::from_records( + &owner, + vec![MergeConfigRecord { + key: "merge.unknown.arbitrary".to_string(), + value: GitConfigValue::Implicit, + }], + ) + .expect("implicit unknown snapshot"); + assert_eq!( + unknown_only.namespaces(), + &BTreeSet::from(["unknown".to_string()]) + ); + assert!(!unknown_only.conditional_invalid()); +} + +#[test] +fn conditional_invalid_merge_marker_is_fixed_and_valueless() { + let directory = tempfile::tempdir().expect("config directory"); + let config = directory.path().join("config"); + std::fs::write(&config, b"[core]\n\tbare = false\n").expect("write base config"); + + append_conditional_invalid_merge_config(&config).expect("append fixed marker"); + + assert_eq!( + std::fs::read(&config).expect("read marker config"), + b"[core]\n\tbare = false\n\n[merge \"codex-conditional-invalid\"]\n\tdriver\n" + ); +} + +#[test] +fn projected_merge_attribute_patterns_are_rooted_and_literal() { + let target = "dir/literal *?[]\"quote\"\\slash\tline\n.txt".to_string(); + #[cfg(not(windows))] + let wildcard_decoy = target.replacen('*', "X", 1); + #[cfg(not(windows))] + let nested_decoy = format!("nested/{target}"); + #[cfg(not(windows))] + let projected_target = target.clone(); + #[cfg(windows)] + let projected_target = target; + let projection = projected_merge_attributes(&BTreeMap::from([( + projected_target, + frozen_path(BuiltinMergeDriver::Union), + )])) + .expect("literal projection"); + #[cfg(not(windows))] + let projection_for_git = projection.clone(); + let rendered = String::from_utf8(projection).expect("UTF-8 projection"); + assert!(rendered.starts_with("\"/dir/"), "{rendered:?}"); + assert!(rendered.contains("\\\\*"), "{rendered:?}"); + assert!(rendered.contains("\\\\?"), "{rendered:?}"); + assert!(rendered.contains("\\\\["), "{rendered:?}"); + assert!(rendered.contains("\\\\]"), "{rendered:?}"); + assert!(rendered.contains("\\\"quote\\\""), "{rendered:?}"); + assert!(rendered.contains("\\\\\\\\slash"), "{rendered:?}"); + assert!(rendered.contains("\\tline\\n.txt"), "{rendered:?}"); + + #[cfg(not(windows))] + { + let repo = tempfile::tempdir().expect("repo"); + run_git(repo.path(), &["init", "-q"]); + std::fs::write(repo.path().join(".git/info/attributes"), projection_for_git) + .expect("write projected attributes"); + let output = git_output( + repo.path(), + &[ + "check-attr", + "-z", + "merge", + "--", + &target, + &wildcard_decoy, + &nested_decoy, + ], + ); + assert!( + output.status.success(), + "check projected attributes: {}", + String::from_utf8_lossy(&output.stderr) + ); + let paths = vec![target.clone(), wildcard_decoy.clone(), nested_decoy.clone()]; + let parsed = crate::merge_driver::parse_merge_attributes(&output.stdout, &paths) + .expect("parse projected attributes"); + assert_eq!(parsed.get(&target).map(String::as_str), Some("union")); + assert_eq!( + parsed.get(&wildcard_decoy).map(String::as_str), + Some("unspecified") + ); + assert_eq!( + parsed.get(&nested_decoy).map(String::as_str), + Some("unspecified") + ); + } +} + +#[test] +fn projected_whitespace_states_mask_lower_sources() { + let paths = ["set.txt", "unset.txt", "unspecified.txt", "value.txt"].map(str::to_string); + let whitespace = [ + ProjectedAttribute::Set, + ProjectedAttribute::Unset, + ProjectedAttribute::Unspecified, + ProjectedAttribute::Value(b"indent-with-non-tab,tabwidth=4".to_vec()), + ]; + let attributes = paths + .iter() + .cloned() + .zip(whitespace.iter().cloned()) + .map(|(path, whitespace)| { + let mut attributes = frozen_path(BuiltinMergeDriver::Text); + attributes.safe.whitespace = whitespace; + (path, attributes) + }) + .collect::>(); + let projection = + projected_merge_attributes(&attributes).expect("project all whitespace states"); + let rendered = String::from_utf8(projection.clone()).expect("UTF-8 projection"); + assert!(rendered.contains("/set.txt\" merge=text !filter whitespace ")); + assert!(rendered.contains("/unset.txt\" merge=text !filter -whitespace ")); + assert!(rendered.contains("/unspecified.txt\" merge=text !filter !whitespace ")); + assert!( + rendered + .contains("/value.txt\" merge=text !filter whitespace=indent-with-non-tab,tabwidth=4 ") + ); + + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + run_git(root, &["init", "-q"]); + let lower = tempfile::NamedTempFile::new().expect("core attributes file"); + std::fs::write( + lower.path(), + "set.txt -whitespace\nunset.txt whitespace\nunspecified.txt -whitespace\nvalue.txt whitespace\n", + ) + .expect("write lower core attributes"); + run_git( + root, + &[ + "config", + "core.attributesFile", + lower.path().to_str().expect("UTF-8 attributes path"), + ], + ); + std::fs::write( + root.join(".gitattributes"), + "set.txt -whitespace\nunset.txt whitespace\nunspecified.txt whitespace\nvalue.txt -whitespace\n", + ) + .expect("write lower worktree attributes"); + std::fs::write(root.join(".git/info/attributes"), projection) + .expect("write highest-precedence projection"); + + let output = git_output( + root, + &[ + "check-attr", + "-z", + "merge", + "whitespace", + "conflict-marker-size", + "text", + "crlf", + "eol", + "ident", + "filter", + "working-tree-encoding", + "--", + &paths[0], + &paths[1], + &paths[2], + &paths[3], + ], + ); + assert!( + output.status.success(), + "check projected attributes: {}", + String::from_utf8_lossy(&output.stderr) + ); + let actual = + parse_three_way_attributes(&output.stdout, &paths).expect("parse projected attributes"); + assert!(actual.values().all(|attributes| attributes.merge == "text")); + assert_eq!( + actual + .values() + .map(|attributes| attributes.safe.whitespace.clone()) + .collect::>(), + whitespace + ); + assert!( + actual + .values() + .all(|attributes| attributes.safe._filter == ProjectedAttribute::Unspecified) + ); +} + +#[test] +fn three_way_attribute_parser_rejects_malformed_or_unrepresentable_values() { + let paths = vec!["file.txt".to_string()]; + let valid = complete_attribute_output( + "file.txt", + &[ + ("whitespace", b"native-unknown,,tabwidth=4junk"), + ("conflict-marker-size", b"12"), + ("eol", b"crlf"), + ("working-tree-encoding", b"UTF-16LE"), + ("filter", b"selected-but-never-projected"), + ], + ); + let attributes = parse_three_way_attributes(&valid, &paths).expect("valid attribute snapshot"); + let safe = &attributes.get("file.txt").expect("file attributes").safe; + assert_eq!( + safe.whitespace, + ProjectedAttribute::Value(b"native-unknown,,tabwidth=4junk".to_vec()) + ); + assert_eq!( + safe.conflict_marker_size, + ProjectedAttribute::Value(b"12".to_vec()) + ); + assert_eq!( + safe._filter, + ProjectedAttribute::Value(b"selected-but-never-projected".to_vec()) + ); + assert_eq!( + ProjectedAttribute::from_check_attr(b"").expect("native empty value"), + ProjectedAttribute::Value(Vec::new()) + ); + assert_eq!( + ProjectedAttribute::Value(Vec::new()).projected_token("whitespace"), + b"whitespace=" + ); + + let mut duplicate = valid.clone(); + duplicate.extend_from_slice(b"file.txt\0text\0set\0"); + let mut unexpected_name = valid.clone(); + let name_start = unexpected_name + .windows(b"whitespace".len()) + .position(|window| window == b"whitespace") + .expect("whitespace name"); + unexpected_name.splice( + name_start..name_start + b"whitespace".len(), + b"other".iter().copied(), + ); + let mut unrepresentable = valid; + let value_start = unrepresentable + .windows(b"native-unknown,,tabwidth=4junk".len()) + .position(|window| window == b"native-unknown,,tabwidth=4junk") + .expect("whitespace value"); + unrepresentable[value_start] = b' '; + for malformed in [ + duplicate, + unexpected_name, + complete_attribute_output("other.txt", &[]), + complete_attribute_output("file.txt", &[])[..20].to_vec(), + unrepresentable, + ] { + assert!( + parse_three_way_attributes(&malformed, &paths).is_err(), + "accepted malformed attribute output {malformed:?}" + ); + } +} + +#[test] +fn projected_safe_attributes_preserve_raw_values_and_neutralize_filter() { + let mut attributes = frozen_path(BuiltinMergeDriver::Union); + attributes.safe = SafeApplyAttributes { + whitespace: ProjectedAttribute::Value(b"unknown,,tabwidth=4junk".to_vec()), + conflict_marker_size: ProjectedAttribute::Value(b"12".to_vec()), + text: ProjectedAttribute::Set, + crlf: ProjectedAttribute::Unset, + eol: ProjectedAttribute::Value(b"crlf".to_vec()), + ident: ProjectedAttribute::Set, + working_tree_encoding: ProjectedAttribute::Value(b"UTF-16LE".to_vec()), + _filter: ProjectedAttribute::Value(b"executable".to_vec()), + }; + let projection = + projected_merge_attributes(&BTreeMap::from([("file.txt".to_string(), attributes)])) + .expect("project safe attributes"); + let rendered = String::from_utf8(projection).expect("ASCII projection"); + assert!(rendered.contains("merge=union"), "{rendered}"); + assert!(rendered.contains("!filter"), "{rendered}"); + assert!(!rendered.contains("filter=executable"), "{rendered}"); + assert!( + rendered.contains("whitespace=unknown,,tabwidth=4junk"), + "{rendered}" + ); + assert!(rendered.contains("conflict-marker-size=12"), "{rendered}"); + assert!(rendered.contains(" text "), "{rendered}"); + assert!(rendered.contains(" -crlf "), "{rendered}"); + assert!(rendered.contains(" eol=crlf "), "{rendered}"); + assert!(rendered.contains(" ident "), "{rendered}"); + assert!( + rendered.contains("working-tree-encoding=UTF-16LE"), + "{rendered}" + ); +} + +#[test] +fn projected_attribute_lines_split_below_git_limit_or_fail_closed() { + let mut split = frozen_path(BuiltinMergeDriver::Text); + split.safe.whitespace = ProjectedAttribute::Value(vec![b'w'; 1_500]); + split.safe.conflict_marker_size = ProjectedAttribute::Value(vec![b'1'; 1_500]); + let projection = projected_merge_attributes(&BTreeMap::from([("file.txt".to_string(), split)])) + .expect("split long projection"); + let lines = projection + .strip_suffix(b"\n") + .expect("terminated projection") + .split(|byte| *byte == b'\n') + .collect::>(); + assert!(lines.len() >= 2, "projection did not split"); + assert!( + lines + .iter() + .all(|line| line.len() < GIT_ATTRIBUTE_LINE_LENGTH_LIMIT), + "oversized projected line" + ); + + let mut too_long = frozen_path(BuiltinMergeDriver::Text); + too_long.safe.whitespace = ProjectedAttribute::Value(vec![b'w'; 2_048]); + assert_eq!( + projected_merge_attributes(&BTreeMap::from([("file.txt".to_string(), too_long,)])) + .expect_err("reject unprojectable value") + .kind(), + io::ErrorKind::InvalidData + ); +} + +#[test] +fn native_check_attr_conflates_sentinels_for_every_projected_name() { + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + run_git(root, &["init", "-q"]); + let names = [ + "merge", + "whitespace", + "conflict-marker-size", + "text", + "crlf", + "eol", + "ident", + "filter", + "working-tree-encoding", + ]; + let bare_set = names.join(" "); + let literal_set = names + .iter() + .map(|name| format!("{name}=set")) + .collect::>() + .join(" "); + let bare_unset = names + .iter() + .map(|name| format!("-{name}")) + .collect::>() + .join(" "); + let literal_unset = names + .iter() + .map(|name| format!("{name}=unset")) + .collect::>() + .join(" "); + let bare_unspecified = names + .iter() + .map(|name| format!("!{name}")) + .collect::>() + .join(" "); + let literal_unspecified = names + .iter() + .map(|name| format!("{name}=unspecified")) + .collect::>() + .join(" "); + std::fs::write( + root.join(".gitattributes"), + format!( + "bare-set {bare_set}\nliteral-set {literal_set}\nbare-unset {bare_unset}\nliteral-unset {literal_unset}\nbare-unspecified {bare_unspecified}\nliteral-unspecified {literal_unspecified}\n" + ), + ) + .expect("write sentinel fixtures"); + let paths = [ + "bare-set", + "literal-set", + "bare-unset", + "literal-unset", + "bare-unspecified", + "literal-unspecified", + ]; + let mut args = vec!["check-attr", "-z"]; + args.extend(names); + args.push("--"); + args.extend(paths); + let output = git_output(root, &args); + assert!( + output.status.success(), + "check sentinel attributes: {}", + String::from_utf8_lossy(&output.stderr) + ); + let fields = output.stdout.split(|byte| *byte == 0).collect::>(); + assert_eq!(fields.len(), paths.len() * names.len() * 3 + 1); + let values = fields[..fields.len() - 1] + .chunks_exact(3) + .map(|record| record[2]) + .collect::>(); + for (path_index, expected) in [ + b"set".as_slice(), + b"set".as_slice(), + b"unset".as_slice(), + b"unset".as_slice(), + b"unspecified".as_slice(), + b"unspecified".as_slice(), + ] + .into_iter() + .enumerate() + { + assert!( + values[path_index * names.len()..(path_index + 1) * names.len()] + .iter() + .all(|actual| *actual == expected), + "path {} did not render as {:?}", + paths[path_index], + String::from_utf8_lossy(expected) + ); + } + + let expected_paths = paths.map(str::to_string).to_vec(); + let parsed = parse_three_way_attributes(&output.stdout, &expected_paths) + .expect("parse conventional sentinel rendering"); + // The bounded implementation accepts this documented residual: literal + // sentinel values are projected as their same-spelled special states. + assert_eq!(parsed["literal-set"].safe.text, ProjectedAttribute::Set); + assert_eq!( + parsed["literal-unset"].safe.ident, + ProjectedAttribute::Unset + ); + assert_eq!( + parsed["literal-unspecified"].safe._filter, + ProjectedAttribute::Unspecified + ); +} + +#[test] +fn merge_attribute_snapshot_normalizes_only_builtin_semantics() { + for (attribute, default, expected) in [ + ("set", "union", BuiltinMergeDriver::Text), + ("text", "binary", BuiltinMergeDriver::Text), + ("unset", "text", BuiltinMergeDriver::Binary), + ("binary", "union", BuiltinMergeDriver::Binary), + ("union", "binary", BuiltinMergeDriver::Union), + ("missing-custom", "union", BuiltinMergeDriver::Text), + ("unspecified", "binary", BuiltinMergeDriver::Binary), + ("unspecified", "union", BuiltinMergeDriver::Union), + ("unspecified", "other", BuiltinMergeDriver::Text), + ] { + assert_eq!( + BuiltinMergeDriver::from_effective_attribute(attribute, default), + expected, + "attribute={attribute:?}, default={default:?}" + ); + } +} + +#[test] +fn isolated_format_snapshot_ignores_non_common_and_included_spoofs() { + const TEST_NAME: &str = "guarded_config::merge_overlay::tests::isolated_format_snapshot_ignores_non_common_and_included_spoofs"; + if std::env::var_os("CODEX_GIT_UTILS_MERGE_OVERLAY_CHILD").is_none() { + let environment = tempfile::tempdir().expect("config environment"); + let global = environment.path().join("global.gitconfig"); + let system = environment.path().join("system.gitconfig"); + std::fs::write( + &global, + "[core]\n\trepositoryFormatVersion = 1\n\tsharedRepository = world\n[extensions]\n\tobjectFormat = sha256\n", + ) + .expect("write global spoof"); + std::fs::write(&system, "").expect("write system config"); + run_isolated_overlay_test( + TEST_NAME, + &[ + ("GIT_CONFIG_GLOBAL", global.as_os_str()), + ("GIT_CONFIG_SYSTEM", system.as_os_str()), + ( + "CODEX_APPLY_GIT_CFG", + OsStr::new("core.repositoryFormatVersion=1,extensions.objectFormat=sha256"), + ), + ], + ); + return; + } + + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + run_git(root, &["init", "-q"]); + run_git(root, &["config", "core.sharedRepository", "0660"]); + run_git(root, &["config", "extensions.worktreeConfig", "true"]); + run_git( + root, + &["config", "--worktree", "core.repositoryFormatVersion", "1"], + ); + run_git( + root, + &["config", "--worktree", "extensions.objectFormat", "sha256"], + ); + let included = tempfile::NamedTempFile::new().expect("included config"); + std::fs::write( + included.path(), + "[core]\n\trepositoryFormatVersion = 1\n[extensions]\n\tobjectFormat = sha256\n", + ) + .expect("write included spoof"); + run_git( + root, + &[ + "config", + "--add", + "include.path", + included.path().to_str().expect("UTF-8 include path"), + ], + ); + + let git = GitRunner::for_cwd_io(root).expect("runner"); + let mut guarded = + GuardedGitConfig::authorize(&git, root, crate::apply::configured_git_config_parts()) + .expect("guarded config"); + guarded + .authorize_filter_paths(&["file.txt".to_string()]) + .expect("filter snapshot"); + guarded + .install_three_way_merge_policy(&["file.txt".to_string()]) + .expect("install merge policy"); + let isolated = guarded + .merge_common_config_path() + .expect("isolated common config"); + + assert_eq!( + config_file_value(root, &isolated, "core.repositoryFormatVersion"), + Some("0".to_string()) + ); + assert_eq!( + config_file_value(root, &isolated, "extensions.objectFormat"), + None + ); + assert_eq!( + config_file_value(root, &isolated, "core.sharedRepository"), + Some("0660".to_string()) + ); +} + +#[test] +fn shared_repository_values_are_normalized_or_rejected() { + assert_eq!( + normalize_shared_repository(&GitConfigValue::Implicit) + .expect("valid implicit shared repository value"), + "group" + ); + for (input, expected) in [ + ("", "umask"), + ("true", "group"), + ("YES", "group"), + ("false", "umask"), + ("off", "umask"), + ("group", "group"), + ("world", "all"), + ("everybody", "all"), + ("0", "umask"), + ("00", "umask"), + ("1", "group"), + ("01", "group"), + ("2", "all"), + ("02", "all"), + ("600", "0600"), + ("0600", "0600"), + ("640", "0640"), + ("0640", "0640"), + ("660", "0660"), + ("0660", "0660"), + ("664", "0664"), + ("0777", "0666"), + ("000660", "0660"), + ("06600", "0600"), + ("+0660", "0660"), + ("-0", "umask"), + ("-1", "0666"), + ("-2", "0666"), + ("-3", "0664"), + ("8", "group"), + ("9", "group"), + ("0x1", "group"), + ("0x2", "group"), + ("1k", "group"), + ("-1k", "group"), + ("0x0", "umask"), + ("0k", "umask"), + (" 0660", "0660"), + ("2147483647", "group"), + ] { + let value = GitConfigValue::Explicit(input.to_string()); + assert_eq!( + normalize_shared_repository(&value).expect("valid shared repository value"), + expected, + "{input:?}" + ); + } + for invalid in [ + "UMASK", + "GROUP", + "ALL", + "WORLD", + "EVERYBODY", + "3", + "7", + "10", + "20", + "100", + "0444", + "0003", + "-0660", + "-0777", + "invalid", + "0999", + "0o660", + "0660 ", + " 0660 ", + " true", + "true ", + " ", + "2147483648", + "777777777777777777777777777777777777777", + ] { + let value = GitConfigValue::Explicit(invalid.to_string()); + assert_eq!( + normalize_shared_repository(&value) + .expect_err("reject malformed shared repository value") + .kind(), + io::ErrorKind::InvalidData, + "{invalid:?}" + ); + } +} + +#[test] +fn pinned_direct_common_reader_preserves_compat_object_format_without_repo_setup() { + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + run_git(root, &["init", "-q", "--object-format=sha256"]); + let git = GitRunner::for_cwd_io(root).expect("runner before compat extension"); + let guarded = GuardedGitConfig::authorize(&git, root, Vec::new()).expect("guarded config"); + let config_path = root.join(".git/config"); + let mut config = std::fs::read_to_string(&config_path).expect("read common config"); + config.push_str("\n[extensions]\n\tcompatObjectFormat = sha1\n"); + std::fs::write(&config_path, config).expect("append compat format"); + + let (output, expected_origin) = git + .read_active_common_config_without_includes( + REPOSITORY_FORMAT_CONFIG_PATTERN, + /*show_scope*/ true, + ) + .expect("read direct common format without repository setup"); + assert!( + output.status.success(), + "direct format read: {}", + String::from_utf8_lossy(&output.stderr) + ); + let entries = crate::git_config::parse_config_entries(&output.stdout) + .expect("parse direct common format"); + assert!(entries.iter().all(|entry| { + entry.origin == crate::git_config::GitConfigOrigin::File(expected_origin.clone()) + })); + assert!( + entries + .iter() + .any(|entry| { entry.key == "core.repositoryformatversion" && entry.value == "1" }) + ); + assert!( + entries + .iter() + .any(|entry| entry.key == "extensions.objectformat" && entry.value == "sha256") + ); + assert!( + entries + .iter() + .any(|entry| { entry.key == "extensions.compatobjectformat" && entry.value == "sha1" }) + ); + + let isolated = git + .create_isolated_common_dir() + .expect("isolated common directory"); + let isolated_config = isolated.config_path(); + for entry in &entries { + guarded + .write_sanitized_config_value(&isolated_config, &entry.key, &entry.value) + .expect("project direct format entry"); + } + assert_eq!( + config_file_value(root, &isolated_config, "extensions.compatObjectFormat"), + Some("sha1".to_string()) + ); +} diff --git a/codex-rs/git-utils/src/guarded_config/status_context.rs b/codex-rs/git-utils/src/guarded_config/status_context.rs new file mode 100644 index 0000000000..cfde52cf6c --- /dev/null +++ b/codex-rs/git-utils/src/guarded_config/status_context.rs @@ -0,0 +1,324 @@ +use std::collections::BTreeMap; +use std::ffi::OsStr; +use std::ffi::OsString; +use std::io; +use std::path::Path; +use std::sync::Arc; + +use super::CapabilityIdentity; +use super::GuardedGitConfig; +use super::command_failure; +use crate::git_command::IsolatedGitReadContext; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; +use crate::git_config::parse_git_boolean; +const STATUS_SAFE_CONFIG_PATTERN: &str = r"^(attr\.tree|core\.(filemode|symlinks|ignorecase|precomposeunicode|protecthfs|protectntfs|trustctime|checkstat|longpaths|fscache|splitindex|sparsecheckout|sparsecheckoutcone|autocrlf|eol|safecrlf|checkroundtripencoding|bigfilethreshold|quotepath|abbrev)|index\.(sparse|version))$"; +const REPOSITORY_FORMAT_CONFIG_PATTERN: &str = + r"^(core\.repositoryformatversion|extensions\.(objectformat|compatobjectformat))$"; +const MAX_STATUS_ATTRIBUTE_SOURCE_BYTES: usize = 16 * 1024 * 1024; +const MAX_STATUS_PROJECTED_CONFIG_BYTES: usize = 1024 * 1024; +const MAX_STATUS_PROJECTED_CONFIG_ENTRIES: usize = 256; + +pub(super) struct SealedStatusReadContext { + owner: Arc, + context: IsolatedGitReadContext, + has_untracked: bool, +} + +impl SealedStatusReadContext { + pub(super) fn context( + &self, + owner: &Arc, + ) -> io::Result<&IsolatedGitReadContext> { + if !Arc::ptr_eq(&self.owner, owner) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "sealed Status read context belongs to another operation", + )); + } + Ok(&self.context) + } + + pub(super) fn has_untracked(&self, owner: &Arc) -> io::Result { + let _ = self.context(owner)?; + Ok(self.has_untracked) + } + + #[cfg(test)] + pub(super) fn config_path(&self, owner: &Arc) -> io::Result { + Ok(self.context(owner)?.config_path()) + } + + #[cfg(test)] + pub(super) fn attributes_path( + &self, + owner: &Arc, + ) -> io::Result { + Ok(self.context(owner)?.attributes_path()) + } +} + +impl GuardedGitConfig<'_> { + pub(super) async fn build_status_read_context_async( + &self, + head_oid: Option<&str>, + has_untracked: bool, + ) -> io::Result { + if self.sources.git.attribute_source_is_custom() { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "frozen Status is unavailable with GIT_ATTR_SOURCE", + )); + } + let info_attributes = self + .sources + .git + .read_active_info_attributes_bounded_async(MAX_STATUS_ATTRIBUTE_SOURCE_BYTES) + .await?; + let core_attributes_file = self.read_status_core_attributes_file_async().await?; + let operation_identity = self.operation_identity(); + let context = self + .sources + .git + .create_isolated_read_context(head_oid, &operation_identity)?; + self.write_status_projection_config_async(&context, core_attributes_file.as_deref()) + .await?; + std::fs::write( + context.attributes_path(), + status_info_attributes(info_attributes)?, + )?; + let context = context.seal_projected_files()?; + Ok(SealedStatusReadContext { + owner: Arc::clone(&self.identity), + context, + has_untracked, + }) + } + + async fn write_status_projection_config_async( + &self, + context: &IsolatedGitReadContext, + core_attributes_file: Option<&OsStr>, + ) -> io::Result<()> { + let entries = self + .sources + .read_effective_async(STATUS_SAFE_CONFIG_PATTERN, "status allowlist") + .await?; + let repository_format = self + .sources + .read_direct_common_config_async( + REPOSITORY_FORMAT_CONFIG_PATTERN, + "repository format", + ) + .await?; + if entries.len().saturating_add(repository_format.len()) + > MAX_STATUS_PROJECTED_CONFIG_ENTRIES + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "status config projection exceeds its entry limit", + )); + } + refuse_sparse_status(&entries)?; + let projected_bytes = entries + .iter() + .chain(repository_format.iter()) + .try_fold(0_usize, |total, (key, entry)| { + total + .checked_add(key.len()) + .and_then(|total| total.checked_add(entry.value.len())) + .and_then(|total| total.checked_add(2)) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "status config projection size overflow", + ) + }) + })?; + if projected_bytes > MAX_STATUS_PROJECTED_CONFIG_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "status config projection exceeds its byte limit", + )); + } + for entry in entries.values() { + self.write_status_config_value_async( + &context.config_path(), + &entry.key, + &entry.value, + ) + .await?; + } + for entry in repository_format.values() { + self.write_status_config_value_async( + &context.config_path(), + &entry.key, + &entry.value, + ) + .await?; + } + self.write_status_config_value_async(&context.config_path(), "core.bare", "false") + .await?; + if let Some(core_attributes_file) = core_attributes_file { + self.write_status_config_value_async( + &context.config_path(), + "core.attributesfile", + core_attributes_file, + ) + .await?; + } + if std::fs::metadata(context.config_path())?.len() + > MAX_STATUS_PROJECTED_CONFIG_BYTES as u64 + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "serialized status config projection exceeds its byte limit", + )); + } + Ok(()) + } + + async fn write_status_config_value_async( + &self, + config_path: &Path, + key: &str, + value: impl AsRef, + ) -> io::Result<()> { + let mut command = self + .sources + .git + .async_config_file_write_command(config_path); + command.arg(key).arg(value); + let output = self + .sources + .git + .output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES) + .await?; + if output.status.success() { + Ok(()) + } else { + Err(command_failure("status config projection write", &output)) + } + } + + /// Resolve the effective configured-global attribute selector using the + /// path semantics available on the oldest supported Git. The returned + /// absolute bytes are written into the owned config so a relative or `~` + /// spelling cannot be reinterpreted against the synthetic config file. + async fn read_status_core_attributes_file_async(&self) -> io::Result> { + let mut command = self.pending_status_command( + crate::FsmonitorOverride::Disabled, + /*neutralizer*/ None, + )?; + command.disable_optional_locks().args([ + "config", + "--null", + "--path", + "--get", + "core.attributesFile", + ]); + let output = command.output().await?; + if output.status.code() == Some(1) + && output.stdout.is_empty() + && output.stderr.is_empty() + { + return Ok(None); + } + if !output.status.success() { + return Err(command_failure( + "status core.attributesFile discovery", + &output, + )); + } + let configured = parse_status_config_path(&output.stdout)?; + if configured.is_empty() { + return Ok(Some(configured)); + } + let configured_path = std::path::PathBuf::from(&configured); + if configured_path.is_absolute() { + return Ok(Some(configured)); + } + if configured_path + .components() + .any(|component| matches!(component, std::path::Component::Prefix(_))) + { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "frozen Status is unavailable with a drive-relative core.attributesFile", + )); + } + Ok(Some( + self.sources + .canonical_root + .join(configured_path) + .into_os_string(), + )) + } +} + +fn refuse_sparse_status( + entries: &BTreeMap, +) -> io::Result<()> { + if entries.contains_key("attr.tree") { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "frozen Status is unavailable with attr.tree", + )); + } + for key in [ + "core.sparsecheckout", + "core.sparsecheckoutcone", + "index.sparse", + ] { + let Some(entry) = entries.get(key) else { + continue; + }; + match parse_git_boolean(entry.value.as_bytes()) { + Some(false) | Some(true) if key == "core.sparsecheckoutcone" => {} + Some(false) => {} + Some(true) => { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "frozen Status is unavailable for sparse-checkout repositories", + )); + } + None => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("invalid sparse Status config value for {key}"), + )); + } + } + } + Ok(()) +} + +fn status_info_attributes(mut original: Vec) -> io::Result> { + const RESET: &[u8] = b"* !filter !diff\n"; + if !original.is_empty() && !original.ends_with(b"\n") { + original.push(b'\n'); + } + if original.len().saturating_add(RESET.len()) > MAX_STATUS_ATTRIBUTE_SOURCE_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "owned Git info attributes exceed their byte limit", + )); + } + original.extend_from_slice(RESET); + Ok(original) +} + +fn parse_status_config_path(output: &[u8]) -> io::Result { + let value = output.strip_suffix(&[0]).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "unterminated Git core.attributesFile path output", + ) + })?; + if value.contains(&0) || value.contains(&b'\n') || value.contains(&b'\r') { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "ambiguous Git core.attributesFile path output", + )); + } + crate::safe_git::git_path_argument(value) +} diff --git a/codex-rs/git-utils/src/guarded_config_tests.rs b/codex-rs/git-utils/src/guarded_config_tests.rs index 47806be71d..8dd766180b 100644 --- a/codex-rs/git-utils/src/guarded_config_tests.rs +++ b/codex-rs/git-utils/src/guarded_config_tests.rs @@ -40,6 +40,201 @@ fn run_isolated_config_test(test_name: &str) { ); } +#[test] +fn frozen_apply_policy_overrides_later_repository_config_changes() { + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + run_git(root, &["init", "-q"]); + run_git(root, &["config", "user.email", "codex@example.com"]); + run_git(root, &["config", "user.name", "Codex"]); + run_git(root, &["config", "core.autocrlf", "false"]); + run_git(root, &["config", "apply.whitespace", "warn"]); + run_git(root, &["config", "apply.ignoreWhitespace", "change"]); + run_git(root, &["config", "core.whitespace", "-trailing-space"]); + std::fs::write(root.join("file.txt"), "old\n").expect("write base"); + run_git(root, &["add", "file.txt"]); + run_git(root, &["commit", "-qm", "base"]); + let patch_dir = tempfile::tempdir().expect("patch directory"); + let patch = patch_dir.path().join("change.diff"); + std::fs::write( + &patch, + "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new \n", + ) + .expect("write patch"); + + let git = GitRunner::for_cwd_io(root).expect("runner"); + let mut config = + GuardedGitConfig::authorize(&git, root, Vec::new()).expect("authorized config"); + config.freeze_apply_policy().expect("freeze apply policy"); + config + .authorize_filter_paths(&["file.txt".to_string()]) + .expect("authorize filter path"); + let patch = patch.to_str().expect("UTF-8 patch path"); + let (rendered, gate) = config + .run_apply_policy_gate(false, patch) + .expect("run policy gate"); + assert!(rendered.contains("apply.whitespace=warn"), "{rendered}"); + assert!( + rendered.contains("apply.ignoreWhitespace=change"), + "{rendered}" + ); + assert!( + rendered.contains("core.whitespace=-trailing-space"), + "{rendered}" + ); + assert!( + gate.status.success(), + "{}", + String::from_utf8_lossy(&gate.stderr) + ); + + run_git(root, &["config", "apply.whitespace", "error"]); + run_git(root, &["config", "apply.ignoreWhitespace", "false"]); + run_git(root, &["config", "core.whitespace", "trailing-space"]); + + let final_apply = config + .run_direct_apply(false, patch) + .expect("run final apply"); + assert!( + final_apply.status.success(), + "frozen policy must survive config mutation: {}", + String::from_utf8_lossy(&final_apply.stderr) + ); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")).expect("read result"), + "new \n" + ); +} + +#[test] +fn frozen_apply_policy_materializes_git_defaults() { + let repo = tempfile::tempdir().expect("repo"); + run_git(repo.path(), &["init", "-q"]); + let git = GitRunner::for_cwd_io(repo.path()).expect("runner"); + let mut config = + GuardedGitConfig::authorize(&git, repo.path(), Vec::new()).expect("authorized config"); + config.freeze_apply_policy().expect("freeze apply policy"); + + let rendered = config + .render_apply_command_for_log(&["apply".to_string(), "--check".to_string()]) + .expect("render frozen defaults"); + assert!(rendered.contains("apply.whitespace=warn"), "{rendered}"); + assert!( + rendered.contains("apply.ignoreWhitespace=false"), + "{rendered}" + ); + assert!( + rendered.contains("core.whitespace=blank-at-eol,blank-at-eof,space-before-tab"), + "{rendered}" + ); +} + +#[test] +fn apply_whitespace_modes_are_typed_and_case_sensitive_at_the_gate() { + for (value, expected) in [ + ("warn", ApplyWhitespaceMode::Warn), + ("nowarn", ApplyWhitespaceMode::Nowarn), + ("error", ApplyWhitespaceMode::Error), + ("error-all", ApplyWhitespaceMode::ErrorAll), + ("fix", ApplyWhitespaceMode::Fix), + ("strip", ApplyWhitespaceMode::Fix), + ("ERROR", ApplyWhitespaceMode::Invalid), + ("unknown", ApplyWhitespaceMode::Invalid), + ] { + assert_eq!(ApplyWhitespaceMode::normalize(value), expected, "{value}"); + } + + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + run_git(root, &["init", "-q"]); + run_git(root, &["config", "user.email", "codex@example.com"]); + run_git(root, &["config", "user.name", "Codex"]); + run_git(root, &["config", "apply.whitespace", "ERROR"]); + std::fs::write(root.join("file.txt"), "old\n").expect("write base"); + run_git(root, &["add", "file.txt"]); + run_git(root, &["commit", "-qm", "base"]); + let patch_dir = tempfile::tempdir().expect("patch directory"); + let patch = patch_dir.path().join("change.diff"); + std::fs::write( + &patch, + "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new\n", + ) + .expect("write patch"); + + let git = GitRunner::for_cwd_io(root).expect("runner"); + let mut config = + GuardedGitConfig::authorize(&git, root, Vec::new()).expect("authorized config"); + config.freeze_apply_policy().expect("freeze invalid policy"); + config + .authorize_filter_paths(&["file.txt".to_string()]) + .expect("authorize filter path"); + assert!( + config + .final_apply_whitespace_mode(false, patch.to_str().expect("UTF-8 patch path")) + .is_err() + ); + let (_, gate) = config + .run_apply_policy_gate(false, patch.to_str().expect("UTF-8 patch path")) + .expect("run invalid policy gate"); + assert!(!gate.status.success()); + assert!( + String::from_utf8_lossy(&gate.stderr).contains("unrecognized whitespace"), + "{}", + String::from_utf8_lossy(&gate.stderr) + ); + assert!( + config + .final_apply_whitespace_mode(false, patch.to_str().expect("UTF-8 patch path")) + .is_err() + ); +} + +#[test] +fn successful_apply_policy_gate_is_one_shot_and_bound_to_patch_orientation() { + let repo = tempfile::tempdir().expect("repo"); + let root = repo.path(); + run_git(root, &["init", "-q"]); + run_git(root, &["config", "user.email", "codex@example.com"]); + run_git(root, &["config", "user.name", "Codex"]); + run_git(root, &["config", "apply.whitespace", "error"]); + std::fs::write(root.join("file.txt"), "old\n").expect("write base"); + run_git(root, &["add", "file.txt"]); + run_git(root, &["commit", "-qm", "base"]); + let patch_dir = tempfile::tempdir().expect("patch directory"); + let patch = patch_dir.path().join("change.diff"); + std::fs::write( + &patch, + "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new\n", + ) + .expect("write patch"); + let patch = patch.to_str().expect("UTF-8 patch path"); + + let git = GitRunner::for_cwd_io(root).expect("runner"); + let mut config = + GuardedGitConfig::authorize(&git, root, Vec::new()).expect("authorized config"); + config.freeze_apply_policy().expect("freeze policy"); + config + .authorize_filter_paths(&["file.txt".to_string()]) + .expect("authorize filter path"); + let (_, gate) = config + .run_apply_policy_gate(false, patch) + .expect("run successful policy gate"); + assert!(gate.status.success()); + assert_eq!( + config + .final_apply_whitespace_mode(false, patch) + .expect("matching proof"), + ApplyWhitespaceMode::Error + ); + assert!(config.final_apply_whitespace_mode(true, patch).is_err()); + assert!( + config + .final_apply_whitespace_mode(false, "different.patch") + .is_err() + ); + assert!(config.run_apply_policy_gate(false, patch).is_err()); +} + #[test] fn attached_filter_snapshots_retain_multiple_owned_overrides() { let repo = tempfile::tempdir().expect("repo"); @@ -125,7 +320,7 @@ fn attached_filter_snapshots_retain_multiple_owned_overrides() { } #[test] -fn composed_staging_subset_proof_requires_exactly_one_apply_snapshot() { +fn reverse_staging_subset_proof_requires_exactly_one_apply_snapshot() { let repo = tempfile::tempdir().expect("repo"); run_git(repo.path(), &["init", "-q"]); let git = GitRunner::for_cwd_io(repo.path()).expect("runner"); @@ -172,7 +367,7 @@ fn zero_driver_merge_policy_still_occupies_the_single_install_slot() { GuardedGitConfig::authorize(&git, repo.path(), Vec::new()).expect("authorized config"); let error = config - .install_three_way_merge_policy() + .install_three_way_merge_policy(&[]) .expect_err("merge policy without apply snapshot must refuse"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); @@ -180,22 +375,22 @@ fn zero_driver_merge_policy_still_occupies_the_single_install_slot() { .authorize_filter_paths(&["file.txt".to_string()]) .expect("apply snapshot"); config - .install_three_way_merge_policy() + .install_three_way_merge_policy(&["file.txt".to_string()]) .expect("zero-driver merge policy"); assert!(config.merge_policy_installed); - assert!(config.merge.is_none()); + assert!(config.merge.is_some()); let error = config - .install_three_way_merge_policy() + .install_three_way_merge_policy(&["file.txt".to_string()]) .expect_err("second merge policy must refuse"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); } #[test] -fn command_order_is_apply_filter_then_merge_then_git_add_filter() { +fn isolated_merge_config_is_not_attached_to_preparatory_commands() { if std::env::var_os("CODEX_GIT_UTILS_GUARDED_CONFIG_ENV_CHILD").is_none() { run_isolated_config_test( - "guarded_config::tests::command_order_is_apply_filter_then_merge_then_git_add_filter", + "guarded_config::tests::isolated_merge_config_is_not_attached_to_preparatory_commands", ); return; } @@ -215,7 +410,7 @@ fn command_order_is_apply_filter_then_merge_then_git_add_filter() { .authorize_filter_paths(&["file.txt".to_string()]) .expect("apply filter policy"); config - .install_three_way_merge_policy() + .install_three_way_merge_policy(&["file.txt".to_string()]) .expect("merge policy"); config .authorize_git_add_filter_paths(&["file.txt".to_string()]) @@ -226,26 +421,24 @@ fn command_order_is_apply_filter_then_merge_then_git_add_filter() { .expect("apply filter overlay") .include_arg .clone(); - let merge_include = config - .merge_include_arg() - .expect("merge overlay") - .to_string(); + let merge_config = config + .merge_common_config_path() + .expect("isolated merge config"); let git_add_include = config.filters[1] .neutralizer() .expect("Git-add filter overlay") .include_arg .clone(); - let overlay_paths = [&apply_include, &merge_include, &git_add_include] + let overlay_paths = [&apply_include, &git_add_include] .map(|include| PathBuf::from(include.strip_prefix("include.path=").expect("include path"))); let rendered = config .render_command_for_log(&["ls-files".to_string()]) .expect("render command"); let apply_offset = rendered.find(&apply_include).expect("apply include"); - let merge_offset = rendered.find(&merge_include).expect("merge include"); let git_add_offset = rendered.find(&git_add_include).expect("Git-add include"); - assert!(apply_offset < merge_offset && merge_offset < git_add_offset); - assert_eq!(rendered.matches(&merge_include).count(), 1); + assert!(apply_offset < git_add_offset); + assert!(!rendered.contains(&merge_config.display().to_string())); let output = config .ls_files_command() @@ -254,9 +447,11 @@ fn command_order_is_apply_filter_then_merge_then_git_add_filter() { .expect("execute bound command"); assert!(output.status.success()); assert!(overlay_paths.iter().all(|path| path.is_file())); + assert!(merge_config.is_file()); drop(config); assert!(overlay_paths.iter().all(|path| !path.exists())); + assert!(!merge_config.exists()); } #[test] @@ -385,7 +580,10 @@ async fn zero_driver_status_occupies_its_slot_and_excludes_every_mutation_policy .expect("zero-driver status policy"); assert_eq!(status_filter_policy_read_count(), 1); let status = config.status.as_ref().expect("occupied status slot"); - assert!(status.neutralizer.is_none()); + status + .context + .context(&config.identity) + .expect("sealed zero-driver Status context"); assert_eq!(status.fsmonitor, None); let error = config @@ -403,15 +601,23 @@ async fn zero_driver_status_occupies_its_slot_and_excludes_every_mutation_policy .expect_err("status plus GitAdd must fail"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); let error = config - .install_three_way_merge_policy() + .install_three_way_merge_policy(&[]) .expect_err("status plus merge must fail"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + let error = config + .freeze_apply_policy() + .expect_err("status plus frozen apply policy must fail"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(config.apply_policy.is_none()); + assert!(matches!( + config.apply_policy_gate, + ApplyPolicyGateState::NotRun + )); let error = config .status_output_async() .await .expect_err("status sink requires a retained fsmonitor decision"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); - let first = config.detect_status_fsmonitor_async().await; let second = config.detect_status_fsmonitor_async().await; assert_eq!(first, second); @@ -433,13 +639,27 @@ async fn zero_driver_status_occupies_its_slot_and_excludes_every_mutation_policy .expect_err("Apply plus status must fail before a status read"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); assert_eq!(status_filter_policy_read_count(), reads_before); + + let mut apply_policy_only = + GuardedGitConfig::authorize(&git, repo.path(), Vec::new()).expect("apply capability"); + apply_policy_only + .freeze_apply_policy() + .expect("frozen apply policy"); + let reads_before = status_filter_policy_read_count(); + let error = apply_policy_only + .install_status_policy_async() + .await + .expect_err("frozen apply policy plus status must fail before a status read"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert_eq!(status_filter_policy_read_count(), reads_before); + assert!(apply_policy_only.status.is_none()); } #[tokio::test] -async fn status_uses_the_shared_four_entry_overlay_and_retains_it_through_the_sink() { +async fn status_replaces_filter_config_with_an_owned_helper_free_context() { if std::env::var_os("CODEX_GIT_UTILS_GUARDED_CONFIG_ENV_CHILD").is_none() { run_isolated_config_test( - "guarded_config::tests::status_uses_the_shared_four_entry_overlay_and_retains_it_through_the_sink", + "guarded_config::tests::status_replaces_filter_config_with_an_owned_helper_free_context", ); return; } @@ -463,42 +683,30 @@ async fn status_uses_the_shared_four_entry_overlay_and_retains_it_through_the_si .install_status_policy_async() .await .expect("optional smudge policy"); - let neutralizer = config - .status - .as_ref() - .and_then(|status| status.neutralizer.as_ref()) - .expect("status neutralizer"); - let overlay = PathBuf::from( - neutralizer - .include_arg - .strip_prefix("include.path=") - .expect("sealed include path"), - ); - assert!(overlay.is_file()); - let mut actual = Vec::new(); - for (name, expected) in FILTER_NEUTRALIZATION_PLAN { - let output = std::process::Command::new("git") - .args(["config", "--file"]) - .arg(&overlay) - .args(["--get", &format!("filter.demo.{name}")]) - .output() - .expect("read neutralization entry"); - assert!(output.status.success(), "read {name}"); - actual.push(( - name, - String::from_utf8_lossy(&output.stdout).trim().to_string(), - )); - assert_eq!(actual.last().map(|entry| entry.1.as_str()), Some(expected)); - } - assert_eq!(actual.len(), FILTER_NEUTRALIZATION_PLAN.len()); + let status = config.status.as_ref().expect("Status context"); + let owned_config = status + .context + .config_path(&config.identity) + .expect("owned config path"); + let owned_attributes = status + .context + .attributes_path(&config.identity) + .expect("owned attributes path"); + let config_contents = std::fs::read_to_string(&owned_config).expect("read owned config"); + assert!(!config_contents.contains("filter.demo")); + let attribute_contents = + std::fs::read_to_string(&owned_attributes).expect("read owned attributes"); + assert!(attribute_contents.contains("!filter")); config.detect_status_fsmonitor_async().await; let output = config.status_output_async().await.expect("guarded status"); assert!(output.status.success()); - assert!(overlay.is_file(), "overlay must outlive the final child"); - drop(config); + assert!(owned_config.is_file(), "owned config must outlive final child"); assert!( - !overlay.exists(), - "overlay must be removed with the capability" + owned_attributes.is_file(), + "owned attributes must outlive final child" ); + drop(config); + assert!(!owned_config.exists(), "owned config must be removed"); + assert!(!owned_attributes.exists(), "owned attributes must be removed"); } diff --git a/codex-rs/git-utils/src/merge_driver.rs b/codex-rs/git-utils/src/merge_driver.rs index 9f6a1d61f7..2c409f0802 100644 --- a/codex-rs/git-utils/src/merge_driver.rs +++ b/codex-rs/git-utils/src/merge_driver.rs @@ -1,3 +1,4 @@ +#[cfg(test)] use crate::git_config::GitConfigEntry; #[cfg(test)] use crate::safe_git::isolate_git_command_environment; @@ -5,6 +6,7 @@ use std::collections::BTreeMap; use std::collections::BTreeSet; use std::io; +#[cfg(test)] pub(crate) fn parse_merge_attributes( output: &[u8], expected_paths: &[String], @@ -52,34 +54,66 @@ pub(crate) fn parse_merge_attributes( Ok(attributes) } +#[cfg(test)] pub(crate) fn untrusted_driver_selection( entries: &BTreeMap, attributes: &BTreeMap, ) -> io::Result> { - let mut drivers = BTreeMap::new(); + let mut driver_names = BTreeSet::new(); for entry in entries.values() { - if entry.key == "merge.default" { - continue; + if let Some(name) = merge_driver_subsection(&entry.key)? { + driver_names.insert(name.to_string()); } - let name = entry - .key - .strip_prefix("merge.") - .and_then(|key| key.strip_suffix(".driver")) - .ok_or_else(|| invalid_config_entry("malformed merge driver key"))?; - drivers.insert(name.to_string(), entry.value.as_str()); } - let default = entries .get("merge.default") .map(|entry| entry.value.as_str()); + Ok( + untrusted_driver_selections(&driver_names, default, attributes) + .into_iter() + .next() + .map(|(path, driver)| (driver, path)), + ) +} + +/// Return every path whose effective merge selection names a configured user +/// driver namespace. Git creates that namespace for any subsection key, even +/// when `.driver` is missing or explicitly empty; those cases fail or attempt +/// an empty command rather than falling back to built-in text. The complete +/// set is required by the scratch classifier so every selected namespace is +/// quarantined. +pub(crate) fn untrusted_driver_selections( + driver_names: &BTreeSet, + default: Option<&str>, + attributes: &BTreeMap, +) -> BTreeMap { + let mut selected = BTreeMap::new(); for (path, attribute) in attributes { for name in candidate_driver_names(attribute, default) { - if drivers.get(name).is_some_and(|value| !value.is_empty()) { - return Ok(Some((name.to_string(), path.clone()))); + if driver_names.contains(name) { + selected.insert(path.clone(), name.to_string()); + break; } } } - Ok(None) + selected +} + +/// Parse the user-driver subsection using Git 2.54's last-dot behavior. +/// Empty and dotted subsection names are valid; only `merge.default` has no +/// user-driver subsection in the fixed query. +pub(crate) fn merge_driver_subsection(key: &str) -> io::Result> { + if key == "merge.default" { + return Ok(None); + } + let (name, final_key) = key + .strip_prefix("merge.") + .and_then(|key| key.rsplit_once('.')) + .ok_or_else(|| invalid_config_entry("malformed merge driver key"))?; + if final_key.is_empty() { + return Err(invalid_config_entry("empty merge driver configuration key")); + } + Ok(Some(name)) } fn candidate_driver_names<'a>(attribute: &'a str, default: Option<&'a str>) -> BTreeSet<&'a str> { @@ -92,6 +126,7 @@ fn candidate_driver_names<'a>(attribute: &'a str, default: Option<&'a str>) -> B names } +#[cfg(test)] fn invalid_attribute_output(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } 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 53d45f5b6a..b77f251a24 100644 --- a/codex-rs/git-utils/src/merge_driver_race_tests.rs +++ b/codex-rs/git-utils/src/merge_driver_race_tests.rs @@ -2,6 +2,7 @@ use super::*; use crate::apply::ApplyGitRequest; use crate::apply::apply_git_patch; use pretty_assertions::assert_eq; +use std::ffi::OsStr; use std::fs::OpenOptions; use std::io::Write; use std::path::Path; @@ -10,8 +11,8 @@ use std::thread; use std::time::Duration; use std::time::Instant; -const OLD_DRIVER_COMMAND: &str = "git config codex.oldmergeran true && false"; -const NEW_DRIVER_COMMAND: &str = "git config codex.newmergeran true && false"; +const OLD_DRIVER_COMMAND: &str = "git config --file .git/config codex.oldmergeran true && false"; +const NEW_DRIVER_COMMAND: &str = "git config --file .git/config codex.newmergeran true && false"; const TRACE_MUTATION_MARKER: &str = "CODEX_MERGE_DRIVER_TEST_MUTATION"; fn run(cwd: &Path, args: &[&str]) -> (i32, String, String) { @@ -109,6 +110,10 @@ fn index_tree(root: &Path) -> String { } fn run_isolated_test(test_name: &str) { + run_isolated_test_with_env(test_name, &[]); +} + +fn run_isolated_test_with_env(test_name: &str, extra_env: &[(&str, &OsStr)]) { let environment = tempfile::tempdir().expect("isolated Git environment"); let global_config = environment.path().join("global.gitconfig"); let system_config = environment.path().join("system.gitconfig"); @@ -119,7 +124,7 @@ fn run_isolated_test(test_name: &str) { let mut command = std::process::Command::new(std::env::current_exe().expect("test binary")); isolate_git_command_environment(&mut command); - let output = command + command .arg(test_name) .arg("--exact") .arg("--nocapture") @@ -127,9 +132,11 @@ fn run_isolated_test(test_name: &str) { .env("GIT_CONFIG_GLOBAL", &global_config) .env("GIT_CONFIG_SYSTEM", &system_config) .env("GIT_TRACE2_EVENT", &trace) - .env("RUST_TEST_THREADS", "1") - .output() - .expect("run isolated test process"); + .env("RUST_TEST_THREADS", "1"); + for (name, value) in extra_env { + command.env(name, value); + } + let output = command.output().expect("run isolated test process"); assert!( output.status.success(), "isolated test {test_name} failed:\nstdout:\n{}\nstderr:\n{}", @@ -189,6 +196,26 @@ fn append_driver_config(root: &Path, driver: &str, command: &str) { .expect("append replacement merge driver"); } +fn append_default_and_driver_config(root: &Path, driver: &str, command: &str) { + let mut config = OpenOptions::new() + .append(true) + .open(root.join(".git/config")) + .expect("open local config"); + writeln!( + config, + "\n[merge]\n\tdefault = {driver}\n[merge \"{driver}\"]\n\tdriver = {command}" + ) + .expect("append replacement default merge driver"); +} + +#[derive(Clone, Copy, Debug)] +enum DriverNamespaceRace { + KnownEmpty, + SelectedMissing, + BrandNewAttribute, + BrandNewDefault, +} + #[test] fn clean_reverse_checks_worktree_before_staging_and_skips_merge_driver() { let repo = init_repo(); @@ -378,6 +405,209 @@ fn post_probe_attribute_and_same_driver_command_change_stays_neutralized() { assert!(!configured_marker_exists(root, "codex.newmergeran")); } +#[test] +fn post_probe_worktree_attribute_change_preserves_probed_union_semantics() { + if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() { + run_isolated_test( + "merge_driver::race_tests::post_probe_worktree_attribute_change_preserves_probed_union_semantics", + ); + return; + } + + let repo = init_repo(); + let root = repo.path(); + let patch = build_conflicting_patch(root, "target.txt merge=union\n"); + let trace = trace_path(); + std::fs::write(&trace, "").expect("clear fixture trace"); + let watcher_trace = trace.clone(); + let attributes = root.join(".gitattributes"); + let watcher = thread::spawn(move || { + let observed = wait_for_merge_attribute_probe(&watcher_trace); + if observed { + std::fs::write(attributes, "target.txt -merge\n") + .expect("replace union with binary merge semantics"); + record_trace_mutation(&watcher_trace); + } + observed + }); + + let result = apply_git_patch(&request(root, patch, /*revert*/ false)) + .expect("run frozen union three-way apply"); + assert!(watcher.join().expect("attribute watcher")); + + assert_mutation_happened_between_probe_and_three_way(&trace); + assert_eq!(result.exit_code, 0, "{}", result.stderr); + let contents = read_file_normalized(&root.join("target.txt")); + assert!(contents.contains("ours\n"), "{contents}"); + assert!(contents.contains("theirs\n"), "{contents}"); + assert!(!contents.contains("<<<<<<<"), "{contents}"); +} + +#[test] +fn isolated_three_way_config_blocks_driver_namespace_introduction_races() { + if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() { + run_isolated_test( + "merge_driver::race_tests::isolated_three_way_config_blocks_driver_namespace_introduction_races", + ); + return; + } + + for race in [ + DriverNamespaceRace::KnownEmpty, + DriverNamespaceRace::SelectedMissing, + DriverNamespaceRace::BrandNewAttribute, + DriverNamespaceRace::BrandNewDefault, + ] { + let repo = init_repo(); + let root = repo.path(); + let attributes = match race { + DriverNamespaceRace::KnownEmpty | DriverNamespaceRace::SelectedMissing => { + "target.txt merge=demo\n" + } + DriverNamespaceRace::BrandNewAttribute | DriverNamespaceRace::BrandNewDefault => { + "# initially safe\n" + } + }; + let patch = build_conflicting_patch(root, attributes); + if matches!(race, DriverNamespaceRace::KnownEmpty) { + configure_driver(root, "demo", ""); + } + let trace = trace_path(); + std::fs::write(&trace, "").expect("clear fixture trace"); + let watcher_trace = trace.clone(); + let watcher_root = root.to_path_buf(); + let watcher = thread::spawn(move || { + let observed = wait_for_merge_attribute_probe(&watcher_trace); + if observed { + match race { + DriverNamespaceRace::KnownEmpty | DriverNamespaceRace::SelectedMissing => { + append_driver_config(&watcher_root, "demo", NEW_DRIVER_COMMAND); + } + DriverNamespaceRace::BrandNewAttribute => { + append_driver_config(&watcher_root, "brandnew", NEW_DRIVER_COMMAND); + std::fs::write( + watcher_root.join(".gitattributes"), + "target.txt merge=brandnew\n", + ) + .expect("select brand-new merge driver"); + } + DriverNamespaceRace::BrandNewDefault => { + append_default_and_driver_config( + &watcher_root, + "brandnew", + NEW_DRIVER_COMMAND, + ); + } + } + record_trace_mutation(&watcher_trace); + } + observed + }); + + let outcome = apply_git_patch(&request(root, patch, /*revert*/ false)); + assert!(watcher.join().expect("namespace watcher"), "{race:?}"); + + assert_mutation_happened_between_probe_and_three_way(&trace); + if matches!(race, DriverNamespaceRace::KnownEmpty) { + let error = outcome.expect_err( + "an explicit empty driver is a selected namespace and must refuse when reachable", + ); + assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{error}"); + } else { + let result = outcome.expect("run isolated three-way apply"); + assert_ne!(result.exit_code, 0, "{race:?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + } + assert!(!configured_marker_exists(root, "codex.oldmergeran")); + assert!(!configured_marker_exists(root, "codex.newmergeran")); + } +} + +#[test] +fn isolated_three_way_config_scrubs_command_config_channels() { + if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() { + run_isolated_test_with_env( + "merge_driver::race_tests::isolated_three_way_config_scrubs_command_config_channels", + &[ + ("GIT_CONFIG_COUNT", OsStr::new("1")), + ("GIT_CONFIG_KEY_0", OsStr::new("merge.env-selected.driver")), + ( + "GIT_CONFIG_VALUE_0", + OsStr::new("git config --file .git/config codex.envmergeran true && false"), + ), + ( + "CODEX_APPLY_GIT_CFG", + OsStr::new( + "merge.base-selected.driver=git config --file .git/config codex.basemergeran true && false", + ), + ), + ], + ); + return; + } + + for driver in ["env-selected", "base-selected"] { + let repo = init_repo(); + let root = repo.path(); + let patch = build_conflicting_patch(root, "# initially safe\n"); + let trace = trace_path(); + std::fs::write(&trace, "").expect("clear fixture trace"); + let watcher_trace = trace.clone(); + let attributes = root.join(".gitattributes"); + let watcher = thread::spawn(move || { + let observed = wait_for_merge_attribute_probe(&watcher_trace); + if observed { + std::fs::write(attributes, format!("target.txt merge={driver}\n")) + .expect("select command-config merge driver"); + record_trace_mutation(&watcher_trace); + } + observed + }); + + let result = apply_git_patch(&request(root, patch, /*revert*/ false)) + .expect("run isolated three-way apply"); + assert!(watcher.join().expect("config-channel watcher"), "{driver}"); + + assert_mutation_happened_between_probe_and_three_way(&trace); + assert_ne!(result.exit_code, 0, "{driver}"); + assert!(!configured_marker_exists(root, "codex.envmergeran")); + assert!(!configured_marker_exists(root, "codex.basemergeran")); + } +} + +#[test] +fn isolated_three_way_config_updates_the_linked_worktree_index() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("seed.txt"), "seed\n").expect("write seed"); + run_success(root, &["add", "seed.txt"]); + run_success(root, &["commit", "-m", "seed"]); + + let linked_parent = tempfile::tempdir().expect("linked worktree parent"); + let linked_root = linked_parent.path().join("linked"); + run_success( + root, + &[ + "worktree", + "add", + "-b", + "isolated-three-way-linked", + linked_root.to_str().expect("UTF-8 linked path"), + ], + ); + let patch = build_conflicting_patch(&linked_root, "# no custom merge driver\n"); + + let result = apply_git_patch(&request(&linked_root, patch, /*revert*/ false)) + .expect("run linked-worktree three-way apply"); + + assert_ne!(result.exit_code, 0); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let unmerged = run_success(&linked_root, &["ls-files", "--unmerged", "target.txt"]); + assert!(unmerged.contains(" 1\ttarget.txt"), "{unmerged}"); + assert!(unmerged.contains(" 2\ttarget.txt"), "{unmerged}"); + assert!(unmerged.contains(" 3\ttarget.txt"), "{unmerged}"); +} + #[test] fn same_patch_attribute_activation_does_not_run_merge_driver() { let repo = init_repo(); diff --git a/codex-rs/git-utils/src/merge_driver_tests.rs b/codex-rs/git-utils/src/merge_driver_tests.rs index ba87579397..d849c643a7 100644 --- a/codex-rs/git-utils/src/merge_driver_tests.rs +++ b/codex-rs/git-utils/src/merge_driver_tests.rs @@ -23,7 +23,7 @@ fn apply_allows_unused_global_merge_driver() { let system_config = config_dir.path().join("system.gitconfig"); std::fs::write( &global_config, - "[merge \"unused\"]\n\tdriver = git config codex.mergeran true && false\n", + "[merge \"unused\"]\n\tdriver = git config --file .git/config codex.mergeran true && false\n", ) .expect("write global config"); std::fs::write(&system_config, "").expect("write system config"); @@ -71,7 +71,7 @@ fn apply_rejects_global_merge_driver_before_three_way() { let system_config = config_dir.path().join("system.gitconfig"); std::fs::write( &global_config, - "[merge \"codex-test\"]\n\tdriver = git config codex.mergeran true && false\n", + "[merge \"codex-test\"]\n\tdriver = git config --file .git/config codex.mergeran true && false\n", ) .expect("write global config"); std::fs::write(&system_config, "").expect("write system config"); @@ -135,7 +135,7 @@ fn apply_rejects_global_merge_driver_before_three_way() { assert_eq!(config_source_authorization_count(), 1); assert_eq!(merge_config_read_count(), 1); assert_eq!(merge_attribute_read_count(), 1); - assert_eq!(merge_overlay_count(), 0); + assert_eq!(merge_overlay_count(), 1); assert_eq!(error.kind(), io::ErrorKind::Unsupported); let (marker_code, _, _) = run(root, &["git", "config", "--get", "codex.mergeran"]); assert_ne!(marker_code, 0, "merge driver must not run"); @@ -148,6 +148,632 @@ fn apply_rejects_global_merge_driver_before_three_way() { assert!(status.is_empty(), "worktree/index changed: {status}"); } +#[test] +fn three_way_allows_trivial_selected_custom_path_when_peer_forces_fallback() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "clean.txt merge=codex-test\n") + .expect("write attributes"); + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "A\nB\nC\n").expect("write base"); + } + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + assert_eq!(run(root, &["git", "update-index", "--split-index"]).0, 0); + + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "A-patched\nB\nC\n").expect("write patch side"); + } + let (_, diff, diff_err) = run( + root, + &["git", "diff", "--full-index", "--", "clean.txt", "peer.txt"], + ); + assert!(diff_err.is_empty(), "create patch: {diff_err}"); + assert_eq!( + run(root, &["git", "checkout", "--", "clean.txt", "peer.txt"]).0, + 0 + ); + std::fs::write(root.join("peer.txt"), "A\nB\nC-local\n").expect("write ours"); + assert_eq!(run(root, &["git", "add", "peer.txt"]).0, 0); + assert_eq!( + run( + root, + &[ + "git", + "config", + "merge.codex-test.driver", + "git config --file .git/config codex.mergeran true && false", + ], + ) + .0, + 0 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("allow base-equals-ours custom path"); + + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert!(result.cmd_for_log.contains("--3way")); + assert_eq!( + std::fs::read_to_string(root.join("clean.txt")).expect("read clean"), + "A-patched\nB\nC\n" + ); + assert_eq!( + std::fs::read_to_string(root.join("peer.txt")).expect("read peer"), + "A-patched\nB\nC-local\n" + ); + assert_ne!( + run(root, &["git", "config", "--get", "codex.mergeran"]).0, + 0, + "custom merge driver must not run" + ); +} + +#[test] +fn three_way_allows_selected_custom_path_when_ours_equals_theirs() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "clean.txt merge=codex-test\n") + .expect("write attributes"); + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "A\nB\nC\n").expect("write base"); + } + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "A-patched\nB\nC\n").expect("write patch side"); + } + let (_, diff, _) = run( + root, + &["git", "diff", "--full-index", "--", "clean.txt", "peer.txt"], + ); + assert_eq!(run(root, &["git", "checkout", "--", "peer.txt"]).0, 0); + std::fs::write(root.join("peer.txt"), "A\nB\nC-local\n").expect("write peer ours"); + assert_eq!(run(root, &["git", "add", "clean.txt", "peer.txt"]).0, 0); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("allow ours-equals-theirs custom path"); + assert_eq!(result.exit_code, 0, "{result:?}"); + assert_eq!( + std::fs::read_to_string(root.join("clean.txt")).expect("read clean"), + "A-patched\nB\nC\n" + ); +} + +#[test] +fn three_way_allows_trivial_configured_namespaces_and_implicit_merge_values() { + for (label, attributes, config) in [ + ("implicit default", "", "[merge]\n\tdefault\n"), + ( + "unused implicit known key", + "", + "[merge \"unused\"]\n\tdriver\n", + ), + ( + "selected implicit driver", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tdriver\n", + ), + ( + "selected implicit unknown", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tunknown\n", + ), + ( + "selected name-only namespace", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tname = Demo\n", + ), + ( + "selected recursive-only namespace", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\trecursive = text\n", + ), + ( + "selected explicit empty driver", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tdriver =\n", + ), + ( + "selected dotted namespace", + "file.txt merge=dotted.name\n", + "[merge \"dotted.name\"]\n\tunknown = value\n", + ), + ( + "selected empty namespace", + "file.txt merge=\n", + "[merge \"\"]\n\tdriver = false\n", + ), + ] { + let repo = init_repo(); + let root = repo.path(); + if !attributes.is_empty() { + std::fs::write(root.join(".gitattributes"), attributes).expect("write attributes"); + } + std::fs::write(root.join("file.txt"), "base\n").expect("write base"); + assert_eq!(run(root, &["git", "add", "."]).0, 0, "{label}"); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0, "{label}"); + std::fs::write(root.join("file.txt"), "patched\n").expect("write patched"); + let (_, diff, diff_err) = run(root, &["git", "diff", "--full-index", "--", "file.txt"]); + assert!(diff_err.is_empty(), "{label}: {diff_err}"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0, "{label}"); + append_raw_merge_config(root, config); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .unwrap_or_else(|error| panic!("{label}: trivial three-way must succeed: {error}")); + assert_eq!(result.exit_code, 0, "{label}: {result:?}"); + assert!(result.cmd_for_log.contains("--3way"), "{label}"); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")).expect("read file"), + "patched\n", + "{label}" + ); + } +} + +#[test] +fn three_way_refuses_nontrivial_configured_namespaces_and_implicit_merge_values() { + for (label, attributes, config) in [ + ("implicit default", "", "[merge]\n\tdefault\n"), + ( + "unused implicit known key", + "", + "[merge \"unused\"]\n\tdriver\n", + ), + ( + "selected implicit driver", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tdriver\n", + ), + ( + "selected implicit unknown", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tunknown\n", + ), + ( + "selected name-only namespace", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tname = Demo\n", + ), + ( + "selected recursive-only namespace", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\trecursive = text\n", + ), + ( + "selected explicit empty driver", + "file.txt merge=demo\n", + "[merge \"demo\"]\n\tdriver =\n", + ), + ( + "selected dotted namespace", + "file.txt merge=dotted.name\n", + "[merge \"dotted.name\"]\n\tunknown = value\n", + ), + ( + "selected empty namespace", + "file.txt merge=\n", + "[merge \"\"]\n\tdriver = false\n", + ), + ] { + let repo = init_repo(); + let root = repo.path(); + let diff = build_three_way_fixture(root); + if !attributes.is_empty() { + std::fs::write(root.join(".gitattributes"), attributes).expect("write attributes"); + } + append_raw_merge_config(root, config); + let before_index = std::fs::read(root.join(".git/index")).expect("read index"); + + let error = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect_err("nontrivial merge policy must refuse before real mutation"); + assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{label}: {error}"); + assert_eq!( + std::fs::read(root.join(".git/index")).expect("read index after refusal"), + before_index, + "{label}: refusal changed the real index" + ); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")).expect("read ours"), + "ours\n", + "{label}: refusal changed the worktree" + ); + } +} + +#[cfg(unix)] +#[test] +fn three_way_allows_selected_custom_path_when_theirs_equals_base() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "clean.txt merge=codex-test\n") + .expect("write attributes"); + std::fs::write(root.join("clean.txt"), "base\n").expect("write clean base"); + std::fs::write(root.join("peer.txt"), "A\nB\nC\n").expect("write peer base"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + let (_, clean_oid, _) = run(root, &["git", "rev-parse", ":clean.txt"]); + std::fs::write(root.join("peer.txt"), "A-patched\nB\nC\n").expect("write peer patch"); + let (_, peer_patch, _) = run(root, &["git", "diff", "--full-index", "--", "peer.txt"]); + assert_eq!(run(root, &["git", "checkout", "--", "peer.txt"]).0, 0); + let diff = format!( + "diff --git a/clean.txt b/clean.txt\nold mode 100644\nnew mode 100755\nindex {oid}..{oid}\n{peer_patch}", + oid = clean_oid.trim() + ); + std::fs::write(root.join("clean.txt"), "ours\n").expect("write clean ours"); + std::fs::write(root.join("peer.txt"), "A\nB\nC-local\n").expect("write peer ours"); + assert_eq!(run(root, &["git", "add", "clean.txt", "peer.txt"]).0, 0); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("allow theirs-equals-base custom path"); + assert_eq!(result.exit_code, 0, "{result:?}"); + assert_eq!( + std::fs::read_to_string(root.join("clean.txt")).expect("read clean"), + "ours\n" + ); + let (_, mode, _) = run(root, &["git", "ls-files", "--stage", "--", "clean.txt"]); + assert!(mode.starts_with("100755 "), "{mode:?}"); +} + +#[test] +fn trivial_selected_custom_path_survives_noncustom_peer_conflict() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "clean.txt merge=codex-test\n") + .expect("write attributes"); + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "base\n").expect("write base"); + } + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "theirs\n").expect("write patch side"); + } + let (_, diff, _) = run( + root, + &["git", "diff", "--full-index", "--", "clean.txt", "peer.txt"], + ); + assert_eq!( + run(root, &["git", "checkout", "--", "clean.txt", "peer.txt"]).0, + 0 + ); + std::fs::write(root.join("peer.txt"), "ours\n").expect("write conflicting ours"); + assert_eq!(run(root, &["git", "add", "peer.txt"]).0, 0); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("allow proven custom path beside noncustom conflict"); + + assert_eq!(result.exit_code, 1, "{result:?}"); + assert_eq!( + std::fs::read_to_string(root.join("clean.txt")).expect("read clean"), + "theirs\n" + ); + let (_, stages, stage_err) = run(root, &["git", "ls-files", "--stage", "--", "peer.txt"]); + assert!(stage_err.is_empty(), "read conflict stages: {stage_err}"); + assert!(stages.lines().any(|line| line.contains(" 1\tpeer.txt"))); + assert!(stages.lines().any(|line| line.contains(" 2\tpeer.txt"))); + assert!(stages.lines().any(|line| line.contains(" 3\tpeer.txt"))); +} + +#[test] +fn reverse_three_way_models_staging_before_proving_trivial_custom_path() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "clean.txt merge=codex-test\n") + .expect("write attributes"); + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "A\nB\nC\n").expect("write base"); + } + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + for path in ["clean.txt", "peer.txt"] { + std::fs::write(root.join(path), "A-patched\nB\nC\n").expect("write patched"); + } + let (_, diff, _) = run( + root, + &["git", "diff", "--full-index", "--", "clean.txt", "peer.txt"], + ); + assert_eq!(run(root, &["git", "add", "clean.txt", "peer.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "patched"]).0, 0); + std::fs::write(root.join("peer.txt"), "A-patched\nB\nC-local\n").expect("write reverse ours"); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: true, + preflight: false, + }) + .expect("reverse with prospective scratch staging"); + + assert_eq!(result.exit_code, 0, "{result:?}"); + assert!(result.cmd_for_log.contains("--3way")); + assert!(result.cmd_for_log.contains("-R")); + assert_eq!( + std::fs::read_to_string(root.join("clean.txt")).expect("read clean"), + "A\nB\nC\n" + ); + assert_eq!( + std::fs::read_to_string(root.join("peer.txt")).expect("read peer"), + "A\nB\nC-local\n" + ); +} + +#[test] +fn custom_merge_driver_proof_is_consumed_before_final_spawn() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt merge=codex-test\n") + .expect("write attributes"); + std::fs::write(root.join("file.txt"), "base\n").expect("write base"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + std::fs::write(root.join("file.txt"), "patched\n").expect("write patched"); + let (_, diff, _) = run(root, &["git", "diff", "--full-index", "--", "file.txt"]); + assert_eq!(run(root, &["git", "checkout", "--", "file.txt"]).0, 0); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + + let patch_dir = tempfile::tempdir().expect("patch dir"); + let patch = patch_dir.path().join("change.patch"); + std::fs::write(&patch, diff).expect("write patch"); + let patch = patch.to_str().expect("UTF-8 patch"); + let git = GitRunner::for_cwd_io(root).expect("runner"); + let mut config = GuardedGitConfig::authorize(&git, root, Vec::new()).expect("config"); + config.freeze_apply_policy().expect("freeze apply policy"); + config + .authorize_filter_paths(&["file.txt".to_string()]) + .expect("apply filter policy"); + let (_, gate) = config + .run_apply_policy_gate(false, patch) + .expect("policy gate"); + assert!(gate.status.success()); + config + .install_three_way_merge_policy(&["file.txt".to_string()]) + .expect("merge policy"); + let scratch = config.create_three_way_scratch_storage().expect("scratch"); + config + .prove_three_way_merge_policy_safety(&scratch, false, patch) + .expect("proof"); + + let first = config + .run_three_way_apply(false, patch) + .expect("first final apply"); + assert!(first.status.success()); + let second = config + .run_three_way_apply(false, patch) + .expect_err("proof must not be reusable"); + assert_eq!(second.kind(), io::ErrorKind::PermissionDenied); +} + +#[test] +fn custom_merge_driver_proof_is_consumed_before_failed_index_revalidation() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt merge=codex-test\n") + .expect("write attributes"); + std::fs::write(root.join("file.txt"), "base\n").expect("write base"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + std::fs::write(root.join("file.txt"), "patched\n").expect("write patched"); + let (_, diff, _) = run(root, &["git", "diff", "--full-index", "--", "file.txt"]); + assert_eq!(run(root, &["git", "checkout", "--", "file.txt"]).0, 0); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + + let patch_dir = tempfile::tempdir().expect("patch dir"); + let patch = patch_dir.path().join("change.patch"); + std::fs::write(&patch, diff).expect("write patch"); + let patch = patch.to_str().expect("UTF-8 patch"); + let git = GitRunner::for_cwd_io(root).expect("runner"); + let mut config = GuardedGitConfig::authorize(&git, root, Vec::new()).expect("config"); + config.freeze_apply_policy().expect("freeze apply policy"); + config + .authorize_filter_paths(&["file.txt".to_string()]) + .expect("apply filter policy"); + let (_, gate) = config + .run_apply_policy_gate(false, patch) + .expect("policy gate"); + assert!(gate.status.success()); + config + .install_three_way_merge_policy(&["file.txt".to_string()]) + .expect("merge policy"); + let scratch = config.create_three_way_scratch_storage().expect("scratch"); + config + .prove_three_way_merge_policy_safety(&scratch, false, patch) + .expect("proof"); + + std::fs::write(root.join("file.txt"), "index-raced\n").expect("write raced index entry"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + + let first = config + .run_three_way_apply(false, patch) + .expect_err("changed live index must invalidate proof"); + assert_eq!(first.kind(), io::ErrorKind::PermissionDenied); + assert!(first.to_string().contains("index changed"), "{first}"); + + let second = config + .run_three_way_apply(false, patch) + .expect_err("failed revalidation must still consume proof"); + assert_eq!(second.kind(), io::ErrorKind::PermissionDenied); + assert!( + second.to_string().contains("unused scratch proof"), + "{second}" + ); +} + +#[test] +fn conditional_merge_config_proof_is_consumed_before_failed_index_revalidation() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("file.txt"), "base\n").expect("write base"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + std::fs::write(root.join("file.txt"), "patched\n").expect("write patched"); + let (_, diff, _) = run(root, &["git", "diff", "--full-index", "--", "file.txt"]); + assert_eq!(run(root, &["git", "checkout", "--", "file.txt"]).0, 0); + append_raw_merge_config(root, "[merge \"unused\"]\n\tdriver\n"); + + let patch_dir = tempfile::tempdir().expect("patch dir"); + let patch = patch_dir.path().join("change.patch"); + std::fs::write(&patch, diff).expect("write patch"); + let patch = patch.to_str().expect("UTF-8 patch"); + let git = GitRunner::for_cwd_io(root).expect("runner"); + let mut config = GuardedGitConfig::authorize(&git, root, Vec::new()).expect("config"); + config.freeze_apply_policy().expect("freeze apply policy"); + config + .authorize_filter_paths(&["file.txt".to_string()]) + .expect("apply filter policy"); + let (_, gate) = config + .run_apply_policy_gate(false, patch) + .expect("policy gate"); + assert!(gate.status.success()); + config + .install_three_way_merge_policy(&["file.txt".to_string()]) + .expect("merge policy"); + assert!( + config + .three_way_requires_merge_policy_proof() + .expect("proof requirement"), + "implicit known merge config must require proof without a selected namespace" + ); + let scratch = config.create_three_way_scratch_storage().expect("scratch"); + config + .prove_three_way_merge_policy_safety(&scratch, false, patch) + .expect("conditional merge-config proof"); + + std::fs::write(root.join("file.txt"), "index-raced\n").expect("write raced index entry"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + + let first = config + .run_three_way_apply(false, patch) + .expect_err("changed live index must invalidate proof"); + assert_eq!(first.kind(), io::ErrorKind::PermissionDenied); + assert!(first.to_string().contains("index changed"), "{first}"); + let second = config + .run_three_way_apply(false, patch) + .expect_err("failed revalidation must still consume proof"); + assert_eq!(second.kind(), io::ErrorKind::PermissionDenied); + assert!( + second.to_string().contains("unused scratch proof"), + "{second}" + ); +} + +#[test] +fn merge_policy_rejects_repeated_selected_custom_destination_records() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt merge=codex-test\n") + .expect("write attributes"); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + + let repeated = ["file.txt".to_string(), "file.txt".to_string()]; + let error = install_merge_policy(root, &repeated) + .expect_err("selected custom destinations must be unique patch records"); + assert_eq!(error.kind(), io::ErrorKind::Unsupported); + assert!( + error.to_string().contains("repeated patch records"), + "{error}" + ); +} + +#[test] +fn rejected_custom_merge_probe_does_not_pollute_real_object_store() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "file.txt merge=codex-test\n") + .expect("write attributes"); + std::fs::write(root.join("file.txt"), "base\n").expect("write base"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + std::fs::write(root.join("file.txt"), "uncommitted-theirs\n").expect("write theirs"); + let (_, post_oid, _) = run(root, &["git", "hash-object", "file.txt"]); + let (_, diff, _) = run(root, &["git", "diff", "--full-index", "--", "file.txt"]); + assert_eq!(run(root, &["git", "checkout", "--", "file.txt"]).0, 0); + std::fs::write(root.join("file.txt"), "ours\n").expect("write ours"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + assert_eq!( + run(root, &["git", "config", "merge.codex-test.driver", "false"]).0, + 0 + ); + assert_ne!( + run(root, &["git", "cat-file", "-e", post_oid.trim()]).0, + 0, + "fixture postimage unexpectedly already exists" + ); + + let error = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect_err("all-distinct custom merge must refuse"); + assert_eq!(error.kind(), io::ErrorKind::Unsupported); + assert_ne!( + run(root, &["git", "cat-file", "-e", post_oid.trim()]).0, + 0, + "scratch probe wrote its generated blob into the real object store" + ); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")).expect("read ours"), + "ours\n" + ); +} + #[test] fn three_way_apply_allows_unrelated_local_merge_driver() { let repo = init_repo(); @@ -173,7 +799,7 @@ fn three_way_apply_allows_unrelated_local_merge_driver() { "git", "config", "merge.unused.driver", - "git config codex.mergeran true && false", + "git config --file .git/config codex.mergeran true && false", ], ); assert_eq!( @@ -206,6 +832,895 @@ fn three_way_apply_allows_unrelated_local_merge_driver() { assert_ne!(marker_code, 0, "unused merge driver must not run"); } +#[test] +fn isolated_three_way_config_preserves_builtin_union_default() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("file.txt"), "top\nbase\nbottom\n").expect("write base"); + let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]); + assert_eq!(add_code, 0, "add base: {add_err}"); + let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "base"]); + assert_eq!(commit_code, 0, "commit base: {commit_err}"); + let (base_code, base, base_err) = run(root, &["git", "rev-parse", "HEAD"]); + assert_eq!(base_code, 0, "resolve base: {base_err}"); + + std::fs::write(root.join("file.txt"), "top\ntheirs\nbottom\n").expect("write theirs"); + let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]); + assert_eq!(add_code, 0, "add theirs: {add_err}"); + let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "theirs"]); + assert_eq!(commit_code, 0, "commit theirs: {commit_err}"); + let (diff_code, diff, diff_err) = run( + root, + &[ + "git", + "diff", + "--full-index", + base.trim(), + "HEAD", + "--", + "file.txt", + ], + ); + assert_eq!(diff_code, 0, "create full-index patch: {diff_err}"); + + let (checkout_code, _, checkout_err) = + run(root, &["git", "checkout", "-b", "ours", base.trim()]); + assert_eq!(checkout_code, 0, "checkout base: {checkout_err}"); + std::fs::write(root.join("file.txt"), "top\nours\nbottom\n").expect("write ours"); + let (commit_code, _, commit_err) = run(root, &["git", "commit", "-am", "ours"]); + assert_eq!(commit_code, 0, "commit ours: {commit_err}"); + let (config_code, _, config_err) = run(root, &["git", "config", "merge.default", "union"]); + assert_eq!(config_code, 0, "configure union default: {config_err}"); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("apply with builtin union default"); + + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let contents = std::fs::read_to_string(root.join("file.txt")) + .expect("read union merge") + .replace("\r\n", "\n"); + assert!(contents.contains("ours\n"), "{contents}"); + assert!(contents.contains("theirs\n"), "{contents}"); + assert!(!contents.contains("<<<<<<<"), "{contents}"); +} + +#[derive(Clone, Copy, Debug)] +enum MergeAttributeSource { + Info, + CoreAttributesFile, +} + +#[derive(Clone, Copy, Debug)] +enum SafeMergeAttribute { + Union, + Binary, +} + +fn configure_attribute_source( + root: &Path, + source: MergeAttributeSource, + storage: &tempfile::TempDir, + contents: &str, +) { + match source { + MergeAttributeSource::Info => { + std::fs::write(root.join(".git/info/attributes"), contents) + .expect("write info attributes"); + } + MergeAttributeSource::CoreAttributesFile => { + let attributes = storage.path().join("attributes"); + std::fs::write(&attributes, contents).expect("write core attributes"); + let configured = run( + root, + &[ + "git", + "config", + "core.attributesFile", + attributes.to_str().expect("UTF-8 attributes path"), + ], + ); + assert_eq!(configured.0, 0, "configure attributes: {}", configured.2); + } + } +} + +#[test] +fn isolated_three_way_config_projects_safe_external_merge_attributes() { + for source in [ + MergeAttributeSource::Info, + MergeAttributeSource::CoreAttributesFile, + ] { + for attribute in [SafeMergeAttribute::Union, SafeMergeAttribute::Binary] { + let repo = init_repo(); + let root = repo.path(); + let diff = build_three_way_fixture(root); + let attribute_storage = tempfile::tempdir().expect("attribute storage"); + let contents = match attribute { + SafeMergeAttribute::Union => "file.txt merge=union\n", + SafeMergeAttribute::Binary => "file.txt -merge\n", + }; + match source { + MergeAttributeSource::Info => { + std::fs::write(root.join(".git/info/attributes"), contents) + .expect("write info attributes"); + } + MergeAttributeSource::CoreAttributesFile => { + let attributes = attribute_storage.path().join("attributes"); + std::fs::write(&attributes, contents).expect("write core attributes file"); + let configured = run( + root, + &[ + "git", + "config", + "core.attributesFile", + attributes.to_str().expect("UTF-8 attributes path"), + ], + ); + assert_eq!(configured.0, 0, "configure attributes: {}", configured.2); + } + } + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run projected built-in merge"); + + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let merged = std::fs::read_to_string(root.join("file.txt")) + .expect("read merge result") + .replace("\r\n", "\n"); + match attribute { + SafeMergeAttribute::Union => { + assert_eq!(result.exit_code, 0, "{source:?}: {}", result.stderr); + assert!(merged.contains("ours\n"), "{source:?}: {merged}"); + assert!(merged.contains("theirs\n"), "{source:?}: {merged}"); + assert!(!merged.contains("<<<<<<<"), "{source:?}: {merged}"); + } + SafeMergeAttribute::Binary => { + assert_ne!(result.exit_code, 0, "{source:?}: {merged}"); + assert_eq!(merged, "ours\n", "{source:?}"); + assert!(!merged.contains("<<<<<<<"), "{source:?}: {merged}"); + } + } + } + } +} + +#[test] +fn isolated_three_way_projects_external_conversion_and_marker_attributes() { + for source in [ + MergeAttributeSource::Info, + MergeAttributeSource::CoreAttributesFile, + ] { + let repo = init_repo(); + let root = repo.path(); + let diff = build_clean_three_way_addition(root, "$Id$\n"); + let storage = tempfile::tempdir().expect("attribute storage"); + configure_attribute_source(root, source, &storage, "file.txt text eol=crlf ident\n"); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run projected conversion apply"); + + assert_eq!(result.exit_code, 0, "{source:?}: {result:#?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let worktree = std::fs::read(root.join("file.txt")).expect("read converted worktree"); + assert!( + worktree.windows(2).any(|window| window == b"\r\n"), + "{source:?}: expected CRLF bytes: {worktree:?}" + ); + let worktree = String::from_utf8(worktree).expect("UTF-8 converted worktree"); + assert!(worktree.contains("$Id: "), "{source:?}: {worktree:?}"); + let canonical = run(root, &["git", "show", ":file.txt"]); + assert_eq!(canonical.0, 0, "read canonical blob: {}", canonical.2); + assert_eq!(canonical.1, "current\nbase\n$Id$\n", "{source:?}"); + + let repo = init_repo(); + let root = repo.path(); + let diff = build_three_way_fixture(root); + let storage = tempfile::tempdir().expect("marker attribute storage"); + configure_attribute_source(root, source, &storage, "file.txt conflict-marker-size=12\n"); + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run projected marker-size apply"); + assert_ne!(result.exit_code, 0, "{source:?}: expected conflict"); + let conflict = std::fs::read_to_string(root.join("file.txt")) + .expect("read conflict") + .replace("\r\n", "\n"); + assert!( + conflict.contains("<<<<<<<<<<<< ours"), + "{source:?}: {conflict}" + ); + assert!( + conflict.contains("============\n"), + "{source:?}: {conflict}" + ); + assert!( + conflict.contains(">>>>>>>>>>>> theirs"), + "{source:?}: {conflict}" + ); + } +} + +#[test] +fn isolated_three_way_filter_reset_masks_lower_executable_selection() { + let repo = init_repo(); + let root = repo.path(); + let diff = build_clean_three_way_addition(root, "patched\n"); + std::fs::write(root.join(".gitattributes"), "file.txt filter=evil\n") + .expect("write lower filter attribute"); + std::fs::write(root.join(".git/info/attributes"), "file.txt !filter\n") + .expect("mask lower filter attribute"); + assert_eq!( + run( + root, + &[ + "git", + "config", + "filter.evil.smudge", + "git config --file .git/config codex.filterran true && cat", + ], + ) + .0, + 0 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run with masked executable filter"); + assert_eq!(result.exit_code, 0, "{result:#?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")) + .expect("read helper-free result") + .replace("\r\n", "\n"), + "current\nbase\npatched\n" + ); + assert_ne!( + run(root, &["git", "config", "--get", "codex.filterran"]).0, + 0, + "masked filter helper ran" + ); +} + +#[test] +fn linked_worktree_projects_common_info_conversion_attributes() { + let repo = init_repo(); + let primary = repo.path(); + std::fs::write(primary.join("seed.txt"), "seed\n").expect("write seed"); + assert_eq!(run(primary, &["git", "add", "seed.txt"]).0, 0); + assert_eq!(run(primary, &["git", "commit", "-m", "seed"]).0, 0); + let linked_parent = tempfile::tempdir().expect("linked worktree parent"); + let linked = linked_parent.path().join("linked"); + let added = run( + primary, + &[ + "git", + "worktree", + "add", + "-b", + "attribute-linked", + linked.to_str().expect("UTF-8 linked path"), + ], + ); + assert_eq!(added.0, 0, "add linked worktree: {}", added.2); + let diff = build_clean_three_way_addition(&linked, "patched\n"); + std::fs::write( + primary.join(".git/info/attributes"), + "file.txt text eol=crlf\n", + ) + .expect("write common info attributes"); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: linked.clone(), + diff, + revert: false, + preflight: false, + }) + .expect("run linked projected conversion apply"); + assert_eq!(result.exit_code, 0, "{result:#?}"); + let worktree = std::fs::read(linked.join("file.txt")).expect("read linked worktree"); + assert!( + worktree.windows(2).any(|window| window == b"\r\n"), + "expected projected CRLF bytes: {worktree:?}" + ); + assert_eq!( + run(&linked, &["git", "show", ":file.txt"]).1, + "current\nbase\npatched\n" + ); +} + +#[test] +fn isolated_three_way_config_preserves_direct_sha256_repository_format() { + let repo = tempfile::tempdir().expect("repo tempdir"); + let root = repo.path(); + let initialized = run(root, &["git", "init", "-q", "--object-format=sha256"]); + assert_eq!( + initialized.0, 0, + "initialize SHA-256 repo: {}", + initialized.2 + ); + assert_eq!( + run(root, &["git", "config", "user.email", "codex@example.com"]).0, + 0 + ); + assert_eq!(run(root, &["git", "config", "user.name", "Codex"]).0, 0); + let diff = build_three_way_fixture(root); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run isolated SHA-256 three-way apply"); + + assert_ne!(result.exit_code, 0, "text conflict unexpectedly merged"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let contents = std::fs::read_to_string(root.join("file.txt")) + .expect("read SHA-256 conflict") + .replace("\r\n", "\n"); + assert!(contents.contains("<<<<<<<"), "{contents}"); + let object_format = run(root, &["git", "rev-parse", "--show-object-format"]); + assert_eq!( + object_format.0, 0, + "resolve object format: {}", + object_format.2 + ); + assert_eq!(object_format.1.trim(), "sha256"); +} + +#[test] +fn isolated_three_way_config_reads_separate_common_directory() { + let fixture = tempfile::tempdir().expect("fixture"); + let root = fixture.path().join("worktree"); + let common = fixture.path().join("common.git"); + let initialized = run( + fixture.path(), + &[ + "git", + "init", + "-q", + "--separate-git-dir", + common.to_str().expect("UTF-8 common directory"), + root.to_str().expect("UTF-8 worktree"), + ], + ); + assert_eq!( + initialized.0, 0, + "initialize separate repo: {}", + initialized.2 + ); + assert_eq!( + run(&root, &["git", "config", "user.email", "codex@example.com"]).0, + 0 + ); + assert_eq!(run(&root, &["git", "config", "user.name", "Codex"]).0, 0); + let diff = build_three_way_fixture(&root); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.clone(), + diff, + revert: false, + preflight: false, + }) + .expect("run separate-common three-way apply"); + + assert_ne!(result.exit_code, 0, "text conflict unexpectedly merged"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let contents = std::fs::read_to_string(root.join("file.txt")) + .expect("read separate-common conflict") + .replace("\r\n", "\n"); + assert!(contents.contains("<<<<<<<"), "{contents}"); +} + +#[test] +fn malformed_shared_repository_refuses_before_reverse_index_staging() { + let repo = init_repo(); + let root = repo.path(); + let diff = build_three_way_fixture(root); + let index_path = root.join(".git/index"); + let before_index = std::fs::read(&index_path).expect("read index before refusal"); + let configured = run( + root, + &["git", "config", "core.sharedRepository", "not-a-permission"], + ); + assert_eq!( + configured.0, 0, + "configure malformed value: {}", + configured.2 + ); + + let error = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: true, + preflight: false, + }) + .expect_err("reject malformed shared repository policy"); + + assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error:?}"); + assert_eq!( + std::fs::read(index_path).expect("read index after refusal"), + before_index, + "reverse staging ran before shared-repository validation" + ); +} + +#[cfg(unix)] +#[test] +fn isolated_three_way_config_preserves_shared_repository_permissions() { + const TEST_NAME: &str = + "merge_driver::tests::isolated_three_way_config_preserves_shared_repository_permissions"; + if std::env::var_os("CODEX_GIT_UTILS_MERGE_ENV_CHILD").is_none() { + run_isolated_merge_test(TEST_NAME, &[]); + return; + } + + use std::os::unix::fs::PermissionsExt; + + let repo = init_repo(); + let root = repo.path(); + let diff = build_three_way_fixture(root); + std::fs::write(root.join(".git/info/attributes"), "file.txt merge=union\n") + .expect("write union attributes"); + let configured = run(root, &["git", "config", "core.sharedRepository", "0660"]); + assert_eq!( + configured.0, 0, + "configure shared repository: {}", + configured.2 + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run shared-repository three-way apply"); + assert_eq!(result.exit_code, 0, "{}", result.stderr); + + let index_mode = std::fs::metadata(root.join(".git/index")) + .expect("index metadata") + .permissions() + .mode() + & 0o777; + assert_eq!(index_mode, 0o660, "index mode {index_mode:o}"); + let stage = run(root, &["git", "ls-files", "--stage", "--", "file.txt"]); + assert_eq!(stage.0, 0, "read merged index: {}", stage.2); + let object_id = stage + .1 + .split_ascii_whitespace() + .nth(1) + .expect("merged object id"); + let object = root + .join(".git/objects") + .join(&object_id[..2]) + .join(&object_id[2..]); + let object_mode = std::fs::metadata(&object) + .expect("new merged loose object") + .permissions() + .mode() + & 0o777; + assert_eq!(object_mode, 0o440, "object mode {object_mode:o}"); +} + +#[cfg(unix)] +#[test] +fn isolated_three_way_preserves_git_init_shared_all_in_main_and_linked_worktrees() { + const TEST_NAME: &str = "merge_driver::tests::isolated_three_way_preserves_git_init_shared_all_in_main_and_linked_worktrees"; + if std::env::var_os("CODEX_GIT_UTILS_MERGE_ENV_CHILD").is_none() { + run_isolated_merge_test_with_umask_077(TEST_NAME); + return; + } + + use std::os::unix::fs::PermissionsExt; + + fn init_shared_all_repo() -> tempfile::TempDir { + let repo = tempfile::tempdir().expect("shared-all repo tempdir"); + let root = repo.path(); + let initialized = run(root, &["git", "init", "--shared=all"]); + assert_eq!( + initialized.0, 0, + "initialize shared repo: {}", + initialized.2 + ); + assert_eq!( + run(root, &["git", "config", "user.email", "codex@example.com"]).0, + 0 + ); + assert_eq!(run(root, &["git", "config", "user.name", "Codex"]).0, 0); + let configured = run(root, &["git", "config", "--get", "core.sharedRepository"]); + assert_eq!(configured.0, 0, "read shared config: {}", configured.2); + assert_eq!( + configured.1.trim(), + "2", + "Git must serialize --shared=all as 2" + ); + repo + } + + fn assert_shared_all_apply_modes(root: &Path, index: &Path, objects: &Path) { + let index_mode = std::fs::metadata(index) + .expect("index metadata") + .permissions() + .mode() + & 0o777; + assert_eq!(index_mode, 0o664, "index mode {index_mode:o}"); + + let stage = run(root, &["git", "ls-files", "--stage", "--", "file.txt"]); + assert_eq!(stage.0, 0, "read merged index: {}", stage.2); + let object_id = stage + .1 + .split_ascii_whitespace() + .nth(1) + .expect("merged object id"); + let object = objects.join(&object_id[..2]).join(&object_id[2..]); + let object_mode = std::fs::metadata(&object) + .expect("new merged loose object metadata") + .permissions() + .mode() + & 0o777; + assert_eq!(object_mode, 0o444, "object mode {object_mode:o}"); + } + + let main_repo = init_shared_all_repo(); + let main = main_repo.path(); + let patch = build_three_way_fixture(main); + std::fs::write(main.join(".git/info/attributes"), "file.txt merge=union\n") + .expect("write main union attributes"); + let result = apply_git_patch(&ApplyGitRequest { + cwd: main.to_path_buf(), + diff: patch, + revert: false, + preflight: false, + }) + .expect("run main shared-all three-way apply"); + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + assert_shared_all_apply_modes(main, &main.join(".git/index"), &main.join(".git/objects")); + + let linked_repo = init_shared_all_repo(); + let primary = linked_repo.path(); + std::fs::write(primary.join("seed.txt"), "seed\n").expect("write linked seed"); + assert_eq!(run(primary, &["git", "add", "seed.txt"]).0, 0); + assert_eq!(run(primary, &["git", "commit", "-m", "seed"]).0, 0); + let linked_parent = tempfile::tempdir().expect("linked worktree parent"); + let linked = linked_parent.path().join("linked"); + let added = run( + primary, + &[ + "git", + "worktree", + "add", + "-b", + "shared-all-linked", + linked.to_str().expect("UTF-8 linked path"), + ], + ); + assert_eq!(added.0, 0, "add linked worktree: {}", added.2); + let patch = build_three_way_fixture(&linked); + std::fs::write( + primary.join(".git/info/attributes"), + "file.txt merge=union\n", + ) + .expect("write linked union attributes"); + let result = apply_git_patch(&ApplyGitRequest { + cwd: linked.clone(), + diff: patch, + revert: false, + preflight: false, + }) + .expect("run linked shared-all three-way apply"); + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let linked_git_dir = run(&linked, &["git", "rev-parse", "--absolute-git-dir"]); + assert_eq!( + linked_git_dir.0, 0, + "resolve linked Git directory: {}", + linked_git_dir.2 + ); + assert_shared_all_apply_modes( + &linked, + &std::path::PathBuf::from(linked_git_dir.1.trim()).join("index"), + &primary.join(".git/objects"), + ); +} + +#[test] +fn isolated_three_way_add_add_conflict_preserves_markers_and_index_stages() { + let repo = init_repo(); + let root = repo.path(); + let target = root.join("conflict.txt"); + std::fs::write(&target, "existing\n").expect("write existing file"); + assert_eq!(run(root, &["git", "add", "conflict.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "existing"]).0, 0); + + let incoming = root.join("incoming.txt"); + std::fs::write(&incoming, "incoming\n").expect("write incoming file"); + let (hash_code, object_id, hash_error) = + run(root, &["git", "hash-object", "-w", "incoming.txt"]); + assert_eq!(hash_code, 0, "hash incoming blob: {hash_error}"); + std::fs::remove_file(incoming).expect("remove incoming fixture"); + let object_id = object_id.trim(); + let null_object_id = "0".repeat(object_id.len()); + let patch = format!( + "diff --git a/conflict.txt b/conflict.txt\nnew file mode 100644\nindex {null_object_id}..{object_id}\n--- /dev/null\n+++ b/conflict.txt\n@@ -0,0 +1 @@\n+incoming\n" + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: patch, + revert: false, + preflight: false, + }) + .expect("run isolated add/add three-way apply"); + + assert_ne!(result.exit_code, 0, "add/add apply unexpectedly succeeded"); + assert!( + result.cmd_for_log.contains("GIT_COMMON_DIR=") + && result.cmd_for_log.contains("--3way"), + "unexpected final command: {}", + result.cmd_for_log + ); + let contents = std::fs::read_to_string(&target).expect("read conflicted file"); + assert!( + contents.contains("<<<<<<<") + && contents.contains("=======") + && contents.contains(">>>>>>>"), + "three-way add/add apply did not leave conflict markers:\nresult: {result:#?}\ncontents:\n{contents}" + ); + let (stage_code, stages, stage_error) = + run(root, &["git", "ls-files", "--stage", "--", "conflict.txt"]); + assert_eq!(stage_code, 0, "read conflict stages: {stage_error}"); + let actual_stages = stages + .lines() + .filter_map(|line| line.split_ascii_whitespace().nth(2)) + .collect::>(); + assert_eq!(actual_stages, vec!["2", "3"], "{result:#?}"); +} + +#[test] +fn isolated_three_way_config_preserves_core_whitespace_error_classification() { + let repo = init_repo(); + let root = repo.path(); + let diff = build_clean_three_way_addition(root, "patched \n"); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", "error"]).0, + 0 + ); + assert_eq!( + run( + root, + &["git", "config", "core.whitespace", "-trailing-space"] + ) + .0, + 0 + ); + configure_unused_marker_driver(root); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run forced three-way apply with whitespace error policy"); + + assert_eq!(result.exit_code, 0, "{result:?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let contents = std::fs::read_to_string(root.join("file.txt")) + .expect("read whitespace result") + .replace("\r\n", "\n"); + assert_eq!(contents, "current\nbase\npatched \n"); + let marker = run(root, &["git", "config", "--get", "codex.mergeran"]); + assert_ne!(marker.0, 0, "unused merge driver ran"); +} + +#[test] +fn isolated_three_way_config_preserves_core_whitespace_fix_output() { + for (classifier, expected_line) in [ + ("-indent-with-non-tab", " patched\n"), + ("indent-with-non-tab", "\tpatched\n"), + ] { + let repo = init_repo(); + let root = repo.path(); + let diff = build_clean_three_way_addition(root, " patched\n"); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", "fix"]).0, + 0 + ); + assert_eq!( + run(root, &["git", "config", "core.whitespace", classifier]).0, + 0 + ); + configure_unused_marker_driver(root); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run forced three-way apply with whitespace fix policy"); + + assert_eq!(result.exit_code, 0, "{classifier}: {result:?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + let contents = std::fs::read_to_string(root.join("file.txt")) + .expect("read fixed whitespace result") + .replace("\r\n", "\n"); + assert_eq!(contents, format!("current\nbase\n{expected_line}")); + let marker = run(root, &["git", "config", "--get", "codex.mergeran"]); + assert_ne!(marker.0, 0, "unused merge driver ran for {classifier}"); + } +} + +#[test] +fn isolated_three_way_config_projects_external_whitespace_attributes() { + for source in [ + MergeAttributeSource::Info, + MergeAttributeSource::CoreAttributesFile, + ] { + // `warn`: an external unset must keep the isolated child from + // re-reading a stricter lower/default source and inventing a warning. + { + let repo = init_repo(); + let root = repo.path(); + let diff = build_clean_three_way_addition(root, "patched \n"); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", "warn"]).0, + 0 + ); + assert_eq!( + run( + root, + &["git", "config", "core.whitespace", "trailing-space"] + ) + .0, + 0 + ); + let storage = tempfile::tempdir().expect("attribute storage"); + configure_attribute_source(root, source, &storage, "file.txt -whitespace\n"); + if matches!(source, MergeAttributeSource::Info) { + std::fs::write(root.join(".gitattributes"), "file.txt whitespace\n") + .expect("write lower worktree attribute"); + } + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run projected warn apply"); + + assert_eq!(result.exit_code, 0, "{source:?}: {result:?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + assert!( + !result.stderr.contains("trailing whitespace"), + "{source:?}: {}", + result.stderr + ); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")) + .expect("read warn result") + .replace("\r\n", "\n"), + "current\nbase\npatched \n" + ); + } + + // `fix`: a string classifier must survive source removal and retain + // its exact byte-correcting behavior in the isolated child. + { + let repo = init_repo(); + let root = repo.path(); + let diff = build_clean_three_way_addition(root, " patched\n"); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", "fix"]).0, + 0 + ); + assert_eq!( + run( + root, + &["git", "config", "core.whitespace", "-indent-with-non-tab"] + ) + .0, + 0 + ); + let storage = tempfile::tempdir().expect("attribute storage"); + configure_attribute_source( + root, + source, + &storage, + "file.txt whitespace=indent-with-non-tab,tabwidth=8\n", + ); + if matches!(source, MergeAttributeSource::Info) { + std::fs::write(root.join(".gitattributes"), "file.txt -whitespace\n") + .expect("write lower worktree attribute"); + } + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run projected fix apply"); + + assert_eq!(result.exit_code, 0, "{source:?}: {result:?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + assert!( + !result.cmd_for_log.contains("--whitespace=nowarn"), + "fix must retain correction behavior: {}", + result.cmd_for_log + ); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")) + .expect("read fix result") + .replace("\r\n", "\n"), + "current\nbase\n\tpatched\n" + ); + } + + // `error`: the real-policy gate is authoritative, and the isolated + // final child cannot reclassify a gate-approved patch after staging. + { + let repo = init_repo(); + let root = repo.path(); + let diff = build_clean_three_way_addition(root, "patched \n"); + assert_eq!( + run(root, &["git", "config", "apply.whitespace", "error"]).0, + 0 + ); + let storage = tempfile::tempdir().expect("attribute storage"); + configure_attribute_source(root, source, &storage, "file.txt -whitespace\n"); + if matches!(source, MergeAttributeSource::Info) { + std::fs::write(root.join(".gitattributes"), "file.txt whitespace\n") + .expect("write lower worktree attribute"); + } + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect("run projected fatal-mode apply"); + + assert_eq!(result.exit_code, 0, "{source:?}: {result:?}"); + assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); + assert!(result.cmd_for_log.contains("--whitespace=nowarn")); + assert_eq!( + std::fs::read_to_string(root.join("file.txt")) + .expect("read error result") + .replace("\r\n", "\n"), + "current\nbase\npatched \n" + ); + } + } +} + #[test] fn apply_allows_clean_patch_with_selected_merge_driver() { let repo = init_repo(); @@ -223,7 +1738,7 @@ fn apply_allows_clean_patch_with_selected_merge_driver() { "git", "config", "merge.codex-test.driver", - "git config codex.mergeran true && false", + "git config --file .git/config codex.mergeran true && false", ], ); assert_eq!(config_code, 0, "configure merge driver: {config_err}"); @@ -275,7 +1790,7 @@ fn reverse_apply_allows_clean_patch_with_selected_merge_driver() { "git", "config", "merge.codex-test.driver", - "git config codex.mergeran true && false", + "git config --file .git/config codex.mergeran true && false", ], ); assert_eq!(config_code, 0, "configure merge driver: {config_err}"); @@ -336,7 +1851,7 @@ fn preflight_does_not_probe_or_run_selected_merge_driver() { "git", "config", "merge.codex-test.driver", - "git config codex.mergeran true && false", + "git config --file .git/config codex.mergeran true && false", ], ); assert_eq!(config_code, 0, "configure merge driver: {config_err}"); @@ -397,7 +1912,7 @@ fn merge_override_rejects_process_temp_directory_inside_worktree() { "git", "config", "merge.unused.driver", - "git config codex.mergeran true && false", + "git config --file .git/config codex.mergeran true && false", ], ); assert_eq!(config_code, 0, "configure merge driver: {config_err}"); @@ -434,9 +1949,7 @@ fn empty_name_driver_follows_effective_git_selection() { std::fs::write(root.join(".gitattributes"), "file.txt merge=\n") .expect("select empty-name driver"); - let selected_error = - install_merge_policy(root, &paths).expect_err("reject selected empty-name driver"); - assert_eq!(selected_error.kind(), io::ErrorKind::Unsupported); + install_merge_policy(root, &paths).expect("quarantine selected empty-name driver"); std::fs::write(root.join(".gitattributes"), "").expect("clear attributes"); let (default_code, _, default_err) = run(root, &["git", "config", "merge.default", ""]); @@ -444,16 +1957,16 @@ fn empty_name_driver_follows_effective_git_selection() { default_code, 0, "configure empty merge.default: {default_err}" ); - let default_error = install_merge_policy(root, &paths) - .expect_err("reject empty-name driver selected by empty default"); - assert_eq!(default_error.kind(), io::ErrorKind::Unsupported); + install_merge_policy(root, &paths) + .expect("quarantine empty-name driver selected by empty default"); let (empty_code, _, empty_err) = run(root, &["git", "config", "merge..driver", ""]); assert_eq!(empty_code, 0, "empty effective driver: {empty_err}"); - install_merge_policy(root, &paths).expect("allow selected empty command through empty default"); + install_merge_policy(root, &paths) + .expect("quarantine selected empty command through empty default"); std::fs::write(root.join(".gitattributes"), "file.txt merge=\n") .expect("select empty-name driver"); - install_merge_policy(root, &paths).expect("allow explicitly selected empty command"); + install_merge_policy(root, &paths).expect("quarantine explicitly selected empty command"); } #[test] @@ -498,11 +2011,46 @@ fn selected_driver_policy_allows_unused_global_and_rejects_selected() { .clear(); assert_eq!( untrusted_driver_selection(&entries, &selected_empty_name).expect("empty selected command"), - None + Some((String::new(), "file.txt".to_string())) ); assert_eq!( untrusted_driver_selection(&entries, &selected_by_empty_default) .expect("empty defaulted command"), + Some((String::new(), "file.txt".to_string())) + ); +} + +#[test] +fn selected_driver_policy_treats_every_configured_namespace_as_custom() { + let entries = config_entries([ + ("merge.named.name", "display name"), + ("merge.recursive.recursive", "text"), + ("merge.unknown.unrecognized", "value"), + ("merge.empty.driver", ""), + ("merge.dotted.name.recursive", "binary"), + ("merge..name", "empty subsection"), + ("merge.text.name", "shadows builtin"), + ]); + for name in [ + "named", + "recursive", + "unknown", + "empty", + "dotted.name", + "", + "text", + ] { + let attributes = BTreeMap::from([("file.txt".to_string(), name.to_string())]); + assert_eq!( + untrusted_driver_selection(&entries, &attributes).expect("namespace selection"), + Some((name.to_string(), "file.txt".to_string())), + "{name:?}" + ); + } + + let missing = BTreeMap::from([("file.txt".to_string(), "missing".to_string())]); + assert_eq!( + untrusted_driver_selection(&entries, &missing).expect("missing namespace"), None ); } @@ -588,6 +2136,16 @@ fn merge_attribute_parser_is_strict() { } } +fn append_raw_merge_config(root: &Path, config: &str) { + use std::io::Write as _; + + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(root.join(".git/config")) + .expect("open repository config"); + write!(file, "\n{config}").expect("append merge config"); +} + fn config_entries(values: [(&str, &str); N]) -> BTreeMap { values .into_iter() @@ -609,7 +2167,7 @@ fn install_merge_policy(root: &Path, paths: &[String]) -> io::Result<()> { let git = GitRunner::for_cwd_io(root)?; let mut config = GuardedGitConfig::authorize(&git, root, Vec::new())?; config.authorize_filter_paths(paths)?; - config.install_three_way_merge_policy() + config.install_three_way_merge_policy(paths) } fn build_three_way_fixture(root: &Path) -> String { @@ -642,6 +2200,32 @@ fn build_three_way_fixture(root: &Path) -> String { patch.1 } +fn build_clean_three_way_addition(root: &Path, added_line: &str) -> String { + std::fs::write(root.join("file.txt"), "base\n").expect("write base"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + std::fs::write(root.join("file.txt"), format!("base\n{added_line}")).expect("write patch side"); + let patch = run(root, &["git", "diff", "--full-index", "--", "file.txt"]); + assert_eq!(patch.0, 0, "create patch: {}", patch.2); + assert_eq!(run(root, &["git", "checkout", "--", "file.txt"]).0, 0); + std::fs::write(root.join("file.txt"), "current\nbase\n").expect("write current side"); + assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); + patch.1 +} + +fn configure_unused_marker_driver(root: &Path) { + let configured = run( + root, + &[ + "git", + "config", + "merge.unused.driver", + "git config --file .git/config codex.mergeran true && false", + ], + ); + assert_eq!(configured.0, 0, "configure unused driver: {}", configured.2); +} + fn run(cwd: &Path, args: &[&str]) -> (i32, String, String) { let mut command = std::process::Command::new(args[0]); isolate_git_command_environment(&mut command); @@ -686,6 +2270,27 @@ fn run_isolated_merge_test(test_name: &str, env: &[(&str, &OsStr)]) { ); } +#[cfg(unix)] +fn run_isolated_merge_test_with_umask_077(test_name: &str) { + let mut command = std::process::Command::new("/bin/sh"); + isolate_git_command_environment(&mut command); + command + .args(["-c", "umask 077; exec \"$@\"", "sh"]) + .arg(std::env::current_exe().expect("test binary")) + .arg(test_name) + .arg("--exact") + .arg("--nocapture") + .env("CODEX_GIT_UTILS_MERGE_ENV_CHILD", "1") + .env("RUST_TEST_THREADS", "1"); + let output = command.output().expect("run umask-isolated test process"); + 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) + ); +} + fn init_repo() -> tempfile::TempDir { let repo = tempfile::tempdir().expect("repo tempdir"); let root = repo.path(); diff --git a/codex-rs/git-utils/src/patch_paths.rs b/codex-rs/git-utils/src/patch_paths.rs index fceba6a5b3..3e86bc247d 100644 --- a/codex-rs/git-utils/src/patch_paths.rs +++ b/codex-rs/git-utils/src/patch_paths.rs @@ -2,6 +2,7 @@ use std::collections::BTreeSet; use std::io; +use std::path::Component; use std::path::Path; use std::path::PathBuf; @@ -13,6 +14,11 @@ use crate::guarded_config::GuardedGitConfig; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct PatchPathInventory { + /// Requested-orientation destination records in patch order. Unlike + /// `primary_paths`, duplicates are retained so security-sensitive merge + /// classification can reject a later record that would hide an earlier + /// low-level merge result for the same path. + pub(crate) primary_records: Vec, pub(crate) primary_paths: Vec, pub(crate) effective_paths: Vec, } @@ -34,14 +40,16 @@ pub(crate) fn extract_patch_path_inventory_guarded( "forward and reverse patch parsing returned different path counts", )); } - let primary_paths = primary_paths + let primary_records = primary_paths .into_iter() .map(validate_patch_path) - .collect::>>()?; - let opposite_paths = opposite_paths + .collect::>>()?; + let opposite_records = opposite_paths .into_iter() .map(validate_patch_path) - .collect::>>()?; + .collect::>>()?; + let primary_paths = primary_records.iter().cloned().collect::>(); + let opposite_paths = opposite_records.into_iter().collect::>(); let effective_paths = primary_paths .iter() .cloned() @@ -54,11 +62,43 @@ pub(crate) fn extract_patch_path_inventory_guarded( )); } Ok(PatchPathInventory { + primary_records, primary_paths: primary_paths.into_iter().collect(), effective_paths: effective_paths.into_iter().collect(), }) } +#[cfg(test)] +enum StagePathsHookPoint { + BindRunner = 0, + ResolvePhysicalCwd = 1, + PreSpawn = 2, +} + +#[cfg(test)] +std::thread_local! { + #[allow(clippy::type_complexity)] + static STAGE_PATHS_HOOKS: std::cell::RefCell<[Option>; 3]> = + std::cell::RefCell::new([None, None, None]); +} + +#[cfg(test)] +#[cfg_attr(not(unix), allow(dead_code))] +fn set_stage_paths_hook(point: StagePathsHookPoint, hook: impl FnOnce() + 'static) { + STAGE_PATHS_HOOKS.with(|slots| { + let prior = slots.borrow_mut()[point as usize].replace(Box::new(hook)); + assert!(prior.is_none()); + }); +} + +#[cfg(test)] +fn run_stage_paths_hook(point: StagePathsHookPoint) { + let hook = STAGE_PATHS_HOOKS.with(|slots| slots.borrow_mut()[point as usize].take()); + if let Some(hook) = hook { + hook(); + } +} + /// Extract effective patch paths through a bound operation configuration. pub(crate) fn extract_effective_paths_from_patch_guarded( config: &GuardedGitConfig<'_>, @@ -73,13 +113,9 @@ fn git_apply_numstat_paths_guarded( patch_path: &Path, revert: bool, ) -> io::Result> { - let mut command = config.apply_command()?; - command.args(["--numstat", "-z"]); - if revert { - command.arg("-R"); - } - command.arg("--").arg(patch_path); - let output = command.output()?; + #[cfg(test)] + run_stage_paths_hook(StagePathsHookPoint::PreSpawn); + let output = config.run_apply_numstat_path_inventory(revert, patch_path)?; if !output.status.success() { return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -110,10 +146,11 @@ fn extract_paths_from_patch_from_cwd(diff_text: &str, cwd: &Path) -> Vec let paths = (|| -> io::Result> { let git = GitRunner::for_cwd_io(cwd)?; let requested_cwd = std::fs::canonicalize(cwd)?; - let git_root = crate::get_git_repo_root(&requested_cwd) - .ok_or_else(|| io::Error::other("not a Git repository"))?; - let git_root = std::fs::canonicalize(git_root)?; - let config = GuardedGitConfig::authorize(&git, &git_root, Vec::new())?; + let authorized_cwd = crate::get_git_repo_root(&requested_cwd) + .map(std::fs::canonicalize) + .transpose()? + .unwrap_or(requested_cwd); + let config = GuardedGitConfig::authorize(&git, &authorized_cwd, Vec::new())?; extract_effective_paths_from_patch_guarded(&config, &patch_path, /*revert*/ false) })() .unwrap_or_default(); @@ -261,9 +298,52 @@ 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)?; - git.ensure_repository_root_route(git_root)?; - let canonical_root = std::fs::canonicalize(git_root)?; + let immutable_traversal = !git_root.is_absolute() + && git_root.components().next().is_some() + && git_root + .components() + .all(|component| matches!(component, Component::CurDir | Component::ParentDir)); + let (guarded_root, bound_git) = if git_root.is_absolute() { + (git_root.to_path_buf(), None) + } else if immutable_traversal { + let git = GitRunner::for_cwd_io(Path::new("."))?; + #[cfg(test)] + run_stage_paths_hook(StagePathsHookPoint::BindRunner); + let resolve_immutable_traversal = || -> io::Result { + let mut root = std::fs::canonicalize(Path::new("."))?; + for component in git_root.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + root.pop(); + } + _ => unreachable!("non-traversal component"), + } + } + Ok(root) + }; + let initial_root = resolve_immutable_traversal()?; + git.ensure_active_worktree_root(&initial_root)?; + #[cfg(test)] + run_stage_paths_hook(StagePathsHookPoint::ResolvePhysicalCwd); + let live_root = resolve_immutable_traversal()?; + git.ensure_active_worktree_root(&live_root)?; + (live_root, Some(git)) + } else { + (std::env::current_dir()?.join(git_root), None) + }; + if !guarded_root.is_absolute() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "repository root route could not be anchored to an absolute path", + )); + } + let git = match bound_git { + Some(git) => git, + None => GitRunner::for_cwd_io(&guarded_root)?, + }; + git.ensure_repository_root_route(&guarded_root)?; + let canonical_root = std::fs::canonicalize(&guarded_root)?; let mut config = GuardedGitConfig::authorize(&git, &canonical_root, Vec::new())?; let (tmpdir, patch_path) = write_temp_patch(diff)?; let paths = diff --git a/codex-rs/git-utils/src/patch_paths_tests.rs b/codex-rs/git-utils/src/patch_paths_tests.rs index 7f39edec53..71913f9e8a 100644 --- a/codex-rs/git-utils/src/patch_paths_tests.rs +++ b/codex-rs/git-utils/src/patch_paths_tests.rs @@ -1,9 +1,8 @@ use super::*; use crate::apply::ApplyGitRequest; use crate::apply::apply_git_patch; -use crate::apply::safe_git_config_parts; use crate::exact_staging::StagePathsResult; -use crate::exact_staging::update_index_exact_paths_from_apply; +use crate::exact_staging::prepare_index_exact_paths_for_reverse_apply; use crate::exact_staging::update_index_exact_paths_standalone; use crate::guarded_config::config_source_authorization_count; use crate::guarded_config::reset_config_source_authorization_count; @@ -84,8 +83,8 @@ fn effective_paths(diff: &str, revert: bool) -> io::Result> { } fn best_effort_paths(diff: &str) -> Vec { - let repo = init_repo(); - extract_paths_from_patch_from_cwd(diff, repo.path()) + let cwd = tempfile::tempdir().expect("non-repository cwd"); + extract_paths_from_patch_from_cwd(diff, cwd.path()) } #[cfg(unix)] @@ -234,6 +233,324 @@ fn standalone_stage_paths_rejects_a_route_crossing_a_related_worktree() { ); } +#[cfg(any(unix, windows))] +fn configure_and_commit_seed(root: &Path) { + assert_eq!(run(root, &["git", "config", "user.email", "a@b.c"]).0, 0); + assert_eq!(run(root, &["git", "config", "user.name", "Codex"]).0, 0); + commit_seed(root); +} + +#[cfg(any(unix, windows))] +fn linked_route_fixture() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) { + let fixture = tempfile::tempdir().expect("fixture"); + let common = fixture.path().join("repository.git"); + let primary = fixture.path().join("primary"); + let linked = fixture.path().join("linked"); + let nested = primary.join("nested"); + let c = common.to_string_lossy().into_owned(); + let p = primary.to_string_lossy().into_owned(); + assert_eq!(run(fixture.path(), &["git", "init", "--bare", &c]).0, 0); + let primary_add = run( + fixture.path(), + &["git", "--git-dir", &c, "worktree", "add", "--orphan", &p], + ); + assert_eq!(primary_add.0, 0, "add primary: {primary_add:?}"); + configure_and_commit_seed(&primary); + let primary_head = run(&primary, &["git", "rev-parse", "HEAD"]); + assert_eq!(primary_head.0, 0, "resolve primary HEAD: {primary_head:?}"); + let primary_head = primary_head.1.trim().to_string(); + let l = linked.to_string_lossy().into_owned(); + let linked_add = run( + fixture.path(), + &[ + "git", + "--git-dir", + &c, + "worktree", + "add", + "--detach", + &l, + &primary_head, + ], + ); + assert_eq!(linked_add.0, 0, "add linked: {linked_add:?}"); + std::fs::create_dir_all(&nested).expect("nested primary directory"); + std::fs::write(linked.join("routed.txt"), "routed\n").expect("write linked file"); + (fixture, primary, linked, nested) +} + +#[cfg(any(unix, windows))] +#[test] +fn standalone_stage_paths_rejects_relative_related_worktree_routes_from_nested_cwd() { + const TEST_NAME: &str = "patch_paths::tests::standalone_stage_paths_rejects_relative_related_worktree_routes_from_nested_cwd"; + const CWD_ALIAS_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_CWD_ALIAS"; + const INDEPENDENT_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_INDEPENDENT"; + const PRIMARY_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_PRIMARY"; + const NESTED_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_NESTED"; + + if std::env::var_os(NESTED_ENV).is_none() { + let (fixture, primary, linked, nested) = linked_route_fixture(); + let deeper = nested.join("deeper"); + let independent = primary.join("independent"); + std::fs::create_dir_all(nested.join("routes")).expect("nested primary directories"); + std::fs::create_dir_all(&deeper).expect("deeper primary directory"); + std::fs::create_dir_all(&independent).expect("independent repository directory"); + assert_eq!(run(&independent, &["git", "init", "-q"]).0, 0); + configure_and_commit_seed(&independent); + let linked_child = linked.join("child"); + std::fs::create_dir_all(&linked_child).expect("linked child directory"); + for path in [ + "absolute-parent-control.txt", + "deep-curdir-control.txt", + "deep-parent-control.txt", + "parent-control.txt", + "physical-cwd-control.txt", + "root-curdir-control.txt", + ] { + std::fs::write(primary.join(path), "control\n").expect("write control file"); + } + let _direct_route = create_dir_alias(&linked, &nested.join("linked-route")); + let _nested_route = create_dir_alias(&linked, &nested.join("routes/linked-route")); + let _direct_parent_route = + create_dir_alias(&linked_child, &nested.join("linked-child-route")); + let _nested_parent_route = + create_dir_alias(&linked_child, &nested.join("routes/linked-child-route")); + let cwd_alias = fixture.path().join("nested-cwd-route"); + let _cwd_alias = create_dir_alias(&nested, &cwd_alias); + + run_isolated_test( + TEST_NAME, + &[ + (CWD_ALIAS_ENV, cwd_alias.as_os_str()), + (INDEPENDENT_ENV, independent.as_os_str()), + (PRIMARY_ENV, primary.as_os_str()), + (NESTED_ENV, nested.as_os_str()), + ], + ); + assert!( + run(&linked, &["git", "diff", "--cached", "--name-only"]) + .1 + .is_empty(), + "relative related-worktree routes must not stage the linked index" + ); + assert_eq!( + run(&primary, &["git", "diff", "--cached", "--name-only"]).1, + "absolute-parent-control.txt\ndeep-curdir-control.txt\ndeep-parent-control.txt\nparent-control.txt\nphysical-cwd-control.txt\nroot-curdir-control.txt\n" + ); + assert!( + run(&independent, &["git", "diff", "--cached", "--name-only"]) + .1 + .is_empty(), + "parent traversal must not mutate the nested independent index" + ); + return; + } + + let primary = PathBuf::from(std::env::var_os(PRIMARY_ENV).expect("primary route")); + let nested = PathBuf::from(std::env::var_os(NESTED_ENV).expect("nested route")); + let independent = + PathBuf::from(std::env::var_os(INDEPENDENT_ENV).expect("independent repository")); + std::env::set_current_dir(&nested).expect("enter nested primary directory"); + let primary_before = git_index_bytes(&primary); + let linked = primary.parent().expect("fixture").join("linked"); + let linked_before = git_index_bytes(&linked); + for route in [ + ".", + "linked-route", + "routes/linked-route", + "linked-child-route/..", + "routes/linked-child-route/./..", + ] { + let error = stage_paths(Path::new(route), &new_file_diff("routed.txt")) + .expect_err("unsafe relative route must reject"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{route}"); + assert_eq!(git_index_bytes(&primary), primary_before, "{route}"); + assert_eq!(git_index_bytes(&linked), linked_before, "{route}"); + } + + stage_paths(Path::new(".."), &new_file_diff("parent-control.txt")) + .expect("parent-only route from nested cwd selects the active root"); + + std::env::set_current_dir(nested.join("deeper")).expect("enter deeper primary directory"); + stage_paths( + Path::new("../.."), + &new_file_diff("deep-parent-control.txt"), + ) + .expect("deeper parent-only route selects the active root"); + stage_paths( + Path::new("./.././.."), + &new_file_diff("deep-curdir-control.txt"), + ) + .expect("deeper parent and current-directory route selects the active root"); + + let cwd_alias = PathBuf::from(std::env::var_os(CWD_ALIAS_ENV).expect("cwd alias")); + std::env::set_current_dir(cwd_alias).expect("enter aliased nested cwd"); + stage_paths(Path::new(".."), &new_file_diff("physical-cwd-control.txt")) + .expect("parent traversal is based on the captured physical cwd"); + + std::env::set_current_dir(&primary).expect("enter primary worktree root"); + stage_paths(Path::new("."), &new_file_diff("root-curdir-control.txt")) + .expect("ordinary relative active-worktree route remains supported"); + + std::env::set_current_dir(&independent).expect("enter nested independent repository"); + let primary_before = git_index_bytes(&primary); + let independent_before = git_index_bytes(&independent); + let error = stage_paths(Path::new(".."), &new_file_diff("parent-control.txt")) + .expect_err("parent traversal must not escape a nested independent repository"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert_eq!(git_index_bytes(&primary), primary_before); + assert_eq!(git_index_bytes(&independent), independent_before); + stage_paths(&primary, &new_file_diff("absolute-parent-control.txt")) + .expect("explicit outer route remains supported"); + assert_eq!(git_index_bytes(&independent), independent_before); +} + +#[cfg(unix)] +#[test] +fn standalone_stage_paths_rejects_actual_cwd_reparented_into_linked_worktree() { + const TEST_NAME: &str = "patch_paths::tests::standalone_stage_paths_rejects_actual_cwd_reparented_into_linked_worktree"; + const MODE_ENV: &str = "CODEX_GIT_UTILS_REPARENTED_CWD_MODE"; + const PRIMARY_ENV: &str = "CODEX_GIT_UTILS_REPARENTED_CWD_PRIMARY"; + const NESTED_ENV: &str = "CODEX_GIT_UTILS_REPARENTED_CWD_NESTED"; + + if std::env::var_os(MODE_ENV).is_none() { + for mode in ["pathname", "aba", "reparent", "combined", "prespawn"] { + let (_fixture, primary, linked, nested) = linked_route_fixture(); + if mode == "pathname" { + std::fs::create_dir_all(linked.join("child")).expect("linked child directory"); + } + + run_isolated_test( + TEST_NAME, + &[ + (MODE_ENV, OsStr::new(mode)), + (PRIMARY_ENV, primary.as_os_str()), + (NESTED_ENV, nested.as_os_str()), + ], + ); + } + return; + } + + let mode = std::env::var(MODE_ENV).expect("reparent mode"); + let primary = PathBuf::from(std::env::var_os(PRIMARY_ENV).expect("primary route")); + let nested = PathBuf::from(std::env::var_os(NESTED_ENV).expect("nested route")); + let linked = primary.parent().expect("fixture").join("linked"); + let moved_primary = primary.parent().expect("fixture").join("primary-moved"); + std::env::set_current_dir(&nested).expect("enter nested primary directory"); + let index_path = |root: &Path| { + let output = run(root, &["git", "rev-parse", "--git-path", "index"]); + assert_eq!(output.0, 0, "resolve index path: {output:?}"); + let path = PathBuf::from(output.1.trim()); + let path = if path.is_absolute() { + path + } else { + root.join(path) + }; + std::fs::canonicalize(path).expect("canonical index path") + }; + let primary_index = index_path(&primary); + let linked_index = index_path(&linked); + let primary_before = std::fs::read(&primary_index).expect("read primary index"); + let linked_before = std::fs::read(&linked_index).expect("read linked index"); + let replacement = std::rc::Rc::new(std::cell::RefCell::new(None)); + if matches!(mode.as_str(), "combined" | "prespawn") { + let replacement_for_hook = std::rc::Rc::clone(&replacement); + let primary_for_hook = primary.clone(); + let linked_for_hook = linked; + let moved_primary_for_hook = moved_primary; + let primary_admin = PathBuf::from( + run(&primary, &["git", "rev-parse", "--absolute-git-dir"]) + .1 + .trim(), + ); + let hook = move || { + std::fs::rename(&primary_for_hook, &moved_primary_for_hook) + .expect("rename initial repository root"); + std::fs::write( + primary_admin.join("gitdir"), + format!("{}\n", moved_primary_for_hook.join(".git").display()), + ) + .expect("update moved primary worktree backlink"); + std::fs::rename( + moved_primary_for_hook.join("nested"), + linked_for_hook.join("child"), + ) + .expect("reparent actual cwd into linked worktree"); + replacement_for_hook + .borrow_mut() + .replace(create_dir_alias(&linked_for_hook, &primary_for_hook)); + }; + set_stage_paths_hook( + if mode == "combined" { + StagePathsHookPoint::BindRunner + } else { + StagePathsHookPoint::PreSpawn + }, + hook, + ); + } else if mode == "aba" { + let primary_for_hook = primary; + let linked_for_hook = linked; + let moved_primary_for_hook = moved_primary; + set_stage_paths_hook(StagePathsHookPoint::BindRunner, move || { + std::fs::rename(&primary_for_hook, &moved_primary_for_hook).expect("rename root"); + drop(create_dir_alias(&linked_for_hook, &primary_for_hook)); + std::fs::rename(&moved_primary_for_hook, &primary_for_hook).expect("restore root"); + }); + } else if mode == "reparent" { + let nested_for_hook = nested; + let linked_child_for_hook = linked.join("child"); + set_stage_paths_hook(StagePathsHookPoint::ResolvePhysicalCwd, move || { + std::fs::rename(&nested_for_hook, &linked_child_for_hook) + .expect("reparent actual cwd into linked worktree"); + }); + } else { + let replacement_for_hook = std::rc::Rc::clone(&replacement); + let nested_for_hook = nested; + let moved_nested_for_hook = primary.join("nested-moved"); + let linked_child_for_hook = linked.join("child"); + set_stage_paths_hook(StagePathsHookPoint::ResolvePhysicalCwd, move || { + std::fs::rename(&nested_for_hook, &moved_nested_for_hook) + .expect("rename actual cwd directory"); + replacement_for_hook + .borrow_mut() + .replace(create_dir_alias(&linked_child_for_hook, &nested_for_hook)); + }); + } + + let result = stage_paths(Path::new(".."), &new_file_diff("routed.txt")); + assert_eq!( + std::fs::read(primary_index).expect("reread primary index"), + primary_before + ); + assert_eq!( + std::fs::read(linked_index).expect("reread linked index"), + linked_before + ); + if matches!(mode.as_str(), "pathname" | "aba") { + result.expect("a restored or renamed pathname must remain bound to the origin repository"); + } else { + let error = result.expect_err("reparented cwd must fail closed"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + if matches!(mode.as_str(), "combined" | "prespawn") { + let expected = if mode == "combined" { + "does not match runner repository" + } else { + "changed before Git launch" + }; + let message = error.to_string(); + let accepted_earlier_route_refusal = mode == "prespawn" + && message.contains("no longer resolves within the selected worktree"); + assert!( + message.contains(expected) || accepted_earlier_route_refusal, + "{mode}: {error}" + ); + } + } + drop(replacement.borrow_mut().take()); +} + #[test] fn effective_paths_cover_supported_patch_headers() { let cases = [ @@ -300,6 +617,31 @@ fn effective_paths_cover_supported_patch_headers() { assert_eq!(nul_rename_paths, vec!["new name.txt".to_string()]); } +#[cfg(target_os = "linux")] +#[test] +fn best_effort_parser_returns_empty_for_process_relative_primary_config() { + const TEST_NAME: &str = + "patch_paths::tests::best_effort_parser_returns_empty_for_process_relative_primary_config"; + if std::env::var_os("CODEX_GIT_UTILS_PATH_ENV_CHILD").is_none() { + run_isolated_test( + TEST_NAME, + &[ + ( + "GIT_CONFIG_GLOBAL", + OsStr::new("/proc/self/cwd/codex-process-relative.gitconfig"), + ), + ("GIT_CONFIG_NOSYSTEM", OsStr::new("1")), + ], + ); + return; + } + + assert_eq!( + extract_paths_from_patch(&new_file_diff("safe.txt")), + Vec::::new() + ); +} + #[test] fn effective_paths_follow_git_for_mismatched_headers() { let mismatch = "diff --git a/safe.txt b/safe.txt\n--- a/nested/file.txt\n+++ b/nested/file.txt\n@@ -1 +1 @@\n-old\n+new\n"; @@ -700,18 +1042,117 @@ fn exact_stage(root: &Path, paths: &[&str], content_filter_paths: &[&str]) -> St .expect("run exact staging primitive") } -fn stage_effective_paths( - git: &GitRunner, - root: &Path, - paths: &[String], - legacy_config_args: &[String], -) -> io::Result<()> { - let _ = legacy_config_args; +fn stage_effective_paths(git: &GitRunner, root: &Path, paths: &[String]) -> io::Result<()> { let canonical_root = std::fs::canonicalize(root)?; let mut config = GuardedGitConfig::authorize(git, &canonical_root, Vec::new())?; stage_effective_paths_standalone(&mut config, paths) } +#[test] +fn reverse_staging_refuses_sparse_excluded_peer_before_eligible_mutation() { + let repo = init_repo(); + let root = repo.path(); + std::fs::create_dir_all(root.join("inside")).expect("create included directory"); + std::fs::create_dir_all(root.join("outside")).expect("create excluded directory"); + std::fs::write(root.join("inside/base.txt"), "inside\n").expect("write included base"); + std::fs::write(root.join("outside/base.txt"), "outside\n").expect("write excluded base"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "sparse base"]).0, 0); + assert_eq!( + run(root, &["git", "sparse-checkout", "init", "--cone"]).0, + 0 + ); + assert_eq!(run(root, &["git", "sparse-checkout", "set", "inside"]).0, 0); + std::fs::write(root.join("inside/eligible.txt"), "eligible\n").expect("write eligible path"); + std::fs::create_dir_all(root.join("outside")).expect("recreate excluded directory"); + std::fs::write(root.join("outside/base.txt"), "changed outside\n") + .expect("modify sparse-excluded tracked path"); + let paths = vec![ + "inside/eligible.txt".to_string(), + "outside/base.txt".to_string(), + ]; + let before = git_index_bytes(root); + + let git = GitRunner::for_cwd_io(root).expect("trusted Git"); + let canonical_root = std::fs::canonicalize(root).expect("canonical root"); + let mut config = + GuardedGitConfig::authorize(&git, &canonical_root, Vec::new()).expect("authorization"); + config + .authorize_filter_paths(&paths) + .expect("apply filter snapshot"); + let error = prepare_index_exact_paths_for_reverse_apply(&mut config, &paths, &paths) + .err() + .expect("sparse-excluded peer must refuse the whole reverse staging plan"); + + assert_eq!(error.kind(), io::ErrorKind::Unsupported); + assert!(error.to_string().contains("sparse-checkout"), "{error}"); + assert_eq!(git_index_bytes(root), before); + assert!( + run(root, &["git", "diff", "--cached", "--", "outside/base.txt"]) + .1 + .is_empty(), + "sparse-excluded tracked path must retain its prior index entry" + ); +} + +#[test] +fn reverse_staging_late_filter_refusal_precedes_eligible_index_mutation() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "ordinary.txt filter=fresh\n") + .expect("write attributes"); + std::fs::write(root.join("ordinary.txt"), "base\n").expect("write ordinary base"); + std::fs::write(root.join("peer.txt"), "base\n").expect("write peer base"); + assert_eq!( + run( + root, + &["git", "add", ".gitattributes", "ordinary.txt", "peer.txt"] + ) + .0, + 0 + ); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + std::fs::write(root.join("ordinary.txt"), "changed\n").expect("modify ordinary path"); + std::fs::write(root.join("peer.txt"), "changed\n").expect("modify peer path"); + let paths = vec!["ordinary.txt".to_string(), "peer.txt".to_string()]; + + let git = GitRunner::for_cwd_io(root).expect("trusted Git"); + let canonical_root = std::fs::canonicalize(root).expect("canonical root"); + reset_filter_policy_counts(); + let mut config = + GuardedGitConfig::authorize(&git, &canonical_root, Vec::new()).expect("authorization"); + config + .authorize_filter_paths(&paths) + .expect("initial apply filter snapshot"); + assert_eq!( + run( + root, + &[ + "git", + "config", + "filter.fresh.clean", + "git config codex.stage-filter-ran true && git hash-object --stdin", + ], + ) + .0, + 0 + ); + let before = git_index_bytes(root); + + let error = prepare_index_exact_paths_for_reverse_apply(&mut config, &paths, &paths) + .err() + .expect("fresh selected filter must refuse before staging eligible paths"); + assert_eq!(error.kind(), io::ErrorKind::Unsupported); + assert!(error.to_string().contains("filter"), "{error}"); + assert_eq!(filter_policy_read_count(), 2); + assert_eq!(git_index_bytes(root), before); + assert_ne!( + run(root, &["git", "config", "--get", "codex.stage-filter-ran"]).0, + 0, + "refused filter helper must not execute" + ); +} + #[test] fn standalone_stage_paths_uses_one_source_authorization_and_one_filter_read() { if std::env::var_os("CODEX_GIT_UTILS_PATH_ENV_CHILD").is_none() { @@ -744,7 +1185,7 @@ fn standalone_stage_paths_uses_one_source_authorization_and_one_filter_read() { } #[test] -fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() { +fn reverse_staging_freshly_observes_a_new_clean_driver_and_attribute() { if std::env::var_os("CODEX_GIT_UTILS_PATH_ENV_CHILD").is_none() { let config_dir = tempfile::tempdir().expect("config tempdir"); let global_config = config_dir.path().join("global.gitconfig"); @@ -752,7 +1193,7 @@ fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() { std::fs::write(&global_config, "").expect("empty global config"); std::fs::write(&system_config, "").expect("empty system config"); run_isolated_test( - "patch_paths::tests::composed_staging_freshly_observes_a_new_clean_driver_and_attribute", + "patch_paths::tests::reverse_staging_freshly_observes_a_new_clean_driver_and_attribute", &[ ("GIT_CONFIG_GLOBAL", global_config.as_os_str()), ("GIT_CONFIG_SYSTEM", system_config.as_os_str()), @@ -794,12 +1235,13 @@ fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() { std::fs::write(root.join(".gitattributes"), "file.txt filter=fresh\n") .expect("select fresh filter"); - let error = update_index_exact_paths_from_apply( + let error = prepare_index_exact_paths_for_reverse_apply( &mut config, &["file.txt".to_string()], &["file.txt".to_string()], ) - .expect_err("fresh clean driver must refuse"); + .err() + .expect("fresh clean driver must refuse"); assert_eq!(error.kind(), io::ErrorKind::Unsupported); assert_eq!(config_source_authorization_count(), 1); assert_eq!(filter_policy_read_count(), 2); @@ -812,7 +1254,7 @@ fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() { } #[test] -fn composed_staging_required_read_ignores_the_apply_overlay_and_is_fresh() { +fn reverse_staging_required_read_ignores_the_apply_overlay_and_is_fresh() { let repo = init_repo(); let root = repo.path(); std::fs::write(root.join("file.txt"), "base\n").expect("write base file"); @@ -850,12 +1292,13 @@ fn composed_staging_required_read_ignores_the_apply_overlay_and_is_fresh() { 0 ); - let error = update_index_exact_paths_from_apply( + let error = prepare_index_exact_paths_for_reverse_apply( &mut config, &["file.txt".to_string()], &["file.txt".to_string()], ) - .expect_err("fresh required=true must refuse"); + .err() + .expect("fresh required=true must refuse"); assert_eq!(error.kind(), io::ErrorKind::Unsupported); assert_eq!(config_source_authorization_count(), 1); assert_eq!(filter_policy_read_count(), 2); @@ -868,7 +1311,7 @@ fn composed_staging_required_read_ignores_the_apply_overlay_and_is_fresh() { } #[test] -fn composed_exact_staging_refuses_requested_and_mapped_paths_outside_apply_universe() { +fn reverse_exact_staging_refuses_requested_and_mapped_paths_outside_apply_universe() { let requested_repo = init_repo(); let requested_root = requested_repo.path(); let requested_git = GitRunner::for_cwd_io(requested_root).expect("trusted Git"); @@ -881,12 +1324,13 @@ fn composed_exact_staging_refuses_requested_and_mapped_paths_outside_apply_unive requested_config .authorize_filter_paths(&["allowed.txt".to_string()]) .expect("apply snapshot"); - let requested_error = update_index_exact_paths_from_apply( + let requested_error = prepare_index_exact_paths_for_reverse_apply( &mut requested_config, &["allowed.txt".to_string(), "outside.txt".to_string()], &["outside.txt".to_string()], ) - .expect_err("requested off-universe path must refuse"); + .err() + .expect("requested off-universe path must refuse"); assert_eq!(requested_error.kind(), io::ErrorKind::PermissionDenied); let mapped_repo = init_repo(); @@ -909,17 +1353,18 @@ fn composed_exact_staging_refuses_requested_and_mapped_paths_outside_apply_unive mapped_config .authorize_filter_paths(&["file.txt".to_string()]) .expect("narrow apply snapshot"); - let mapped_error = update_index_exact_paths_from_apply( + let mapped_error = prepare_index_exact_paths_for_reverse_apply( &mut mapped_config, &["File.txt".to_string(), "file.txt".to_string()], &["file.txt".to_string()], ) - .expect_err("mapped off-universe path must refuse"); + .err() + .expect("mapped off-universe path must refuse"); assert_eq!(mapped_error.kind(), io::ErrorKind::PermissionDenied); } #[test] -fn composed_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty() { +fn reverse_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty() { let repo = init_repo(); let root = repo.path(); let git = GitRunner::for_cwd_io(root).expect("trusted Git"); @@ -927,8 +1372,9 @@ fn composed_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty() let mut zero = GuardedGitConfig::authorize(&git, &canonical_root, Vec::new()).expect("authorization"); - let error = update_index_exact_paths_from_apply(&mut zero, &[], &[]) - .expect_err("zero snapshots must refuse"); + let error = prepare_index_exact_paths_for_reverse_apply(&mut zero, &[], &[]) + .err() + .expect("zero snapshots must refuse"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); let mut two = @@ -936,8 +1382,9 @@ fn composed_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty() two.authorize_filter_paths(&[]).expect("apply snapshot"); two.authorize_git_add_filter_paths(&[]) .expect("Git-add snapshot"); - let error = update_index_exact_paths_from_apply(&mut two, &[], &[]) - .expect_err("two snapshots must refuse"); + let error = prepare_index_exact_paths_for_reverse_apply(&mut two, &[], &[]) + .err() + .expect("two snapshots must refuse"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); } @@ -1287,7 +1734,6 @@ fn ignored_untracked_path_returns_nonzero_without_partial_staging() { &git, root, &["ignored.txt".to_string(), "ordinary.txt".to_string()], - &safe_git_config_parts(), ) .expect("public staging remains best effort for ignored paths"); assert!( @@ -1410,13 +1856,8 @@ fn exact_staging_refuses_skip_and_assume_unchanged_without_mutation() { assert_eq!(git_index_bytes(root), before); let git = GitRunner::for_cwd_io(root).expect("trusted Git"); - stage_effective_paths( - &git, - root, - &["existing.txt".to_string()], - &safe_git_config_parts(), - ) - .expect("public staging remains best effort for skip-worktree paths"); + stage_effective_paths(&git, root, &["existing.txt".to_string()]) + .expect("public staging remains best effort for skip-worktree paths"); assert_eq!(git_index_bytes(root), before); assert_eq!( @@ -2148,13 +2589,8 @@ fn staging_rejects_global_lfs_filter_without_running_it() { std::env::var_os("CODEX_GIT_UTILS_TARGET_REPO").expect("target repository"), ); let git = GitRunner::for_cwd_io(&root).expect("trusted Git"); - let error = stage_effective_paths( - &git, - &root, - &["file.txt".to_string()], - &safe_git_config_parts(), - ) - .expect_err("reject global Git LFS filter"); + let error = stage_effective_paths(&git, &root, &["file.txt".to_string()]) + .expect_err("reject global Git LFS filter"); assert_eq!(error.kind(), io::ErrorKind::Unsupported); return; } @@ -2219,25 +2655,15 @@ fn staging_rejects_selected_process_but_allows_smudge_only_filter() { let process_repo = init_repo_with_selected_filter("filter.selected.process"); let process_root = process_repo.path(); let process_git = GitRunner::for_cwd_io(process_root).expect("trusted Git"); - let error = stage_effective_paths( - &process_git, - process_root, - &["file.txt".to_string()], - &safe_git_config_parts(), - ) - .expect_err("reject selected process filter"); + let error = stage_effective_paths(&process_git, process_root, &["file.txt".to_string()]) + .expect_err("reject selected process filter"); assert_eq!(error.kind(), io::ErrorKind::Unsupported); let smudge_repo = init_repo_with_selected_filter("filter.selected.smudge"); let smudge_root = smudge_repo.path(); let smudge_git = GitRunner::for_cwd_io(smudge_root).expect("trusted Git"); - stage_effective_paths( - &smudge_git, - smudge_root, - &["file.txt".to_string()], - &safe_git_config_parts(), - ) - .expect("smudge-only filters do not run during staging"); + stage_effective_paths(&smudge_git, smudge_root, &["file.txt".to_string()]) + .expect("smudge-only filters do not run during staging"); let (code, staged, stderr) = run(smudge_root, &["git", "diff", "--cached", "--name-only"]); assert_eq!(code, 0, "read staged paths: {stderr}"); assert_eq!(staged, "file.txt\n"); @@ -2279,13 +2705,8 @@ fn staging_neutralizes_off_path_racy_filters_without_changing_their_index_entry( std::fs::write(guarded_root.join("target.txt"), "new target\n") .expect("modify guarded target"); let git = GitRunner::for_cwd_io(guarded_root).expect("trusted Git"); - stage_effective_paths( - &git, - guarded_root, - &["target.txt".to_string()], - &safe_git_config_parts(), - ) - .expect("stage with off-path filters neutralized"); + stage_effective_paths(&git, guarded_root, &["target.txt".to_string()]) + .expect("stage with off-path filters neutralized"); assert!( !guarded.marker.exists(), @@ -2331,8 +2752,7 @@ fn staging_allows_selected_symlink_while_neutralizing_off_path_filters() { let outside_before = index_entry(root, "outside.txt"); let git = GitRunner::for_cwd_io(root).expect("trusted Git"); - stage_effective_paths(&git, root, &["link".to_string()], &safe_git_config_parts()) - .expect("stage selected symlink"); + stage_effective_paths(&git, root, &["link".to_string()]).expect("stage selected symlink"); assert!( !fixture.marker.exists(), @@ -2400,12 +2820,7 @@ fn staging_allows_optional_smudge_only_but_refuses_required_or_malformed_smudge( .expect("modify selected target"); let before = git_index_bytes(root); let git = GitRunner::for_cwd_io(root).expect("trusted Git"); - let result = stage_effective_paths( - &git, - root, - &["selected.txt".to_string()], - &safe_git_config_parts(), - ); + let result = stage_effective_paths(&git, root, &["selected.txt".to_string()]); assert!( !fixture.marker.exists(), @@ -2472,13 +2887,8 @@ fn optional_smudge_target_does_not_mask_a_later_clean_target() { let before = git_index_bytes(root); let git = GitRunner::for_cwd_io(root).expect("trusted Git"); - let error = stage_effective_paths( - &git, - root, - &["a.txt".to_string(), "z.txt".to_string()], - &safe_git_config_parts(), - ) - .expect_err("reject the selected clean target after optional smudge"); + let error = stage_effective_paths(&git, root, &["a.txt".to_string(), "z.txt".to_string()]) + .expect_err("reject the selected clean target after optional smudge"); assert_eq!(error.kind(), io::ErrorKind::Unsupported); assert_eq!(git_index_bytes(root), before); } @@ -2521,7 +2931,6 @@ fn staging_filter_probe_uses_only_existing_non_directory_leaves() { "deleted.txt".to_string(), "kept.txt".to_string(), ], - &safe_git_config_parts(), ) .expect("probe only the surviving staging leaf"); @@ -2565,7 +2974,6 @@ fn staging_skips_filter_probe_when_no_leaf_will_be_staged() { &git, root, &["missing.txt".to_string(), "deleted.txt".to_string()], - &safe_git_config_parts(), ) .expect("skip staging when every effective leaf is absent"); diff --git a/codex-rs/git-utils/src/path_authority.rs b/codex-rs/git-utils/src/path_authority.rs index c27f9e698c..39e9fe29db 100644 --- a/codex-rs/git-utils/src/path_authority.rs +++ b/codex-rs/git-utils/src/path_authority.rs @@ -16,6 +16,7 @@ use route_walker::RouteObservationSnapshot; #[cfg(windows)] use route_walker::invalid_data; use route_walker::observe_route; +use route_walker::route_contains_process_relative_procfs_path; #[cfg(any(windows, test))] pub(crate) use windows_path::windows_authority_path_is_ambiguous; #[cfg(any(windows, test))] @@ -64,6 +65,13 @@ impl RepositoryRouteBoundaries { &self.metadata_identities, )? != CandidateBoundary::Outside) } + + pub(crate) fn route_contains_process_relative_procfs_path( + &self, + route: &Path, + ) -> io::Result { + route_contains_process_relative_procfs_path(route) + } } pub(crate) fn repository_route_boundaries( diff --git a/codex-rs/git-utils/src/path_authority/route_walker.rs b/codex-rs/git-utils/src/path_authority/route_walker.rs index 12f14df273..b1d883f06e 100644 --- a/codex-rs/git-utils/src/path_authority/route_walker.rs +++ b/codex-rs/git-utils/src/path_authority/route_walker.rs @@ -107,6 +107,82 @@ fn symlink_route_hops(path: &Path) -> io::Result> { Ok(hops) } +/// Detect Linux procfs routes whose target can differ in a later Git process. +/// +/// Existing procfs-hosted symlinks are process-dependent, and missing procfs +/// descendants can materialize when the Git child's PID or descriptors exist. +pub(super) fn route_contains_process_relative_procfs_path(path: &Path) -> io::Result { + #[cfg(target_os = "linux")] + { + let hops = symlink_route_hops(path)?; + for hop in &hops { + if symlink_is_on_procfs(&hop.entry)? { + return Ok(true); + } + } + if missing_descendant_is_below_procfs(path)? { + return Ok(true); + } + for hop in hops { + if missing_descendant_is_below_procfs(&hop.target)? + || missing_descendant_is_below_procfs(&hop.projected)? + { + return Ok(true); + } + } + } + #[cfg(not(target_os = "linux"))] + let _ = path; + Ok(false) +} + +#[cfg(target_os = "linux")] +fn symlink_is_on_procfs(path: &Path) -> io::Result { + filesystem_is_procfs( + path, + rustix::fs::OFlags::PATH | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, + ) +} + +#[cfg(target_os = "linux")] +fn missing_descendant_is_below_procfs(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(_) => return Ok(false), + Err(error) if is_missing_path_error(&error) => {} + Err(error) => return Err(error), + } + for ancestor in path.ancestors().skip(1) { + match std::fs::symlink_metadata(ancestor) { + Ok(_) => match filesystem_is_procfs( + ancestor, + rustix::fs::OFlags::PATH | rustix::fs::OFlags::CLOEXEC, + ) { + Ok(is_procfs) => return Ok(is_procfs), + Err(error) if is_missing_path_error(&error) => {} + Err(error) => return Err(error), + }, + Err(error) if is_missing_path_error(&error) => {} + Err(error) => return Err(error), + } + } + Err(invalid_data("authority path has no existing ancestor")) +} + +#[cfg(target_os = "linux")] +fn filesystem_is_procfs(path: &Path, flags: rustix::fs::OFlags) -> io::Result { + let fd = rustix::fs::open(path, flags, rustix::fs::Mode::empty()).map_err(io::Error::from)?; + let filesystem = rustix::fs::fstatfs(&fd).map_err(io::Error::from)?; + Ok(filesystem.f_type == rustix::fs::PROC_SUPER_MAGIC) +} + +#[cfg(target_os = "linux")] +fn is_missing_path_error(error: &io::Error) -> bool { + matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) +} + fn collect_symlink_route_hops( path: &Path, depth: usize, 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 index 1b7604d93a..6ff3e68b18 100644 --- a/codex-rs/git-utils/src/path_authority/route_walker_tests.rs +++ b/codex-rs/git-utils/src/path_authority/route_walker_tests.rs @@ -1,6 +1,12 @@ use pretty_assertions::assert_eq; +#[cfg(target_os = "linux")] +use std::path::Path; +#[cfg(target_os = "linux")] +use std::path::PathBuf; use super::read_link_if_symlink; +#[cfg(target_os = "linux")] +use super::route_contains_process_relative_procfs_path; #[test] fn ordinary_paths_are_not_treated_as_failed_symlink_reads() { @@ -16,3 +22,59 @@ fn ordinary_paths_are_not_treated_as_failed_symlink_reads() { ); assert_eq!(read_link_if_symlink(&file).expect("ordinary file"), None); } + +#[cfg(target_os = "linux")] +#[test] +fn process_relative_procfs_detection_follows_aliases_without_rejecting_ordinary_paths() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().expect("fixture"); + let external = fixture.path().join("external"); + let ordinary_alias = fixture.path().join("ordinary-alias"); + let procfs_alias = fixture.path().join("procfs-alias"); + let procfs_root_alias = fixture.path().join("procfs-root-alias"); + let chained_alias = fixture.path().join("chained-alias"); + let literal = fixture.path().join("proc/self/cwd/config"); + std::fs::create_dir_all(&external).expect("external directory"); + std::fs::create_dir_all(literal.parent().expect("literal parent")) + .expect("literal directories"); + std::fs::write(&literal, "[safe]\n").expect("literal config"); + symlink(&external, &ordinary_alias).expect("ordinary alias"); + symlink("/proc/self/cwd", &procfs_alias).expect("procfs alias"); + symlink("/proc", &procfs_root_alias).expect("procfs root alias"); + symlink("procfs-alias", &chained_alias).expect("chained alias"); + + let mut procfs_paths = vec![ + PathBuf::from("/proc/self/cwd/missing-config"), + PathBuf::from("/proc/thread-self/cwd/missing-config"), + PathBuf::from("/proc/self/fd/1048575/missing-config"), + PathBuf::from("/proc/self/exe"), + PathBuf::from(format!("/proc/{}/cwd/missing-config", std::process::id())), + PathBuf::from("/proc/4294967295/cwd/missing-config"), + procfs_alias.join("missing-config"), + procfs_root_alias.join("4294967295/cwd/missing-config"), + chained_alias.join("missing-config"), + ]; + if Path::new("/dev/fd").exists() { + procfs_paths.push(PathBuf::from("/dev/fd/1048575/missing-config")); + } + for path in procfs_paths { + assert!( + route_contains_process_relative_procfs_path(&path).expect("inspect procfs route"), + "expected process-relative procfs route in {}", + path.display() + ); + } + + for path in [ + PathBuf::from("/proc/version"), + ordinary_alias.join("missing-config"), + literal, + ] { + assert!( + !route_contains_process_relative_procfs_path(&path).expect("inspect ordinary route"), + "unexpected process-relative procfs route in {}", + path.display() + ); + } +} diff --git a/codex-rs/git-utils/src/repository_authority/authority.rs b/codex-rs/git-utils/src/repository_authority/authority.rs index ff00ccafe9..0877f93cd3 100644 --- a/codex-rs/git-utils/src/repository_authority/authority.rs +++ b/codex-rs/git-utils/src/repository_authority/authority.rs @@ -2,6 +2,8 @@ use std::io; use std::path::Path; use std::path::PathBuf; +use same_file::Handle; + use crate::errors::GitReadError; use crate::git_config::path_is_within; use crate::path_authority::RepositoryRouteBoundaries; @@ -25,11 +27,37 @@ use super::resolve_repository_metadata; mod policy; +fn open_active_worktree_identity(path: &Path) -> io::Result { + #[cfg(windows)] + { + use std::fs::OpenOptions; + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ; + use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE; + + // Deliberately omit FILE_SHARE_DELETE so the repository root cannot + // be renamed or replaced between validation and the guarded child. + let directory = OpenOptions::new() + .read(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) + .open(path)?; + Handle::from_file(directory) + } + + #[cfg(not(windows))] + { + Handle::from_path(path) + } +} + /// Repository and filesystem authority retained for the lifetime of one /// trusted Git runner. #[derive(Debug)] pub(crate) struct RepositoryAuthority { active_worktree_root: PathBuf, + active_worktree_identity: Option, roots: Vec, worktree_roots: Vec, common_dirs: Vec, @@ -58,8 +86,11 @@ impl RepositoryAuthority { 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 active_worktree_identity = open_active_worktree_identity(&worktree_root) + .map_err(|error| invalid_metadata(&worktree_root, error))?; let mut authority = Self { active_worktree_root: worktree_root.clone(), + active_worktree_identity: Some(active_worktree_identity), roots: Vec::new(), worktree_roots: Vec::new(), common_dirs: Vec::new(), @@ -123,6 +154,7 @@ impl RepositoryAuthority { } pub(crate) fn revalidate_active_repository_metadata(&self) -> io::Result<()> { + self.revalidate_active_worktree_identity()?; let Some(expected) = &self.active_metadata else { return Ok(()); }; @@ -148,11 +180,15 @@ impl RepositoryAuthority { pub(crate) fn ensure_active_worktree_root(&self, root: &Path) -> io::Result<()> { let canonical_root = std::fs::canonicalize(root)?; - let same_root = canonical_root == self.active_worktree_root - || same_file::is_same_file(&canonical_root, &self.active_worktree_root)?; + let same_root = if let Some(expected) = &self.active_worktree_identity { + Handle::from_path(&canonical_root)? == *expected + } else { + canonical_root == self.active_worktree_root + || same_file::is_same_file(&canonical_root, &self.active_worktree_root)? + }; if !same_root { return Err(authority_refusal(format!( - "guarded Git repository root {} does not match runner repository {}", + "guarded Git repository identity {} does not match runner repository {}", canonical_root.display(), self.active_worktree_root.display() ))); @@ -160,6 +196,23 @@ impl RepositoryAuthority { Ok(()) } + fn revalidate_active_worktree_identity(&self) -> io::Result<()> { + let Some(expected) = &self.active_worktree_identity else { + return Ok(()); + }; + let actual = Handle::from_path(&self.active_worktree_root).map_err(|error| { + authority_refusal(format!( + "guarded Git repository identity could not be revalidated: {error}" + )) + })?; + if &actual != expected { + return Err(authority_refusal( + "guarded Git repository identity changed before Git launch", + )); + } + Ok(()) + } + #[cfg(test)] pub(crate) fn from_test_locations( roots: Vec, @@ -168,12 +221,15 @@ impl RepositoryAuthority { ) -> Result { let route_boundaries = repository_route_boundaries(&worktree_roots, &common_dirs) .map_err(|error| invalid_metadata(Path::new(""), error))?; + let active_worktree_root = worktree_roots + .first() + .or_else(|| roots.first()) + .cloned() + .unwrap_or_default(); + let active_worktree_identity = open_active_worktree_identity(&active_worktree_root).ok(); Ok(Self { - active_worktree_root: worktree_roots - .first() - .or_else(|| roots.first()) - .cloned() - .unwrap_or_default(), + active_worktree_root, + active_worktree_identity, roots, worktree_roots, common_dirs, @@ -185,13 +241,18 @@ impl RepositoryAuthority { }) } - #[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()) } + pub(crate) fn active_common_dir(&self) -> Option<&Path> { + self.active_metadata + .as_ref() + .map(|metadata| metadata.common_dir.as_path()) + } + #[cfg(test)] pub(crate) fn contains_root(&self, root: &Path) -> bool { self.roots diff --git a/codex-rs/git-utils/src/repository_authority/authority/policy.rs b/codex-rs/git-utils/src/repository_authority/authority/policy.rs index 6995d06c93..b35c452a6a 100644 --- a/codex-rs/git-utils/src/repository_authority/authority/policy.rs +++ b/codex-rs/git-utils/src/repository_authority/authority/policy.rs @@ -70,6 +70,12 @@ impl RepositoryAuthority { if !path.is_absolute() { return Err(worktree_controlled_config_source(path, description)); } + if self + .route_boundaries + .route_contains_process_relative_procfs_path(path)? + { + return Err(process_relative_config_source(path, description)); + } let inspection = self.route_boundaries.inspect_route(path)?; if inspection.crosses_worktree { return Err(worktree_controlled_config_source(path, description)); @@ -204,3 +210,10 @@ fn worktree_controlled_config_source(path: &Path, description: &str) -> io::Erro path.display() )) } + +fn process_relative_config_source(path: &Path, description: &str) -> io::Error { + authority_refusal(format!( + "refusing to use process-relative {description}: {}", + path.display() + )) +} diff --git a/codex-rs/git-utils/src/repository_authority/plain_config.rs b/codex-rs/git-utils/src/repository_authority/plain_config.rs index b3a4253b77..1464ac9095 100644 --- a/codex-rs/git-utils/src/repository_authority/plain_config.rs +++ b/codex-rs/git-utils/src/repository_authority/plain_config.rs @@ -4,6 +4,7 @@ use std::path::PathBuf; use super::bytes_to_path; use super::read_bounded_file; +use crate::git_config::parse_git_boolean; #[derive(Debug, Eq, PartialEq)] pub(crate) enum CommonConfigAuthority { @@ -50,7 +51,7 @@ pub(crate) fn inspect_plain_common_config_authority( return Ok(CommonConfigAuthority::Unproven); } let bare = match unique_explicit_value(&config, "core", "bare") { - Ok(Some(value)) => match explicit_boolean(value.as_ref()) { + Ok(Some(value)) => match parse_git_boolean(value.as_ref()) { Some(value) => Some(value), None => return Ok(CommonConfigAuthority::Unproven), }, @@ -58,7 +59,7 @@ pub(crate) fn inspect_plain_common_config_authority( Err(()) => return Ok(CommonConfigAuthority::Unproven), }; match unique_explicit_value(&config, "extensions", "worktreeConfig") { - Ok(Some(value)) if explicit_boolean(value.as_ref()) == Some(false) => {} + Ok(Some(value)) if parse_git_boolean(value.as_ref()) == Some(false) => {} Ok(None) => {} Ok(Some(_)) | Err(()) => return Ok(CommonConfigAuthority::Unproven), } @@ -99,39 +100,29 @@ fn unique_explicit_value( let Some(sections) = config.sections_by_name(section_name) else { return Ok(None); }; - let mut occurrences = 0usize; - let mut explicit_values = Vec::new(); + let mut occurrence = None; 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()), - ); + for name in section.value_names() { + let name: &str = name.as_ref(); + if !name.eq_ignore_ascii_case(value_name) { + continue; + } + if occurrence.is_some() { + return Err(()); + } + let value = section + .value_implicit(name) + .ok_or(())? + .map(|value| value.as_ref().to_vec()); + occurrence = Some(value); + } } - 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 + match occurrence { + None => Ok(None), + Some(Some(value)) => Ok(Some(value)), + Some(None) => Err(()), } } diff --git a/codex-rs/git-utils/src/repository_authority_tests.rs b/codex-rs/git-utils/src/repository_authority_tests.rs index 0447fa0d82..9f07340939 100644 --- a/codex-rs/git-utils/src/repository_authority_tests.rs +++ b/codex-rs/git-utils/src/repository_authority_tests.rs @@ -81,6 +81,36 @@ fn plain_common_bare_parser_matches_native_boolean_syntax_and_is_stricter_on_dup CommonConfigAuthority::Bare, Some(true), ), + ( + "yes", + b"[core]\n\tbare = yes\n".as_slice(), + CommonConfigAuthority::Bare, + Some(true), + ), + ( + "on", + b"[core]\n\tbare = on\n".as_slice(), + CommonConfigAuthority::Bare, + Some(true), + ), + ( + "numeric true", + b"[core]\n\tbare = 1\n".as_slice(), + CommonConfigAuthority::Bare, + Some(true), + ), + ( + "hex true", + b"[core]\n\tbare = 0x1\n".as_slice(), + CommonConfigAuthority::Bare, + Some(true), + ), + ( + "suffixed true", + b"[core]\n\tbare = 1k\n".as_slice(), + CommonConfigAuthority::Bare, + Some(true), + ), ( "false", b"[core]\n\tbare = false\n".as_slice(), @@ -133,13 +163,13 @@ fn plain_common_bare_parser_matches_native_boolean_syntax_and_is_stricter_on_dup } #[test] -fn common_bare_proof_accepts_only_explicit_boolean_literals() { +fn common_bare_proof_rejects_invalid_git_boolean_values() { 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()), + ( + "negative leading zero", + b"[core]\n\tbare = -08\n".as_slice(), + ), ( "positive overflow", b"[core]\n\tbare = 2147483648\n".as_slice(), @@ -152,6 +182,8 @@ fn common_bare_proof_accepts_only_explicit_boolean_literals() { "i64 max", b"[core]\n\tbare = 9223372036854775807\n".as_slice(), ), + ("suffix overflow", b"[core]\n\tbare = 2g\n".as_slice()), + ("trailing junk", b"[core]\n\tbare = 1foo\n".as_slice()), ] { let common = write_common_config(body); assert_eq!( @@ -162,6 +194,34 @@ fn common_bare_proof_accepts_only_explicit_boolean_literals() { } } +#[test] +fn common_bare_proof_accepts_explicit_false_worktree_config_spellings() { + for value in ["false", "no", "off", "", "0", "-0", "+0", "00", "0x0"] { + let common = write_common_config( + format!("[core]\n\tbare = yes\n[extensions]\n\tworktreeConfig = {value}\n").as_bytes(), + ); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect(value), + CommonConfigAuthority::Bare, + "authority result for worktreeConfig={value:?}" + ); + } +} + +#[test] +fn common_bare_proof_rejects_explicit_true_worktree_config_spellings() { + for value in ["true", "yes", "on", "1", "-1", "0x1", "1k"] { + let common = write_common_config( + format!("[core]\n\tbare = yes\n[extensions]\n\tworktreeConfig = {value}\n").as_bytes(), + ); + assert_eq!( + inspect_plain_common_config_authority(common.path()).expect(value), + CommonConfigAuthority::Unproven, + "authority result for worktreeConfig={value:?}" + ); + } +} + #[test] fn common_bare_proof_rejects_includes_worktree_config_and_relative_worktree() { let include_target = tempfile::NamedTempFile::new().expect("included config"); @@ -226,6 +286,25 @@ fn common_config_absolute_worktree_is_returned_as_authority() { ); } +#[test] +fn common_config_false_bare_spellings_allow_absolute_worktree() { + let worktree = tempfile::tempdir().expect("worktree"); + for bare in ["false", "no", "off", "", "0", "-0", "+0", "00", "0x0"] { + 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(bare), + CommonConfigAuthority::Worktree(worktree.path().to_path_buf()), + "authority result for core.bare={bare:?}" + ); + } +} + #[test] fn common_config_rejects_contradictory_or_malformed_bare_with_absolute_worktree() { let worktree = tempfile::tempdir().expect("worktree"); diff --git a/codex-rs/git-utils/src/reverse_apply_tests.rs b/codex-rs/git-utils/src/reverse_apply_tests.rs index c700a6b803..21852c3ed3 100644 --- a/codex-rs/git-utils/src/reverse_apply_tests.rs +++ b/codex-rs/git-utils/src/reverse_apply_tests.rs @@ -92,6 +92,52 @@ fn request(root: &Path, patch: &str) -> ApplyGitRequest { } } +#[test] +fn reverse_preflight_refuses_the_same_divergent_staged_blob_without_mutation() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("file.txt"), b"old\n").expect("base file"); + run_success(root, &["add", "file.txt"]); + run_success(root, &["commit", "-qm", "base"]); + std::fs::write(root.join("file.txt"), b"staged\n").expect("staged file"); + run_success(root, &["add", "file.txt"]); + std::fs::write(root.join("file.txt"), b"new\n").expect("reverse worktree"); + let patch = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new\n"; + let index_before = std::fs::read(root.join(".git/index")).expect("read index"); + let worktree_before = std::fs::read(root.join("file.txt")).expect("read worktree"); + + let mut preflight = request(root, patch); + preflight.preflight = true; + let preflight_error = apply_git_patch(&preflight).expect_err("preflight must refuse"); + assert_eq!(preflight_error.kind(), io::ErrorKind::PermissionDenied); + assert!( + preflight_error + .to_string() + .contains("would replace existing staged data"), + "{preflight_error}" + ); + assert_eq!( + std::fs::read(root.join(".git/index")).expect("index after preflight"), + index_before + ); + assert_eq!( + std::fs::read(root.join("file.txt")).expect("worktree after preflight"), + worktree_before + ); + + let apply_error = apply_git_patch(&request(root, patch)).expect_err("apply must refuse"); + assert_eq!(apply_error.kind(), io::ErrorKind::PermissionDenied); + assert_eq!(apply_error.to_string(), preflight_error.to_string()); + assert_eq!( + std::fs::read(root.join(".git/index")).expect("index after apply"), + index_before + ); + assert_eq!( + std::fs::read(root.join("file.txt")).expect("worktree after apply"), + worktree_before + ); +} + fn topology_fixture(topology: Topology) -> (tempfile::TempDir, String) { let repo = init_repo(); let root = repo.path(); @@ -158,6 +204,8 @@ fn assert_refused_without_mutation(root: &Path, patch: &str) { let before_leaves = [ leaf_snapshot(root, "old.txt"), leaf_snapshot(root, "new.txt"), + leaf_snapshot(root, "file.txt"), + leaf_snapshot(root, "other.txt"), ]; let error = apply_git_patch(&request(root, patch)).expect_err("unsafe reverse must fail"); assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); @@ -165,7 +213,9 @@ fn assert_refused_without_mutation(root: &Path, patch: &str) { assert_eq!( [ leaf_snapshot(root, "old.txt"), - leaf_snapshot(root, "new.txt") + leaf_snapshot(root, "new.txt"), + leaf_snapshot(root, "file.txt"), + leaf_snapshot(root, "other.txt") ], before_leaves ); @@ -195,6 +245,65 @@ fn reverse_delete_and_rename_preserve_divergent_staged_blobs() { } } +#[test] +fn reverse_three_way_refuses_staged_content_change_matching_the_worktree() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("file.txt"), b"top\nbase\nbottom\n").expect("base file"); + run_success(root, &["add", "file.txt"]); + run_success(root, &["commit", "-qm", "base"]); + let base = String::from_utf8(run_success(root, &["rev-parse", "HEAD"])).expect("base OID"); + std::fs::write(root.join("file.txt"), b"top\ntheirs\nbottom\n").expect("theirs file"); + run_success(root, &["add", "file.txt"]); + run_success(root, &["commit", "-qm", "theirs"]); + let patch = String::from_utf8(run_success( + root, + &[ + "diff", + "--full-index", + base.trim(), + "HEAD", + "--", + "file.txt", + ], + )) + .expect("patch"); + std::fs::write(root.join("file.txt"), b"top\nuser-staged\nbottom\n").expect("user staged file"); + run_success(root, &["add", "file.txt"]); + + assert_refused_without_mutation(root, &patch); +} + +#[test] +fn reverse_three_way_refuses_staged_non_candidate_before_staging_another_path() { + let repo = init_repo(); + let root = repo.path(); + for path in ["file.txt", "other.txt"] { + std::fs::write(root.join(path), b"top\nbase\nbottom\n").expect("base file"); + } + run_success(root, &["add", "."]); + run_success(root, &["commit", "-qm", "base"]); + let base = String::from_utf8(run_success(root, &["rev-parse", "HEAD"])).expect("base OID"); + for path in ["file.txt", "other.txt"] { + std::fs::write(root.join(path), b"top\ntheirs\nbottom\n").expect("theirs file"); + } + run_success(root, &["add", "."]); + run_success(root, &["commit", "-qm", "theirs"]); + let patch = String::from_utf8(run_success( + root, + &["diff", "--full-index", base.trim(), "HEAD"], + )) + .expect("patch"); + + std::fs::write(root.join("file.txt"), b"top\nuser-staged\nbottom\n") + .expect("staged non-candidate"); + run_success(root, &["add", "file.txt"]); + std::fs::write(root.join("other.txt"), b"top\nunstaged\nbottom\n") + .expect("unstaged staging candidate"); + + assert_refused_without_mutation(root, &patch); +} + #[test] fn reverse_rename_accepts_each_partially_staged_form() { for staged_endpoints in ["old", "new", "both"] { @@ -470,6 +579,47 @@ fn reverse_refuses_ignored_untracked_rename_endpoint_without_mutation() { ); } +#[test] +fn reverse_refuses_ignored_endpoint_before_staging_eligible_peer() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join("old.txt"), b"old\n").unwrap(); + std::fs::write(root.join("other.txt"), b"old\n").unwrap(); + run_success(root, &["add", "old.txt", "other.txt"]); + run_success(root, &["commit", "-qm", "base"]); + run_success(root, &["mv", "old.txt", "new.txt"]); + std::fs::write(root.join("other.txt"), b"new\n").unwrap(); + run_success(root, &["add", "other.txt"]); + let patch = String::from_utf8(run_success( + root, + &["diff", "--cached", "--full-index", "--binary", "-M"], + )) + .unwrap(); + run_success(root, &["reset", "--hard", "-q", "HEAD"]); + + std::fs::write(root.join(".gitignore"), b"new.txt\n").unwrap(); + std::fs::rename(root.join("old.txt"), root.join("new.txt")).unwrap(); + std::fs::write(root.join("other.txt"), b"new\n").unwrap(); + + let before_index = index_snapshot(root); + let before_leaves = [ + leaf_snapshot(root, "old.txt"), + leaf_snapshot(root, "new.txt"), + leaf_snapshot(root, "other.txt"), + ]; + let error = apply_git_patch(&request(root, &patch)).expect_err("ignored endpoint"); + assert!(error.to_string().contains("ignored"), "{error}"); + assert_eq!(index_snapshot(root), before_index); + assert_eq!( + [ + leaf_snapshot(root, "old.txt"), + leaf_snapshot(root, "new.txt"), + leaf_snapshot(root, "other.txt") + ], + before_leaves + ); +} + #[test] fn reverse_handles_unborn_empty_index_and_refuses_unborn_index_state() { const DELETE_PATCH: &str = "diff --git a/old.txt b/old.txt\ndeleted file mode 100644\n--- a/old.txt\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n"; diff --git a/codex-rs/git-utils/src/reverse_staging.rs b/codex-rs/git-utils/src/reverse_staging.rs index c82d07eb87..0d0418ff56 100644 --- a/codex-rs/git-utils/src/reverse_staging.rs +++ b/codex-rs/git-utils/src/reverse_staging.rs @@ -4,16 +4,52 @@ use std::collections::BTreeMap; use std::collections::BTreeSet; use std::io; -use crate::exact_staging::update_index_exact_paths_from_apply; +use crate::exact_staging::PreparedReverseIndexUpdate; +use crate::exact_staging::execute_prepared_reverse_index_update; +use crate::exact_staging::prepare_index_exact_paths_for_reverse_apply; +use crate::git_command::IsolatedGitStorage; use crate::guarded_config::GuardedGitConfig; +use crate::guarded_config::GuardedOperationIdentity; use crate::patch_paths::confine_patch_paths_guarded; use crate::patch_paths::leaf_is_traversable_directory; use crate::patch_paths::leaf_may_run_git_content_filter; -pub(crate) fn stage_effective_paths_for_reverse( - config: &mut GuardedGitConfig<'_>, +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ReverseApplyMode { + Direct, + ThreeWay, +} + +pub(crate) struct ReverseStagingPlan { + staging_candidates: Vec, + content_filter_paths: Vec, +} + +pub(crate) struct SealedReverseStagingPlan { + owner: GuardedOperationIdentity, + update: PreparedReverseIndexUpdate, + scratch_use_available: bool, +} + +/// Validate every reverse-staging precondition without changing the index. +/// +/// Preflight uses the same plan builder as the real operation so an +/// applicability-only `git apply --check -R` cannot report success when +/// preparing the index would overwrite staged data. +pub(crate) fn validate_effective_paths_for_reverse( + config: &GuardedGitConfig<'_>, paths: &[String], + mode: ReverseApplyMode, ) -> io::Result<()> { + let _ = prepare_reverse_staging_plan(config, paths, mode)?; + Ok(()) +} + +pub(crate) fn prepare_reverse_staging_plan( + config: &GuardedGitConfig<'_>, + paths: &[String], + mode: ReverseApplyMode, +) -> io::Result { let confined = confine_patch_paths_guarded(config, paths)?; let mut worktree_paths = BTreeMap::new(); for path in confined.into_exact_leaves()? { @@ -82,6 +118,15 @@ pub(crate) fn stage_effective_paths_for_reverse( "refusing to stage reverse patch path {path:?} because it has intent-to-add index state" ))); } + if mode == ReverseApplyMode::ThreeWay + && let Some(path) = exact_paths + .iter() + .find(|path| cached_visible_status.contains_key(*path)) + { + return Err(reverse_staging_error(format!( + "refusing a three-way reverse patch because it would replace existing staged data for {path:?}" + ))); + } let worktree_changed_paths = read_changed_paths(config, &exact_paths)?; let mut staging_candidates = Vec::new(); @@ -101,7 +146,10 @@ pub(crate) fn stage_effective_paths_for_reverse( } } if staging_candidates.is_empty() { - return Ok(()); + return Ok(ReverseStagingPlan { + staging_candidates, + content_filter_paths: Vec::new(), + }); } if let Some(path) = staging_candidates @@ -122,8 +170,54 @@ pub(crate) fn stage_effective_paths_for_reverse( }) .cloned() .collect::>(); - let result = - update_index_exact_paths_from_apply(config, &staging_candidates, &content_filter_paths)?; + Ok(ReverseStagingPlan { + staging_candidates, + content_filter_paths, + }) +} + +pub(crate) fn execute_reverse_staging_plan_in_scratch( + config: &GuardedGitConfig<'_>, + plan: &mut SealedReverseStagingPlan, + storage: &IsolatedGitStorage, +) -> io::Result<()> { + config.ensure_operation_identity(&plan.owner)?; + if !std::mem::replace(&mut plan.scratch_use_available, false) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "sealed reverse staging plan scratch use was already consumed", + )); + } + let result = execute_prepared_reverse_index_update(config, &plan.update, Some(storage))?; + reverse_staging_result(result) +} + +pub(crate) fn seal_reverse_staging_plan( + config: &mut GuardedGitConfig<'_>, + plan: ReverseStagingPlan, +) -> io::Result { + let update = prepare_index_exact_paths_for_reverse_apply( + config, + &plan.staging_candidates, + &plan.content_filter_paths, + )?; + Ok(SealedReverseStagingPlan { + owner: config.operation_identity(), + update, + scratch_use_available: true, + }) +} + +pub(crate) fn execute_reverse_staging_plan( + config: &GuardedGitConfig<'_>, + plan: SealedReverseStagingPlan, +) -> io::Result<()> { + config.ensure_operation_identity(&plan.owner)?; + let result = execute_prepared_reverse_index_update(config, &plan.update, None)?; + reverse_staging_result(result) +} + +fn reverse_staging_result(result: crate::exact_staging::StagePathsResult) -> io::Result<()> { if result.exit_code == 0 { Ok(()) } else { diff --git a/codex-rs/git-utils/src/safe_git.rs b/codex-rs/git-utils/src/safe_git.rs index e999252790..12bcfc7bf2 100644 --- a/codex-rs/git-utils/src/safe_git.rs +++ b/codex-rs/git-utils/src/safe_git.rs @@ -469,6 +469,25 @@ pub(crate) fn executable_filter_drivers( Ok(ExecutableFilterDrivers(executable_drivers)) } +/// Status must also inspect required-only namespaces. A selected +/// `filter..required=true` with no clean/process command makes native +/// status fail closed, so silently resetting it would turn an unavailable +/// result into a potentially misleading Boolean. +pub(crate) fn status_policy_filter_drivers( + entries: &BTreeMap, +) -> io::Result { + let mut drivers = executable_filter_drivers(entries)?.0; + for entry in entries.values() { + let Some(remainder) = entry.key.strip_prefix("filter.") else { + return Err(invalid_filter_output("malformed filter config key")); + }; + if let Some(driver) = remainder.strip_suffix(".required") { + drivers.insert(driver.to_string()); + } + } + Ok(ExecutableFilterDrivers(drivers)) +} + fn effective_filter_value<'a>( entries: &'a BTreeMap, driver: &str, diff --git a/codex-rs/git-utils/src/safe_git_tests.rs b/codex-rs/git-utils/src/safe_git_tests.rs index 66639bdc2d..03bcf7af6f 100644 --- a/codex-rs/git-utils/src/safe_git_tests.rs +++ b/codex-rs/git-utils/src/safe_git_tests.rs @@ -670,6 +670,19 @@ async fn get_has_changes_rejects_configured_clean_filter_without_running_it() { assert!(!configured_filter_ran(&repo_path).await); } +#[tokio::test] +async fn get_has_changes_pins_normal_untracked_files_over_repository_config() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo_path = create_test_git_repo(&temp_dir).await; + run_git_async(&repo_path, &["config", "status.showUntrackedFiles", "no"]).await; + std::fs::write(repo_path.join("untracked.txt"), "untracked\n").expect("write untracked file"); + + assert_eq!( + try_get_has_changes_with_test_timeout(&repo_path).await, + Ok(true) + ); +} + #[tokio::test] async fn get_has_changes_distinguishes_filter_sentinels_from_literal_driver_names() { for (driver, sentinel_attribute) in diff --git a/codex-rs/git-utils/src/status_guard.rs b/codex-rs/git-utils/src/status_guard.rs index a80cb3958f..06a29259cf 100644 --- a/codex-rs/git-utils/src/status_guard.rs +++ b/codex-rs/git-utils/src/status_guard.rs @@ -62,7 +62,12 @@ pub(crate) async fn read_status(config: &GuardedGitConfig<'_>) -> Result GitReadError { diff --git a/codex-rs/git-utils/src/status_guard_tests.rs b/codex-rs/git-utils/src/status_guard_tests.rs index 602cb9904a..a99405ee2c 100644 --- a/codex-rs/git-utils/src/status_guard_tests.rs +++ b/codex-rs/git-utils/src/status_guard_tests.rs @@ -26,6 +26,23 @@ async fn run_git(cwd: &Path, args: &[&str]) -> std::process::Output { output } +async fn run_git_without_attr_source(cwd: &Path, args: &[&str]) -> std::process::Output { + let output = Command::new("git") + .env_remove("GIT_ATTR_SOURCE") + .args(args) + .current_dir(cwd) + .output() + .await + .expect("run Git without GIT_ATTR_SOURCE"); + assert!( + output.status.success(), + "git {args:?} without GIT_ATTR_SOURCE 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"); @@ -100,6 +117,76 @@ fn run_isolated_config_test(test_name: &str) { ); } +fn run_isolated_environment_test( + test_name: &str, + marker: &str, + variables: &[(&str, &str)], + global_attributes: Option<&str>, +) { + let environment = tempfile::tempdir().expect("isolated Git environment"); + let global_config = environment.path().join("global.gitconfig"); + let system_config = environment.path().join("system.gitconfig"); + let home = environment.path().join("home"); + let xdg = environment.path().join("xdg"); + std::fs::create_dir_all(xdg.join("git")).expect("create isolated XDG Git directory"); + std::fs::create_dir_all(&home).expect("create isolated HOME"); + std::fs::write(&global_config, "").expect("empty global config"); + std::fs::write(&system_config, "").expect("empty system config"); + if let Some(contents) = global_attributes { + std::fs::write(xdg.join("git/attributes"), contents) + .expect("write isolated global attributes"); + } + + 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(marker, "1") + .env("GIT_CONFIG_GLOBAL", &global_config) + .env("GIT_CONFIG_SYSTEM", &system_config) + .env("GIT_CONFIG_NOSYSTEM", "0") + .env("GIT_CONFIG_COUNT", "0") + .env("GIT_ATTR_NOSYSTEM", "0") + .env("HOME", &home) + .env("XDG_CONFIG_HOME", &xdg) + .env_remove("GIT_CONFIG_PARAMETERS") + .env("RUST_TEST_THREADS", "1"); + for (name, value) in variables { + command.env(name, value); + } + let output = command.output().expect("run isolated test process"); + 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) + ); +} + +async fn guarded_status(repo: &Path, git: &GitRunner) -> Result { + let mut guard = prepare_status_config(git, repo).await?; + detect_status_fsmonitor(&mut guard).await; + read_status(&guard).await +} + +async fn replacement_fixture(repo: &Path) -> (String, String) { + let original = String::from_utf8(run_git(repo, &["rev-parse", "HEAD"]).await.stdout) + .expect("original commit UTF-8") + .trim() + .to_string(); + std::fs::write(repo.join("test.txt"), "replacement\n").expect("write replacement contents"); + run_git(repo, &["add", "test.txt"]).await; + run_git(repo, &["commit", "-m", "replacement commit"]).await; + let replacement = String::from_utf8(run_git(repo, &["rev-parse", "HEAD"]).await.stdout) + .expect("replacement commit UTF-8") + .trim() + .to_string(); + run_git(repo, &["checkout", "--detach", &original]).await; + (original, replacement) +} + #[test] fn io_error_mapping_preserves_authority_provenance() { for error in [ @@ -129,6 +216,27 @@ fn io_error_mapping_preserves_authority_provenance() { ); } +#[cfg(target_os = "linux")] +#[tokio::test] +async fn process_relative_config_policy_maps_to_authority_refusal() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + let error = git + .ensure_config_source_is_not_worktree_controlled( + Path::new("/proc/self/cwd/config"), + "Git config include", + ) + .expect_err("process-relative config must be refused"); + + assert_eq!( + map_io_error("statusFilterPreparation", error), + GitReadError::AuthorityRefused { + operation: "statusFilterPreparation".to_string(), + } + ); +} + #[tokio::test] async fn dropping_status_preparation_kills_the_active_git_child() { let temp_dir = tempfile::tempdir().expect("create temp dir"); @@ -238,6 +346,375 @@ async fn prepared_guard_neutralizes_filter_selected_after_the_probe() { assert!(!filter_marker_is_set(&repo, "codex.race-ran").await); } +#[tokio::test] +async fn frozen_status_blocks_a_new_filter_namespace_and_attribute_after_preparation() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + let mut guard = prepare_status_config(&git, &repo) + .await + .expect("prepare zero-driver status guard"); + + run_git( + &repo, + &[ + "config", + "filter.fresh.clean", + "git config codex.fresh-ran true && git hash-object --stdin", + ], + ) + .await; + std::fs::write(repo.join(".gitattributes"), "test.txt filter=fresh\n") + .expect("select new filter namespace after preparation"); + std::fs::write(repo.join("test.txt"), "changed\n").expect("modify tracked path"); + + detect_status_fsmonitor(&mut guard).await; + assert_eq!(read_status(&guard).await, Ok(true)); + assert!(!filter_marker_is_set(&repo, "codex.fresh-ran").await); +} + +#[tokio::test] +async fn frozen_status_preserves_info_global_core_and_system_attribute_selection() { + const MARKER: &str = "CODEX_GIT_UTILS_STATUS_ATTRIBUTE_ENV_CHILD"; + if std::env::var_os(MARKER).is_none() { + run_isolated_environment_test( + "status_guard::tests::frozen_status_preserves_info_global_core_and_system_attribute_selection", + MARKER, + &[], + Some("global.txt ident\n"), + ); + return; + } + + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + let core_attributes = temp_dir.path().join("core.attributes"); + std::fs::write(&core_attributes, "core.txt ident\n").expect("write core attributes file"); + std::fs::write(repo.join(".git/info/attributes"), "info.txt ident\n") + .expect("write info attributes"); + for name in ["global.txt", "core.txt", "info.txt", "literal.txt"] { + std::fs::write(repo.join(name), "$Id$\n").expect("write source-parity fixture"); + } + run_git(&repo, &["add", "."]).await; + run_git(&repo, &["commit", "-m", "attribute source fixtures"]).await; + for name in ["global.txt", "info.txt"] { + std::fs::remove_file(repo.join(name)).expect("remove source-parity fixture"); + run_git(&repo, &["checkout", "--", name]).await; + assert!( + std::fs::read_to_string(repo.join(name)) + .expect("read expanded ident fixture") + .starts_with("$Id: "), + "{name} did not select its attribute source" + ); + } + let stock = run_git(&repo, &["status", "--porcelain"]).await; + assert!( + stock.stdout.is_empty(), + "global/info source-parity fixture must be clean under stock Git: {}", + String::from_utf8_lossy(&stock.stdout), + ); + + 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|%s|%s|%s\\n' \"${{GIT_ATTR_NOSYSTEM-unset}}\" \"${{HOME-unset}}\" \"${{XDG_CONFIG_HOME-unset}}\" \"$*\" >>{}\nexec {real_git} \"$@\"\n", + shell_quote(&log), + ), + ); + let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner"); + let mut global_info_guard = prepare_status_config(&git, &repo) + .await + .expect("prepare global/info source-parity guard"); + detect_status_fsmonitor(&mut global_info_guard).await; + let global_info_output = global_info_guard + .status_output_async() + .await + .expect("run global/info source-parity status"); + assert!(global_info_output.status.success()); + assert!( + global_info_output.stdout.is_empty(), + "isolated global/info source parity diverged: {}", + String::from_utf8_lossy(&global_info_output.stdout) + ); + assert!(!global_info_guard.status_has_untracked_snapshot().expect("untracked snapshot")); + + let home = std::env::var("HOME").expect("isolated HOME"); + let xdg = std::env::var("XDG_CONFIG_HOME").expect("isolated XDG config home"); + let log_contents = + std::fs::read_to_string(&log).expect("read attribute environment log"); + let final_status = log_contents + .lines() + .find(|line| line.contains(" status --porcelain")) + .expect("final status environment"); + assert!( + final_status.starts_with(&format!("0|{home}|{xdg}|")), + "captured system/global attribute selectors were not restored: {final_status}" + ); + + run_git(&repo, &["config", "core.attributesFile", "../core.attributes"]).await; + std::fs::remove_file(repo.join("global.txt")).expect("remove global attribute fixture"); + run_git(&repo, &["checkout", "--", "global.txt"]).await; + std::fs::remove_file(repo.join("core.txt")).expect("remove core attribute fixture"); + run_git(&repo, &["checkout", "--", "core.txt"]).await; + assert!( + std::fs::read_to_string(repo.join("core.txt")) + .expect("read expanded core ident fixture") + .starts_with("$Id: "), + "relative core.attributesFile did not select ident" + ); + let stock = run_git(&repo, &["status", "--porcelain"]).await; + assert!( + stock.stdout.is_empty(), + "core.attributesFile fixture must be clean under stock Git: {}", + String::from_utf8_lossy(&stock.stdout) + ); + let mut core_guard = prepare_status_config(&git, &repo) + .await + .expect("prepare core.attributesFile source-parity guard"); + detect_status_fsmonitor(&mut core_guard).await; + let core_output = core_guard + .status_output_async() + .await + .expect("run core.attributesFile source-parity status"); + assert!(core_output.status.success()); + assert!( + core_output.stdout.is_empty(), + "isolated core.attributesFile source parity diverged: {}", + String::from_utf8_lossy(&core_output.stdout) + ); + assert!(!core_guard.status_has_untracked_snapshot().expect("untracked snapshot")); + + std::fs::write( + repo.join(".git/info/attributes"), + "info.txt ident\nliteral.txt ident=set\n", + ) + .expect("write literal sentinel info attribute"); + std::fs::write(repo.join("literal.txt"), "$Id: fake $\n") + .expect("write literal-sentinel ident fixture"); + assert_eq!( + guarded_status(&repo, &git).await, + Ok(true), + "literal ident=set must not be reserialized as special Set" + ); +} + +#[tokio::test] +async fn frozen_status_refuses_git_attr_source_and_attr_tree() { + const MARKER: &str = "CODEX_GIT_UTILS_STATUS_ATTR_SOURCE_CHILD"; + if std::env::var_os(MARKER).is_some() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = temp_dir.path().join("repo"); + std::fs::create_dir(&repo).expect("create repository"); + run_git_without_attr_source(&repo, &["init", "-q"]).await; + run_git_without_attr_source(&repo, &["config", "user.name", "Test User"]).await; + run_git_without_attr_source(&repo, &["config", "user.email", "test@example.com"]).await; + std::fs::write(repo.join("test.txt"), "contents\n").expect("write tracked file"); + run_git_without_attr_source(&repo, &["add", "test.txt"]).await; + run_git_without_attr_source(&repo, &["commit", "-m", "seed"]).await; + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + assert!( + prepare_status_config(&git, &repo).await.is_err(), + "GIT_ATTR_SOURCE must make frozen Status unavailable" + ); + return; + } + + run_isolated_environment_test( + "status_guard::tests::frozen_status_refuses_git_attr_source_and_attr_tree", + MARKER, + &[("GIT_ATTR_SOURCE", "HEAD")], + None, + ); + + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + run_git(&repo, &["config", "attr.tree", "HEAD"]).await; + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + assert!( + prepare_status_config(&git, &repo).await.is_err(), + "attr.tree must make frozen Status unavailable" + ); +} + +#[tokio::test] +async fn frozen_untracked_presence_honors_all_standard_ignore_sources() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + std::fs::write(repo.join(".gitignore"), "root-ignored.txt\n") + .expect("write root ignore"); + run_git(&repo, &["add", ".gitignore"]).await; + run_git(&repo, &["commit", "-m", "ignore rules"]).await; + std::fs::write(repo.join(".git/info/exclude"), "info-ignored.txt\n") + .expect("write info exclude"); + let global_excludes = temp_dir.path().join("global-excludes"); + std::fs::write(&global_excludes, "global-ignored.txt\n").expect("write global excludes"); + run_git( + &repo, + &[ + "config", + "core.excludesFile", + global_excludes.to_str().expect("UTF-8 excludes path"), + ], + ) + .await; + for name in [ + "root-ignored.txt", + "info-ignored.txt", + "global-ignored.txt", + ] { + std::fs::write(repo.join(name), "ignored\n").expect("write ignored file"); + } + + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + let mut guard = prepare_status_config(&git, &repo) + .await + .expect("prepare ignored-only status"); + detect_status_fsmonitor(&mut guard).await; + assert_eq!(read_status(&guard).await, Ok(false)); + + std::fs::write(repo.join("visible.txt"), "visible\n").expect("write visible untracked file"); + run_git(&repo, &["config", "status.showUntrackedFiles", "no"]).await; + let mut guard = prepare_status_config(&git, &repo) + .await + .expect("prepare visible-untracked status"); + detect_status_fsmonitor(&mut guard).await; + assert_eq!(read_status(&guard).await, Ok(true)); +} + +#[tokio::test] +async fn frozen_status_reports_an_ordinary_unmerged_index_as_dirty() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + let base_branch = String::from_utf8( + run_git(&repo, &["rev-parse", "--abbrev-ref", "HEAD"]) + .await + .stdout, + ) + .expect("base branch UTF-8") + .trim() + .to_string(); + run_git(&repo, &["checkout", "-b", "side"]).await; + std::fs::write(repo.join("test.txt"), "side\n").expect("write side contents"); + run_git(&repo, &["commit", "-am", "side change"]).await; + run_git(&repo, &["checkout", &base_branch]).await; + std::fs::write(repo.join("test.txt"), "main\n").expect("write main contents"); + run_git(&repo, &["commit", "-am", "main change"]).await; + let merge = Command::new("git") + .args(["merge", "side"]) + .current_dir(&repo) + .output() + .await + .expect("run conflicting merge"); + assert!(!merge.status.success(), "fixture must produce a conflict"); + let stages = run_git(&repo, &["ls-files", "--unmerged"]).await; + assert!( + stages.stdout.split(|byte| *byte == b'\n').count() >= 3, + "fixture must retain multiple index stages" + ); + + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + assert_eq!(guarded_status(&repo, &git).await, Ok(true)); +} + +#[tokio::test] +async fn status_head_snapshot_distinguishes_valid_detached_unborn_and_corrupt_states() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + let commit = String::from_utf8(run_git(&repo, &["rev-parse", "HEAD"]).await.stdout) + .expect("commit UTF-8") + .trim() + .to_string(); + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + prepare_status_config(&git, &repo) + .await + .expect("normal symbolic HEAD"); + + run_git(&repo, &["checkout", "--detach", &commit]).await; + prepare_status_config(&git, &repo) + .await + .expect("valid detached HEAD"); + run_git(&repo, &["checkout", "-B", "restored", &commit]).await; + + let ref_path = repo.join(".git/refs/heads/restored"); + std::fs::write(&ref_path, format!("{}\n", "a".repeat(40))) + .expect("write missing-object ref"); + assert!( + prepare_status_config(&git, &repo).await.is_err(), + "missing-object symbolic HEAD must not become unborn" + ); + + let blob = String::from_utf8(run_git(&repo, &["hash-object", "-w", "test.txt"]).await.stdout) + .expect("blob UTF-8") + .trim() + .to_string(); + std::fs::write(&ref_path, format!("{blob}\n")).expect("write blob ref"); + assert_eq!( + prepare_status_config(&git, &repo).await.map(|_| ()), + Err(GitReadError::CommandFailed { + operation: "statusFilterPreparation".to_string(), + exit_code: Some(1), + }) + ); + + let unborn = temp_dir.path().join("unborn"); + std::fs::create_dir(&unborn).expect("create unborn repo"); + run_git(&unborn, &["init", "-q"]).await; + let unborn_git = GitRunner::for_cwd(&unborn).expect("unborn Git runner"); + let mut guard = prepare_status_config(&unborn_git, &unborn) + .await + .expect("genuine unborn HEAD"); + detect_status_fsmonitor(&mut guard).await; + assert_eq!(read_status(&guard).await, Ok(false)); +} + +#[tokio::test] +async fn frozen_status_refuses_active_or_custom_replacements_and_ignores_late_replacements() { + const MARKER: &str = "CODEX_GIT_UTILS_STATUS_REPLACE_BASE_CHILD"; + if std::env::var_os(MARKER).is_some() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + assert!( + prepare_status_config(&git, &repo).await.is_err(), + "custom replacement-ref namespace must make frozen Status unavailable" + ); + return; + } + run_isolated_environment_test( + "status_guard::tests::frozen_status_refuses_active_or_custom_replacements_and_ignores_late_replacements", + MARKER, + &[("GIT_REPLACE_REF_BASE", "refs/codex-replacements")], + None, + ); + + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + let (original, replacement) = replacement_fixture(&repo).await; + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + let mut guard = prepare_status_config(&git, &repo) + .await + .expect("prepare before replacement ref exists"); + run_git(&repo, &["replace", &original, &replacement]).await; + let stock = run_git(&repo, &["status", "--porcelain"]).await; + assert!( + !stock.stdout.is_empty(), + "replacement fixture must make stock Status dirty" + ); + detect_status_fsmonitor(&mut guard).await; + assert_eq!( + read_status(&guard).await, + Ok(false), + "late replacement must not alter the frozen no-replacement view" + ); + assert!( + prepare_status_config(&git, &repo).await.is_err(), + "an active default replacement must make frozen Status unavailable" + ); +} + #[tokio::test] async fn optional_smudge_only_filter_is_allowed_but_required_is_refused() { let temp_dir = tempfile::tempdir().expect("create temp dir"); @@ -273,6 +750,60 @@ async fn optional_smudge_only_filter_is_allowed_but_required_is_refused() { assert!(!filter_marker_is_set(&repo, "codex.smudge-ran").await); } +#[tokio::test] +async fn selected_required_only_filter_is_typed_and_refused_when_truthy() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + std::fs::write(repo.join(".gitattributes"), "test.txt filter=required-only\n") + .expect("select required-only filter"); + run_git(&repo, &["add", ".gitattributes"]).await; + run_git(&repo, &["commit", "-m", "required-only attribute"]).await; + + run_git( + &repo, + &["config", "filter.required-only.required", "false"], + ) + .await; + let git = GitRunner::for_cwd(&repo).expect("trusted Git"); + prepare_status_config(&git, &repo) + .await + .expect("selected required=false filter is inert"); + + run_git( + &repo, + &["config", "filter.required-only.required", "true"], + ) + .await; + assert_eq!( + prepare_status_config(&git, &repo).await.map(|_| ()), + Err(GitReadError::SelectedExecutableFilter { + driver: "required-only".to_string(), + path: "test.txt".to_string(), + }) + ); + + run_git( + &repo, + &["config", "filter.required-only.required", "not-a-bool"], + ) + .await; + assert!( + prepare_status_config(&git, &repo).await.is_err(), + "selected malformed required value must fail closed" + ); + + std::fs::write(repo.join(".gitattributes"), "other.txt filter=required-only\n") + .expect("move required-only filter off tracked paths"); + run_git( + &repo, + &["config", "filter.required-only.required", "true"], + ) + .await; + prepare_status_config(&git, &repo) + .await + .expect("unselected required-only namespace remains available"); +} + #[tokio::test] async fn optional_smudge_required_value_is_queried_once_per_driver() { let temp_dir = tempfile::tempdir().expect("create temp dir"); @@ -464,14 +995,12 @@ async fn ordinary_driver_uses_one_bulk_path_and_attribute_probe() { let fsmonitor = status .find("core.fsmonitor=") .expect("fsmonitor override before status"); - let filter = status - .find("include.path=") - .expect("sealed filter include before status"); let status_command = status .find(" status --porcelain") .expect("status subcommand"); - assert!(hooks < fsmonitor && fsmonitor < filter && filter < status_command); - assert_eq!(status.matches("include.path=").count(), 1); + assert!(hooks < fsmonitor && fsmonitor < status_command); + assert!(!status.contains("include.path=")); + assert!(status.ends_with("--untracked-files=no")); assert!(!filter_marker_is_set(&repo, "codex.ordinary-filter-ran").await); } @@ -499,11 +1028,11 @@ async fn fsmonitor_probe_is_base_only_and_the_sealed_decision_controls_final_ord assert_eq!( detect_status_fsmonitor(&mut config).await, - FsmonitorOverride::BuiltIn + FsmonitorOverride::Disabled ); assert_eq!( detect_status_fsmonitor(&mut config).await, - FsmonitorOverride::BuiltIn, + FsmonitorOverride::Disabled, "the retained decision must avoid a second probe" ); read_status(&config).await.expect("final status"); @@ -513,30 +1042,24 @@ async fn fsmonitor_probe_is_base_only_and_the_sealed_decision_controls_final_ord .lines() .map(str::to_string) .collect::>(); - assert_eq!( - lines.len(), - 3, - "one config probe, one feature probe, one status" - ); - assert!(lines[0].ends_with("config --null --get core.fsmonitor")); - assert!(!lines[0].contains("core.fsmonitor=false")); - assert!(lines[1].ends_with("version --build-options")); - assert!(!lines[1].contains("core.fsmonitor=false")); + assert_eq!(lines.len(), 1, "synthetic context must not probe or start fsmonitor"); let hooks = format!("core.hooksPath={}", crate::safe_git::DISABLED_HOOKS_PATH); - let hooks_offset = lines[2].find(&hooks).expect("hooks override"); - let fsmonitor_offset = lines[2] - .find("core.fsmonitor=true") - .expect("typed fsmonitor override"); - let status_offset = lines[2].find("status --porcelain").expect("status command"); + let hooks_offset = lines[0].find(&hooks).expect("hooks override"); + let fsmonitor_offset = lines[0] + .find("core.fsmonitor=false") + .expect("disabled fsmonitor override"); + let status_offset = lines[0].find("status --porcelain").expect("status command"); assert!(hooks_offset < fsmonitor_offset && fsmonitor_offset < status_offset); - assert!(lines[2].ends_with("status --porcelain --ignore-submodules=dirty")); + assert!(lines[0].ends_with( + "status --porcelain --ignore-submodules=dirty --untracked-files=no" + )); } #[tokio::test] -async fn zero_driver_status_skips_tracked_paths_attributes_and_overlay_writes() { +async fn zero_driver_status_builds_the_same_frozen_context_without_an_overlay() { if std::env::var_os("CODEX_GIT_UTILS_STATUS_GUARD_ENV_CHILD").is_none() { run_isolated_config_test( - "status_guard::tests::zero_driver_status_skips_tracked_paths_attributes_and_overlay_writes", + "status_guard::tests::zero_driver_status_builds_the_same_frozen_context_without_an_overlay", ); return; } @@ -558,9 +1081,11 @@ async fn zero_driver_status_skips_tracked_paths_attributes_and_overlay_writes() .await .expect("zero-driver status capability"); let lines = std::fs::read_to_string(log).expect("read wrapper log"); - assert!(!lines.contains(" ls-files -z --cached"), "{lines}"); + assert!(lines.contains(" ls-files -z --cached"), "{lines}"); assert!(!lines.contains(" check-attr --stdin -z filter"), "{lines}"); - assert!(!lines.contains(" config --file "), "{lines}"); + assert!(!lines.contains(" check-attr --stdin -z"), "{lines}"); + assert!(lines.contains("config --file "), "{lines}"); + assert!(!lines.contains("include.path="), "{lines}"); } #[tokio::test]