diff --git a/src/git.rs b/src/git.rs index c88f567..bfe6301 100644 --- a/src/git.rs +++ b/src/git.rs @@ -2,12 +2,24 @@ //! local changes. use std::path::{Path, PathBuf}; +use std::process::Stdio; -use tokio::process::Command; +use tokio::io::{AsyncRead, AsyncReadExt as _}; +use tokio::process::{Child, Command}; /// The largest patch the server reviews. pub const MAX_PATCH_BYTES: usize = 5 << 20; const MAX_PATCH_FILES: usize = 3_000; +/// Bounded `--raw -z` metadata limit before `--patch` begins. +/// +/// Even in the worst case of 3,000 renamed entries at POSIX `PATH_MAX` +/// (4,096 bytes × 2 paths + ~150 bytes per raw header ≈ 24.9 MiB), 32 MiB +/// accommodates valid metadata while bounding NUL-free or runaway output. +// ponytail: fixed 32 MiB ceiling assumes <= 3,000 entries within POSIX path +// sizes; upgrade to parsing records into `Vec` directly without +// retaining raw header bytes if longer path budgets are ever needed. +const MAX_RAW_BYTES: usize = 32 << 20; +const MAX_STDERR_BYTES: usize = 64 << 10; #[derive(Debug, thiserror::Error)] pub enum GitError { @@ -27,9 +39,13 @@ pub enum GitError { NoBase(String), #[error("the local changes include text that is not UTF-8, which Proofline cannot review")] NotUtf8, - #[error("the local changes make a {0} MiB patch; Proofline reviews patches up to 5 MiB")] + #[error( + "the local changes make a patch larger than {0} MiB; Proofline reviews patches up to 5 MiB" + )] TooLarge(usize), - #[error("the local changes include {0} files; Proofline reviews patches up to 3,000 files")] + #[error( + "the local changes include more than {0} files; Proofline reviews patches up to 3,000 files" + )] TooManyFiles(usize), #[error("could not read the local patch's Git path metadata; no review was requested")] InvalidDiff, @@ -385,6 +401,222 @@ pub async fn new_branch_base(dir: &Path, remote: &str, head: &str) -> Result GitError { + match self { + Self::Io(error) => GitError::Unavailable(error.to_string()), + Self::TooLarge => GitError::TooLarge(limits.max_patch_bytes >> 20), + Self::TooManyFiles => GitError::TooManyFiles(limits.max_patch_files), + Self::InvalidDiff => GitError::InvalidDiff, + } + } +} + +#[derive(Clone, Copy, Debug)] +enum RawStatus { + Added, + Deleted, + Modified, + Paired, +} + +impl RawStatus { + const fn path_count(self) -> u8 { + match self { + Self::Paired => 2, + Self::Added | Self::Deleted | Self::Modified => 1, + } + } +} + +fn parse_raw_status(header: &[u8]) -> Option { + if !header.starts_with(b":") { + return None; + } + let status = header + .split(|byte| *byte == b' ') + .next_back() + .and_then(|status| status.first())?; + match status { + b'A' => Some(RawStatus::Added), + b'D' => Some(RawStatus::Deleted), + b'M' | b'T' => Some(RawStatus::Modified), + b'R' | b'C' => Some(RawStatus::Paired), + _ => None, + } +} + +/// Runs `git` with bounded `--raw -z --patch` collection, draining `stderr` +/// concurrently and terminating the child immediately if a limit is exceeded. +async fn diff_output( + dir: &Path, + index: Option<&Path>, + args: &[&str], + limits: DiffLimits, +) -> Result<(Vec, Vec), GitError> { + let mut command = Command::new("git"); + command.arg("-C").arg(dir).args(args); + if let Some(index) = index { + command.env("GIT_INDEX_FILE", index); + } + diff_command_output(command, &args.join(" "), limits).await +} + +async fn diff_command_output( + mut command: Command, + description: &str, + limits: DiffLimits, +) -> Result<(Vec, Vec), GitError> { + command + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + let mut child = command + .spawn() + .map_err(|error| GitError::Unavailable(error.to_string()))?; + let Some(stdout) = child.stdout.take() else { + terminate_and_reap(&mut child).await; + return Err(GitError::Unavailable("missing git stdout pipe".to_owned())); + }; + let Some(stderr) = child.stderr.take() else { + drop(stdout); + terminate_and_reap(&mut child).await; + return Err(GitError::Unavailable("missing git stderr pipe".to_owned())); + }; + + // Keeps bounded metadata and patch separate so diff parsing and any + // caller inspection remain within limits without pipe deadlocks. + let streamed = tokio::try_join!(read_diff_stdout(stdout, limits), drain_stderr(stderr)); + match streamed { + Ok(((raw, patch), stderr_bytes)) => { + let status = child + .wait() + .await + .map_err(|error| GitError::Unavailable(error.to_string()))?; + if !status.success() { + return Err(GitError::Failed { + command: description.to_owned(), + stderr: String::from_utf8_lossy(&stderr_bytes).trim().to_owned(), + }); + } + Ok((raw, patch)) + } + Err(error) => { + terminate_and_reap(&mut child).await; + Err(error.into_git_error(limits)) + } + } +} + +async fn terminate_and_reap(child: &mut Child) { + let _ = child.start_kill(); + let _ = child.wait().await; +} + +async fn drain_stderr(mut reader: R) -> Result, DiffStreamError> { + let mut kept = Vec::new(); + let mut chunk = [0u8; 8 << 10]; + loop { + let read = reader.read(&mut chunk).await.map_err(DiffStreamError::Io)?; + if read == 0 { + return Ok(kept); + } + let remaining = MAX_STDERR_BYTES.saturating_sub(kept.len()); + if remaining > 0 { + kept.extend_from_slice(&chunk[..read.min(remaining)]); + } + } +} + +async fn read_diff_stdout( + mut reader: R, + limits: DiffLimits, +) -> Result<(Vec, Vec), DiffStreamError> { + let mut raw = Vec::new(); + let mut patch: Option> = None; + let mut scan_pos = 0; + let mut expecting_paths = 0u8; + let mut files = 0usize; + let mut chunk = [0u8; 16 << 10]; + + loop { + let read = reader.read(&mut chunk).await.map_err(DiffStreamError::Io)?; + if read == 0 { + return Ok((raw, patch.unwrap_or_default())); + } + let bytes = &chunk[..read]; + if let Some(patch_buf) = patch.as_mut() { + if read > limits.max_patch_bytes.saturating_sub(patch_buf.len()) { + return Err(DiffStreamError::TooLarge); + } + patch_buf.extend_from_slice(bytes); + continue; + } + + raw.extend_from_slice(bytes); + while let Some(rel_nul) = raw[scan_pos..].iter().position(|byte| *byte == 0) { + let end = scan_pos + rel_nul; + let field = &raw[scan_pos..end]; + scan_pos = end + 1; + if expecting_paths > 0 { + if field.is_empty() { + return Err(DiffStreamError::InvalidDiff); + } + expecting_paths -= 1; + } else if field.is_empty() { + if files == 0 { + return Err(DiffStreamError::InvalidDiff); + } + let trailing = raw.split_off(scan_pos); + if trailing.len() > limits.max_patch_bytes { + return Err(DiffStreamError::TooLarge); + } + patch = Some(trailing); + break; + } else { + let Some(status) = parse_raw_status(field) else { + return Err(DiffStreamError::InvalidDiff); + }; + expecting_paths = status.path_count(); + files += 1; + if files > limits.max_patch_files { + return Err(DiffStreamError::TooManyFiles); + } + } + if scan_pos > limits.max_raw_bytes { + return Err(DiffStreamError::InvalidDiff); + } + } + if patch.is_none() && raw.len() > limits.max_raw_bytes { + return Err(DiffStreamError::InvalidDiff); + } + } +} + /// The patch from `base_commit_sha` to `head`, or to `index` when `head` is /// `None`. async fn diff( @@ -432,15 +664,18 @@ async fn diff( args.extend(head); args.push("--"); args.extend(path); - let output = git_in(root, index, &args).await?; - let (paths, patch) = diff_paths(&output)?; + let (raw, patch) = diff_output(root, index, &args, DiffLimits::DEFAULT).await?; + let (paths, remainder) = diff_paths(&raw)?; + if !remainder.is_empty() { + return Err(GitError::InvalidDiff); + } if patch.len() > MAX_PATCH_BYTES { - return Err(GitError::TooLarge(patch.len().div_ceil(1 << 20))); + return Err(GitError::TooLarge(MAX_PATCH_BYTES >> 20)); } if paths.len() > MAX_PATCH_FILES { - return Err(GitError::TooManyFiles(paths.len())); + return Err(GitError::TooManyFiles(MAX_PATCH_FILES)); } - let patch = String::from_utf8(patch.to_vec()).map_err(|_| GitError::NotUtf8)?; + let patch = String::from_utf8(patch).map_err(|_| GitError::NotUtf8)?; if paths.len() != patch .lines() @@ -464,33 +699,27 @@ fn diff_paths(mut output: &[u8]) -> Result<(Vec, &[u8]), GitError> { if header.is_empty() { break; } - if !header.starts_with(b":") { + let Some(status) = parse_raw_status(header) else { return Err(GitError::InvalidDiff); - } - let status = header - .split(|byte| *byte == b' ') - .next_back() - .and_then(|status| status.first()) - .ok_or(GitError::InvalidDiff)?; + }; let first = diff_path(&mut output)?; let file = match status { - b'A' => PatchPaths { + RawStatus::Added => PatchPaths { old: None, new: Some(first), }, - b'D' => PatchPaths { + RawStatus::Deleted => PatchPaths { old: Some(first), new: None, }, - b'R' | b'C' => PatchPaths { + RawStatus::Paired => PatchPaths { old: Some(first), new: Some(diff_path(&mut output)?), }, - b'M' | b'T' => PatchPaths { + RawStatus::Modified => PatchPaths { old: Some(first.clone()), new: Some(first), }, - _ => return Err(GitError::InvalidDiff), }; paths.push(file); } @@ -869,4 +1098,430 @@ mod tests { staged ); } + + fn init_repo() -> tempfile::TempDir { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + run(dir, &["init", "-q", "-b", "main"]); + run(dir, &["config", "user.email", "dev@example.com"]); + run(dir, &["config", "user.name", "dev"]); + run(dir, &["commit", "-q", "--allow-empty", "-m", "base"]); + let base = run(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + run(dir, &["update-ref", "refs/remotes/origin/main", &base]); + run( + dir, + &[ + "symbolic-ref", + "refs/remotes/origin/HEAD", + "refs/remotes/origin/main", + ], + ); + repo + } + + fn run_with(dir: &Path, args: &[&str], input: &[u8]) -> String { + use std::io::Write as _; + + let mut child = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(input).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "git {args:?}: {output:?}"); + String::from_utf8(output.stdout).unwrap().trim().to_owned() + } + + fn commit_empty_files(dir: &Path, base: &str, count: usize, path_prefix: &str) -> String { + use std::fmt::Write as _; + + let empty_blob = run_with(dir, &["hash-object", "-w", "--stdin"], b""); + let index_file = dir.join(".git/tmp-bulk-index"); + let mut entries = String::new(); + for index in 0..count { + writeln!( + entries, + "100644 blob {empty_blob}\t{path_prefix}{index:04}.txt" + ) + .unwrap(); + } + let mut child = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .env("GIT_INDEX_FILE", &index_file) + .args(["update-index", "--index-info"]) + .stdin(Stdio::piped()) + .spawn() + .unwrap(); + std::io::Write::write_all(&mut child.stdin.take().unwrap(), entries.as_bytes()).unwrap(); + assert!(child.wait().unwrap().success()); + let tree_output = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .env("GIT_INDEX_FILE", &index_file) + .arg("write-tree") + .output() + .unwrap(); + assert!(tree_output.status.success()); + let tree = String::from_utf8(tree_output.stdout).unwrap(); + std::fs::remove_file(&index_file).unwrap(); + run_with( + dir, + &["commit-tree", tree.trim(), "-p", base, "-m", "bulk"], + b"", + ) + } + + fn stage_single_line_patch_size(dir: &Path, base: &str, file: &str, target_patch_len: usize) { + let mut payload_len = target_patch_len.saturating_sub(128); + for _ in 0..4 { + let mut content = vec![b'a'; payload_len]; + content.push(b'\n'); + std::fs::write(dir.join(file), &content).unwrap(); + run(dir, &["add", file]); + let output = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args([ + "--literal-pathspecs", + "-c", + "core.quotePath=false", + "-c", + "diff.renames=true", + "-c", + "diff.suppressBlankEmpty=false", + "diff", + "--cached", + "--patch", + "--find-renames", + "--no-relative", + "--no-ext-diff", + "--no-textconv", + "--no-color", + "--ignore-submodules=none", + "--submodule=short", + "--src-prefix=a/", + "--dst-prefix=b/", + base, + "--", + ]) + .output() + .unwrap(); + assert!(output.status.success()); + let actual = output.stdout.len(); + if actual == target_patch_len { + return; + } + if actual < target_patch_len { + payload_len += target_patch_len - actual; + } else { + payload_len -= actual - target_patch_len; + } + } + panic!("could not construct patch of {target_patch_len} bytes"); + } + + #[tokio::test] + async fn local_patch_enforces_exact_five_mib_and_large_patch_bounds() { + let repo = init_repo(); + let dir = repo.path(); + let base = run(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + + // Below 5 MiB. + std::fs::write(dir.join("payload.txt"), "a".repeat(4 << 20)).unwrap(); + run(dir, &["add", "payload.txt"]); + let below = local_changes(dir, "origin", LocalSelection::Staged, None) + .await + .unwrap(); + assert!(below.patch.len() < MAX_PATCH_BYTES); + assert_eq!(below.files(), 1); + + // Exactly 5 MiB (raw metadata pushes stdout over 5 MiB while patch equals MAX_PATCH_BYTES). + stage_single_line_patch_size(dir, &base, "payload.txt", MAX_PATCH_BYTES); + let exact = local_changes(dir, "origin", LocalSelection::Staged, None) + .await + .unwrap(); + assert_eq!(exact.patch.len(), MAX_PATCH_BYTES); + assert_eq!(exact.files(), 1); + + // Just above 5 MiB (`MAX_PATCH_BYTES + 1`). + stage_single_line_patch_size(dir, &base, "payload.txt", MAX_PATCH_BYTES + 1); + let over = local_changes(dir, "origin", LocalSelection::Staged, None) + .await + .unwrap_err(); + assert!( + matches!(over, GitError::TooLarge(5)), + "unexpected error: {over:?}" + ); + assert_eq!( + over.to_string(), + "the local changes make a patch larger than 5 MiB; Proofline reviews patches up to 5 MiB" + ); + + // Very large patch (12 MiB) stops early cleanly without altering index. + let before_index = std::fs::read(dir.join(".git/index")).unwrap(); + std::fs::write( + dir.join("payload.txt"), + format!("{}\n", "b".repeat(12 << 20)), + ) + .unwrap(); + let huge = local_changes(dir, "origin", LocalSelection::Tracked, None) + .await + .unwrap_err(); + assert!(matches!(huge, GitError::TooLarge(5)), "{huge:?}"); + assert_eq!(std::fs::read(dir.join(".git/index")).unwrap(), before_index); + } + + #[tokio::test] + async fn file_limit_and_large_metadata_with_small_patch() { + let repo = init_repo(); + let dir = repo.path(); + let base = run(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + + let exact_head = commit_empty_files(dir, &base, MAX_PATCH_FILES, "f"); + let exact = range_changes(dir, &base, &exact_head).await.unwrap(); + assert_eq!(exact.files(), MAX_PATCH_FILES); + + let too_many_head = commit_empty_files(dir, &base, MAX_PATCH_FILES + 1, "g"); + let err = range_changes(dir, &base, &too_many_head).await.unwrap_err(); + assert!( + matches!(err, GitError::TooManyFiles(MAX_PATCH_FILES)), + "{err:?}" + ); + assert_eq!( + err.to_string(), + "the local changes include more than 3000 files; Proofline reviews patches up to 3,000 files" + ); + + // 2,500 long-path files (~550 KiB `--raw -z` metadata and ~1.02 MiB of empty-file + // diff headers) alongside a ~3.75 MiB file edit stays below MAX_PATCH_FILES and + // MAX_PATCH_BYTES (~4.77 MiB patch) despite total stdout > 5.2 MiB. + let long_prefix = format!("{}/", "nested_directory_name_segment".repeat(6)); + let many_head = commit_empty_files(dir, &base, 2_500, &long_prefix); + run(dir, &["reset", "--hard", "-q", &many_head]); + std::fs::write( + dir.join("big.txt"), + format!("{}\n", "x".repeat((3 << 20) + (768 << 10))), + ) + .unwrap(); + run(dir, &["add", "big.txt"]); + let big_meta = local_changes(dir, "origin", LocalSelection::Staged, None) + .await + .unwrap(); + assert_eq!(big_meta.files(), 2_501); + assert!(big_meta.patch.len() < MAX_PATCH_BYTES); + } + + #[tokio::test] + async fn oversized_diff_with_renames_copies_and_submodules() { + let repo = init_repo(); + let dir = repo.path(); + let sub = dir.join("sub"); + std::fs::create_dir_all(&sub).unwrap(); + run(&sub, &["init", "-q", "-b", "main"]); + run(&sub, &["config", "user.email", "dev@example.com"]); + run(&sub, &["config", "user.name", "dev"]); + std::fs::write(sub.join("inner.txt"), "v1\n").unwrap(); + run(&sub, &["add", "."]); + run(&sub, &["commit", "-qm", "sub v1"]); + std::fs::write(dir.join("moved.txt"), "alpha\nbeta\ngamma\ndelta\n").unwrap(); + run(dir, &["add", "."]); + run(dir, &["commit", "-qm", "with sub and moved"]); + let base = run(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + run(dir, &["update-ref", "refs/remotes/origin/main", &base]); + run(dir, &["config", "diff.renames", "copies"]); + run(dir, &["config", "diff.ignoreSubmodules", "all"]); + + std::fs::write(sub.join("inner.txt"), "v2\n").unwrap(); + run(&sub, &["commit", "-qam", "sub v2"]); + run(dir, &["add", "sub"]); + run(dir, &["mv", "moved.txt", "renamed.txt"]); + std::fs::write(dir.join("copy.txt"), "alpha\nbeta\ngamma\ndelta\n").unwrap(); + run(dir, &["add", "copy.txt"]); + + let ok = local_changes(dir, "origin", LocalSelection::Staged, None) + .await + .unwrap(); + assert!(ok.patch.contains("rename from moved.txt")); + assert!(!ok.patch.contains("copy from")); + assert!(ok.patch.contains("+Subproject commit ")); + + std::fs::write(dir.join("huge.txt"), format!("{}\n", "z".repeat(6 << 20))).unwrap(); + run(dir, &["add", "huge.txt"]); + let err = local_changes(dir, "origin", LocalSelection::Staged, None) + .await + .unwrap_err(); + assert!(matches!(err, GitError::TooLarge(5)), "{err:?}"); + } + + #[tokio::test] + async fn streaming_parser_handles_chunked_renames_copies_invalid_and_stderr() { + struct ChunkedReader<'a> { + data: &'a [u8], + step: usize, + } + + impl AsyncRead for ChunkedReader<'_> { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + buf: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + if self.data.is_empty() { + return std::task::Poll::Ready(Ok(())); + } + let take = self.step.min(self.data.len()).min(buf.remaining()); + buf.put_slice(&self.data[..take]); + self.data = &self.data[take..]; + std::task::Poll::Ready(Ok(())) + } + } + + // Empty diff. + let limits = DiffLimits { + max_patch_bytes: 64, + max_patch_files: 3, + max_raw_bytes: 512, + }; + let (raw, patch) = read_diff_stdout(ChunkedReader { data: b"", step: 1 }, limits) + .await + .unwrap(); + assert!(raw.is_empty() && patch.is_empty()); + + // Rename + Copy metadata larger than max_patch_bytes, split 3 bytes at a time, + // with patch exactly at max_patch_bytes (64). + let stream_ok = [ + b":100644 100644 1111111 1111111 R100\0old_name.txt\0new_name.txt\0".as_slice(), + b":100644 100644 2222222 2222222 C100\0src.txt\0copied.txt\0\0".as_slice(), + &[b'p'; 64], + ] + .concat(); + assert!(stream_ok.len() > 64 + 64); + let (raw, patch) = read_diff_stdout( + ChunkedReader { + data: &stream_ok, + step: 3, + }, + limits, + ) + .await + .unwrap(); + assert_eq!(patch.len(), 64); + let (paths, rem) = diff_paths(&raw).unwrap(); + assert!(rem.is_empty()); + assert_eq!(paths.len(), 2); + + // One more patch byte trips TooLarge. + let mut stream_over = stream_ok; + stream_over.push(b'!'); + assert!(matches!( + read_diff_stdout( + ChunkedReader { + data: &stream_over, + step: 5, + }, + limits, + ) + .await, + Err(DiffStreamError::TooLarge) + )); + + // Corrupt metadata cases -> InvalidDiff. + for bad in [ + b"\0diff --git a/x b/x\n".as_slice(), + b"not-a-raw-header\0\0patch".as_slice(), + b":100644 100644 1111111 2222222 X\0x.txt\0\0".as_slice(), + b":100644 100644 1111111 2222222 R100\0only_one\0\0".as_slice(), + ] { + assert!( + matches!( + read_diff_stdout(ChunkedReader { data: bad, step: 2 }, limits).await, + Err(DiffStreamError::InvalidDiff) + ), + "{bad:?}" + ); + } + + // Metadata exceeding max_raw_bytes aborts without waiting for patch. + let long_meta = [ + b":100644 100644 1111111 2222222 A\0".as_slice(), + &[b'x'; 600], + b"\0\0", + ] + .concat(); + assert!(matches!( + read_diff_stdout( + ChunkedReader { + data: &long_meta, + step: 7, + }, + limits, + ) + .await, + Err(DiffStreamError::InvalidDiff) + )); + + // Concurrent stderr flood larger than MAX_STDERR_BYTES does not deadlock or retain excess. + let flood = vec![b'e'; MAX_STDERR_BYTES + 32_768]; + let drained = drain_stderr(ChunkedReader { + data: &flood, + step: 1_024, + }) + .await + .unwrap(); + assert_eq!(drained.len(), MAX_STDERR_BYTES); + + // Non-zero Git failure reports GitError::Failed, not InvalidDiff. + let repo = init_repo(); + let missing = "f".repeat(40); + let base = run(repo.path(), &["rev-parse", "HEAD"]).trim().to_owned(); + let failed = range_changes(repo.path(), &base, &missing) + .await + .unwrap_err(); + assert!(matches!(failed, GitError::Failed { .. }), "{failed:?}"); + } + + #[cfg(unix)] + #[tokio::test] + async fn oversized_stream_kills_and_reaps_child_without_waiting() { + let tmp = tempfile::tempdir().unwrap(); + let pid_file = tmp.path().join("child.pid"); + let mut command = Command::new("sh"); + command.args([ + "-c", + "echo $$ > \"$1\"; trap '' PIPE; printf ':000000 100644 0000000 1111111 A\\0f.txt\\0\\0'; \ + dd if=/dev/zero bs=65536 count=96 2>/dev/null | tr '\\0' 'a'; sleep 60", + "sh", + ]); + command.arg(&pid_file); + let limits = DiffLimits { + max_patch_bytes: 1 << 20, + max_patch_files: 10, + max_raw_bytes: 4_096, + }; + let result = tokio::time::timeout( + std::time::Duration::from_secs(10), + diff_command_output(command, "sh test", limits), + ) + .await + .expect("timed out waiting for bounded reader to kill child"); + assert!(matches!(result, Err(GitError::TooLarge(1))), "{result:?}"); + + let pid = std::fs::read_to_string(&pid_file).unwrap(); + let pid = pid.trim(); + assert!(!pid.is_empty()); + let ps = std::process::Command::new("ps") + .args(["-o", "stat=", "-p", pid]) + .output() + .unwrap(); + assert!( + !ps.status.success() || ps.stdout.is_empty(), + "child {pid} still alive or zombie: {}", + String::from_utf8_lossy(&ps.stdout) + ); + } } diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 1c41110..7e945e9 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -1223,3 +1223,28 @@ async fn local_path_never_expands_a_file_replaced_by_a_directory() { assert_eq!(checkout.index().await, index); server.close().await; } + +#[tokio::test] +async fn oversized_local_patches_are_refused_before_http() { + let checkout = Checkout::new(&[("big.txt", "base\n")]).await; + let server = Server::start(true).await; + + let huge = format!("{}\n", "a".repeat(6 << 20)); + checkout.write("big.txt", &huge).await; + let index = checkout.index().await; + let tracked = checkout.review(&server, &[], &[]).await; + assert_eq!(tracked.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&tracked.stderr).contains("larger than 5 MiB")); + server.assert_no_requests(); + assert_eq!(checkout.index().await, index); + + checkout.git(&["add", "big.txt"]).await; + let staged_index = checkout.index().await; + let staged = checkout.review(&server, &[], &["--staged"]).await; + assert_eq!(staged.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&staged.stderr).contains("larger than 5 MiB")); + server.assert_no_requests(); + assert_eq!(checkout.index().await, staged_index); + + server.close().await; +}