mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
git-utils: harden frozen status sentinel probes
This commit is contained in:
@@ -553,7 +553,7 @@ async fn responses_stream_includes_turn_metadata_header_for_git_workspace_e2e()
|
||||
// Git enrichment is intentionally asynchronous. Keep the first
|
||||
// response open long enough for the follow-up request to observe
|
||||
// the enriched metadata, even on slower CI hosts.
|
||||
responses::sse_response(first_response).set_delay(std::time::Duration::from_secs(2)),
|
||||
responses::sse_response(first_response).set_delay(std::time::Duration::from_secs(7)),
|
||||
responses::sse_response(follow_up_response),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -14,7 +14,6 @@ use tokio::io::AsyncReadExt;
|
||||
|
||||
use crate::errors::GitReadError;
|
||||
use crate::git_config_environment::GitConfigEnvironmentSnapshot;
|
||||
use crate::guarded_config::GuardedOperationIdentity;
|
||||
#[cfg(test)]
|
||||
use crate::git_executable::git_executable_name;
|
||||
use crate::git_executable::harden_git_launch_environment;
|
||||
@@ -25,6 +24,7 @@ use crate::git_executable::search_directory_is_untrusted;
|
||||
use crate::git_executable::select_git_executable;
|
||||
#[cfg(all(test, windows))]
|
||||
use crate::git_executable::windows_path_requires_fail_closed;
|
||||
use crate::guarded_config::GuardedOperationIdentity;
|
||||
use crate::repository_authority::RepositoryAuthority;
|
||||
#[cfg(test)]
|
||||
use crate::repository_authority::parse_marker_path as parse_git_marker_path;
|
||||
@@ -146,8 +146,7 @@ impl IsolatedGitReadContext {
|
||||
|
||||
pub(crate) fn seal_projected_files(mut self) -> io::Result<Self> {
|
||||
self.config_contents = Some(std::fs::read(self.config_path())?.into_boxed_slice());
|
||||
self.attributes_contents =
|
||||
Some(std::fs::read(self.attributes_path())?.into_boxed_slice());
|
||||
self.attributes_contents = Some(std::fs::read(self.attributes_path())?.into_boxed_slice());
|
||||
self.validate()?;
|
||||
Ok(self)
|
||||
}
|
||||
@@ -379,10 +378,7 @@ impl GitRunner {
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
pub(crate) fn async_config_file_write_command(
|
||||
&self,
|
||||
config_path: &Path,
|
||||
) -> GitAsyncCommand {
|
||||
pub(crate) fn async_config_file_write_command(&self, config_path: &Path) -> GitAsyncCommand {
|
||||
let mut command = self.async_command();
|
||||
scrub_repository_and_config_environment(command.inner.as_std_mut());
|
||||
command
|
||||
@@ -1075,42 +1071,42 @@ async fn output_async_bounded_inner(
|
||||
mut command: GitAsyncCommand,
|
||||
max_bytes_per_stream: usize,
|
||||
) -> io::Result<std::process::Output> {
|
||||
command.inner.kill_on_drop(true);
|
||||
if !command.stdin_configured {
|
||||
command.inner.stdin(Stdio::null());
|
||||
command.inner.kill_on_drop(true);
|
||||
if !command.stdin_configured {
|
||||
command.inner.stdin(Stdio::null());
|
||||
}
|
||||
command.inner.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = command.inner.spawn()?;
|
||||
// No caller can obtain the pipe writer through this opaque command.
|
||||
// Close it immediately so a child configured with `Stdio::piped()`
|
||||
// observes EOF instead of waiting forever for unreachable input.
|
||||
drop(child.stdin.take());
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| io::Error::other("missing bounded Git stdout pipe"))?;
|
||||
let stderr = child
|
||||
.stderr
|
||||
.take()
|
||||
.ok_or_else(|| io::Error::other("missing bounded Git stderr pipe"))?;
|
||||
let output = tokio::try_join!(
|
||||
read_bounded_output(stdout, max_bytes_per_stream),
|
||||
read_bounded_output(stderr, max_bytes_per_stream)
|
||||
);
|
||||
let (stdout, stderr) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) => {
|
||||
let _ = child.kill().await;
|
||||
let _ = child.wait().await;
|
||||
return Err(error);
|
||||
}
|
||||
command.inner.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = command.inner.spawn()?;
|
||||
// No caller can obtain the pipe writer through this opaque command.
|
||||
// Close it immediately so a child configured with `Stdio::piped()`
|
||||
// observes EOF instead of waiting forever for unreachable input.
|
||||
drop(child.stdin.take());
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| io::Error::other("missing bounded Git stdout pipe"))?;
|
||||
let stderr = child
|
||||
.stderr
|
||||
.take()
|
||||
.ok_or_else(|| io::Error::other("missing bounded Git stderr pipe"))?;
|
||||
let output = tokio::try_join!(
|
||||
read_bounded_output(stdout, max_bytes_per_stream),
|
||||
read_bounded_output(stderr, max_bytes_per_stream)
|
||||
);
|
||||
let (stdout, stderr) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) => {
|
||||
let _ = child.kill().await;
|
||||
let _ = child.wait().await;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let status = child.wait().await?;
|
||||
Ok(std::process::Output {
|
||||
status,
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
};
|
||||
let status = child.wait().await?;
|
||||
Ok(std::process::Output {
|
||||
status,
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_bounded_output(
|
||||
@@ -1145,7 +1141,12 @@ async fn read_common_info_attributes_bounded_async(
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
|
||||
fn openat(directory: &std::fs::File, name: &str, flags: i32) -> io::Result<std::fs::File> {
|
||||
let name = CString::new(name).expect("fixed path component");
|
||||
let name = CString::new(name).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Git attribute path component contains NUL",
|
||||
)
|
||||
})?;
|
||||
// SAFETY: the directory descriptor is live and the fixed component is
|
||||
// NUL-free. The returned descriptor is immediately owned by File.
|
||||
let descriptor = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) };
|
||||
@@ -1164,11 +1165,7 @@ async fn read_common_info_attributes_bounded_async(
|
||||
let info = match openat(
|
||||
&root,
|
||||
"info",
|
||||
libc::O_RDONLY
|
||||
| libc::O_DIRECTORY
|
||||
| libc::O_NOFOLLOW
|
||||
| libc::O_NONBLOCK
|
||||
| libc::O_CLOEXEC,
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC,
|
||||
) {
|
||||
Ok(info) => info,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
|
||||
@@ -52,7 +52,7 @@ async fn bounded_async_output_rejects_the_first_byte_over_limit() {
|
||||
async fn common_info_attributes_treat_a_missing_info_directory_as_empty_and_bound_bytes() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
assert_eq!(
|
||||
read_common_info_attributes_bounded_async(fixture.path(), 4)
|
||||
read_common_info_attributes_bounded_async(fixture.path(), /*max_bytes*/ 4)
|
||||
.await
|
||||
.expect("missing info directory is an empty source"),
|
||||
Vec::<u8>::new()
|
||||
@@ -62,7 +62,7 @@ async fn common_info_attributes_treat_a_missing_info_directory_as_empty_and_boun
|
||||
std::fs::write(fixture.path().join("info/attributes"), b"1234")
|
||||
.expect("write exact-limit attributes");
|
||||
assert_eq!(
|
||||
read_common_info_attributes_bounded_async(fixture.path(), 4)
|
||||
read_common_info_attributes_bounded_async(fixture.path(), /*max_bytes*/ 4)
|
||||
.await
|
||||
.expect("exact-limit attributes"),
|
||||
b"1234"
|
||||
@@ -70,7 +70,7 @@ async fn common_info_attributes_treat_a_missing_info_directory_as_empty_and_boun
|
||||
std::fs::write(fixture.path().join("info/attributes"), b"12345")
|
||||
.expect("write over-limit attributes");
|
||||
assert_eq!(
|
||||
read_common_info_attributes_bounded_async(fixture.path(), 4)
|
||||
read_common_info_attributes_bounded_async(fixture.path(), /*max_bytes*/ 4)
|
||||
.await
|
||||
.expect_err("over-limit attributes must fail")
|
||||
.kind(),
|
||||
|
||||
@@ -35,18 +35,18 @@ use crate::safe_git::FilterPolicySnapshot;
|
||||
use crate::safe_git::MAX_EXECUTABLE_FILTER_DRIVERS;
|
||||
use crate::safe_git::SelectedFilterPolicy;
|
||||
use crate::safe_git::SentinelFilterProbeBudget;
|
||||
use crate::safe_git::SentinelFilterProbeResolution;
|
||||
use crate::safe_git::build_filter_policy_snapshot;
|
||||
use crate::safe_git::classify_selected_filter;
|
||||
use crate::safe_git::classify_sentinel_filter_probes;
|
||||
use crate::safe_git::status_policy_filter_drivers;
|
||||
use crate::safe_git::git_path_argument;
|
||||
use crate::safe_git::parse_filter_attributes;
|
||||
use crate::safe_git::parse_nul_paths;
|
||||
use crate::safe_git::status_policy_filter_drivers;
|
||||
use crate::safe_git::validate_executable_driver_count;
|
||||
use crate::safe_git::write_nul_paths;
|
||||
|
||||
const MAX_STATUS_TRACKED_PATHS: usize = 250_000;
|
||||
const MAX_STATUS_SENTINEL_PATHSPEC_BYTES: usize = 16 * 1024;
|
||||
const MAX_STATUS_SENTINEL_STAGE_RECORDS: usize = 3;
|
||||
const FILTER_NEUTRALIZATION_PLAN: [(&str, &str); 4] = [
|
||||
("clean", ""),
|
||||
("smudge", ""),
|
||||
@@ -224,8 +224,7 @@ impl<'git> ValidatedConfigSources<'git> {
|
||||
let (legacy, legacy_path) = self
|
||||
.git
|
||||
.read_active_common_config_without_includes_async(
|
||||
pattern,
|
||||
/*show_scope*/ false,
|
||||
pattern, /*show_scope*/ false,
|
||||
)
|
||||
.await?;
|
||||
if legacy_path != scoped_path {
|
||||
@@ -1302,10 +1301,7 @@ 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)
|
||||
.await?;
|
||||
self.status = Some(StatusPolicySnapshot {
|
||||
context,
|
||||
@@ -1318,8 +1314,7 @@ impl<'git> GuardedGitConfig<'git> {
|
||||
&self,
|
||||
neutralizer: Option<&SealedFilterConfigOverride>,
|
||||
) -> io::Result<bool> {
|
||||
let mut command =
|
||||
self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
let mut command = self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
command.disable_optional_locks().args([
|
||||
"ls-files",
|
||||
"-z",
|
||||
@@ -1331,7 +1326,10 @@ impl<'git> GuardedGitConfig<'git> {
|
||||
]);
|
||||
let output = command.output().await?;
|
||||
if !output.status.success() {
|
||||
return Err(command_failure("status untracked-presence inventory", &output));
|
||||
return Err(command_failure(
|
||||
"status untracked-presence inventory",
|
||||
&output,
|
||||
));
|
||||
}
|
||||
let paths = parse_nul_paths(&output.stdout)?;
|
||||
if paths.len() > MAX_STATUS_TRACKED_PATHS {
|
||||
@@ -1347,24 +1345,23 @@ impl<'git> GuardedGitConfig<'git> {
|
||||
&self,
|
||||
neutralizer: Option<&SealedFilterConfigOverride>,
|
||||
) -> io::Result<Option<String>> {
|
||||
let mut command =
|
||||
self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
command
|
||||
.disable_optional_locks()
|
||||
.args(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]);
|
||||
let mut command = self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
command.disable_optional_locks().args([
|
||||
"rev-parse",
|
||||
"--verify",
|
||||
"--quiet",
|
||||
"HEAD^{commit}",
|
||||
]);
|
||||
let output = command.output().await?;
|
||||
if output.status.success() {
|
||||
return parse_status_head_oid(&output.stdout).map(Some);
|
||||
}
|
||||
if output.status.code() != Some(1)
|
||||
|| !output.stdout.is_empty()
|
||||
|| !output.stderr.is_empty()
|
||||
if output.status.code() != Some(1) || !output.stdout.is_empty() || !output.stderr.is_empty()
|
||||
{
|
||||
return Err(command_failure("status HEAD snapshot", &output));
|
||||
}
|
||||
|
||||
let mut symbolic =
|
||||
self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
let mut symbolic = self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
symbolic
|
||||
.disable_optional_locks()
|
||||
.args(["symbolic-ref", "--quiet", "HEAD"]);
|
||||
@@ -1380,10 +1377,7 @@ impl<'git> GuardedGitConfig<'git> {
|
||||
.args(["show-ref", "--verify", "--quiet", "--"])
|
||||
.arg(&target);
|
||||
let verify = verify.output().await?;
|
||||
if verify.status.code() == Some(1)
|
||||
&& verify.stdout.is_empty()
|
||||
&& verify.stderr.is_empty()
|
||||
{
|
||||
if verify.status.code() == Some(1) && verify.stdout.is_empty() && verify.stderr.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if verify.status.success() {
|
||||
@@ -1409,8 +1403,7 @@ impl<'git> GuardedGitConfig<'git> {
|
||||
"frozen Status is unavailable with a custom Git replacement-ref namespace",
|
||||
));
|
||||
}
|
||||
let mut command =
|
||||
self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
let mut command = self.pending_status_command(FsmonitorOverride::Disabled, neutralizer)?;
|
||||
command.disable_optional_locks().args([
|
||||
"for-each-ref",
|
||||
"--format=%(refname)",
|
||||
@@ -1592,49 +1585,6 @@ impl<'git> GuardedGitConfig<'git> {
|
||||
neutralizer: &SealedFilterConfigOverride,
|
||||
probe_budget: &mut SentinelFilterProbeBudget,
|
||||
) -> io::Result<bool> {
|
||||
let required = self
|
||||
.run_status_sentinel_probe_async(
|
||||
path,
|
||||
driver,
|
||||
/*required*/ true,
|
||||
neutralizer,
|
||||
probe_budget,
|
||||
)
|
||||
.await?;
|
||||
if classify_sentinel_filter_probes(
|
||||
required.status.success(),
|
||||
/*optional_succeeded*/ None,
|
||||
) == SentinelFilterProbeResolution::SpecialAttributeState
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let optional = self
|
||||
.run_status_sentinel_probe_async(
|
||||
path,
|
||||
driver,
|
||||
/*required*/ false,
|
||||
neutralizer,
|
||||
probe_budget,
|
||||
)
|
||||
.await?;
|
||||
if classify_sentinel_filter_probes(
|
||||
required.status.success(),
|
||||
Some(optional.status.success()),
|
||||
) == SentinelFilterProbeResolution::LiteralDriver
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
Err(command_failure("status filter sentinel probe", &optional))
|
||||
}
|
||||
|
||||
async fn run_status_sentinel_probe_async(
|
||||
&self,
|
||||
path: &[u8],
|
||||
driver: &str,
|
||||
required: bool,
|
||||
neutralizer: &SealedFilterConfigOverride,
|
||||
probe_budget: &mut SentinelFilterProbeBudget,
|
||||
) -> io::Result<std::process::Output> {
|
||||
if !matches!(driver, "set" | "unset" | "unspecified") {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
@@ -1653,14 +1603,14 @@ impl<'git> GuardedGitConfig<'git> {
|
||||
self.pending_status_command(FsmonitorOverride::Disabled, Some(neutralizer))?;
|
||||
command
|
||||
.disable_optional_locks()
|
||||
.args(["-c", &format!("filter.{driver}.required={required}")])
|
||||
.args(["hash-object", "--stdin"])
|
||||
.arg("--path")
|
||||
.arg(git_path_argument(path)?)
|
||||
.stdin(Stdio::null());
|
||||
.args(["ls-files", "--cached", "--full-name", "-z", "--"])
|
||||
.arg(status_filter_special_pathspec(path, driver)?);
|
||||
let output = command.output().await?;
|
||||
probe_budget.record_completed_probe();
|
||||
Ok(output)
|
||||
if !output.status.success() {
|
||||
return Err(command_failure("status filter sentinel probe", &output));
|
||||
}
|
||||
status_filter_sentinel_probe_selects_driver(&output.stdout, path)
|
||||
}
|
||||
|
||||
fn ensure_owned_config_path(&self, path: &Path, description: &str) -> io::Result<()> {
|
||||
@@ -2112,7 +2062,10 @@ fn safe_scalar_override_args() -> [String; 4] {
|
||||
|
||||
fn parse_status_head_oid(output: &[u8]) -> io::Result<String> {
|
||||
let line = output.strip_suffix(b"\n").ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "unterminated Status HEAD output")
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"unterminated Status HEAD output",
|
||||
)
|
||||
})?;
|
||||
let line = line.strip_suffix(b"\r").unwrap_or(line);
|
||||
if !matches!(line.len(), 40 | 64) || !line.iter().all(u8::is_ascii_hexdigit) {
|
||||
@@ -2121,7 +2074,62 @@ fn parse_status_head_oid(output: &[u8]) -> io::Result<String> {
|
||||
"Status HEAD did not resolve to one full object ID",
|
||||
));
|
||||
}
|
||||
Ok(String::from_utf8(line.to_ascii_lowercase()).expect("ASCII object ID"))
|
||||
String::from_utf8(line.to_ascii_lowercase()).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Status HEAD output was not a valid hexadecimal object ID",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn status_filter_special_pathspec(path: &[u8], driver: &str) -> io::Result<std::ffi::OsString> {
|
||||
if path.is_empty() || path.contains(&0) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid Status filter sentinel path",
|
||||
));
|
||||
}
|
||||
let requirement = match driver {
|
||||
"set" => "filter",
|
||||
"unset" => "-filter",
|
||||
"unspecified" => "!filter",
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Git filter sentinel probe requested for a non-sentinel driver",
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut pathspec = format!(":(top,literal,attr:{requirement})").into_bytes();
|
||||
pathspec.extend_from_slice(path);
|
||||
if pathspec.len() > MAX_STATUS_SENTINEL_PATHSPEC_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"Git filter sentinel pathspec exceeds the Status byte limit",
|
||||
));
|
||||
}
|
||||
git_path_argument(&pathspec)
|
||||
}
|
||||
|
||||
fn status_filter_sentinel_probe_selects_driver(output: &[u8], path: &[u8]) -> io::Result<bool> {
|
||||
let matches = parse_nul_paths(output)?;
|
||||
if matches.is_empty() {
|
||||
// The public check-attr spelling was ambiguous at T0. If the one
|
||||
// authoritative T1 pathspec does not prove the corresponding special
|
||||
// state, conservatively retain the spelling as a literal driver
|
||||
// selection. This preserves the structured selected-filter refusal
|
||||
// and also fails closed for any intervening source drift.
|
||||
return Ok(true);
|
||||
}
|
||||
if matches.len() > MAX_STATUS_SENTINEL_STAGE_RECORDS
|
||||
|| matches.iter().any(|matched| matched != path)
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"status filter sentinel probe returned non-exact index paths",
|
||||
));
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn parse_status_symbolic_ref(output: &[u8]) -> io::Result<std::ffi::OsString> {
|
||||
|
||||
@@ -44,7 +44,10 @@ impl SealedStatusReadContext {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn config_path(&self, owner: &Arc<CapabilityIdentity>) -> io::Result<std::path::PathBuf> {
|
||||
pub(super) fn config_path(
|
||||
&self,
|
||||
owner: &Arc<CapabilityIdentity>,
|
||||
) -> io::Result<std::path::PathBuf> {
|
||||
Ok(self.context(owner)?.config_path())
|
||||
}
|
||||
|
||||
@@ -105,10 +108,7 @@ impl GuardedGitConfig<'_> {
|
||||
.await?;
|
||||
let repository_format = self
|
||||
.sources
|
||||
.read_direct_common_config_async(
|
||||
REPOSITORY_FORMAT_CONFIG_PATTERN,
|
||||
"repository format",
|
||||
)
|
||||
.read_direct_common_config_async(REPOSITORY_FORMAT_CONFIG_PATTERN, "repository format")
|
||||
.await?;
|
||||
if entries.len().saturating_add(repository_format.len())
|
||||
> MAX_STATUS_PROJECTED_CONFIG_ENTRIES
|
||||
@@ -119,10 +119,9 @@ impl GuardedGitConfig<'_> {
|
||||
));
|
||||
}
|
||||
refuse_sparse_status(&entries)?;
|
||||
let projected_bytes = entries
|
||||
.iter()
|
||||
.chain(repository_format.iter())
|
||||
.try_fold(0_usize, |total, (key, entry)| {
|
||||
let projected_bytes = entries.iter().chain(repository_format.iter()).try_fold(
|
||||
0_usize,
|
||||
|total, (key, entry)| {
|
||||
total
|
||||
.checked_add(key.len())
|
||||
.and_then(|total| total.checked_add(entry.value.len()))
|
||||
@@ -133,7 +132,8 @@ impl GuardedGitConfig<'_> {
|
||||
"status config projection size overflow",
|
||||
)
|
||||
})
|
||||
})?;
|
||||
},
|
||||
)?;
|
||||
if projected_bytes > MAX_STATUS_PROJECTED_CONFIG_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
@@ -141,20 +141,12 @@ impl GuardedGitConfig<'_> {
|
||||
));
|
||||
}
|
||||
for entry in entries.values() {
|
||||
self.write_status_config_value_async(
|
||||
&context.config_path(),
|
||||
&entry.key,
|
||||
&entry.value,
|
||||
)
|
||||
.await?;
|
||||
self.write_status_config_value_async(&context.config_path(), &entry.key, &entry.value)
|
||||
.await?;
|
||||
}
|
||||
for entry in repository_format.values() {
|
||||
self.write_status_config_value_async(
|
||||
&context.config_path(),
|
||||
&entry.key,
|
||||
&entry.value,
|
||||
)
|
||||
.await?;
|
||||
self.write_status_config_value_async(&context.config_path(), &entry.key, &entry.value)
|
||||
.await?;
|
||||
}
|
||||
self.write_status_config_value_async(&context.config_path(), "core.bare", "false")
|
||||
.await?;
|
||||
@@ -217,10 +209,7 @@ impl GuardedGitConfig<'_> {
|
||||
"core.attributesFile",
|
||||
]);
|
||||
let output = command.output().await?;
|
||||
if output.status.code() == Some(1)
|
||||
&& output.stdout.is_empty()
|
||||
&& output.stderr.is_empty()
|
||||
{
|
||||
if output.status.code() == Some(1) && output.stdout.is_empty() && output.stderr.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if !output.status.success() {
|
||||
|
||||
@@ -40,6 +40,57 @@ fn run_isolated_config_test(test_name: &str) {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn status_filter_special_pathspec_preserves_raw_literal_paths() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
let path = b"dir/a*?[\\:)-\xff";
|
||||
for (driver, requirement) in [
|
||||
("set", "filter"),
|
||||
("unset", "-filter"),
|
||||
("unspecified", "!filter"),
|
||||
] {
|
||||
let actual = status_filter_special_pathspec(path, driver)
|
||||
.expect("bounded raw Status pathspec")
|
||||
.into_vec();
|
||||
let mut expected = format!(":(top,literal,attr:{requirement})").into_bytes();
|
||||
expected.extend_from_slice(path);
|
||||
assert_eq!(actual, expected, "{driver}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_filter_sentinel_probe_requires_exact_bounded_stage_records() {
|
||||
let path = b"dir/file.txt";
|
||||
assert!(
|
||||
status_filter_sentinel_probe_selects_driver(b"", path).expect("empty exact output"),
|
||||
"no special-state match conservatively retains the literal driver"
|
||||
);
|
||||
assert!(
|
||||
!status_filter_sentinel_probe_selects_driver(b"dir/file.txt\0", path)
|
||||
.expect("one exact stage")
|
||||
);
|
||||
assert!(
|
||||
!status_filter_sentinel_probe_selects_driver(
|
||||
b"dir/file.txt\0dir/file.txt\0dir/file.txt\0",
|
||||
path,
|
||||
)
|
||||
.expect("three exact stages"),
|
||||
"three unmerged stages may repeat the exact path"
|
||||
);
|
||||
for malformed in [
|
||||
b"dir/file.txt".as_slice(),
|
||||
b"other.txt\0".as_slice(),
|
||||
b"dir/file.txt\0dir/file.txt\0dir/file.txt\0dir/file.txt\0".as_slice(),
|
||||
] {
|
||||
assert!(
|
||||
status_filter_sentinel_probe_selects_driver(malformed, path).is_err(),
|
||||
"accepted malformed sentinel output {malformed:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frozen_apply_policy_overrides_later_repository_config_changes() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
@@ -718,12 +769,18 @@ async fn status_replaces_filter_config_with_an_owned_helper_free_context() {
|
||||
config.detect_status_fsmonitor_async().await;
|
||||
let output = config.status_output_async().await.expect("guarded status");
|
||||
assert!(output.status.success());
|
||||
assert!(owned_config.is_file(), "owned config must outlive final child");
|
||||
assert!(
|
||||
owned_config.is_file(),
|
||||
"owned config must outlive final child"
|
||||
);
|
||||
assert!(
|
||||
owned_attributes.is_file(),
|
||||
"owned attributes must outlive final child"
|
||||
);
|
||||
drop(config);
|
||||
assert!(!owned_config.exists(), "owned config must be removed");
|
||||
assert!(!owned_attributes.exists(), "owned attributes must be removed");
|
||||
assert!(
|
||||
!owned_attributes.exists(),
|
||||
"owned attributes must be removed"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -439,12 +439,15 @@ async fn frozen_status_preserves_info_global_core_and_system_attribute_selection
|
||||
"isolated global/info source parity diverged: {}",
|
||||
String::from_utf8_lossy(&global_info_output.stdout)
|
||||
);
|
||||
assert!(!global_info_guard.status_has_untracked_snapshot().expect("untracked snapshot"));
|
||||
assert!(
|
||||
!global_info_guard
|
||||
.status_has_untracked_snapshot()
|
||||
.expect("untracked snapshot")
|
||||
);
|
||||
|
||||
let home = std::env::var("HOME").expect("isolated HOME");
|
||||
let xdg = std::env::var("XDG_CONFIG_HOME").expect("isolated XDG config home");
|
||||
let log_contents =
|
||||
std::fs::read_to_string(&log).expect("read attribute environment log");
|
||||
let log_contents = std::fs::read_to_string(&log).expect("read attribute environment log");
|
||||
let final_status = log_contents
|
||||
.lines()
|
||||
.find(|line| line.contains(" status --porcelain"))
|
||||
@@ -454,7 +457,11 @@ async fn frozen_status_preserves_info_global_core_and_system_attribute_selection
|
||||
"captured system/global attribute selectors were not restored: {final_status}"
|
||||
);
|
||||
|
||||
run_git(&repo, &["config", "core.attributesFile", "../core.attributes"]).await;
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "core.attributesFile", "../core.attributes"],
|
||||
)
|
||||
.await;
|
||||
std::fs::remove_file(repo.join("global.txt")).expect("remove global attribute fixture");
|
||||
run_git(&repo, &["checkout", "--", "global.txt"]).await;
|
||||
std::fs::remove_file(repo.join("core.txt")).expect("remove core attribute fixture");
|
||||
@@ -485,7 +492,11 @@ async fn frozen_status_preserves_info_global_core_and_system_attribute_selection
|
||||
"isolated core.attributesFile source parity diverged: {}",
|
||||
String::from_utf8_lossy(&core_output.stdout)
|
||||
);
|
||||
assert!(!core_guard.status_has_untracked_snapshot().expect("untracked snapshot"));
|
||||
assert!(
|
||||
!core_guard
|
||||
.status_has_untracked_snapshot()
|
||||
.expect("untracked snapshot")
|
||||
);
|
||||
|
||||
std::fs::write(
|
||||
repo.join(".git/info/attributes"),
|
||||
@@ -526,7 +537,7 @@ async fn frozen_status_refuses_git_attr_source_and_attr_tree() {
|
||||
"status_guard::tests::frozen_status_refuses_git_attr_source_and_attr_tree",
|
||||
MARKER,
|
||||
&[("GIT_ATTR_SOURCE", "HEAD")],
|
||||
None,
|
||||
/*global_attributes*/ None,
|
||||
);
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
@@ -543,8 +554,7 @@ async fn frozen_status_refuses_git_attr_source_and_attr_tree() {
|
||||
async fn frozen_untracked_presence_honors_all_standard_ignore_sources() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
std::fs::write(repo.join(".gitignore"), "root-ignored.txt\n")
|
||||
.expect("write root ignore");
|
||||
std::fs::write(repo.join(".gitignore"), "root-ignored.txt\n").expect("write root ignore");
|
||||
run_git(&repo, &["add", ".gitignore"]).await;
|
||||
run_git(&repo, &["commit", "-m", "ignore rules"]).await;
|
||||
std::fs::write(repo.join(".git/info/exclude"), "info-ignored.txt\n")
|
||||
@@ -560,11 +570,7 @@ async fn frozen_untracked_presence_honors_all_standard_ignore_sources() {
|
||||
],
|
||||
)
|
||||
.await;
|
||||
for name in [
|
||||
"root-ignored.txt",
|
||||
"info-ignored.txt",
|
||||
"global-ignored.txt",
|
||||
] {
|
||||
for name in ["root-ignored.txt", "info-ignored.txt", "global-ignored.txt"] {
|
||||
std::fs::write(repo.join(name), "ignored\n").expect("write ignored file");
|
||||
}
|
||||
|
||||
@@ -588,6 +594,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");
|
||||
run_git(&repo, &["add", ".gitattributes"]).await;
|
||||
run_git(&repo, &["commit", "-m", "special filter attribute"]).await;
|
||||
let base_branch = String::from_utf8(
|
||||
run_git(&repo, &["rev-parse", "--abbrev-ref", "HEAD"])
|
||||
.await
|
||||
@@ -614,9 +624,64 @@ async fn frozen_status_reports_an_ordinary_unmerged_index_as_dirty() {
|
||||
stages.stdout.split(|byte| *byte == b'\n').count() >= 3,
|
||||
"fixture must retain multiple index stages"
|
||||
);
|
||||
run_git(
|
||||
&repo,
|
||||
&[
|
||||
"config",
|
||||
"filter.set.clean",
|
||||
"git config codex.unmerged-filter-ran true && git hash-object --stdin",
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
assert_eq!(guarded_status(&repo, &git).await, Ok(true));
|
||||
assert!(!filter_marker_is_set(&repo, "codex.unmerged-filter-ran").await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sentinel_pathspec_handles_opaque_tracked_path_bytes_without_helpers() {
|
||||
use std::ffi::OsString;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
#[cfg(target_os = "macos")]
|
||||
let paths = vec![
|
||||
OsString::from("-leading.txt"),
|
||||
OsString::from("line\nbreak.txt"),
|
||||
];
|
||||
// macOS filesystem APIs reject non-UTF-8 names before Git can observe
|
||||
// them. Other Unix targets exercise the raw-byte path end to end; the
|
||||
// constructor unit test covers byte preservation on every Unix target.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let paths = vec![
|
||||
OsString::from("-leading.txt"),
|
||||
OsString::from("line\nbreak.txt"),
|
||||
OsString::from_vec(b"non-utf8-\xff.txt".to_vec()),
|
||||
];
|
||||
for path in paths {
|
||||
std::fs::write(repo.join(&path), "opaque path\n")
|
||||
.unwrap_or_else(|error| panic!("write opaque tracked path {path:?}: {error}"));
|
||||
}
|
||||
std::fs::write(repo.join(".gitattributes"), "* filter\n")
|
||||
.expect("write special filter attribute");
|
||||
run_git(&repo, &["add", "."]).await;
|
||||
run_git(&repo, &["commit", "-m", "opaque tracked paths"]).await;
|
||||
run_git(
|
||||
&repo,
|
||||
&[
|
||||
"config",
|
||||
"filter.set.clean",
|
||||
"git config codex.opaque-filter-ran true && git hash-object --stdin",
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
assert_eq!(guarded_status(&repo, &git).await, Ok(false));
|
||||
assert!(!filter_marker_is_set(&repo, "codex.opaque-filter-ran").await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -639,17 +704,20 @@ async fn status_head_snapshot_distinguishes_valid_detached_unborn_and_corrupt_st
|
||||
run_git(&repo, &["checkout", "-B", "restored", &commit]).await;
|
||||
|
||||
let ref_path = repo.join(".git/refs/heads/restored");
|
||||
std::fs::write(&ref_path, format!("{}\n", "a".repeat(40)))
|
||||
.expect("write missing-object ref");
|
||||
std::fs::write(&ref_path, format!("{}\n", "a".repeat(40))).expect("write missing-object ref");
|
||||
assert!(
|
||||
prepare_status_config(&git, &repo).await.is_err(),
|
||||
"missing-object symbolic HEAD must not become unborn"
|
||||
);
|
||||
|
||||
let blob = String::from_utf8(run_git(&repo, &["hash-object", "-w", "test.txt"]).await.stdout)
|
||||
.expect("blob UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
let blob = String::from_utf8(
|
||||
run_git(&repo, &["hash-object", "-w", "test.txt"])
|
||||
.await
|
||||
.stdout,
|
||||
)
|
||||
.expect("blob UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
std::fs::write(&ref_path, format!("{blob}\n")).expect("write blob ref");
|
||||
assert_eq!(
|
||||
prepare_status_config(&git, &repo).await.map(|_| ()),
|
||||
@@ -686,8 +754,8 @@ async fn frozen_status_refuses_active_or_custom_replacements_and_ignores_late_re
|
||||
run_isolated_environment_test(
|
||||
"status_guard::tests::frozen_status_refuses_active_or_custom_replacements_and_ignores_late_replacements",
|
||||
MARKER,
|
||||
&[("GIT_REPLACE_REF_BASE", "refs/codex-replacements")],
|
||||
None,
|
||||
&[("GIT_REPLACE_REF_BASE", "refs/codex-replacements/")],
|
||||
/*global_attributes*/ None,
|
||||
);
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
@@ -754,26 +822,21 @@ async fn optional_smudge_only_filter_is_allowed_but_required_is_refused() {
|
||||
async fn selected_required_only_filter_is_typed_and_refused_when_truthy() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
std::fs::write(repo.join(".gitattributes"), "test.txt filter=required-only\n")
|
||||
.expect("select required-only filter");
|
||||
std::fs::write(
|
||||
repo.join(".gitattributes"),
|
||||
"test.txt filter=required-only\n",
|
||||
)
|
||||
.expect("select required-only filter");
|
||||
run_git(&repo, &["add", ".gitattributes"]).await;
|
||||
run_git(&repo, &["commit", "-m", "required-only attribute"]).await;
|
||||
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "filter.required-only.required", "false"],
|
||||
)
|
||||
.await;
|
||||
run_git(&repo, &["config", "filter.required-only.required", "false"]).await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("selected required=false filter is inert");
|
||||
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "filter.required-only.required", "true"],
|
||||
)
|
||||
.await;
|
||||
run_git(&repo, &["config", "filter.required-only.required", "true"]).await;
|
||||
assert_eq!(
|
||||
prepare_status_config(&git, &repo).await.map(|_| ()),
|
||||
Err(GitReadError::SelectedExecutableFilter {
|
||||
@@ -792,13 +855,12 @@ async fn selected_required_only_filter_is_typed_and_refused_when_truthy() {
|
||||
"selected malformed required value must fail closed"
|
||||
);
|
||||
|
||||
std::fs::write(repo.join(".gitattributes"), "other.txt filter=required-only\n")
|
||||
.expect("move required-only filter off tracked paths");
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "filter.required-only.required", "true"],
|
||||
std::fs::write(
|
||||
repo.join(".gitattributes"),
|
||||
"other.txt filter=required-only\n",
|
||||
)
|
||||
.await;
|
||||
.expect("move required-only filter off tracked paths");
|
||||
run_git(&repo, &["config", "filter.required-only.required", "true"]).await;
|
||||
prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("unselected required-only namespace remains available");
|
||||
@@ -850,24 +912,22 @@ async fn optional_smudge_required_value_is_queried_once_per_driver() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sentinel_probe_neutralizes_a_race_selected_known_driver() {
|
||||
async fn sentinel_pathspec_refuses_a_raced_new_filter_namespace_without_helper() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
std::fs::write(repo.join(".gitattributes"), "test.txt filter\n")
|
||||
.expect("write sentinel attribute");
|
||||
run_git(&repo, &["add", ".gitattributes"]).await;
|
||||
run_git(&repo, &["commit", "-m", "sentinel attribute"]).await;
|
||||
for driver in ["set", "race"] {
|
||||
run_git(
|
||||
&repo,
|
||||
&[
|
||||
"config",
|
||||
&format!("filter.{driver}.clean"),
|
||||
"git config codex.probe-filter-ran true && git hash-object --stdin",
|
||||
],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
run_git(
|
||||
&repo,
|
||||
&[
|
||||
"config",
|
||||
"filter.set.clean",
|
||||
"git config codex.probe-filter-ran true && git hash-object --stdin",
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let wrapper = temp_dir.path().join("git-wrapper");
|
||||
let real_git = shell_quote(&real_git());
|
||||
@@ -875,14 +935,18 @@ async fn sentinel_probe_neutralizes_a_race_selected_known_driver() {
|
||||
write_wrapper(
|
||||
&wrapper,
|
||||
&format!(
|
||||
"#!/bin/sh\nfor arg in \"$@\"; do\n if [ \"$arg\" = check-attr ]; then\n {real_git} \"$@\" >\"$0.output\"\n status=$?\n printf 'test.txt filter=race\\n' >{attributes}\n /bin/cat \"$0.output\"\n /bin/rm -f \"$0.output\"\n exit $status\n fi\ndone\nexec {real_git} \"$@\"\n"
|
||||
"#!/bin/sh\nfor arg in \"$@\"; do\n if [ \"$arg\" = check-attr ]; then\n {real_git} \"$@\" >\"$0.output\"\n status=$?\n {real_git} config filter.evil.clean 'git config codex.probe-filter-ran true && git hash-object --stdin'\n printf 'test.txt filter=evil\\n' >{attributes}\n /bin/cat \"$0.output\"\n /bin/rm -f \"$0.output\"\n exit $status\n fi\ndone\nexec {real_git} \"$@\"\n"
|
||||
),
|
||||
);
|
||||
let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner");
|
||||
|
||||
prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("probe remains non-executing across attribute race");
|
||||
assert_eq!(
|
||||
prepare_status_config(&git, &repo).await.map(|_| ()),
|
||||
Err(GitReadError::SelectedExecutableFilter {
|
||||
driver: "set".to_string(),
|
||||
path: "test.txt".to_string(),
|
||||
})
|
||||
);
|
||||
assert!(!filter_marker_is_set(&repo, "codex.probe-filter-ran").await);
|
||||
}
|
||||
|
||||
@@ -926,7 +990,9 @@ async fn sentinel_probe_budget_fails_closed_at_the_exact_process_limit() {
|
||||
let probe_count = std::fs::read_to_string(log)
|
||||
.expect("read wrapper log")
|
||||
.lines()
|
||||
.filter(|line| line.contains(" hash-object --stdin --path "))
|
||||
.filter(|line| {
|
||||
line.contains(" ls-files --cached --full-name -z -- :(top,literal,attr:!filter)")
|
||||
})
|
||||
.count();
|
||||
assert_eq!(probe_count, max_probes);
|
||||
assert!(!filter_marker_is_set(&repo, "codex.budget-filter-ran").await);
|
||||
@@ -1042,7 +1108,11 @@ async fn fsmonitor_probe_is_base_only_and_the_sealed_decision_controls_final_ord
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(lines.len(), 1, "synthetic context must not probe or start fsmonitor");
|
||||
assert_eq!(
|
||||
lines.len(),
|
||||
1,
|
||||
"synthetic context must not probe or start fsmonitor"
|
||||
);
|
||||
let hooks = format!("core.hooksPath={}", crate::safe_git::DISABLED_HOOKS_PATH);
|
||||
let hooks_offset = lines[0].find(&hooks).expect("hooks override");
|
||||
let fsmonitor_offset = lines[0]
|
||||
@@ -1050,9 +1120,9 @@ async fn fsmonitor_probe_is_base_only_and_the_sealed_decision_controls_final_ord
|
||||
.expect("disabled fsmonitor override");
|
||||
let status_offset = lines[0].find("status --porcelain").expect("status command");
|
||||
assert!(hooks_offset < fsmonitor_offset && fsmonitor_offset < status_offset);
|
||||
assert!(lines[0].ends_with(
|
||||
"status --porcelain --ignore-submodules=dirty --untracked-files=no"
|
||||
));
|
||||
assert!(
|
||||
lines[0].ends_with("status --porcelain --ignore-submodules=dirty --untracked-files=no")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in New Issue
Block a user