From a44ec411cfa99f19bc71c3e7219227913a40aa40 Mon Sep 17 00:00:00 2001 From: Chris Bookholt Date: Mon, 6 Jul 2026 23:52:09 -0700 Subject: [PATCH] git-utils: fix frozen status portability --- codex-rs/git-utils/src/git_command.rs | 100 +++++++++-- codex-rs/git-utils/src/git_command_tests.rs | 23 +++ codex-rs/git-utils/src/guarded_config.rs | 44 ++--- .../src/guarded_config/status_context.rs | 46 ++++- .../src/guarded_config/status_index.rs | 151 +++++++++++++++++ .../src/guarded_config/status_index_tests.rs | 89 ++++++++++ .../git-utils/src/guarded_config_tests.rs | 38 +++++ codex-rs/git-utils/src/safe_git_tests.rs | 158 ++++++++++++++++++ codex-rs/git-utils/src/status_guard_tests.rs | 52 +++++- 9 files changed, 641 insertions(+), 60 deletions(-) create mode 100644 codex-rs/git-utils/src/guarded_config/status_index.rs create mode 100644 codex-rs/git-utils/src/guarded_config/status_index_tests.rs diff --git a/codex-rs/git-utils/src/git_command.rs b/codex-rs/git-utils/src/git_command.rs index e16b5cfed3..1f129d43bd 100644 --- a/codex-rs/git-utils/src/git_command.rs +++ b/codex-rs/git-utils/src/git_command.rs @@ -775,16 +775,8 @@ impl GitRunner { 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 alternate_object_directories = + storage.map(|_| encode_git_alternate_object_directory(&real_object_directory)); let system_config = isolated_root.join("system.gitconfig"); let global_config = isolated_root.join("global.gitconfig"); let home = isolated_root.join("home"); @@ -945,12 +937,7 @@ impl GitRunner { let real_object_directory = common_dir.join("objects"); let alternate_object_directories = - std::env::join_paths([&real_object_directory]).map_err(|error| { - io::Error::new( - io::ErrorKind::InvalidData, - format!("cannot encode isolated Git object alternate: {error}"), - ) - })?; + encode_git_alternate_object_directory(&real_object_directory); let system_config = isolated_root.join("system.gitconfig"); let global_config = isolated_root.join("global.gitconfig"); command @@ -1592,6 +1579,87 @@ fn ascii_u16_eq_ignore_case(unit: u16, ascii: u8) -> bool { unit == ascii.to_ascii_lowercase() as u16 || unit == ascii.to_ascii_uppercase() as u16 } +/// Encode one object directory using Git's alternate-object-directory grammar. +/// +/// This environment variable is a Git path list, not a platform `PATH` list. +/// Quoting every entry with Git's C-style syntax keeps the platform list +/// separator literal and preserves backslashes as path data. +#[cfg(unix)] +fn encode_git_alternate_object_directory(path: &Path) -> OsString { + use std::os::unix::ffi::OsStrExt; + use std::os::unix::ffi::OsStringExt; + + OsString::from_vec(quote_git_c_style_bytes(path.as_os_str().as_bytes())) +} + +#[cfg(windows)] +fn encode_git_alternate_object_directory(path: &Path) -> OsString { + use std::os::windows::ffi::OsStrExt; + use std::os::windows::ffi::OsStringExt; + + let units = path.as_os_str().encode_wide().collect::>(); + OsString::from_wide("e_git_c_style_windows_units(&units)) +} + +#[cfg(not(any(unix, windows)))] +fn encode_git_alternate_object_directory(path: &Path) -> OsString { + let encoded = quote_git_c_style_bytes(path.to_string_lossy().as_bytes()); + OsString::from(String::from_utf8(encoded).expect("quoted UTF-8 path remains UTF-8")) +} + +#[cfg(any(not(windows), test))] +fn quote_git_c_style_bytes(value: &[u8]) -> Vec { + let mut encoded = Vec::with_capacity(value.len().saturating_add(2)); + encoded.push(b'"'); + for &byte in value { + match byte { + b'"' | b'\\' => { + encoded.push(b'\\'); + encoded.push(byte); + } + 0x00..=0x1f | 0x7f..=0xff => { + encoded.extend([ + b'\\', + b'0' + ((byte >> 6) & 0o7), + b'0' + ((byte >> 3) & 0o7), + b'0' + (byte & 0o7), + ]); + } + _ => encoded.push(byte), + } + } + encoded.push(b'"'); + encoded +} + +#[cfg(any(windows, test))] +fn quote_git_c_style_windows_units(value: &[u16]) -> Vec { + const BACKSLASH: u16 = b'\\' as u16; + const DOUBLE_QUOTE: u16 = b'"' as u16; + + let mut encoded = Vec::with_capacity(value.len().saturating_add(2)); + encoded.push(DOUBLE_QUOTE); + for &unit in value { + match unit { + DOUBLE_QUOTE | BACKSLASH => { + encoded.push(BACKSLASH); + encoded.push(unit); + } + 0x00..=0x1f | 0x7f => { + encoded.extend([ + BACKSLASH, + b'0' as u16 + ((unit >> 6) & 0o7), + b'0' as u16 + ((unit >> 3) & 0o7), + b'0' as u16 + (unit & 0o7), + ]); + } + _ => encoded.push(unit), + } + } + encoded.push(DOUBLE_QUOTE); + encoded +} + fn scrub_repository_and_config_environment(command: &mut Command) { let mut names = std::env::vars_os() .map(|(name, _)| name) diff --git a/codex-rs/git-utils/src/git_command_tests.rs b/codex-rs/git-utils/src/git_command_tests.rs index 2646ee1718..c33804cc58 100644 --- a/codex-rs/git-utils/src/git_command_tests.rs +++ b/codex-rs/git-utils/src/git_command_tests.rs @@ -4,6 +4,29 @@ use std::process::Command; use crate::safe_git::DISABLED_HOOKS_PATH; +#[test] +fn alternate_object_directory_uses_git_c_style_byte_quoting() { + assert_eq!( + quote_git_c_style_bytes(b"/repo:colon;semi\\slash\"quote\n\xff/objects"), + b"\"/repo:colon;semi\\\\slash\\\"quote\\012\\377/objects\"" + ); +} + +#[test] +fn alternate_object_directory_preserves_windows_wide_paths_and_escapes_backslashes() { + let mut path = r"C:\repo;semi:colon\wide-" + .encode_utf16() + .collect::>(); + path.push(0xd800); + path.extend(r"\objects".encode_utf16()); + + let mut expected = r#""C:\\repo;semi:colon\\wide-"#.encode_utf16().collect::>(); + expected.push(0xd800); + expected.extend(r#"\\objects""#.encode_utf16()); + + assert_eq!(quote_git_c_style_windows_units(&path), expected); +} + #[cfg(unix)] fn write_executable(path: &Path, body: &str) { use std::os::unix::fs::PermissionsExt; diff --git a/codex-rs/git-utils/src/guarded_config.rs b/codex-rs/git-utils/src/guarded_config.rs index f4ea94f064..e9fd80dc95 100644 --- a/codex-rs/git-utils/src/guarded_config.rs +++ b/codex-rs/git-utils/src/guarded_config.rs @@ -67,6 +67,8 @@ pub(crate) use merge_overlay::reset_merge_policy_counts; mod reverse_probe; mod status_context; use status_context::SealedStatusReadContext; +mod status_index; +use status_index::status_core_symlinks_for_filter_screening; /// Proof that one exact Git config invocation has no worktree-controlled /// source routes for one runner and canonical repository root. @@ -1197,38 +1199,6 @@ impl<'git> GuardedGitConfig<'git> { Ok(()) } - /// Return the exact tracked-path byte strings for the Status policy. - async fn read_status_tracked_paths_async(&self) -> io::Result>> { - if self.status.is_some() { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "tracked paths must be read before status policy installation", - )); - } - let mut command = - self.pending_status_command(FsmonitorOverride::Disabled, /*neutralizer*/ None)?; - command - .disable_optional_locks() - .args(["ls-files", "-z", "--cached"]); - let output = command.output().await?; - if !output.status.success() { - return Err(command_failure("tracked-path probe", &output)); - } - let mut paths = parse_nul_paths(&output.stdout)?; - if paths.len() > MAX_STATUS_TRACKED_PATHS { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!( - "tracked path record count {} exceeds the status limit {MAX_STATUS_TRACKED_PATHS}", - paths.len() - ), - )); - } - paths.sort(); - paths.dedup(); - Ok(paths) - } - /// Install the mutually exclusive Status filter policy and publish one /// operation-owned config, attribute, HEAD, and untracked-presence view. pub(crate) async fn install_status_policy_async(&mut self) -> io::Result<()> { @@ -1247,7 +1217,9 @@ impl<'git> GuardedGitConfig<'git> { .await?; let executable_drivers = status_policy_filter_drivers(&entries)?; validate_executable_driver_count(&executable_drivers)?; - let paths = self.read_status_tracked_paths_async().await?; + let configured_core_symlinks = self.sources.read_bool_async("core.symlinks").await?; + let core_symlinks = status_core_symlinks_for_filter_screening(configured_core_symlinks); + let paths = self.read_status_tracked_paths_async(core_symlinks).await?; let neutralizer = if executable_drivers.is_empty() { None } else { @@ -1301,7 +1273,11 @@ impl<'git> GuardedGitConfig<'git> { .read_status_head_oid_async(neutralizer.as_ref()) .await?; let context = self - .build_status_read_context_async(head_oid.as_deref(), has_untracked) + .build_status_read_context_async( + head_oid.as_deref(), + has_untracked, + configured_core_symlinks, + ) .await?; self.status = Some(StatusPolicySnapshot { context, diff --git a/codex-rs/git-utils/src/guarded_config/status_context.rs b/codex-rs/git-utils/src/guarded_config/status_context.rs index ba5c578a07..c9039e9b0f 100644 --- a/codex-rs/git-utils/src/guarded_config/status_context.rs +++ b/codex-rs/git-utils/src/guarded_config/status_context.rs @@ -65,6 +65,7 @@ impl GuardedGitConfig<'_> { &self, head_oid: Option<&str>, has_untracked: bool, + configured_core_symlinks: Option, ) -> io::Result { if self.sources.git.attribute_source_is_custom() { return Err(io::Error::new( @@ -83,8 +84,12 @@ impl GuardedGitConfig<'_> { .sources .git .create_isolated_read_context(head_oid, &operation_identity)?; - self.write_status_projection_config_async(&context, core_attributes_file.as_deref()) - .await?; + self.write_status_projection_config_async( + &context, + core_attributes_file.as_deref(), + configured_core_symlinks, + ) + .await?; std::fs::write( context.attributes_path(), status_info_attributes(info_attributes)?, @@ -101,6 +106,7 @@ impl GuardedGitConfig<'_> { &self, context: &IsolatedGitReadContext, core_attributes_file: Option<&OsStr>, + configured_core_symlinks: Option, ) -> io::Result<()> { let entries = self .sources @@ -119,6 +125,13 @@ impl GuardedGitConfig<'_> { )); } refuse_sparse_status(&entries)?; + let projected_core_symlinks = configured_status_core_symlinks(&entries)?; + if projected_core_symlinks != configured_core_symlinks { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "core.symlinks changed during Status preparation", + )); + } let projected_bytes = entries.iter().chain(repository_format.iter()).try_fold( 0_usize, |total, (key, entry)| { @@ -140,7 +153,10 @@ impl GuardedGitConfig<'_> { "status config projection exceeds its byte limit", )); } - for entry in entries.values() { + for entry in entries + .values() + .filter(|entry| entry.key != "core.symlinks") + { self.write_status_config_value_async(&context.config_path(), &entry.key, &entry.value) .await?; } @@ -150,6 +166,14 @@ impl GuardedGitConfig<'_> { } self.write_status_config_value_async(&context.config_path(), "core.bare", "false") .await?; + if let Some(core_symlinks) = configured_core_symlinks { + self.write_status_config_value_async( + &context.config_path(), + "core.symlinks", + if core_symlinks { "true" } else { "false" }, + ) + .await?; + } if let Some(core_attributes_file) = core_attributes_file { self.write_status_config_value_async( &context.config_path(), @@ -244,6 +268,22 @@ impl GuardedGitConfig<'_> { } } +fn configured_status_core_symlinks( + entries: &BTreeMap, +) -> io::Result> { + let Some(entry) = entries.get("core.symlinks") else { + return Ok(None); + }; + parse_git_boolean(entry.value.as_bytes()) + .map(Some) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "invalid Status config value for core.symlinks", + ) + }) +} + fn refuse_sparse_status( entries: &BTreeMap, ) -> io::Result<()> { diff --git a/codex-rs/git-utils/src/guarded_config/status_index.rs b/codex-rs/git-utils/src/guarded_config/status_index.rs new file mode 100644 index 0000000000..0cdf3b38ba --- /dev/null +++ b/codex-rs/git-utils/src/guarded_config/status_index.rs @@ -0,0 +1,151 @@ +use std::io; + +use super::GuardedGitConfig; +use super::MAX_STATUS_TRACKED_PATHS; +use super::command_failure; +use crate::FsmonitorOverride; +use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES; + +impl GuardedGitConfig<'_> { + /// Return stage-zero paths that can select a Status content filter. + /// Gitlinks and unmerged stages never convert worktree contents through + /// clean/process helpers. Index symlinks do when `core.symlinks=false`, + /// because Git then represents them as ordinary worktree files. + pub(super) async fn read_status_tracked_paths_async( + &self, + core_symlinks: bool, + ) -> io::Result>> { + if self.status.is_some() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "tracked paths must be read before status policy installation", + )); + } + let mut command = + self.pending_status_command(FsmonitorOverride::Disabled, /*neutralizer*/ None)?; + command + .disable_optional_locks() + .args(["ls-files", "-z", "--cached", "--stage"]); + let output = command.output().await?; + if !output.status.success() { + return Err(command_failure("tracked-path probe", &output)); + } + let mut paths = parse_status_filter_candidate_paths(&output.stdout, core_symlinks)?; + paths.sort(); + paths.dedup(); + Ok(paths) + } +} + +fn parse_status_filter_candidate_paths( + output: &[u8], + core_symlinks: bool, +) -> io::Result>> { + if output.len() > MAX_INTERNAL_GIT_OUTPUT_BYTES { + return Err(invalid_status_tracked_path_output( + "Git tracked-path output exceeds the Status byte limit", + )); + } + if output.is_empty() { + return Ok(Vec::new()); + } + let body = output.strip_suffix(&[0]).ok_or_else(|| { + invalid_status_tracked_path_output("unterminated Git tracked-path output") + })?; + if body.is_empty() { + return Err(invalid_status_tracked_path_output( + "empty Git tracked-path record", + )); + } + let record_count = body.split(|byte| *byte == 0).count(); + if record_count > MAX_STATUS_TRACKED_PATHS { + return Err(invalid_status_tracked_path_output(&format!( + "tracked path record count {record_count} exceeds the status limit {MAX_STATUS_TRACKED_PATHS}", + ))); + } + + let mut paths = Vec::new(); + for record in body.split(|byte| *byte == 0) { + if record.is_empty() { + return Err(invalid_status_tracked_path_output( + "empty Git tracked-path record", + )); + } + let separator = record + .iter() + .position(|byte| *byte == b'\t') + .ok_or_else(|| { + invalid_status_tracked_path_output("missing Git tracked-path separator") + })?; + let (header, path) = record.split_at(separator); + let path = &path[1..]; + if path.is_empty() { + return Err(invalid_status_tracked_path_output("empty Git tracked path")); + } + + let mut fields = header.split(|byte| *byte == b' '); + let mode = fields.next().unwrap_or_default(); + let object_id = fields.next().unwrap_or_default(); + let stage = fields.next().unwrap_or_default(); + if fields.next().is_some() || mode.is_empty() || object_id.is_empty() || stage.is_empty() { + return Err(invalid_status_tracked_path_output( + "noncanonical Git tracked-path header", + )); + } + if mode.len() != 6 || !mode.iter().all(|byte| matches!(byte, b'0'..=b'7')) { + return Err(invalid_status_tracked_path_output( + "invalid Git tracked-path mode", + )); + } + let filter_candidate = match mode { + b"100644" | b"100755" => true, + b"120000" => !core_symlinks, + b"160000" => false, + _ => { + return Err(invalid_status_tracked_path_output( + "unsupported Git tracked-path mode", + )); + } + }; + if !matches!(object_id.len(), 40 | 64) + || !object_id + .iter() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) + { + return Err(invalid_status_tracked_path_output( + "invalid Git tracked-path object ID", + )); + } + let stage = match stage { + b"0" => 0, + b"1" => 1, + b"2" => 2, + b"3" => 3, + _ => { + return Err(invalid_status_tracked_path_output( + "invalid Git tracked-path stage", + )); + } + }; + if stage == 0 && filter_candidate { + paths.push(path.to_vec()); + } + } + Ok(paths) +} + +pub(super) fn status_core_symlinks_for_filter_screening(configured: Option) -> bool { + status_core_symlinks_for_filter_screening_on(configured, cfg!(windows)) +} + +fn status_core_symlinks_for_filter_screening_on(configured: Option, windows: bool) -> bool { + configured.unwrap_or(!windows) +} + +fn invalid_status_tracked_path_output(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +#[cfg(test)] +#[path = "status_index_tests.rs"] +mod tests; diff --git a/codex-rs/git-utils/src/guarded_config/status_index_tests.rs b/codex-rs/git-utils/src/guarded_config/status_index_tests.rs new file mode 100644 index 0000000000..66a31b7bac --- /dev/null +++ b/codex-rs/git-utils/src/guarded_config/status_index_tests.rs @@ -0,0 +1,89 @@ +use super::*; +use pretty_assertions::assert_eq; + +#[test] +fn candidates_require_canonical_regular_stage_zero_entries() { + fn push_record(output: &mut Vec, mode: &[u8], oid: &[u8], stage: u8, path: &[u8]) { + output.extend_from_slice(mode); + output.push(b' '); + output.extend_from_slice(oid); + output.extend([b' ', stage, b'\t']); + output.extend_from_slice(path); + output.push(0); + } + + let oid_sha1 = vec![b'1'; 40]; + let oid_sha256 = vec![b'a'; 64]; + let mut output = Vec::new(); + push_record(&mut output, b"100644", &oid_sha1, b'0', b"file.txt"); + push_record( + &mut output, + b"100755", + &oid_sha256, + b'0', + b"bin/tab\topaque-\xff", + ); + push_record(&mut output, b"120000", &oid_sha1, b'0', b"link"); + push_record(&mut output, b"160000", &oid_sha1, b'0', b"nested"); + for stage in [b'1', b'2', b'3'] { + push_record(&mut output, b"100644", &oid_sha1, stage, b"conflict"); + } + + assert_eq!( + parse_status_filter_candidate_paths(&output, /*core_symlinks*/ true) + .expect("canonical stage records with native symlinks"), + vec![b"file.txt".to_vec(), b"bin/tab\topaque-\xff".to_vec()] + ); + assert_eq!( + parse_status_filter_candidate_paths(&output, /*core_symlinks*/ false) + .expect("canonical stage records with emulated symlinks"), + vec![ + b"file.txt".to_vec(), + b"bin/tab\topaque-\xff".to_vec(), + b"link".to_vec(), + ] + ); + assert_eq!( + parse_status_filter_candidate_paths(b"", /*core_symlinks*/ true).expect("empty index"), + Vec::>::new() + ); + + let malformed = [ + b"100644 1111111111111111111111111111111111111111 0\tunterminated".as_slice(), + b"\0".as_slice(), + b"100644 1111111111111111111111111111111111111111 0\t\0".as_slice(), + b"100644 1111111111111111111111111111111111111111 0 no-tab\0".as_slice(), + b"10064 1111111111111111111111111111111111111111 0\tbad-mode\0".as_slice(), + b"040000 1111111111111111111111111111111111111111 0\tsparse-dir\0".as_slice(), + b"100644 A111111111111111111111111111111111111111 0\tuppercase-oid\0".as_slice(), + b"100644 1111111111111111111111111111111111111111 4\tbad-stage\0".as_slice(), + b"100644 1111111111111111111111111111111111111111 0\textra-space\0".as_slice(), + b"100644 1111111111111111111111111111111111111111 0\tfirst\0\0".as_slice(), + ]; + for input in malformed { + assert!( + parse_status_filter_candidate_paths(input, /*core_symlinks*/ true).is_err(), + "accepted malformed tracked-path inventory {input:?}" + ); + } +} + +#[test] +fn core_symlinks_screening_preserves_explicit_values_and_platform_defaults() { + for windows in [false, true] { + assert!(status_core_symlinks_for_filter_screening_on( + Some(true), + windows + )); + assert!(!status_core_symlinks_for_filter_screening_on( + Some(false), + windows + )); + } + assert!(status_core_symlinks_for_filter_screening_on( + None, /*windows*/ false + )); + assert!(!status_core_symlinks_for_filter_screening_on( + None, /*windows*/ true + )); +} diff --git a/codex-rs/git-utils/src/guarded_config_tests.rs b/codex-rs/git-utils/src/guarded_config_tests.rs index 22ee8eccac..0200cfdb33 100644 --- a/codex-rs/git-utils/src/guarded_config_tests.rs +++ b/codex-rs/git-utils/src/guarded_config_tests.rs @@ -762,6 +762,10 @@ async fn status_replaces_filter_config_with_an_owned_helper_free_context() { .expect("owned attributes path"); let config_contents = std::fs::read_to_string(&owned_config).expect("read owned config"); assert!(!config_contents.contains("filter.demo")); + assert!( + !config_contents.contains("symlinks"), + "unset core.symlinks must remain unset in the owned projection: {config_contents}" + ); let attribute_contents = std::fs::read_to_string(&owned_attributes).expect("read owned attributes"); assert!(attribute_contents.contains("!filter")); @@ -784,3 +788,37 @@ async fn status_replaces_filter_config_with_an_owned_helper_free_context() { "owned attributes must be removed" ); } + +#[tokio::test] +async fn status_projection_freezes_explicit_core_symlinks_values() { + for value in ["true", "false"] { + let repo = tempfile::tempdir().expect("repo"); + run_git(repo.path(), &["init", "-q"]); + std::fs::write(repo.path().join("file.txt"), "contents\n").expect("tracked file"); + run_git(repo.path(), &["add", "file.txt"]); + run_git(repo.path(), &["config", "core.symlinks", value]); + + let git = GitRunner::for_cwd_io(repo.path()).expect("runner"); + let mut config = GuardedGitConfig::authorize_status_async(&git) + .await + .expect("authorized status capability"); + config + .verify_status_root_async(repo.path()) + .await + .expect("matching root"); + config + .install_status_policy_async() + .await + .expect("installed status policy"); + let status = config.status.as_ref().expect("Status context"); + let owned_config = status + .context + .config_path(&config.identity) + .expect("owned config path"); + let contents = std::fs::read_to_string(owned_config).expect("read owned config"); + assert!( + contents.contains(&format!("symlinks = {value}")), + "core.symlinks={value} was not frozen: {contents}" + ); + } +} diff --git a/codex-rs/git-utils/src/safe_git_tests.rs b/codex-rs/git-utils/src/safe_git_tests.rs index 03bcf7af6f..0cfbbcd468 100644 --- a/codex-rs/git-utils/src/safe_git_tests.rs +++ b/codex-rs/git-utils/src/safe_git_tests.rs @@ -613,6 +613,65 @@ async fn configured_filter_ran(repo_path: &Path) -> bool { output.status.success() } +#[cfg(unix)] +async fn assert_filter_policy_for_index_entry( + repo_path: &Path, + tracked_path: &str, + expected_mode: &str, + expect_selected_filter: bool, +) { + let stage = TokioCommand::new("git") + .args(["ls-files", "--stage", "--", tracked_path]) + .current_dir(repo_path) + .output() + .await + .expect("read index mode"); + assert!( + stage.status.success(), + "ls-files failed: {}", + String::from_utf8_lossy(&stage.stderr) + ); + assert!( + stage + .stdout + .starts_with(format!("{expected_mode} ").as_bytes()), + "unexpected index entry: {}", + String::from_utf8_lossy(&stage.stdout) + ); + + for (key, command) in [ + ( + "filter.evil.clean", + "git config codex.filterran true && git hash-object --stdin", + ), + ( + "filter.evil.process", + "git config codex.filterran true; exit 1", + ), + ] { + run_git_async(repo_path, &["config", key, command]).await; + run_git_async(repo_path, &["config", "filter.evil.required", "true"]).await; + let expected = if expect_selected_filter { + Err(GitReadError::SelectedExecutableFilter { + driver: "evil".to_string(), + path: tracked_path.to_string(), + }) + } else { + Ok(false) + }; + assert_eq!( + try_get_has_changes_with_test_timeout(repo_path).await, + expected, + "unexpected {key} policy for index mode {expected_mode}" + ); + assert!( + !configured_filter_ran(repo_path).await, + "{key} unexpectedly ran for index mode {expected_mode}" + ); + run_git_async(repo_path, &["config", "--unset-all", key]).await; + } +} + async fn add_submodule_with_clean_filter(parent: &Path) { let source = tempfile::tempdir().expect("submodule source"); let source_path = source.path(); @@ -670,6 +729,87 @@ async fn get_has_changes_rejects_configured_clean_filter_without_running_it() { assert!(!configured_filter_ran(&repo_path).await); } +#[cfg(unix)] +#[tokio::test] +async fn get_has_changes_skips_executable_filters_selected_only_by_a_symlink() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo_path = create_test_git_repo(&temp_dir).await; + std::fs::write(repo_path.join("target"), "target contents\n").expect("write link target"); + std::os::unix::fs::symlink("target", repo_path.join("link")).expect("create symlink"); + std::fs::write(repo_path.join(".gitattributes"), "link filter=evil\n") + .expect("write attributes"); + run_git_async(&repo_path, &["add", ".gitattributes", "link", "target"]).await; + run_git_async(&repo_path, &["commit", "-m", "add filtered symlink"]).await; + run_git_async(&repo_path, &["config", "core.symlinks", "true"]).await; + + assert_filter_policy_for_index_entry( + &repo_path, "link", "120000", /*expect_selected_filter*/ false, + ) + .await; +} + +#[cfg(unix)] +#[tokio::test] +async fn get_has_changes_rejects_filters_for_an_emulated_symlink() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo_path = create_test_git_repo(&temp_dir).await; + std::fs::write(repo_path.join("target"), "target contents\n").expect("write link target"); + std::os::unix::fs::symlink("target", repo_path.join("link")).expect("create symlink"); + std::fs::write(repo_path.join(".gitattributes"), "link filter=evil\n") + .expect("write attributes"); + run_git_async(&repo_path, &["add", ".gitattributes", "link", "target"]).await; + run_git_async(&repo_path, &["commit", "-m", "add filtered symlink"]).await; + + std::fs::remove_file(repo_path.join("link")).expect("remove native symlink"); + run_git_async(&repo_path, &["config", "core.symlinks", "false"]).await; + run_git_async(&repo_path, &["checkout", "--", "link"]).await; + let metadata = + std::fs::symlink_metadata(repo_path.join("link")).expect("read emulated symlink metadata"); + assert!( + metadata.is_file() && !metadata.file_type().is_symlink(), + "core.symlinks=false must materialize an ordinary worktree file" + ); + let contents = std::fs::read(repo_path.join("link")).expect("read emulated symlink"); + assert_eq!(contents, b"target"); + std::thread::sleep(std::time::Duration::from_secs(1)); + std::fs::write(repo_path.join("link"), contents).expect("refresh emulated symlink stat"); + + assert_filter_policy_for_index_entry( + &repo_path, "link", "120000", /*expect_selected_filter*/ true, + ) + .await; +} + +#[cfg(unix)] +#[tokio::test] +async fn get_has_changes_skips_executable_filters_selected_only_by_a_gitlink() { + let source_temp = tempfile::tempdir().expect("create source temp dir"); + let source_path = create_test_git_repo(&source_temp).await; + let parent_temp = tempfile::tempdir().expect("create parent temp dir"); + let repo_path = create_test_git_repo(&parent_temp).await; + run_git_async( + &repo_path, + &[ + "-c", + "protocol.file.allow=always", + "submodule", + "add", + source_path.to_str().expect("UTF-8 source path"), + "nested", + ], + ) + .await; + std::fs::write(repo_path.join(".gitattributes"), "nested filter=evil\n") + .expect("write attributes"); + run_git_async(&repo_path, &["add", ".gitattributes"]).await; + run_git_async(&repo_path, &["commit", "-m", "add filtered gitlink"]).await; + + assert_filter_policy_for_index_entry( + &repo_path, "nested", "160000", /*expect_selected_filter*/ false, + ) + .await; +} + #[tokio::test] async fn get_has_changes_pins_normal_untracked_files_over_repository_config() { let temp_dir = tempfile::tempdir().expect("create temp dir"); @@ -765,6 +905,24 @@ async fn checked_has_changes_accepts_non_utf8_repository_root() { ); } +#[cfg(any(unix, windows))] +#[tokio::test] +async fn checked_has_changes_accepts_repository_root_with_alternate_list_separator() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let original_repo = create_test_git_repo(&temp_dir).await; + #[cfg(unix)] + let repo_path = temp_dir.path().join(r"repo:colon;semicolon\backslash"); + #[cfg(windows)] + let repo_path = temp_dir.path().join("repo;semicolon"); + std::fs::rename(&original_repo, &repo_path).expect("rename repository"); + std::fs::write(repo_path.join("test.txt"), "modified content").expect("modify tracked file"); + + assert_eq!( + try_get_has_changes_with_test_timeout(&repo_path).await, + Ok(true) + ); +} + #[cfg(unix)] #[tokio::test] async fn checked_has_changes_preserves_lexical_repository_ancestry_for_git_selection() { diff --git a/codex-rs/git-utils/src/status_guard_tests.rs b/codex-rs/git-utils/src/status_guard_tests.rs index 7c87ed5824..658745a3a9 100644 --- a/codex-rs/git-utils/src/status_guard_tests.rs +++ b/codex-rs/git-utils/src/status_guard_tests.rs @@ -373,6 +373,44 @@ async fn frozen_status_blocks_a_new_filter_namespace_and_attribute_after_prepara assert!(!filter_marker_is_set(&repo, "codex.fresh-ran").await); } +#[tokio::test] +async fn status_refuses_core_symlinks_drift_between_filter_gate_and_projection() { + let temp_dir = tempfile::tempdir().expect("create temp dir"); + let repo = init_repo(&temp_dir, /*file_count*/ 0).await; + run_git(&repo, &["config", "core.symlinks", "true"]).await; + + let wrapper = temp_dir.path().join("git-wrapper"); + let log = temp_dir.path().join("git-wrapper.log"); + let real_git = shell_quote(&real_git()); + write_wrapper( + &wrapper, + &format!( + "#!/bin/sh\nprintf '%s\\n' \"$*\" >>{}\ncase \"$*\" in\n *\"ls-files -z --cached --stage\"*)\n {real_git} \"$@\" >\"$0.output\"\n status=$?\n {real_git} -C {} config core.symlinks false || exit 125\n /bin/cat \"$0.output\"\n /bin/rm -f \"$0.output\"\n exit $status\n ;;\nesac\nexec {real_git} \"$@\"\n", + shell_quote(&log), + shell_quote(&repo), + ), + ); + let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner"); + let mut config = GuardedGitConfig::authorize_status_async(&git) + .await + .expect("authorized status capability"); + config + .verify_status_root_async(&repo) + .await + .expect("matching root"); + + let result = config.install_status_policy_async().await; + let commands = std::fs::read_to_string(log).expect("read wrapper log"); + let configured = run_git(&repo, &["config", "--get", "core.symlinks"]).await; + assert_eq!( + configured.stdout, b"false\n", + "wrapper did not mutate core.symlinks; commands:\n{commands}" + ); + assert!(commands.contains("ls-files -z --cached --stage")); + let error = result.expect_err("core.symlinks drift must fail before publishing Status context"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); +} + #[tokio::test] async fn frozen_status_preserves_info_global_core_and_system_attribute_selection() { const MARKER: &str = "CODEX_GIT_UTILS_STATUS_ATTRIBUTE_ENV_CHILD"; @@ -594,10 +632,10 @@ async fn frozen_untracked_presence_honors_all_standard_ignore_sources() { async fn frozen_status_reports_an_ordinary_unmerged_index_as_dirty() { let temp_dir = tempfile::tempdir().expect("create temp dir"); let repo = init_repo(&temp_dir, /*file_count*/ 0).await; - std::fs::write(repo.join(".gitattributes"), "* filter\n") - .expect("write special filter attribute"); + std::fs::write(repo.join(".gitattributes"), "test.txt filter=evil\n") + .expect("write literal filter attribute"); run_git(&repo, &["add", ".gitattributes"]).await; - run_git(&repo, &["commit", "-m", "special filter attribute"]).await; + run_git(&repo, &["commit", "-m", "literal filter attribute"]).await; let base_branch = String::from_utf8( run_git(&repo, &["rev-parse", "--abbrev-ref", "HEAD"]) .await @@ -628,7 +666,7 @@ async fn frozen_status_reports_an_ordinary_unmerged_index_as_dirty() { &repo, &[ "config", - "filter.set.clean", + "filter.evil.clean", "git config codex.unmerged-filter-ran true && git hash-object --stdin", ], ) @@ -1033,7 +1071,7 @@ async fn ordinary_driver_uses_one_bulk_path_and_attribute_probe() { assert_eq!( lines .lines() - .filter(|line| line.contains(" ls-files -z --cached")) + .filter(|line| line.contains(" ls-files -z --cached --stage")) .count(), 1 ); @@ -1151,7 +1189,7 @@ async fn zero_driver_status_builds_the_same_frozen_context_without_an_overlay() .await .expect("zero-driver status capability"); let lines = std::fs::read_to_string(log).expect("read wrapper log"); - assert!(lines.contains(" ls-files -z --cached"), "{lines}"); + assert!(lines.contains(" ls-files -z --cached --stage"), "{lines}"); assert!(!lines.contains(" check-attr --stdin -z filter"), "{lines}"); assert!(!lines.contains(" check-attr --stdin -z"), "{lines}"); assert!(lines.contains("config --file "), "{lines}"); @@ -1200,7 +1238,7 @@ async fn status_driver_limit_fails_before_paths_or_overlay_writes() { .expect_err("257th driver must fail closed"); assert_eq!(error.kind(), io::ErrorKind::InvalidData); let lines = std::fs::read_to_string(log).expect("read wrapper log"); - assert!(!lines.contains(" ls-files -z --cached"), "{lines}"); + assert!(!lines.contains(" ls-files -z --cached --stage"), "{lines}"); assert!(!lines.contains(" check-attr --stdin -z filter"), "{lines}"); assert!(!lines.contains(" config --file "), "{lines}"); }