Merge commit '8745d144d4' into codex/psec-4394-git-06-merge-guard

# Conflicts:
#	codex-rs/git-utils/src/apply.rs
This commit is contained in:
Chris Bookholt
2026-07-06 18:55:29 -07:00
31 changed files with 6853 additions and 697 deletions
+9
View File
@@ -33,6 +33,15 @@ 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]
pretty_assertions = { workspace = true }
+536 -214
View File
@@ -10,16 +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::ReverseApplyMode;
use crate::reverse_staging::stage_effective_paths_for_reverse;
#[cfg(test)]
use crate::safe_git::DISABLED_HOOKS_PATH;
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;
@@ -50,6 +50,32 @@ enum ApplyStrategy {
ThreeWay,
}
#[cfg(test)]
thread_local! {
static AFTER_REVERSE_STAGING_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
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 {
@@ -74,6 +100,7 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
.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)?;
@@ -85,15 +112,38 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
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();
@@ -117,38 +167,56 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
// 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 strategy = if plain_check_code != 0 {
config.install_three_way_merge_policy()?;
ApplyStrategy::ThreeWay
} else {
ApplyStrategy::Direct
};
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, strategy.reverse_mode())?;
let reverse_plan = req
.revert
.then(|| prepare_reverse_staging_plan(&config, patch_paths, strategy.reverse_mode()))
.transpose()?;
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 => {
let mut args = vec!["apply".to_string(), "--index".to_string()];
if req.revert {
args.push("-R".to_string());
}
args.push(patch_arg);
let rendered = config.render_command_for_log(&args)?;
let (code, stdout, stderr) = run_guarded_apply(&config, &args)?;
(rendered, (code, stdout, stderr))
// 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)?;
@@ -188,6 +256,31 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
})
}
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<PathBuf> {
let mut command = config.rev_parse_command()?;
command.arg("--show-toplevel");
@@ -239,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<String> {
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;
@@ -293,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;
@@ -360,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"))
@@ -474,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=<isolated>"));
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();
@@ -828,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");
+134 -99
View File
@@ -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,56 +18,124 @@ pub(crate) struct StagePathsResult {
pub(crate) stderr: String,
}
#[derive(Clone, Copy)]
#[cfg_attr(not(test), allow(dead_code))]
enum StagingMode {
ComposedApply,
ReverseApply,
Standalone,
}
enum SparseCheckoutPolicy {
Verified { excluded: BTreeSet<String> },
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.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn update_index_exact_paths_from_apply(
config: &mut GuardedGitConfig<'_>,
paths: &[String],
content_filter_paths: &[String],
) -> io::Result<StagePathsResult> {
update_index_exact_paths_common(
config,
paths,
content_filter_paths,
StagingMode::ComposedApply,
)
pub(crate) struct PreparedReverseIndexUpdate {
paths: Vec<String>,
}
pub(crate) fn update_index_exact_paths_for_reverse_apply(
pub(crate) fn prepare_index_exact_paths_for_reverse_apply(
config: &mut GuardedGitConfig<'_>,
paths: &[String],
content_filter_paths: &[String],
) -> io::Result<PreparedReverseIndexUpdate> {
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::<BTreeSet<_>>();
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<StagePathsResult> {
update_index_exact_paths_common(
config,
paths,
content_filter_paths,
StagingMode::ReverseApply,
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}"),
)
}
@@ -75,15 +144,13 @@ pub(crate) fn update_index_exact_paths_standalone(
paths: &[String],
content_filter_paths: &[String],
) -> io::Result<StagePathsResult> {
update_index_exact_paths_common(config, paths, content_filter_paths, StagingMode::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],
mode: StagingMode,
) -> io::Result<StagePathsResult> {
) -> io::Result<()> {
for path in paths {
if path.as_bytes().contains(&0) {
return Err(io::Error::new(
@@ -103,9 +170,25 @@ fn update_index_exact_paths_common(
"content-filter staging path is not in the exact staging set",
));
}
if !matches!(mode, StagingMode::Standalone) {
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<StagePathsResult> {
validate_exact_staging_inputs(paths, content_filter_paths)?;
if paths.is_empty() {
return Ok(StagePathsResult {
exit_code: 0,
@@ -137,13 +220,7 @@ fn update_index_exact_paths_common(
});
}
};
if !matches!(mode, StagingMode::Standalone) {
config.ensure_apply_filter_path_subset(&content_filter_paths)?;
}
if (matches!(mode, StagingMode::Standalone) && !skip_worktree.is_empty())
|| !assume_unchanged.is_empty()
{
if !skip_worktree.is_empty() || !assume_unchanged.is_empty() {
let mut reasons = Vec::new();
if !skip_worktree.is_empty() {
reasons.push(format!(
@@ -168,21 +245,6 @@ fn update_index_exact_paths_common(
SparseCheckoutPolicy::Verified { excluded } => excluded,
SparseCheckoutPolicy::Refuse { result } => return Ok(result),
};
let non_sparse_skip_worktree = skip_worktree
.difference(&sparse_excluded)
.cloned()
.collect::<BTreeSet<_>>();
if !non_sparse_skip_worktree.is_empty() {
return Ok(StagePathsResult {
exit_code: 1,
stderr: format!(
"refusing to stage skip-worktree path(s): {}",
quote_paths(&non_sparse_skip_worktree)
),
});
}
let mut exclusions = ignored.clone();
exclusions.extend(sparse_excluded.iter().cloned());
let mut exclusion_reasons = Vec::new();
if !ignored.is_empty() {
exclusion_reasons.push(format!(
@@ -196,35 +258,14 @@ fn update_index_exact_paths_common(
quote_paths(&sparse_excluded)
));
}
let exclusion_stderr = exclusion_reasons.join("; ");
if !exclusions.is_empty() && !matches!(mode, StagingMode::ComposedApply) {
if !exclusion_reasons.is_empty() {
return Ok(StagePathsResult {
exit_code: 1,
stderr: exclusion_stderr,
stderr: exclusion_reasons.join("; "),
});
}
// Composed staging is intentionally best effort for ignored and sparse
// paths. Treat those expected omissions as successful after every fallible
// probe has completed, so its caller cannot report an error after the
// eligible subset has already changed the index. Reverse application uses
// the all-or-nothing mode above because every staging candidate is needed
// to align the index before the final patch command.
let paths = paths
.into_iter()
.filter(|path| !exclusions.contains(path))
.collect::<Vec<_>>();
let content_filter_paths = content_filter_paths
.into_iter()
.filter(|path| !exclusions.contains(path))
.collect::<Vec<_>>();
config.authorize_git_add_filter_paths(&content_filter_paths)?;
if paths.is_empty() {
return Ok(StagePathsResult {
exit_code: 0,
stderr: exclusion_stderr,
});
}
let mut command = config.update_index_literal_pathspecs_command()?;
command
.disable_optional_locks()
@@ -232,13 +273,7 @@ fn update_index_exact_paths_common(
.args(&paths);
let output = command.output()?;
let exit_code = output.status.code().unwrap_or(-1);
let mut stderr = String::from_utf8_lossy(&output.stderr).into_owned();
if !exclusions.is_empty() {
if !stderr.is_empty() && !stderr.ends_with('\n') {
stderr.push('\n');
}
stderr.push_str(&exclusion_stderr);
}
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
Ok(StagePathsResult { exit_code, stderr })
}
+255 -6
View File
@@ -53,11 +53,56 @@ 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,
}
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 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")
}
@@ -204,6 +249,42 @@ impl GitRunner {
self.config_environment.value(name)
}
/// 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) fn create_isolated_common_dir(&self) -> io::Result<IsolatedGitCommonDir> {
let root = tempfile::tempdir()?;
self.authority
@@ -227,6 +308,44 @@ impl GitRunner {
Ok(isolated)
}
pub(crate) fn create_isolated_git_storage(&self) -> io::Result<IsolatedGitStorage> {
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 output(&self, mut command: GitCommand) -> io::Result<std::process::Output> {
self.revalidate_active_repository_metadata()?;
isolate_git_command_environment(&mut command.inner);
@@ -236,12 +355,33 @@ impl GitRunner {
}
pub(crate) fn output_in_isolated_common_dir(
&self,
command: GitCommand,
isolated: &IsolatedGitCommonDir,
) -> io::Result<std::process::Output> {
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<std::process::Output> {
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<std::process::Output> {
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(),
@@ -278,8 +418,23 @@ impl GitRunner {
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 index_file = git_dir.join("index");
let object_directory = common_dir.join("objects");
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");
@@ -299,6 +454,11 @@ impl GitRunner {
.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
@@ -310,6 +470,7 @@ impl GitRunner {
self.output_after_isolated_child_validation(
&mut command.inner,
isolated,
storage,
[&git_dir, &common_dir, &worktree, &isolated_root],
)
}
@@ -318,10 +479,14 @@ impl GitRunner {
&self,
command: &mut Command,
isolated: &IsolatedGitCommonDir,
storage: Option<&IsolatedGitStorage>,
child_directories: [&GitChildDirectory; 4],
) -> io::Result<std::process::Output> {
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)
@@ -355,6 +520,71 @@ impl GitRunner {
}
}
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)]
@@ -374,6 +604,25 @@ struct GitChildDirectoryValidation {
_child_identity: Handle,
}
#[cfg(windows)]
fn open_git_child_directory_identity(path: &Path) -> io::Result<Handle> {
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
@@ -397,8 +646,8 @@ impl GitChildDirectory {
format!("{description} is not an existing directory"),
));
}
let canonical_identity = Handle::from_path(&canonical_path)?;
let child_identity = Handle::from_path(&child_path)?;
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,
@@ -424,8 +673,8 @@ impl GitChildDirectory {
format!("{} is no longer an existing directory", self.description),
));
}
let canonical_identity = Handle::from_path(&self.canonical_path)?;
let child_identity = Handle::from_path(&self.child_path)?;
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
+269
View File
@@ -289,6 +289,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,
@@ -436,6 +522,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();
@@ -1453,6 +1572,65 @@ fn git_child_directory_simplifies_canonical_path_without_changing_identity() {
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() {
@@ -1474,6 +1652,29 @@ fn isolated_child_final_validation_rejects_retargeted_spelling_before_spawn() {
"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()
@@ -1492,6 +1693,7 @@ fn isolated_child_final_validation_rejects_retargeted_spelling_before_spawn() {
.output_after_isolated_child_validation(
&mut command.inner,
&isolated,
None,
[&child, &child, &child, &child],
)
.expect_err("retargeted child spelling must fail closed");
@@ -1663,6 +1865,73 @@ 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"
);
}
#[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() {
+255 -26
View File
@@ -5,6 +5,84 @@ use std::path::Path;
use crate::git_command::GitRunner;
pub(crate) fn parse_git_boolean(value: &[u8]) -> Option<bool> {
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<bool> {
parse_git_boolean_with_minimum(value, -i128::from(i32::MAX))
}
fn parse_git_boolean_with_minimum(value: &[u8], minimum: i128) -> Option<bool> {
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,
@@ -23,6 +101,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<GitConfigValueEntry> for GitConfigEntry {
type Error = io::Error;
fn try_from(entry: GitConfigValueEntry) -> Result<Self, Self::Error> {
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,
@@ -40,6 +170,13 @@ pub(crate) fn parse_effective_config(
}
pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result<Vec<GitConfigEntry>> {
parse_config_value_entries(output)?
.into_iter()
.map(GitConfigEntry::try_from)
.collect()
}
fn parse_config_value_entries(output: &[u8]) -> io::Result<Vec<GitConfigValueEntry>> {
if output.is_empty() {
return Ok(Vec::new());
}
@@ -56,19 +193,15 @@ pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result<Vec<GitConfigEnt
let scope = parse_scope(record[0])?;
let origin = parse_config_origin(record[1])?;
let entry = parse_utf8_field(record[2], "config key/value")?;
let Some((key, value)) = entry.split_once('\n') else {
return Err(invalid_config_output(
"Git config record has no key/value separator",
));
};
let (key, value) = parse_config_value(entry);
if key.is_empty() {
return Err(invalid_config_output("empty Git config key"));
}
let entry = GitConfigEntry {
let entry = GitConfigValueEntry {
scope,
origin,
key: key.to_string(),
value: value.to_string(),
value,
};
entries.push(entry);
}
@@ -77,19 +210,17 @@ pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result<Vec<GitConfigEnt
/// Parse the `--show-origin` form used by Git versions that predate
/// `config --show-scope`. The record order still reflects effective config
/// precedence, which is what helper selection relies on. Scope is retained as
/// best-effort metadata only; command-line entries remain distinguishable.
#[cfg(test)]
pub(crate) fn parse_effective_config_with_origins(
output: &[u8],
) -> io::Result<BTreeMap<String, GitConfigEntry>> {
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<Vec<GitConfigEntry>> {
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<Vec<GitConfigEntry>> {
fn parse_config_value_entries_with_origins(output: &[u8]) -> io::Result<Vec<GitConfigValueEntry>> {
if output.is_empty() {
return Ok(Vec::new());
}
@@ -105,11 +236,7 @@ pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result<Vec
for record in fields.chunks_exact(2) {
let origin = parse_config_origin(record[0])?;
let entry = parse_utf8_field(record[1], "config key/value")?;
let Some((key, value)) = entry.split_once('\n') else {
return Err(invalid_config_output(
"Git config record has no key/value separator",
));
};
let (key, value) = parse_config_value(entry);
if key.is_empty() {
return Err(invalid_config_output("empty Git config key"));
}
@@ -120,16 +247,33 @@ pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result<Vec
// emitted precedence order, not on this informational label.
GitConfigScope::Local
};
entries.push(GitConfigEntry {
entries.push(GitConfigValueEntry {
scope,
origin,
key: key.to_string(),
value: value.to_string(),
value,
});
}
Ok(entries)
}
fn parse_config_value(entry: &str) -> (&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<BTreeMap<String, GitConfigEntry>> {
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,
@@ -148,6 +292,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<Option<GitConfigValue>> {
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<Vec<MergeConfigRecord>> {
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,
@@ -176,6 +382,29 @@ fn read_config_entries_with_fallback(
follow_includes: bool,
config_file: Option<&Path>,
) -> io::Result<Vec<GitConfigEntry>> {
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<Vec<GitConfigValueEntry>> {
let scoped = run_effective_config_query(
git,
cwd,
@@ -190,7 +419,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(
@@ -213,7 +442,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)
}
pub(crate) fn read_effective_config_with_fallback(
@@ -61,11 +61,16 @@ impl GitConfigEnvironmentSnapshot {
.collect::<Vec<_>>();
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::<usize>()
.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::<usize>()
.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()
@@ -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::<BTreeMap<_, _>>();
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() {
@@ -7,6 +7,7 @@ use super::path_safety::CONFIG_PATH_KEY;
use super::path_safety::git_var_path_from_bytes;
use super::path_safety::invalid_config_source;
use crate::git_command::GitRunner;
use crate::git_config::parse_git_boolean_symmetric_i32;
pub(super) fn default_system_config_source_candidates(
git: &GitRunner,
@@ -259,19 +260,8 @@ fn git_env_bool(git: &GitRunner, name: &str) -> io::Result<bool> {
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::<i64>()
.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)]
@@ -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
@@ -74,7 +75,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 +104,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 +121,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 +509,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 +521,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 +538,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,
@@ -811,6 +930,73 @@ fn command_scoped_include_paths_follow_the_same_boundary() {
);
}
#[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] {
+251 -1
View File
@@ -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::<Vec<_>>();
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:?}");
}
}
+484 -5
View File
@@ -1,4 +1,5 @@
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::io;
use std::path::Path;
@@ -9,8 +10,16 @@ use std::sync::Arc;
use crate::FsmonitorOverride;
use crate::git_command::GitCommand;
use crate::git_command::GitRunner;
use crate::git_command::IsolatedGitStorage;
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_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::safe_git::DISABLED_HOOKS_PATH;
use crate::safe_git::ExecutableFilterDrivers;
@@ -76,6 +85,79 @@ impl<'git> ValidatedConfigSources<'git> {
)
}
fn read_shared_repository(&self) -> io::Result<Option<GitConfigValue>> {
read_effective_shared_repository_with_fallback(
self.git,
&self.canonical_root,
&self.base_config_args,
)
}
fn read_merge_config(&self) -> io::Result<Vec<MergeConfigRecord>> {
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<BTreeMap<String, GitConfigEntry>> {
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())
}
fn read_bool(&self, key: &str) -> io::Result<Option<bool>> {
let mut command = self.git.command_for_cwd(&self.canonical_root)?;
command
@@ -138,6 +220,14 @@ fn invalid_base_config_args() -> io::Error {
pub(crate) struct GuardedGitConfig<'git> {
sources: ValidatedConfigSources<'git>,
identity: Arc<CapabilityIdentity>,
// 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<ApplyPolicySnapshot>,
// 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.
@@ -151,6 +241,99 @@ pub(crate) struct GuardedGitConfig<'git> {
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<CapabilityIdentity>);
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<Self> {
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<String>) {
parts.extend(self.config_args.iter().cloned());
}
}
#[derive(Clone, Copy)]
enum BoundSubcommand {
Apply,
@@ -275,6 +458,23 @@ impl GuardedGitCommand<'_, '_> {
pub(crate) fn output(self) -> io::Result<std::process::Output> {
self.operation.sources.git.output(self.inner)
}
pub(crate) fn output_in_merge_scratch(
self,
storage: &IsolatedGitStorage,
) -> io::Result<std::process::Output> {
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> {
@@ -286,6 +486,8 @@ 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,
@@ -296,8 +498,181 @@ impl<'git> GuardedGitConfig<'git> {
&self.sources.canonical_root
}
pub(crate) fn apply_command(&self) -> io::Result<GuardedGitCommand<'_, 'git>> {
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.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<std::process::Output> {
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<std::process::Output> {
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<ApplyWhitespaceMode> {
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<GuardedGitCommand<'_, 'git>> {
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<GuardedGitCommand<'_, 'git>> {
@@ -508,13 +883,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
@@ -547,10 +922,45 @@ impl<'git> GuardedGitConfig<'git> {
Ok(apply.checked_paths())
}
pub(crate) fn run_three_way_apply(
pub(crate) fn run_direct_apply(
&self,
revert: bool,
patch_path: &str,
) -> io::Result<std::process::Output> {
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<String> {
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<std::process::Output> {
let (apply, _git_add) = self.ordered_filter_snapshots()?;
if apply.is_none() || !self.merge_policy_installed {
@@ -559,6 +969,7 @@ impl<'git> GuardedGitConfig<'git> {
"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,
@@ -571,8 +982,23 @@ impl<'git> GuardedGitConfig<'git> {
.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");
}
@@ -587,6 +1013,9 @@ impl<'git> GuardedGitConfig<'git> {
revert: bool,
patch_path: &str,
) -> io::Result<String> {
// 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,
@@ -600,8 +1029,23 @@ impl<'git> GuardedGitConfig<'git> {
"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());
}
@@ -629,6 +1073,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::<BTreeSet<_>>()
== paths.iter().cloned().collect::<BTreeSet<_>>() =>
{
return Ok(());
}
_ => {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
@@ -641,6 +1093,7 @@ impl<'git> GuardedGitConfig<'git> {
Ok(())
}
#[cfg(test)]
pub(crate) fn render_command_for_log(&self, args: &[String]) -> io::Result<String> {
let mut parts = vec!["git".to_string()];
parts.extend(self.sources.base_config_args.iter().cloned());
@@ -663,6 +1116,32 @@ impl<'git> GuardedGitConfig<'git> {
.join(" ")
))
}
pub(crate) fn render_apply_command_for_log(&self, args: &[String]) -> io::Result<String> {
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)?;
}
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::<Vec<_>>()
.join(" ")
))
}
}
fn append_safe_scalar_overrides(command: &mut GitCommand) {
File diff suppressed because it is too large Load Diff
@@ -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<String> {
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<u8> {
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,11 +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)
.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(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::<BTreeMap<_, _>>();
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::<Vec<_>>(),
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::<Vec<_>>();
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::<Vec<_>>()
.join(" ");
let bare_unset = names
.iter()
.map(|name| format!("-{name}"))
.collect::<Vec<_>>()
.join(" ");
let literal_unset = names
.iter()
.map(|name| format!("{name}=unset"))
.collect::<Vec<_>>()
.join(" ");
let bare_unspecified = names
.iter()
.map(|name| format!("!{name}"))
.collect::<Vec<_>>()
.join(" ");
let literal_unspecified = names
.iter()
.map(|name| format!("{name}=unspecified"))
.collect::<Vec<_>>()
.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::<Vec<_>>();
assert_eq!(fields.len(), paths.len() * names.len() * 3 + 1);
let values = fields[..fields.len() - 1]
.chunks_exact(3)
.map(|record| record[2])
.collect::<Vec<_>>();
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())
);
}
+200 -5
View File
@@ -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,13 +375,13 @@ 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_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);
}
@@ -215,7 +410,7 @@ fn isolated_merge_config_is_not_attached_to_preparatory_commands() {
.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()])
+48 -13
View File
@@ -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<String, GitConfigEntry>,
attributes: &BTreeMap<String, String>,
) -> io::Result<Option<(String, String)>> {
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<String>,
default: Option<&str>,
attributes: &BTreeMap<String, String>,
) -> BTreeMap<String, String> {
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<Option<&str>> {
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)
}
@@ -405,6 +405,44 @@ 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() {
@@ -466,13 +504,20 @@ fn isolated_three_way_config_blocks_driver_namespace_introduction_races() {
observed
});
let result = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect("run isolated three-way apply");
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);
assert_ne!(result.exit_code, 0, "{race:?}");
assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=<isolated>"));
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=<isolated>"));
}
assert!(!configured_marker_exists(root, "codex.oldmergeran"));
assert!(!configured_marker_exists(root, "codex.newmergeran"));
}
File diff suppressed because it is too large Load Diff
+18 -28
View File
@@ -7,7 +7,6 @@ use std::path::Path;
use std::path::PathBuf;
use crate::apply::write_temp_patch;
use crate::exact_staging::update_index_exact_paths_from_apply;
use crate::exact_staging::update_index_exact_paths_standalone;
use crate::git_command::GitRunner;
use crate::git_config::path_is_within;
@@ -15,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<String>,
pub(crate) primary_paths: Vec<String>,
pub(crate) effective_paths: Vec<String>,
}
@@ -36,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::<io::Result<BTreeSet<_>>>()?;
let opposite_paths = opposite_paths
.collect::<io::Result<Vec<_>>>()?;
let opposite_records = opposite_paths
.into_iter()
.map(validate_patch_path)
.collect::<io::Result<BTreeSet<_>>>()?;
.collect::<io::Result<Vec<_>>>()?;
let primary_paths = primary_records.iter().cloned().collect::<BTreeSet<_>>();
let opposite_paths = opposite_records.into_iter().collect::<BTreeSet<_>>();
let effective_paths = primary_paths
.iter()
.cloned()
@@ -56,6 +62,7 @@ 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(),
})
@@ -106,15 +113,9 @@ fn git_apply_numstat_paths_guarded(
patch_path: &Path,
revert: bool,
) -> io::Result<Vec<String>> {
let mut command = config.apply_command()?;
#[cfg(test)]
run_stage_paths_hook(StagePathsHookPoint::PreSpawn);
command.args(["--numstat", "-z"]);
if revert {
command.arg("-R");
}
command.arg("--").arg(patch_path);
let output = command.output()?;
let output = config.run_apply_numstat_path_inventory(revert, patch_path)?;
if !output.status.success() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
@@ -145,10 +146,11 @@ fn extract_paths_from_patch_from_cwd(diff_text: &str, cwd: &Path) -> Vec<String>
let paths = (|| -> io::Result<Vec<String>> {
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();
@@ -350,18 +352,6 @@ pub fn stage_paths(git_root: &Path, diff: &str) -> io::Result<()> {
stage_effective_paths_standalone(&mut config, &paths)
}
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn stage_effective_paths_from_apply(
config: &mut GuardedGitConfig<'_>,
paths: &[String],
) -> io::Result<()> {
let (existing, content_filter_paths) = classify_exact_staging_leaves(config, paths)?;
let _result = update_index_exact_paths_from_apply(config, &existing, &content_filter_paths)?;
// Preserve the public helper's historical best-effort treatment of a
// non-zero staging command. Security and probe failures still propagate.
Ok(())
}
fn stage_effective_paths_standalone(
config: &mut GuardedGitConfig<'_>,
paths: &[String],
+96 -175
View File
@@ -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<Vec<String>> {
}
fn best_effort_paths(diff: &str) -> Vec<String> {
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)]
@@ -540,7 +539,13 @@ fn standalone_stage_paths_rejects_actual_cwd_reparented_into_linked_worktree() {
} else {
"changed before Git launch"
};
assert!(error.to_string().contains(expected), "{mode}: {error}");
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());
@@ -612,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::<String>::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";
@@ -1012,50 +1042,14 @@ 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 composed_staging_preserves_eligible_path_when_ignored_peer_is_refused() {
let repo = init_repo();
let root = repo.path();
std::fs::write(root.join(".gitignore"), "ignored.txt\n").expect("write ignore rule");
assert_eq!(run(root, &["git", "add", ".gitignore"]).0, 0);
assert_eq!(run(root, &["git", "commit", "-m", "ignore rule"]).0, 0);
std::fs::write(root.join("ignored.txt"), "ignored\n").expect("write ignored file");
std::fs::write(root.join("ordinary.txt"), "ordinary\n").expect("write ordinary file");
let paths = vec!["ignored.txt".to_string(), "ordinary.txt".to_string()];
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 result = update_index_exact_paths_from_apply(&mut config, &paths, &paths)
.expect("ignored peer does not suppress eligible pre-staging");
assert_eq!(result.exit_code, 0, "{result:?}");
assert!(result.stderr.contains("ignored.txt"), "{result:?}");
assert_eq!(
run(root, &["git", "diff", "--cached", "--name-only"]).1,
"ordinary.txt\n"
);
assert!(index_entry(root, "ignored.txt").is_empty());
}
#[test]
fn composed_staging_preserves_eligible_sparse_path_and_skips_excluded_peer() {
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");
@@ -1077,57 +1071,6 @@ fn composed_staging_preserves_eligible_sparse_path_and_skips_excluded_peer() {
"inside/eligible.txt".to_string(),
"outside/base.txt".to_string(),
];
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");
stage_effective_paths_from_apply(&mut config, &paths)
.expect("sparse-excluded peer does not suppress eligible pre-staging");
assert_eq!(
run(root, &["git", "diff", "--cached", "--name-only"]).1,
"inside/eligible.txt\n"
);
assert!(
run(root, &["git", "diff", "--cached", "--", "outside/base.txt"])
.1
.is_empty(),
"sparse-excluded tracked path must retain its prior index entry"
);
}
#[test]
fn composed_staging_non_sparse_skip_worktree_refusal_remains_atomic() {
let repo = init_repo();
let root = repo.path();
std::fs::write(root.join("eligible.txt"), "base eligible\n").expect("write eligible base");
std::fs::write(root.join("skipped.txt"), "base skipped\n").expect("write skipped base");
assert_eq!(
run(root, &["git", "add", "eligible.txt", "skipped.txt"]).0,
0
);
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
assert_eq!(
run(
root,
&[
"git",
"update-index",
"--skip-worktree",
"--",
"skipped.txt"
]
)
.0,
0
);
std::fs::write(root.join("eligible.txt"), "changed eligible\n").expect("modify eligible path");
std::fs::write(root.join("skipped.txt"), "changed skipped\n").expect("modify skipped path");
let paths = vec!["eligible.txt".to_string(), "skipped.txt".to_string()];
let before = git_index_bytes(root);
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
@@ -1137,37 +1080,45 @@ fn composed_staging_non_sparse_skip_worktree_refusal_remains_atomic() {
config
.authorize_filter_paths(&paths)
.expect("apply filter snapshot");
let result = update_index_exact_paths_from_apply(&mut config, &paths, &paths)
.expect("policy refusal is a staging result");
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_ne!(result.exit_code, 0);
assert!(result.stderr.contains("skip-worktree"), "{result:?}");
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 composed_staging_late_filter_refusal_precedes_eligible_index_mutation() {
fn reverse_staging_late_filter_refusal_precedes_eligible_index_mutation() {
let repo = init_repo();
let root = repo.path();
std::fs::write(root.join(".gitignore"), "ignored.txt\n").expect("write ignore rule");
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", ".gitignore", ".gitattributes", "ordinary.txt"]
&["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("ignored.txt"), "ignored\n").expect("write ignored path");
let paths = vec!["ignored.txt".to_string(), "ordinary.txt".to_string()];
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
@@ -1188,9 +1139,12 @@ fn composed_staging_late_filter_refusal_precedes_eligible_index_mutation() {
);
let before = git_index_bytes(root);
let error = stage_effective_paths_from_apply(&mut config, &paths)
.expect_err("fresh selected filter must refuse before staging eligible paths");
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,
@@ -1231,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");
@@ -1239,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()),
@@ -1281,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);
@@ -1299,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");
@@ -1337,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);
@@ -1355,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");
@@ -1368,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();
@@ -1396,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");
@@ -1414,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 =
@@ -1423,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);
}
@@ -1774,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!(
@@ -1897,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!(
@@ -2635,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;
}
@@ -2706,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");
@@ -2766,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(),
@@ -2818,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(),
@@ -2887,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(),
@@ -2959,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);
}
@@ -3008,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");
@@ -3052,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");
+8
View File
@@ -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<bool> {
route_contains_process_relative_procfs_path(route)
}
}
pub(crate) fn repository_route_boundaries(
@@ -107,6 +107,82 @@ fn symlink_route_hops(path: &Path) -> io::Result<Vec<SymlinkRouteHop>> {
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<bool> {
#[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<bool> {
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<bool> {
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<bool> {
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,
@@ -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()
);
}
}
@@ -26,6 +26,31 @@ use super::resolve_repository_metadata;
mod policy;
fn open_active_worktree_identity(path: &Path) -> io::Result<Handle> {
#[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)]
@@ -60,7 +85,7 @@ 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 = Handle::from_path(&worktree_root)
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(),
@@ -208,7 +233,7 @@ impl RepositoryAuthority {
.or_else(|| roots.first())
.cloned()
.unwrap_or_default();
let active_worktree_identity = Handle::from_path(&active_worktree_root).ok();
let active_worktree_identity = open_active_worktree_identity(&active_worktree_root).ok();
Ok(Self {
active_worktree_root,
active_worktree_identity,
@@ -75,6 +75,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));
@@ -212,3 +218,13 @@ fn worktree_controlled_config_source(path: &Path, description: &str) -> io::Erro
),
)
}
fn process_relative_config_source(path: &Path, description: &str) -> io::Error {
io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"refusing to use process-relative {description}: {}",
path.display()
),
)
}
@@ -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<bool> {
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(()),
}
}
@@ -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");
@@ -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();
+82 -7
View File
@@ -4,8 +4,12 @@ use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::io;
use crate::exact_staging::update_index_exact_paths_for_reverse_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;
@@ -16,11 +20,36 @@ pub(crate) enum ReverseApplyMode {
ThreeWay,
}
pub(crate) fn stage_effective_paths_for_reverse(
config: &mut GuardedGitConfig<'_>,
pub(crate) struct ReverseStagingPlan {
staging_candidates: Vec<String>,
content_filter_paths: Vec<String>,
}
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<ReverseStagingPlan> {
let confined = confine_patch_paths_guarded(config, paths)?;
let mut worktree_paths = BTreeMap::new();
for path in confined.into_exact_leaves()? {
@@ -117,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
@@ -138,11 +170,54 @@ pub(crate) fn stage_effective_paths_for_reverse(
})
.cloned()
.collect::<Vec<_>>();
let result = update_index_exact_paths_for_reverse_apply(
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<SealedReverseStagingPlan> {
let update = prepare_index_exact_paths_for_reverse_apply(
config,
&staging_candidates,
&content_filter_paths,
&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 {