diff --git a/crates/twigpine-node/src/api/pulls.rs b/crates/twigpine-node/src/api/pulls.rs index c6891cbf..9257b190 100644 --- a/crates/twigpine-node/src/api/pulls.rs +++ b/crates/twigpine-node/src/api/pulls.rs @@ -14,6 +14,8 @@ use crate::git::store; use crate::state::AppState; use crate::webhooks; +const MAX_PR_DIFF_BYTES: usize = 1024 * 1024; + #[derive(Deserialize)] pub struct CreatePrRequest { pub title: String, @@ -181,8 +183,7 @@ pub async fn get_pr_diff( } }; - // Withhold the entire diff if it touches a path the caller cannot read. - let touched = store::branch_diff_names( + let (target_tip, source_tip) = store::resolve_branch_tips( git_bin, path, &pr.target_branch, @@ -190,28 +191,55 @@ pub async fn get_pr_diff( deadline, ) .map_err(map_git_error)?; - for p in &touched { - let gate = format!("/{}", p.trim_start_matches('/')); - if crate::visibility::visibility_check( - &rules, - is_public, - &owner_did, - caller.as_deref(), - &gate, - ) == crate::visibility::Decision::Deny - { - return Err(AppError::NotFound(format!("PR #{number} not found"))); - } + + let mut denied = false; + let scan = store::scan_branch_diff_names( + git_bin, + path, + &target_tip, + &source_tip, + deadline, + &mut |path| { + let p = String::from_utf8_lossy(path); + let gate = format!("/{}", p.trim_start_matches('/')); + if crate::visibility::visibility_check( + &rules, + is_public, + &owner_did, + caller.as_deref(), + &gate, + ) == crate::visibility::Decision::Deny + { + denied = true; + return false; + } + true + }, + ); + if denied + || scan + .as_ref() + .err() + .is_some_and(|e| e.is::()) + { + return Err(AppError::NotFound(format!("PR #{number} not found"))); } + scan.map_err(map_git_error)?; - let diff = store::branch_diff( + let diff = match store::branch_diff_commits( git_bin, path, - &pr.target_branch, - &pr.source_branch, + &target_tip, + &source_tip, deadline, - ) - .map_err(map_git_error)?; + MAX_PR_DIFF_BYTES, + ) { + Ok(diff) => diff, + Err(e) if e.is::() => { + return Err(AppError::DiffTooLarge(MAX_PR_DIFF_BYTES)); + } + Err(e) => return Err(map_git_error(e)), + }; Ok((diff, pr.source_branch, pr.target_branch)) }, ) @@ -546,7 +574,7 @@ mod tests { use super::*; use axum::body::Body; use axum::http::{Method, StatusCode}; - use axum::routing::post; + use axum::routing::{get, post}; use axum::Router; use std::process::Command; use tower::ServiceExt; @@ -576,6 +604,14 @@ mod tests { fn bare_repo_with_feature( root: &std::path::Path, owner_slug: &str, + ) -> (std::path::PathBuf, String) { + bare_repo_with_feature_contents(root, owner_slug, b"two") + } + + fn bare_repo_with_feature_contents( + root: &std::path::Path, + owner_slug: &str, + feature_contents: &[u8], ) -> (std::path::PathBuf, String) { let work = root.join("work"); std::fs::create_dir_all(&work).unwrap(); @@ -584,7 +620,7 @@ mod tests { git(&work, &["add", "."]); git(&work, &["commit", "-qm", "one"]); git(&work, &["checkout", "-qb", "feature"]); - std::fs::write(work.join("b.txt"), "two").unwrap(); + std::fs::write(work.join("b.txt"), feature_contents).unwrap(); git(&work, &["add", "."]); git(&work, &["commit", "-qm", "two"]); git(&work, &["checkout", "-q", "main"]); @@ -613,6 +649,196 @@ mod tests { (bare, tip) } + async fn seed_pr_diff_state( + pool: sqlx::PgPool, + root: &std::path::Path, + feature_contents: &[u8], + ) -> (AppState, String) { + let owner_slug = OWNER_DID.replace([':', '/'], "_"); + let (bare, _feature_tip) = + bare_repo_with_feature_contents(root, &owner_slug, feature_contents); + let mut state = crate::test_support::test_state(pool.clone()).await; + state.repo_store = crate::git::repo_store::RepoStore::for_testing(root.to_path_buf(), pool); + + let now = Utc::now(); + let repo = crate::db::RepoRecord { + id: uuid::Uuid::new_v4().to_string(), + name: "demo".into(), + owner_did: OWNER_DID.into(), + description: None, + is_public: true, + default_branch: "main".into(), + created_at: now, + updated_at: now, + disk_path: bare.to_string_lossy().into_owned(), + forked_from: None, + machine_id: None, + }; + state.db.create_repo(&repo).await.unwrap(); + let pr = PullRequest { + id: Uuid::new_v4().to_string(), + repo_id: repo.id.clone(), + number: 1, + title: "add b".into(), + body: None, + author_did: OWNER_DID.into(), + source_branch: "feature".into(), + target_branch: "main".into(), + status: "open".into(), + merged_by_did: None, + merged_at: None, + head_commit: None, + created_at: now.to_rfc3339(), + updated_at: now.to_rfc3339(), + }; + state.db.create_pr(&pr).await.unwrap(); + (state, repo.id) + } + + fn pr_diff_app(state: AppState) -> Router { + Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/pulls/{number}/diff", + get(get_pr_diff), + ) + .with_state(state) + } + + fn anonymous_diff_request() -> axum::http::Request { + axum::http::Request::builder() + .uri("/api/v1/repos/z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH/demo/pulls/1/diff") + .body(Body::empty()) + .unwrap() + } + + #[sqlx::test] + async fn get_pr_diff_small_visible_diff_success(pool: sqlx::PgPool) { + let tmp = tempfile::tempdir().unwrap(); + let (state, _repo_id) = seed_pr_diff_state(pool, tmp.path(), b"two").await; + let response = pr_diff_app(state) + .oneshot(anonymous_diff_request()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = crate::test_support::body_json(response).await; + assert_eq!(body["source_branch"], "feature"); + assert_eq!(body["target_branch"], "main"); + assert!( + body["diff"].as_str().unwrap().contains("\n+two"), + "small diff must keep the existing patch body: {body}" + ); + } + + #[sqlx::test] + async fn get_pr_diff_over_cap_returns_413_without_patch(pool: sqlx::PgPool) { + let tmp = tempfile::tempdir().unwrap(); + let large = vec![b'x'; MAX_PR_DIFF_BYTES + 4096]; + let (state, _repo_id) = seed_pr_diff_state(pool, tmp.path(), &large).await; + let response = pr_diff_app(state) + .oneshot(anonymous_diff_request()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); + let body = crate::test_support::body_json(response).await; + assert_eq!( + body, + serde_json::json!({ + "error": "diff_too_large", + "message": "pull request diff exceeds the 1048576-byte limit" + }) + ); + } + + #[sqlx::test] + async fn get_pr_diff_large_visibility_denied_diff_stays_404(pool: sqlx::PgPool) { + let tmp = tempfile::tempdir().unwrap(); + let large = vec![b'x'; MAX_PR_DIFF_BYTES + 4096]; + let (state, repo_id) = seed_pr_diff_state(pool, tmp.path(), &large).await; + state + .db + .set_visibility_rule( + &repo_id, + "/b.txt", + crate::db::VisibilityMode::B, + &[], + OWNER_DID, + ) + .await + .unwrap(); + let response = pr_diff_app(state) + .oneshot(anonymous_diff_request()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = crate::test_support::body_json(response).await; + assert_eq!(body["error"], "not_found"); + assert!( + !body.to_string().contains("b.txt"), + "the read denial must not leak the withheld path: {body}" + ); + } + + #[cfg(unix)] + fn write_executable(path: &std::path::Path, body: &str) { + use std::os::unix::fs::PermissionsExt; + std::fs::write(path, body).unwrap(); + let mut perms = std::fs::metadata(path).unwrap().permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(path, perms).unwrap(); + } + + #[cfg(unix)] + #[sqlx::test] + async fn get_pr_diff_scan_and_patch_use_same_pinned_pair(pool: sqlx::PgPool) { + let tmp = tempfile::tempdir().unwrap(); + let (mut state, _repo_id) = seed_pr_diff_state(pool.clone(), tmp.path(), b"two").await; + let target = "a".repeat(40); + let source = "b".repeat(40); + let log = tmp.path().join("git-args.log"); + let count_log = tmp.path().join("rev-parse-count"); + let fake = tmp.path().join("fakegit"); + let second_target = "c".repeat(40); + let second_source = "d".repeat(40); + write_executable( + &fake, + &format!( + "#!/bin/sh\necho \"$@\" >> \"{}\"\nif [ \"$1\" = rev-parse ]; then count=0; if [ -f \"{}\" ]; then count=$(cat \"{}\"); fi; count=$((count + 1)); echo \"$count\" > \"{}\"; if [ \"$count\" -eq 1 ]; then printf '%s\\n%s\\n' '{}' '{}'; else printf '%s\\n%s\\n' '{}' '{}'; fi; exit 0; fi\nif [ \"$1\" = diff ] && [ \"$2\" = --name-status ]; then exit 0; fi\nif [ \"$1\" = diff ]; then printf 'pinned patch'; exit 0; fi\nexit 128\n", + log.display(), + count_log.display(), + count_log.display(), + count_log.display(), + target, + source, + second_target, + second_source + ), + ); + state.git_bin = fake.to_str().unwrap().to_string(); + + let response = pr_diff_app(state) + .oneshot(anonymous_diff_request()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = crate::test_support::body_json(response).await; + assert_eq!(body["diff"], "pinned patch"); + let args = std::fs::read_to_string(&log).unwrap(); + assert_eq!( + std::fs::read_to_string(&count_log).unwrap().trim(), + "1", + "branch tips must be resolved exactly once: {args}" + ); + let range = format!("{target}...{source}"); + assert!( + args.contains(&format!("diff --name-status -z {range}")), + "scan did not use the pinned pair: {args}" + ); + assert!( + args.lines().any(|line| line == format!("diff {range}")), + "patch did not use the pinned pair: {args}" + ); + } + /// Merging freezes the stored head at the source commit the merge actually /// consumed. The PR row is loaded before the write lock is taken, so a push /// that lands in between leaves the row's own `head_commit` stale; seeding a diff --git a/crates/twigpine-node/src/error.rs b/crates/twigpine-node/src/error.rs index 7e32bbc8..9972ed12 100644 --- a/crates/twigpine-node/src/error.rs +++ b/crates/twigpine-node/src/error.rs @@ -81,6 +81,9 @@ pub enum AppError { continuation: Option, }, + #[error("pull request diff exceeds the {0}-byte limit")] + DiffTooLarge(usize), + #[error("git error: {0}")] Git(String), @@ -250,6 +253,11 @@ impl IntoResponse for AppError { "search_incomplete", message.clone(), ), + AppError::DiffTooLarge(limit) => ( + StatusCode::PAYLOAD_TOO_LARGE, + "diff_too_large", + format!("pull request diff exceeds the {limit}-byte limit"), + ), AppError::Git(msg) => (StatusCode::INTERNAL_SERVER_ERROR, "git_error", msg.clone()), // 504, distinct from the 500 git_error and from the read-gate's 404 / // the auth 401, so the client can tell a deadline from a failure. diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index 32a0fcd8..bdf41f70 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -404,7 +404,6 @@ pub(crate) async fn run_git_bounded( .map_err(|_| anyhow::anyhow!("{label} timed out"))? } -/// Captured git output passed the cap given to [`run_git_bounded_capped`]. #[derive(Debug)] pub(crate) struct OutputTooLarge { pub limit: usize, @@ -418,6 +417,30 @@ impl std::fmt::Display for OutputTooLarge { impl std::error::Error for OutputTooLarge {} +#[derive(Debug)] +pub(crate) struct DiffNameFieldTooLarge { + pub limit: usize, +} + +impl std::fmt::Display for DiffNameFieldTooLarge { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "git diff name field exceeded {} bytes", self.limit) + } +} + +impl std::error::Error for DiffNameFieldTooLarge {} + +#[derive(Debug)] +pub(crate) struct DiffNameScanMalformed(pub &'static str); + +impl std::fmt::Display for DiffNameScanMalformed { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "malformed git diff name output: {}", self.0) + } +} + +impl std::error::Error for DiffNameScanMalformed {} + /// [`run_git_bounded`] plus a hard cap on captured stdout: reads the pipe /// incrementally and kills the child the moment output exceeds /// `max_stdout`, so a huge blob never lands fully in memory. Other callers @@ -2494,66 +2517,311 @@ pub(crate) fn local_branch_ref(short_name: &str) -> String { format!("refs/heads/{short_name}") } -/// Get the diff between two branches: changes on source_branch not in target_branch. -pub fn branch_diff( +fn append_capped(bytes: &mut Vec, max_bytes: usize, chunk: &[u8]) -> bool { + if chunk.len() > max_bytes.saturating_sub(bytes.len()) { + return false; + } + let needed = bytes.len() + chunk.len(); + if needed > bytes.capacity() { + let doubled = bytes.capacity().saturating_mul(2); + let target = needed.max(doubled).min(max_bytes); + bytes.reserve_exact(target.saturating_sub(bytes.len())); + } + bytes.extend_from_slice(chunk); + debug_assert!(bytes.capacity() <= max_bytes); + true +} + +struct CappedPatchOutput { + bytes: Vec, + max_bytes: usize, + exceeded: bool, +} + +impl CappedPatchOutput { + fn new(max_bytes: usize) -> Self { + Self { + bytes: Vec::new(), + max_bytes, + exceeded: false, + } + } + + fn push_chunk(&mut self, chunk: &[u8]) -> bool { + if self.exceeded { + return false; + } + if !append_capped(&mut self.bytes, self.max_bytes, chunk) { + self.exceeded = true; + return false; + } + true + } + + #[cfg(test)] + fn len(&self) -> usize { + self.bytes.len() + } + + #[cfg(test)] + fn capacity(&self) -> usize { + self.bytes.capacity() + } + + fn into_bytes(self) -> Vec { + self.bytes + } +} + +fn valid_commit_id(oid: &str) -> bool { + matches!(oid.len(), 40 | 64) && oid.bytes().all(|b| b.is_ascii_hexdigit()) +} + +fn guard_commit_ids(target: &str, source: &str) -> Result<()> { + if !valid_commit_id(target) || !valid_commit_id(source) || target.len() != source.len() { + bail!("resolved branch tips are not commit object IDs"); + } + Ok(()) +} + +pub(crate) fn resolve_branch_tips( git_bin: &str, repo_path: &Path, target_branch: &str, source_branch: &str, deadline: std::time::Instant, -) -> Result { +) -> Result<(String, String)> { guard_refs(target_branch, source_branch)?; - let target = local_branch_ref(target_branch); - let source = local_branch_ref(source_branch); + let target = format!("{}^{{commit}}", local_branch_ref(target_branch)); + let source = format!("{}^{{commit}}", local_branch_ref(source_branch)); let (status, stdout, stderr) = crate::git::visibility_pack::run_bounded_git_raw( git_bin, - &["diff", &format!("{target}...{source}")], + &["rev-parse", &target, &source], + repo_path, + b"", + deadline, + ) + .context("failed to resolve branch tips")?; + if !status.success() { + let stderr = String::from_utf8_lossy(&stderr); + bail!("git rev-parse failed: {stderr}"); + } + let lines: Vec<&str> = stdout + .split(|b| *b == b'\n') + .filter(|line| !line.is_empty()) + .map(std::str::from_utf8) + .collect::>() + .context("git rev-parse returned non-UTF-8 object IDs")?; + if lines.len() != 2 { + bail!("git rev-parse did not return exactly two branch tips"); + } + let target = lines[0].trim().to_string(); + let source = lines[1].trim().to_string(); + guard_commit_ids(&target, &source)?; + Ok((target, source)) +} + +pub(crate) fn branch_diff_commits( + git_bin: &str, + repo_path: &Path, + target_commit: &str, + source_commit: &str, + deadline: std::time::Instant, + max_bytes: usize, +) -> Result { + guard_commit_ids(target_commit, source_commit)?; + let range = format!("{target_commit}...{source_commit}"); + let mut output = CappedPatchOutput::new(max_bytes); + let (status, stderr, _stopped) = crate::git::visibility_pack::run_bounded_git_streaming( + git_bin, + &["diff", &range], repo_path, b"", deadline, + &mut |chunk| output.push_chunk(chunk), ) .context("failed to run git diff")?; + if output.exceeded { + return Err(OutputTooLarge { limit: max_bytes }.into()); + } if !status.success() { let stderr = String::from_utf8_lossy(&stderr); bail!("git diff failed: {stderr}"); } - Ok(String::from_utf8_lossy(&stdout).into_owned()) + Ok(String::from_utf8_lossy(&output.into_bytes()).into_owned()) } -/// The repo-relative paths changed by `git diff target...source` (the same range -/// as `branch_diff`). Used to enforce per-path visibility on a PR diff: if the -/// caller cannot read one of these paths, the diff is withheld. -pub fn branch_diff_names( +const DIFF_NAME_FIELD_MAX_BYTES: usize = 64 * 1024; + +#[derive(Debug)] +enum DiffNameScanFailure { + FieldTooLarge, + Malformed(&'static str), +} + +impl DiffNameScanFailure { + fn into_error(self) -> anyhow::Error { + match self { + Self::FieldTooLarge => DiffNameFieldTooLarge { + limit: DIFF_NAME_FIELD_MAX_BYTES, + } + .into(), + Self::Malformed(reason) => DiffNameScanMalformed(reason).into(), + } + } +} + +#[derive(Debug)] +enum DiffNameScanState { + Status, + SinglePath, + RenameOld, + RenameNew { old: Vec }, +} + +struct DiffNameScanParser { + partial: Vec, + state: DiffNameScanState, + failure: Option, +} + +impl DiffNameScanParser { + fn new() -> Self { + Self { + partial: Vec::new(), + state: DiffNameScanState::Status, + failure: None, + } + } + + fn fail(&mut self, failure: DiffNameScanFailure) -> bool { + self.failure = Some(failure); + false + } + + fn push(&mut self, chunk: &[u8], emit: &mut dyn FnMut(&[u8]) -> bool) -> bool { + if self.failure.is_some() { + return false; + } + let mut start = 0; + for (index, byte) in chunk.iter().enumerate() { + if *byte != b'\0' { + continue; + } + if !append_capped( + &mut self.partial, + DIFF_NAME_FIELD_MAX_BYTES, + &chunk[start..index], + ) { + return self.fail(DiffNameScanFailure::FieldTooLarge); + } + start = index + 1; + let field = std::mem::take(&mut self.partial); + if !self.complete_field(field, emit) { + return false; + } + } + if start < chunk.len() + && !append_capped( + &mut self.partial, + DIFF_NAME_FIELD_MAX_BYTES, + &chunk[start..], + ) + { + return self.fail(DiffNameScanFailure::FieldTooLarge); + } + true + } + + fn complete_field(&mut self, field: Vec, emit: &mut dyn FnMut(&[u8]) -> bool) -> bool { + match std::mem::replace(&mut self.state, DiffNameScanState::Status) { + DiffNameScanState::Status => { + if field.is_empty() { + return self.fail(DiffNameScanFailure::Malformed("empty status field")); + } + self.state = if matches!(field[0], b'R' | b'C') { + DiffNameScanState::RenameOld + } else { + DiffNameScanState::SinglePath + }; + true + } + DiffNameScanState::SinglePath => { + if field.is_empty() { + return self.fail(DiffNameScanFailure::Malformed("empty path field")); + } + emit(&field) + } + DiffNameScanState::RenameOld => { + if field.is_empty() { + return self.fail(DiffNameScanFailure::Malformed("empty rename source")); + } + self.state = DiffNameScanState::RenameNew { old: field }; + true + } + DiffNameScanState::RenameNew { old } => { + if field.is_empty() { + return self.fail(DiffNameScanFailure::Malformed("empty rename destination")); + } + if !emit(&old) { + return false; + } + emit(&field) + } + } + } + + fn finish(self) -> Result<()> { + if let Some(failure) = self.failure { + return Err(failure.into_error()); + } + if !self.partial.is_empty() { + return Err(DiffNameScanMalformed("trailing unterminated field").into()); + } + match self.state { + DiffNameScanState::Status => Ok(()), + DiffNameScanState::SinglePath => { + Err(DiffNameScanMalformed("status without a path").into()) + } + DiffNameScanState::RenameOld => { + Err(DiffNameScanMalformed("rename without a source path").into()) + } + DiffNameScanState::RenameNew { .. } => { + Err(DiffNameScanMalformed("rename without a destination path").into()) + } + } + } +} + +/// Stream the repo-relative paths changed by `git diff target...source` and +/// invoke `on_path` for each complete path. Returning false stops the scan. +pub(crate) fn scan_branch_diff_names( git_bin: &str, repo_path: &Path, - target_branch: &str, - source_branch: &str, + target_commit: &str, + source_commit: &str, deadline: std::time::Instant, -) -> Result> { - guard_refs(target_branch, source_branch)?; - let target = local_branch_ref(target_branch); - let source = local_branch_ref(source_branch); - let (status, stdout, stderr) = crate::git::visibility_pack::run_bounded_git_raw( + on_path: &mut dyn FnMut(&[u8]) -> bool, +) -> Result<()> { + guard_commit_ids(target_commit, source_commit)?; + let range = format!("{target_commit}...{source_commit}"); + let mut parser = DiffNameScanParser::new(); + let (status, stderr, stopped) = crate::git::visibility_pack::run_bounded_git_streaming( git_bin, - &["diff", "--name-only", "-z", &format!("{target}...{source}")], + &["diff", "--name-status", "-z", &range], repo_path, b"", deadline, + &mut |chunk| parser.push(chunk, on_path), ) - .context("failed to run git diff --name-only")?; - if !status.success() { + .context("failed to run git diff --name-status")?; + parser.finish()?; + if !status.success() && !stopped { let stderr = String::from_utf8_lossy(&stderr); - bail!("git diff --name-only failed: {stderr}"); + bail!("git diff --name-status failed: {stderr}"); } - // Split on NUL (`-z`) so paths containing newlines keep their exact bytes; - // `--name-only` without `-z` would quote/escape such paths and they would no - // longer match the visibility globs in get_pr_diff, leaking the diff. - Ok(stdout - .split(|b| *b == b'\0') - .filter(|s| !s.is_empty()) - .map(|s| String::from_utf8_lossy(s).into_owned()) - .collect()) + Ok(()) } /// Merge source_branch into target_branch in a bare repo using a temporary worktree. @@ -2743,7 +3011,7 @@ pub fn repo_disk_path(repos_dir: &Path, owner_did: &str, repo_name: &str) -> std #[cfg(test)] mod tests { - use super::{branch_diff_names, merge_branch}; + use super::merge_branch; use std::path::Path; use std::process::Command; @@ -3079,24 +3347,40 @@ mod tests { ); } - #[test] - fn branch_diff_names_lists_changed_paths() { + fn run_git_ok(dir: &Path, args: &[&str]) { + let out = Command::new("git") + .args(args) + .current_dir(dir) + .env("GIT_AUTHOR_NAME", "t") + .env("GIT_AUTHOR_EMAIL", "t@example.com") + .env("GIT_COMMITTER_NAME", "t") + .env("GIT_COMMITTER_EMAIL", "t@example.com") + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + } + + fn write_and_commit(dir: &Path, rel: &str, bytes: &[u8], message: &str) { + let path = dir.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(path, bytes).unwrap(); + run_git_ok(dir, &["add", rel]); + run_git_ok(dir, &["commit", "-qm", message]); + } + + fn seeded_diff_repo() -> (tempfile::TempDir, String) { let td = tempfile::TempDir::new().unwrap(); - let work: &Path = td.path(); - let g = |args: &[&str]| { - assert!(Command::new("git") - .args(args) - .current_dir(work) - .status() - .unwrap() - .success()); - }; - g(&["init", "-q"]); - g(&["config", "user.email", "t@t"]); - g(&["config", "user.name", "t"]); - std::fs::write(work.join("base.txt"), b"base\n").unwrap(); - g(&["add", "."]); - g(&["commit", "-qm", "base"]); + let work = td.path(); + run_git_ok(work, &["init", "-q"]); + run_git_ok(work, &["config", "user.email", "t@t"]); + run_git_ok(work, &["config", "user.name", "t"]); + write_and_commit(work, "base.txt", b"base\n", "base"); let main = { let o = Command::new("git") .args(["symbolic-ref", "--short", "HEAD"]) @@ -3105,14 +3389,37 @@ mod tests { .unwrap(); String::from_utf8_lossy(&o.stdout).trim().to_string() }; - g(&["checkout", "-q", "-b", "feature"]); - std::fs::create_dir_all(work.join("secret")).unwrap(); - std::fs::write(work.join("secret/x.txt"), b"secret\n").unwrap(); - g(&["add", "."]); - g(&["commit", "-qm", "feat"]); + run_git_ok(work, &["checkout", "-q", "-b", "feature"]); + write_and_commit(work, "secret/x.txt", b"secret\n", "feat"); + (td, main) + } + + fn diff_deadline() -> std::time::Instant { + std::time::Instant::now() + std::time::Duration::from_secs(5) + } + + fn test_oid(byte: char) -> String { + byte.to_string().repeat(40) + } + + fn scan_names(repo: &Path, target: &str, source: &str) -> Vec { + let mut names = Vec::new(); + super::scan_branch_diff_names("git", repo, target, source, diff_deadline(), &mut |path| { + names.push(String::from_utf8_lossy(path).into_owned()); + true + }) + .unwrap(); + names + } - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - let names = branch_diff_names("git", work, &main, "feature", deadline).unwrap(); + #[test] + fn branch_diff_scan_lists_changed_paths_and_small_patch() { + let (td, main) = seeded_diff_repo(); + let work = td.path(); + let (target, source) = + super::resolve_branch_tips("git", work, &main, "feature", diff_deadline()).unwrap(); + + let names = scan_names(work, &target, &source); assert!( names.iter().any(|p| p == "secret/x.txt"), "expected secret/x.txt in changed paths, got {names:?}" @@ -3121,10 +3428,379 @@ mod tests { !names.iter().any(|p| p == "base.txt"), "unchanged file must not appear: {names:?}" ); - let patch = super::branch_diff("git", work, &main, "feature", deadline).unwrap(); + let patch = + super::branch_diff_commits("git", work, &target, &source, diff_deadline(), 1024 * 1024) + .unwrap(); assert!(patch.contains("\n+secret\n")); } + #[test] + fn diff_name_parser_accepts_fields_split_at_every_boundary() { + let record = b"M\0alpha\0R100\0old\0new\0C100\0copy-old\0copy-new\0"; + let expected = ["alpha", "old", "new", "copy-old", "copy-new"]; + for split in 0..=record.len() { + let mut parser = super::DiffNameScanParser::new(); + let mut seen = Vec::new(); + assert!(parser.push(&record[..split], &mut |path| { + seen.push(String::from_utf8_lossy(path).into_owned()); + true + })); + assert!(parser.push(&record[split..], &mut |path| { + seen.push(String::from_utf8_lossy(path).into_owned()); + true + })); + parser.finish().unwrap(); + assert_eq!(seen, expected, "split at byte {split}"); + } + } + + #[test] + fn scan_empty_diff_invokes_no_callback() { + let (td, main) = seeded_diff_repo(); + let work = td.path(); + let (target, _source) = + super::resolve_branch_tips("git", work, &main, "feature", diff_deadline()).unwrap(); + let mut calls = 0; + super::scan_branch_diff_names("git", work, &target, &target, diff_deadline(), &mut |_| { + calls += 1; + true + }) + .unwrap(); + assert_eq!(calls, 0); + } + + #[test] + fn scan_real_rename_delivers_old_and_new_paths() { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path(); + run_git_ok(work, &["init", "-q"]); + run_git_ok(work, &["config", "user.email", "t@t"]); + run_git_ok(work, &["config", "user.name", "t"]); + write_and_commit(work, "old.txt", b"rename\n", "base"); + let main = { + let o = Command::new("git") + .args(["symbolic-ref", "--short", "HEAD"]) + .current_dir(work) + .output() + .unwrap(); + String::from_utf8_lossy(&o.stdout).trim().to_string() + }; + run_git_ok(work, &["checkout", "-q", "-b", "feature"]); + run_git_ok(work, &["mv", "old.txt", "new.txt"]); + run_git_ok(work, &["commit", "-qm", "rename"]); + let (target, source) = + super::resolve_branch_tips("git", work, &main, "feature", diff_deadline()).unwrap(); + let names = scan_names(work, &target, &source); + assert!( + names.iter().any(|p| p == "old.txt"), + "rename source must be checked: {names:?}" + ); + assert!( + names.iter().any(|p| p == "new.txt"), + "rename destination must be checked: {names:?}" + ); + } + + #[cfg(unix)] + fn fake_git_script(dir: &Path, body: &str) -> String { + let path = dir.join("fakegit"); + write_fake_git(&path, body); + path.to_str().unwrap().to_string() + } + + #[cfg(unix)] + #[test] + fn branch_diff_exact_cap_succeeds() { + let td = tempfile::TempDir::new().unwrap(); + let payload = "x".repeat(16); + let git = fake_git_script(td.path(), &format!("#!/bin/sh\nprintf '%s' '{payload}'\n")); + let patch = super::branch_diff_commits( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + 16, + ) + .unwrap(); + assert_eq!(patch, payload); + } + + #[cfg(unix)] + #[test] + fn branch_diff_one_byte_over_cap_is_typed_error() { + let td = tempfile::TempDir::new().unwrap(); + let payload = "x".repeat(17); + let git = fake_git_script(td.path(), &format!("#!/bin/sh\nprintf '%s' '{payload}'\n")); + let err = super::branch_diff_commits( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + 16, + ) + .expect_err("over-cap diff must fail with OutputTooLarge"); + assert!(err.is::()); + } + + #[test] + fn capped_patch_output_growth_with_spare_capacity_stays_within_cap() { + let mut bytes = Vec::with_capacity(10); + bytes.extend_from_slice(b"123456"); + assert_eq!(bytes.capacity(), 10); + + assert!(super::append_capped(&mut bytes, 14, b"12345678")); + assert_eq!(bytes.len(), 14); + assert!( + bytes.capacity() <= 14, + "capacity {} must remain capped", + bytes.capacity() + ); + } + + #[test] + fn capped_patch_output_failed_append_leaves_len_and_capacity_unchanged() { + let mut out = super::CappedPatchOutput::new(16); + assert!(out.push_chunk(b"12345")); + let len = out.len(); + let capacity = out.capacity(); + + assert!(!out.push_chunk(&[b'x'; 17])); + assert_eq!(out.len(), len); + assert_eq!(out.capacity(), capacity); + } + + #[test] + fn capped_patch_output_capacity_never_exceeds_cap() { + let mut out = super::CappedPatchOutput::new(16); + for chunk in [ + b"12345".as_slice(), + b"67890".as_slice(), + b"abcde".as_slice(), + b"f".as_slice(), + ] { + assert!(out.push_chunk(chunk)); + assert!(out.len() <= 16); + assert!(out.capacity() <= 16, "capacity {}", out.capacity()); + } + assert_eq!(out.len(), 16); + } + + #[cfg(unix)] + #[test] + fn branch_diff_invalid_utf8_below_cap_stays_lossy() { + let td = tempfile::TempDir::new().unwrap(); + let git = fake_git_script(td.path(), "#!/bin/sh\nprintf '\\377x'\n"); + let patch = super::branch_diff_commits( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + 16, + ) + .unwrap(); + assert_eq!(patch, "\u{fffd}x"); + } + + #[test] + fn branch_diff_binary_output_below_cap_keeps_git_format() { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path(); + run_git_ok(work, &["init", "-q"]); + run_git_ok(work, &["config", "user.email", "t@t"]); + run_git_ok(work, &["config", "user.name", "t"]); + write_and_commit(work, "bin", b"a\0b", "base"); + let main = { + let o = Command::new("git") + .args(["symbolic-ref", "--short", "HEAD"]) + .current_dir(work) + .output() + .unwrap(); + String::from_utf8_lossy(&o.stdout).trim().to_string() + }; + run_git_ok(work, &["checkout", "-q", "-b", "feature"]); + write_and_commit(work, "bin", b"c\0d", "binary"); + let (target, source) = + super::resolve_branch_tips("git", work, &main, "feature", diff_deadline()).unwrap(); + let patch = + super::branch_diff_commits("git", work, &target, &source, diff_deadline(), 1024) + .unwrap(); + assert!(patch.contains("Binary files a/bin and b/bin differ")); + } + + #[cfg(unix)] + #[test] + fn branch_diff_stops_child_process_group_when_cap_trips() { + use std::time::Duration; + let td = tempfile::TempDir::new().unwrap(); + let shell_pid = td.path().join("shell.pid"); + let child_pid = td.path().join("child.pid"); + let body = format!( + "#!/bin/sh\necho $$ > \"{}\"\nyes x &\necho $! > \"{}\"\nwait\n", + shell_pid.display(), + child_pid.display() + ); + let git = fake_git_script(td.path(), &body); + let err = super::branch_diff_commits( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + 16, + ) + .unwrap_err(); + assert!(err.is::()); + let pid: i32 = std::fs::read_to_string(&child_pid) + .unwrap() + .trim() + .parse() + .unwrap(); + let mut gone = false; + for _ in 0..100 { + if unsafe { libc::kill(pid, 0) } != 0 { + gone = true; + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + unsafe { + libc::kill(pid, libc::SIGKILL); + } + assert!(gone, "the output producer survived the cap trip"); + } + + #[cfg(unix)] + #[test] + fn branch_diff_nonzero_status_below_cap_is_git_error() { + let td = tempfile::TempDir::new().unwrap(); + let git = fake_git_script( + td.path(), + "#!/bin/sh\nprintf small\necho bad >&2\nexit 128\n", + ); + let err = super::branch_diff_commits( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + 1024, + ) + .unwrap_err(); + assert!(!err.is::()); + assert!(err.to_string().contains("git diff failed")); + } + + #[cfg(unix)] + #[test] + fn scan_callback_false_stops_child_process_group() { + use std::time::Duration; + let td = tempfile::TempDir::new().unwrap(); + let child_pid = td.path().join("scan-child.pid"); + let body = format!( + "#!/bin/sh\nsh -c 'echo $$ > \"$1\"; while :; do printf \"M\\0path\\0\"; done' _ \"{}\" &\nwait\n", + child_pid.display() + ); + let git = fake_git_script(td.path(), &body); + let mut calls = 0; + super::scan_branch_diff_names( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + &mut |_| { + calls += 1; + false + }, + ) + .unwrap(); + assert_eq!(calls, 1); + let pid: i32 = std::fs::read_to_string(&child_pid) + .unwrap() + .trim() + .parse() + .unwrap(); + let mut gone = false; + for _ in 0..100 { + if unsafe { libc::kill(pid, 0) } != 0 { + gone = true; + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + unsafe { + libc::kill(pid, libc::SIGKILL); + } + assert!(gone, "the scan producer survived early denial"); + } + + #[cfg(unix)] + #[test] + fn scan_overlong_partial_field_is_typed_error() { + let td = tempfile::TempDir::new().unwrap(); + let git = fake_git_script( + td.path(), + "#!/bin/sh\nyes x | tr -d '\\n' | head -c 65537\n", + ); + let err = super::scan_branch_diff_names( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + &mut |_| true, + ) + .unwrap_err(); + assert!(err.is::()); + } + + #[cfg(unix)] + #[test] + fn scan_trailing_partial_field_is_malformed() { + let td = tempfile::TempDir::new().unwrap(); + let git = fake_git_script(td.path(), "#!/bin/sh\nprintf 'M\\0abc'\n"); + let mut emitted = 0; + let err = super::scan_branch_diff_names( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + &mut |_| { + emitted += 1; + true + }, + ) + .unwrap_err(); + assert!(err.is::()); + assert_eq!(emitted, 0); + } + + #[cfg(unix)] + #[test] + fn scan_incomplete_rename_pair_is_malformed() { + let td = tempfile::TempDir::new().unwrap(); + let git = fake_git_script(td.path(), "#!/bin/sh\nprintf 'R100\\0old\\0'\n"); + let mut emitted = 0; + let err = super::scan_branch_diff_names( + &git, + td.path(), + &test_oid('a'), + &test_oid('b'), + diff_deadline(), + &mut |_| { + emitted += 1; + true + }, + ) + .unwrap_err(); + assert!(err.is::()); + assert_eq!(emitted, 0); + } + /// #173 round-10 (KTD2): `object_type_bounded` reaps a wedged `cat-file` child at its /// deadline instead of blocking on it to natural exit, so a hung probe cannot pin the /// /ipfs walk admission the owning task holds. A fake `git` records its pid and sleeps