diff --git a/crates/flare-git-core/src/classify.rs b/crates/flare-git-core/src/classify.rs index 2ebe304b5..babd45924 100644 --- a/crates/flare-git-core/src/classify.rs +++ b/crates/flare-git-core/src/classify.rs @@ -47,9 +47,21 @@ pub const WORKTREE_PRUNE_COMMAND: &str = "agentflare git audit prune --all"; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Disposition { Passthrough, - RedirectToWorktree { path: PathBuf }, + RedirectToWorktree { + path: PathBuf, + }, SilentExempt, - Deny { reason: String }, + Deny { + reason: String, + }, + /// The scope-check subprocess itself failed to reach a verdict (crashed, + /// could not be spawned, or returned garbage) -- distinct from `Deny`, + /// which is a deliberate policy verdict. Kept as its own serialized + /// variant so the audit trail can tell "policy denied" apart from + /// "scope-check itself broke" (item #472). + ScopeCheckError { + message: String, + }, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/flare-git-core/src/shell.rs b/crates/flare-git-core/src/shell.rs index e28f5b812..6cfcaf3b0 100644 --- a/crates/flare-git-core/src/shell.rs +++ b/crates/flare-git-core/src/shell.rs @@ -174,6 +174,101 @@ pub fn diff(repo_root: &Path, base: &str, head: &str) -> Result Ok(String::from_utf8_lossy(&out.stdout).to_string()) } +/// Why [`run_in_lines_bounded`] came back with an error. +#[derive(Debug)] +pub enum BoundedLinesError { + /// git itself failed: could not spawn, or exited non-zero (stderr). + Git(String), + /// The output had more than the requested cap of non-empty lines. + TooManyLines, +} + +/// Runs `git ` in `repo_root`, streaming stdout line-by-line and +/// keeping only the first `cap` non-empty lines. +/// +/// Bounds peak memory for outputs that would otherwise materialize as one +/// multi-MB string plus a `Vec` clone of it — the pathological case +/// behind the scope-check child-process OOM (item #472): `git diff +/// ... --name-only` on a branch that diverged massively from +/// the default branch lists the whole tree, and `Command::output()` buffers +/// it all before we can even count the lines. Streaming keeps peak usage at +/// the capped `Vec` plus one line instead. +/// +/// `Err(BoundedLinesError::TooManyLines)` once `cap` lines are collected — +/// the child is killed rather than left to block forever on a full stdout +/// pipe (git is read-only here, so killing it loses nothing). +pub fn run_in_lines_bounded( + repo_root: &Path, + args: &[&str], + cap: usize, +) -> Result, BoundedLinesError> { + use std::io::{BufRead, BufReader, Read}; + use std::process::Stdio; + + let mut cmd = Command::new(git_binary()); + cmd.args(args) + .current_dir(repo_root) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + no_console_window(&mut cmd); + let mut child = cmd + .spawn() + .map_err(|e| BoundedLinesError::Git(format!("git not available: {e}")))?; + // Drain stderr on its own thread: reading stdout to EOF first would + // deadlock if git fills the stderr pipe buffer (~64 KiB) while this + // still-piped stdout read is blocked waiting for more lines. + let stderr_handle = child.stderr.take().map(|mut e| { + std::thread::spawn(move || { + let mut buf = String::new(); + let _ = e.read_to_string(&mut buf); + buf + }) + }); + let mut lines = Vec::new(); + let mut exceeded = false; + let mut read_err = None; + if let Some(stdout) = child.stdout.take() { + for line in BufReader::new(stdout).lines() { + let line = match line { + Ok(l) => l, + Err(e) => { + read_err = Some(format!("reading git output failed: {e}")); + break; + } + }; + if line.is_empty() { + continue; + } + if lines.len() >= cap { + exceeded = true; + break; + } + lines.push(line); + } + } + if exceeded || read_err.is_some() { + // Drain the pipe, else the child blocks forever on a full stdout + // buffer and `wait()` never returns. Killing a read-only `git diff` + // is safe. + let _ = child.kill(); + let _ = child.wait(); + if let Some(e) = read_err { + return Err(BoundedLinesError::Git(e)); + } + return Err(BoundedLinesError::TooManyLines); + } + let stderr = stderr_handle + .and_then(|h| h.join().ok()) + .unwrap_or_default(); + let status = child + .wait() + .map_err(|e| BoundedLinesError::Git(format!("waiting for git failed: {e}")))?; + if !status.success() { + return Err(BoundedLinesError::Git(stderr.trim().to_string())); + } + Ok(lines) +} + #[cfg(test)] pub(crate) mod test_support { use super::run_in; @@ -235,6 +330,54 @@ mod tests { assert!(err.contains("no-such-branch"), "{err}"); } + #[test] + fn run_in_lines_bounded_returns_lines_up_to_the_cap() { + let repo = init_repo_with_branch("master"); + for n in 1..=5 { + std::fs::write(repo.path.join(format!("f{n}.txt")), "x\n").unwrap(); + run_in(&repo.path, &["add", format!("f{n}.txt").as_str()]).unwrap(); + } + run_in(&repo.path, &["commit", "-m", "add five"]).unwrap(); + let lines = + run_in_lines_bounded(&repo.path, &["diff", "--cached", "--name-only"], 5).unwrap(); + assert!( + lines.is_empty(), + "clean tree has no staged paths: {lines:?}" + ); + let all = run_in_lines_bounded(&repo.path, &["ls-files"], 10).unwrap(); + assert_eq!(all.len(), 5, "{all:?}"); + } + + #[test] + fn run_in_lines_bounded_errors_when_cap_is_exceeded() { + let repo = init_repo_with_branch("master"); + for n in 1..=10 { + std::fs::write(repo.path.join(format!("f{n}.txt")), "x\n").unwrap(); + run_in(&repo.path, &["add", format!("f{n}.txt").as_str()]).unwrap(); + } + run_in(&repo.path, &["commit", "-m", "add ten"]).unwrap(); + assert!( + matches!( + run_in_lines_bounded(&repo.path, &["ls-files"], 5), + Err(BoundedLinesError::TooManyLines) + ), + "more tracked files than the cap must error, not silently truncate" + ); + let ok = run_in_lines_bounded(&repo.path, &["ls-files"], 10).unwrap(); + assert_eq!(ok.len(), 10, "{ok:?}"); + } + + #[test] + fn run_in_lines_bounded_propagates_git_errors() { + let repo = init_repo_with_branch("master"); + match run_in_lines_bounded(&repo.path, &["rev-parse", "--verify", "no-such-branch"], 10) { + Err(BoundedLinesError::Git(e)) => { + assert!(e.contains("Needed a single revision"), "{e}") + } + other => panic!("expected a git error, got {other:?}"), + } + } + #[test] fn agentflare_shims_dir_is_excludable_from_git_binary_search() { // git_binary() must filter this exact path out of PATH, or a diff --git a/crates/flare-git-shim/src/main.rs b/crates/flare-git-shim/src/main.rs index 4faf628ae..9a5b1eff2 100644 --- a/crates/flare-git-shim/src/main.rs +++ b/crates/flare-git-shim/src/main.rs @@ -182,16 +182,107 @@ struct ScopeCheckResult { reason: Option, } +/// Outcome of consulting `agentflare git scope-check`. Not a bare +/// `Option` deny-reason: `main` must be able to tell a genuine +/// policy verdict (deny/pass) from a broken scope-check (crashed / +/// unavailable), because the two must NOT be surfaced the same way (item +/// #472). The scope-check protocol is: always exit 0, verdict lives in the +/// JSON. Anything else means the check did not produce a verdict. +#[derive(Debug)] +enum ScopeCheckOutcome { + /// The check ran to completion and nothing is out of scope. + Pass, + /// Genuine policy denial: the check ran and returned `deny:true`. + Deny(String), + /// The check child ran but died before producing a verdict (e.g. an + /// OOM/abort, non-zero exit). Not a policy decision -- passed through + /// with a warning, since a transient tooling crash must not silently + /// transform into a denial that bricks the agent's push. + Crash(String), + /// The check could not be run at all, or its output was not a valid + /// verdict (binary missing, garbage output). Enforcement cannot run, + /// so the op is blocked (fail-closed, item #234) with a message that + /// is explicit about NOT being a policy denial. + Unavailable(String), +} + +fn scope_check_crash_message(status_code: Option, stderr: &[u8]) -> String { + let code = status_code.map_or_else(|| "signal/killed".to_string(), |c| c.to_string()); + let stderr = String::from_utf8_lossy(stderr).trim().to_string(); + if stderr.is_empty() { + format!( + "scope-check itself crashed before producing a verdict (exit {code}) -- this is NOT a policy denial; the git command passed through. Set AGENTFLARE_GIT_BYPASS=1 to bypass scope enforcement entirely." + ) + } else { + format!( + "scope-check itself crashed before producing a verdict (exit {code}): {stderr} -- this is NOT a policy denial; the git command passed through. Set AGENTFLARE_GIT_BYPASS=1 to bypass scope enforcement entirely." + ) + } +} + +/// Interprets the child process's outcome per the scope-check contract +/// (exit 0 + one JSON line; denial lives in the JSON, never the exit code). +/// Split out from the spawning wrapper so it can be unit-tested against +/// synthetic status/stdout/stderr. +fn interpret_scope_check( + status_success: bool, + status_code: Option, + stdout: &[u8], + stderr: &[u8], +) -> ScopeCheckOutcome { + if !status_success { + return ScopeCheckOutcome::Crash(scope_check_crash_message(status_code, stderr)); + } + let stdout = String::from_utf8_lossy(stdout); + let result: ScopeCheckResult = match serde_json::from_str(stdout.trim()) { + Ok(r) => r, + Err(e) => { + return ScopeCheckOutcome::Unavailable(format!( + "scope-check returned unparseable output: {e} -- this is NOT a policy denial; set AGENTFLARE_GIT_BYPASS=1 to bypass scope enforcement entirely." + )); + } + }; + if result.deny { + ScopeCheckOutcome::Deny( + result + .reason + .unwrap_or_else(|| "scope-check denied (no reason given)".to_string()), + ) + } else { + ScopeCheckOutcome::Pass + } +} + /// Path-scope enforcement (item #234): shells out to `agentflare git /// scope-check`, since this shim has no direct DB access to live claims. -/// Deliberately FAIL-CLOSED here, unlike the rest of this crate's fail-open -/// default -- any error resolving scope (binary missing, bad JSON, -/// non-zero exit) is treated as a deny. The existing bypass envs -/// (`AGENTFLARE_GIT_BYPASS` and friends, checked earlier in `main`) remain -/// the escape hatch for a broken/missing `agentflare` binary, same as any -/// other misclassification. -fn scope_check_deny_reason(subcommand: &str) -> Option { - let mut cmd = std::process::Command::new("agentflare"); +/// Fail-closed on "scope-check cannot run at all" (binary missing, +/// unparseable output) -- but fail-open on a mid-run crash (item #472): a +/// crashed child never produced a policy verdict, so blocking the caller on +/// it would surface a transient tooling failure identically to a real +/// denial. The existing bypass envs (`AGENTFLARE_GIT_BYPASS` and friends, +/// checked earlier in `main`) remain the escape hatch for a persistently +/// broken `agentflare` binary, same as any other misclassification. +fn scope_check_outcome(subcommand: &str) -> ScopeCheckOutcome { + // Test-only override for the scope-check binary, compiled out of release + // builds entirely (so the override can never exist in a shipped binary, + // regardless of env vars) and, in debug builds, honored only alongside + // `AGENTFLARE_HOME_OVERRIDE` (which is itself the test-mode marker this + // crate's tests set to keep the audit log out of the real home + // directory) so a stray env var can never silently redirect production + // scope-checks at an arbitrary binary. The integration tests use it to + // point the check at this shim binary itself, producing a genuine + // "child died without a verdict" crash. + #[cfg(debug_assertions)] + let bin = match ( + env::var("AGENTFLARE_GIT_SCOPE_CHECK_BIN"), + env::var_os("AGENTFLARE_HOME_OVERRIDE"), + ) { + (Ok(b), Some(_)) if !b.is_empty() => b, + _ => "agentflare".to_string(), + }; + #[cfg(not(debug_assertions))] + let bin = "agentflare".to_string(); + let mut cmd = std::process::Command::new(&bin); cmd.args(["git", "scope-check", "--subcommand", subcommand]); // Runs on every git invocation through this shim; without this flag, // whenever the invoking parent has no inherited console (e.g. spawned by @@ -206,31 +297,17 @@ fn scope_check_deny_reason(subcommand: &str) -> Option { let output = match cmd.output() { Ok(o) => o, Err(e) => { - return Some(format!( - "scope-check could not run ('agentflare' on PATH?): {e}" + return ScopeCheckOutcome::Unavailable(format!( + "scope-check could not run ('agentflare' on PATH?): {e} -- this is NOT a policy denial; set AGENTFLARE_GIT_BYPASS=1 to bypass scope enforcement entirely." )); } }; - if !output.status.success() { - return Some(format!( - "scope-check exited non-zero: {}", - String::from_utf8_lossy(&output.stderr).trim() - )); - } - let stdout = String::from_utf8_lossy(&output.stdout); - let result: ScopeCheckResult = match serde_json::from_str(stdout.trim()) { - Ok(r) => r, - Err(e) => return Some(format!("scope-check returned unparseable output: {e}")), - }; - if result.deny { - Some( - result - .reason - .unwrap_or_else(|| "scope-check denied (no reason given)".to_string()), - ) - } else { - None - } + interpret_scope_check( + output.status.success(), + output.status.code(), + &output.stdout, + &output.stderr, + ) } /// Hands off to the real git binary, first clearing `RECURSION_ENV`. @@ -391,24 +468,69 @@ fn main() { ); exit(1); } + classify::Disposition::ScopeCheckError { message } => { + // classify() never produces this disposition -- only the shim's + // own scope-check handling constructs it. If one ever leaks + // through here, fail closed with the message rather than guess. + eprintln!("agentflare git shim: denied — {message}"); + exit(1); + } classify::Disposition::Deny { .. } | classify::Disposition::Passthrough | classify::Disposition::SilentExempt => { - if matches!(subcommand.as_str(), "commit" | "push") - && let Some(reason) = scope_check_deny_reason(&subcommand) - { - let scope_event = classify::Event { - subcommand: subcommand.clone(), - args: rest.clone(), - disposition: classify::Disposition::Deny { - reason: reason.clone(), - }, - }; - if let Some(audit_path) = audit::default_path("git.jsonl") { - let _ = audit::log_event(&audit_path, &scope_event); + if matches!(subcommand.as_str(), "commit" | "push") { + match scope_check_outcome(&subcommand) { + ScopeCheckOutcome::Pass => {} + ScopeCheckOutcome::Deny(reason) => { + let scope_event = classify::Event { + subcommand: subcommand.clone(), + args: rest.clone(), + disposition: classify::Disposition::Deny { + reason: reason.clone(), + }, + }; + if let Some(audit_path) = audit::default_path("git.jsonl") { + let _ = audit::log_event(&audit_path, &scope_event); + } + eprintln!("agentflare git shim: denied — {reason}"); + exit(1); + } + ScopeCheckOutcome::Crash(msg) => { + // The check died before reaching a verdict (item + // #472) -- NOT a policy decision. Pass the op + // through but surface + audit it so the failure is + // not silent. + let scope_event = classify::Event { + subcommand: subcommand.clone(), + args: rest.clone(), + disposition: classify::Disposition::ScopeCheckError { + message: msg.clone(), + }, + }; + if let Some(audit_path) = audit::default_path("git.jsonl") { + let _ = audit::log_event(&audit_path, &scope_event); + } + eprintln!("agentflare git shim: warning -- {msg}"); + } + ScopeCheckOutcome::Unavailable(msg) => { + // Scope enforcement cannot run at all (binary + // missing, unparseable output): fail closed (item + // #234), but phrased so it is unmistakably NOT a + // policy verdict on the changes. + let scope_event = classify::Event { + subcommand: subcommand.clone(), + args: rest.clone(), + disposition: classify::Disposition::Deny { + reason: msg.clone(), + }, + }; + if let Some(audit_path) = audit::default_path("git.jsonl") { + let _ = audit::log_event(&audit_path, &scope_event); + } + eprintln!("agentflare git shim: denied — {msg}"); + exit(1); + } } - eprintln!("agentflare git shim: denied — {reason}"); - exit(1); } if snapshots_enabled() && classify::is_destructive(&subcommand, &rest) { let reason = format!("pre-{subcommand} snapshot ({})", rest.join(" ")); @@ -431,3 +553,76 @@ fn main() { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exit_zero_and_deny_false_is_a_pass() { + match interpret_scope_check(true, Some(0), br#"{"deny":false}"#, b"") { + ScopeCheckOutcome::Pass => {} + other => panic!("expected Pass, got {other:?}"), + } + } + + #[test] + fn exit_zero_and_deny_true_returns_the_reason() { + match interpret_scope_check( + true, + Some(0), + br#"{"deny":true,"reason":"overlapping claim"}"#, + b"", + ) { + ScopeCheckOutcome::Deny(reason) => assert_eq!(reason, "overlapping claim"), + other => panic!("expected Deny, got {other:?}"), + } + } + + #[test] + fn exit_zero_and_deny_true_without_reason_has_a_default() { + match interpret_scope_check(true, Some(0), br#"{"deny":true}"#, b"") { + ScopeCheckOutcome::Deny(reason) => { + assert!(reason.contains("no reason given"), "{reason}") + } + other => panic!("expected Deny, got {other:?}"), + } + } + + #[test] + fn non_zero_exit_is_a_crash_not_a_policy_denial() { + // The exact regression from issue #483 bug #2: the scope-check child + // OOM'd ("memory allocation of 6176784 bytes failed") and the shim + // surfaced it as if the policy had denied the push. + let stderr = b"memory allocation of 6176784 bytes failed"; + match interpret_scope_check(false, None, b"", stderr) { + ScopeCheckOutcome::Crash(msg) => { + assert!(msg.contains("NOT a policy denial"), "{msg}"); + assert!(msg.contains("memory allocation"), "{msg}"); + assert!(msg.contains("passed through"), "{msg}"); + } + other => panic!("expected Crash, got {other:?}"), + } + } + + #[test] + fn crash_message_without_stderr_still_explains_the_outcome() { + match interpret_scope_check(false, Some(134), b"", b"") { + ScopeCheckOutcome::Crash(msg) => { + assert!(msg.contains("exit 134"), "{msg}"); + assert!(msg.contains("NOT a policy denial"), "{msg}"); + } + other => panic!("expected Crash, got {other:?}"), + } + } + + #[test] + fn exit_zero_with_garbage_stdout_is_unavailable_not_a_pass() { + match interpret_scope_check(true, Some(0), b"garbage", b"") { + ScopeCheckOutcome::Unavailable(msg) => { + assert!(msg.contains("NOT a policy denial"), "{msg}"); + } + other => panic!("expected Unavailable, got {other:?}"), + } + } +} diff --git a/crates/flare-git-shim/tests/shim_test.rs b/crates/flare-git-shim/tests/shim_test.rs index 27cde5fe4..c9e57c314 100644 --- a/crates/flare-git-shim/tests/shim_test.rs +++ b/crates/flare-git-shim/tests/shim_test.rs @@ -517,3 +517,59 @@ fn push_of_default_branch_is_denied_for_agent_but_passes_through_for_a_human() { let stderr = String::from_utf8_lossy(&out.stderr); assert!(!stderr.contains("denied"), "{stderr}"); } + +/// The exact issue #483 bug #2 regression: when the `agentflare git +/// scope-check` child crashes, the shim must NOT surface it as a policy +/// denial that blocks the git operation -- it warns, audits, and passes +/// through so the legitimate commit can proceed. +/// +/// The scope-check child is normally spawned as `Command::new("agentflare")`. +/// `AGENTFLARE_GIT_SCOPE_CHECK_BIN` (honored only alongside the test-mode +/// `AGENTFLARE_HOME_OVERRIDE`) repoints that spawn at this shim binary +/// itself: asked for the `git scope-check` subcommand it doesn't recognize, +/// it passes through to real git (`git git scope-check ...`), which exits +/// non-zero with an unknown-command error -- a scope-check child that died +/// without ever producing a verdict, exactly the crash shape issue #483 +/// bug #2 reported. +#[test] +fn crashed_scope_check_child_passes_through_with_a_warning_not_a_denial() { + let repo = init_repo(); + let home = tempfile::TempDir::new().unwrap(); + + // Seed a tracked file, then modify it so `commit -a` has something to + // commit (untracked files are ignored by `commit -a`). + std::fs::write(repo.path().join("work.txt"), "v1\n").unwrap(); + flare_git_core::shell::run_in(repo.path(), &["add", "work.txt"]).unwrap(); + flare_git_core::shell::run_in(repo.path(), &["commit", "-q", "-m", "seed work"]).unwrap(); + std::fs::write(repo.path().join("work.txt"), "v2\n").unwrap(); + + let shim_exe = env!("CARGO_BIN_EXE_git"); + let out = Command::new(shim_exe) + .args(["commit", "-a", "-m", "regression commit"]) + .current_dir(repo.path()) + .env("AGENTFLARE_HOME_OVERRIDE", home.path()) + .env("CLAUDECODE", "1") + .env("AGENTFLARE_GIT_SCOPE_CHECK_BIN", shim_exe) + .output() + .unwrap(); + + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{out:?}"); + assert!(stderr.contains("NOT a policy denial"), "{stderr}"); + assert!(stderr.contains("scope-check itself crashed"), "{stderr}"); + assert!(!stderr.contains("denied"), "{stderr}"); + let log = flare_git_core::shell::run_in(repo.path(), &["log", "--oneline", "-1"]).unwrap(); + assert!(log.contains("regression commit"), "{log}"); + + // The audit record must classify this as a scope-check crash, not a + // policy `Deny` -- otherwise the audit trail can't distinguish "tooling + // broke" from "a real denial happened", defeating the point of the + // dedicated `ScopeCheckError` disposition. + let audit_log = home + .path() + .join(".agentflare") + .join("audit") + .join("git.jsonl"); + let audit_content = std::fs::read_to_string(&audit_log).expect("audit log must exist"); + assert!(audit_content.contains("ScopeCheckError"), "{audit_content}"); +} diff --git a/src/cli/git.rs b/src/cli/git.rs index eaab1326f..b85a0054e 100644 --- a/src/cli/git.rs +++ b/src/cli/git.rs @@ -14,6 +14,7 @@ use crate::paths::home; use clap::{Args, Subcommand}; +use flare_git_core::shell::BoundedLinesError; use flare_git_core::{ audit, branch, classify, doctor, provenance, scope, shell, snapshot, worktree, }; @@ -873,8 +874,33 @@ fn run_scope_check(subcommand: &str) -> ScopeCheckResult { let owner = crate::claims::owner_id(); let (own_target, others) = partition_claims_by_owner(&live, &owner); - let changed = changed_paths(&repo_root, subcommand); let in_worktree = branch::is_linked_worktree(&repo_root); + // Only skip computing changed paths when nothing downstream depends on + // them: with no enforceable other-claim scope, nothing can overlap. An + // out-of-tree invoker must still get a *non-empty* pathset here -- + // `classify_scopes` only reaches its `OutOfTree` check past its + // `changed_paths.is_empty() -> Clear` short-circuit, so skipping the + // diff for `out_of_tree` would silently turn a real OutOfTree denial + // into a pass. This is also the memory fix for the scope-check + // child-process OOM (item #472): `git diff ... + // --name-only` on a branch that diverged hugely from the default branch + // lists the whole tree as a multi-MB pathset, which previously crashed + // the child on a memory-constrained environment and surfaced to the + // shim as a fake policy denial. + let out_of_tree = own_target.is_some() && !in_worktree; + let has_enforced_others = others + .iter() + .any(|c| !scope::scope_is_wildcard_or_empty(&c.scopes)); + let changed = if !out_of_tree && !has_enforced_others { + Vec::new() + } else { + match changed_paths(&repo_root, subcommand) { + Ok(p) => p, + Err(e) => { + return scope_deny(format!("scope-check could not classify changed paths: {e}")); + } + } + }; match scope::classify_scopes(&changed, own_target.as_deref(), in_worktree, &others) { scope::ScopeVerdict::Overlapping { owner, @@ -890,6 +916,19 @@ fn run_scope_check(subcommand: &str) -> ScopeCheckResult { } } +/// Cap on the number of changed paths a commit/push scope-check will +/// classify. Beyond this the pathset is too large to classify reliably, and +/// streaming it unbounded is exactly what OOM'd the scope-check child in the +/// first place (item #472) -- so the check fails closed with a clear message +/// instead of crashing the child process. +const MAX_CHANGED_PATHS: usize = 50_000; + +fn too_many_paths_msg(cap: usize) -> String { + format!( + "the changed pathset exceeds the {cap}-path scope-check limit and cannot be classified; shrink this commit/push and retry" + ) +} + /// Changed paths for the mutation about to happen -- staged paths for /// `commit` (unioned with the working-tree diff, since `git commit -a`/ /// `--all` implicitly stages+commits tracked modifications without a prior @@ -900,19 +939,36 @@ fn run_scope_check(subcommand: &str) -> ScopeCheckResult { /// An unreadable diff yields no changed paths (nothing to enforce), matching /// this crate's fail-open default for diff resolution specifically -- only /// scope RESOLUTION errors (ledger/DB) are fail-closed, per the spec. -fn changed_paths(repo_root: &Path, subcommand: &str) -> Vec { +/// +/// `Err` is reserved for the one case where fail-open would be wrong: the +/// changed pathset is so large it cannot be classified at all (see +/// `MAX_CHANGED_PATHS`). The diff is streamed with a line cap so a +/// pathological pathset can't blow the child process's memory first. +fn changed_paths(repo_root: &Path, subcommand: &str) -> Result, String> { + let cap = MAX_CHANGED_PATHS; if subcommand == "commit" { - let mut paths: Vec = shell::run_in(repo_root, &["diff", "--cached", "--name-only"]) - .map(|s| s.lines().map(String::from).collect()) - .unwrap_or_default(); - paths.extend( - shell::run_in(repo_root, &["diff", "--name-only"]) - .map(|s| s.lines().map(String::from).collect::>()) - .unwrap_or_default(), - ); + let mut paths = + match shell::run_in_lines_bounded(repo_root, &["diff", "--cached", "--name-only"], cap) + { + Ok(p) => p, + Err(BoundedLinesError::Git(_)) => Vec::new(), // fail-open on diff resolution + Err(BoundedLinesError::TooManyLines) => return Err(too_many_paths_msg(cap)), + }; + match shell::run_in_lines_bounded(repo_root, &["diff", "--name-only"], cap) { + Ok(p) => paths.extend(p), + Err(BoundedLinesError::Git(_)) => {} + Err(BoundedLinesError::TooManyLines) => return Err(too_many_paths_msg(cap)), + } paths.sort(); paths.dedup(); - return paths; + // Each diff above is capped individually, so a disjoint staged set + // and working-tree set can each land at `cap` and union past it -- + // enforce the documented `MAX_CHANGED_PATHS` limit on the merged, + // deduplicated set too. + if paths.len() > cap { + return Err(too_many_paths_msg(cap)); + } + return Ok(paths); } let range_args: Vec = match subcommand { "push" => { @@ -922,12 +978,14 @@ fn changed_paths(repo_root: &Path, subcommand: &str) -> Vec { let range = format!("{default_branch}...{current}"); vec!["diff".to_string(), "--name-only".to_string(), range] } - _ => return Vec::new(), + _ => return Ok(Vec::new()), }; let args: Vec<&str> = range_args.iter().map(String::as_str).collect(); - shell::run_in(repo_root, &args) - .map(|s| s.lines().map(String::from).collect()) - .unwrap_or_default() + match shell::run_in_lines_bounded(repo_root, &args, cap) { + Ok(p) => Ok(p), + Err(BoundedLinesError::Git(_)) => Ok(Vec::new()), // fail-open on diff resolution + Err(BoundedLinesError::TooManyLines) => Err(too_many_paths_msg(cap)), + } } /// The "ship it" macro: push the current branch, open (or reuse) its PR, @@ -1405,7 +1463,7 @@ mod tests { // enforcement entirely. let repo = init_repo(); std::fs::write(repo.path().join("tracked.txt"), "v2\n").unwrap(); - let paths = changed_paths(repo.path(), "commit"); + let paths = changed_paths(repo.path(), "commit").unwrap(); assert!( paths.iter().any(|p| p == "tracked.txt"), "unstaged modification must be included: {paths:?}" @@ -1417,7 +1475,7 @@ mod tests { let repo = init_repo(); std::fs::write(repo.path().join("new.txt"), "x\n").unwrap(); run_git(repo.path(), &["add", "new.txt"]); - let paths = changed_paths(repo.path(), "commit"); + let paths = changed_paths(repo.path(), "commit").unwrap(); assert_eq!( paths.iter().filter(|p| *p == "new.txt").count(), 1, @@ -1428,6 +1486,6 @@ mod tests { #[test] fn changed_paths_for_commit_is_empty_when_clean() { let repo = init_repo(); - assert!(changed_paths(repo.path(), "commit").is_empty()); + assert!(changed_paths(repo.path(), "commit").unwrap().is_empty()); } }