diff --git a/crates/twigpine-node/src/api/pulls.rs b/crates/twigpine-node/src/api/pulls.rs index 4f6e5d373..c6891cbfb 100644 --- a/crates/twigpine-node/src/api/pulls.rs +++ b/crates/twigpine-node/src/api/pulls.rs @@ -1,7 +1,7 @@ //! Pull request API handlers. use axum::extract::{Extension, Path, State}; -use axum::http::StatusCode; +use axum::http::{HeaderMap, StatusCode}; use axum::Json; use chrono::Utc; use serde::Deserialize; @@ -150,6 +150,8 @@ pub async fn get_pr_diff( State(state): State, Path((owner, name, number)): Path<(String, String, i64)>, auth: Option>, + crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr, + headers: HeaderMap, ) -> Result> { let caller = auth.as_ref().map(|e| e.0 .0.as_str()); let (record, rules) = @@ -161,37 +163,64 @@ pub async fn get_pr_diff( .await? .ok_or_else(|| AppError::NotFound(format!("PR #{number} not found")))?; - let disk_path = state - .repo_store - .acquire(&record.owner_did, &record.name) - .await - .map_err(|e| AppError::Git(e.to_string()))?; - - // Withhold the entire diff if it touches a path the caller cannot read, so a - // PR diff cannot leak private-subtree content of an otherwise-public repo. - let touched = store::branch_diff_names(&disk_path, &pr.target_branch, &pr.source_branch) - .map_err(|e| AppError::Git(e.to_string()))?; - for p in &touched { - let gate = format!("/{}", p.trim_start_matches('/')); - if crate::visibility::visibility_check( - &rules, - record.is_public, - &record.owner_did, - caller, - &gate, - ) == crate::visibility::Decision::Deny - { - return Err(AppError::NotFound(format!("PR #{number} not found"))); - } - } - - let diff = store::branch_diff(&disk_path, &pr.target_branch, &pr.source_branch) - .map_err(|e| AppError::Git(e.to_string()))?; + let owner_did = record.owner_did.clone(); + let is_public = record.is_public; + let caller = auth.map(|e| e.0 .0); + let (diff, source_branch, target_branch) = super::repos::run_repo_git_read( + &state, + &headers, + peer, + &record, + "pr_diff", + move |git_bin, path, deadline| { + let map_git_error = |e: anyhow::Error| { + if e.is::() { + AppError::Timeout("git service timed out".into()) + } else { + AppError::Git(e.to_string()) + } + }; + + // Withhold the entire diff if it touches a path the caller cannot read. + let touched = store::branch_diff_names( + git_bin, + path, + &pr.target_branch, + &pr.source_branch, + 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 diff = store::branch_diff( + git_bin, + path, + &pr.target_branch, + &pr.source_branch, + deadline, + ) + .map_err(map_git_error)?; + Ok((diff, pr.source_branch, pr.target_branch)) + }, + ) + .await?; Ok(Json(serde_json::json!({ "diff": diff, - "source_branch": pr.source_branch, - "target_branch": pr.target_branch, + "source_branch": source_branch, + "target_branch": target_branch, }))) } diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index 2016670f6..6296d265b 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -2493,48 +2493,61 @@ pub(crate) fn local_branch_ref(short_name: &str) -> String { } /// Get the diff between two branches: changes on source_branch not in target_branch. -pub fn branch_diff(repo_path: &Path, target_branch: &str, source_branch: &str) -> Result { +pub fn branch_diff( + git_bin: &str, + repo_path: &Path, + target_branch: &str, + source_branch: &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 output = Command::new("git") - .args(["diff", &format!("{target}...{source}")]) - .current_dir(repo_path) - .output() - .context("failed to run git diff")?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); + let (status, stdout, stderr) = crate::git::visibility_pack::run_bounded_git_raw( + git_bin, + &["diff", &format!("{target}...{source}")], + repo_path, + b"", + deadline, + ) + .context("failed to run git diff")?; + if !status.success() { + let stderr = String::from_utf8_lossy(&stderr); bail!("git diff failed: {stderr}"); } - Ok(String::from_utf8_lossy(&output.stdout).to_string()) + Ok(String::from_utf8_lossy(&stdout).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( + git_bin: &str, repo_path: &Path, target_branch: &str, source_branch: &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 output = Command::new("git") - .args(["diff", "--name-only", "-z", &format!("{target}...{source}")]) - .current_dir(repo_path) - .output() - .context("failed to run git diff --name-only")?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); + let (status, stdout, stderr) = crate::git::visibility_pack::run_bounded_git_raw( + git_bin, + &["diff", "--name-only", "-z", &format!("{target}...{source}")], + repo_path, + b"", + deadline, + ) + .context("failed to run git diff --name-only")?; + if !status.success() { + let stderr = String::from_utf8_lossy(&stderr); bail!("git diff --name-only 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(output - .stdout + Ok(stdout .split(|b| *b == b'\0') .filter(|s| !s.is_empty()) .map(|s| String::from_utf8_lossy(s).into_owned()) @@ -3096,7 +3109,8 @@ mod tests { g(&["add", "."]); g(&["commit", "-qm", "feat"]); - let names = branch_diff_names(work, &main, "feature").unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let names = branch_diff_names("git", work, &main, "feature", deadline).unwrap(); assert!( names.iter().any(|p| p == "secret/x.txt"), "expected secret/x.txt in changed paths, got {names:?}" @@ -3105,6 +3119,8 @@ 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(); + assert!(patch.contains("\n+secret\n")); } /// #173 round-10 (KTD2): `object_type_bounded` reaps a wedged `cat-file` child at its