Skip to content

Commit fc598f5

Browse files
authored
fix(git): allow deleting the default branch (#4297)
Tal here, human. Trying to help. This bug bugged me... ## Summary A repository's first branch becomes its symbolic `HEAD`, and Git's bare-repository default rejects deleting that branch even when another branch survives. This change: - sets `receive.denyDeleteCurrent=ignore` only for the ephemeral `git receive-pack` process - preserves the existing server-side `core.hooksPath` override and authorization hook - lets the existing CAS publication logic select a surviving branch as the next manifest `HEAD` - adds regression coverage using a real stateless `git receive-pack` request and a manifest HEAD-selection test This lets users replace an accidental default branch without deleting the object-storage manifest pointer. ### Related issue Fixes #3572 ### Testing - `cargo test -p buzz-relay api::git::` (128 passed, 5 ignored) - `just ci` - live E2E roundtrip against a release relay with PostgreSQL, Redis, and MinIO: - created a repository through signed Nostr events - verified authorized pushes and rejected unauthorized clone/push - pushed a surviving `master` branch - deleted the active `main` branch over authenticated Smart HTTP - freshly cloned the repository and verified `master` became HEAD, `origin/main` was absent, and repository content remained intact Signed-off-by: Tal Weiss <[email protected]>
1 parent b7bb151 commit fc598f5

2 files changed

Lines changed: 165 additions & 7 deletions

File tree

‎crates/buzz-relay/src/api/git/cas_publish.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,6 +1370,15 @@ mod tests {
13701370
);
13711371
}
13721372

1373+
#[test]
1374+
fn published_head_moves_to_surviving_branch_after_current_branch_deletion() {
1375+
let refs = BTreeMap::from([("refs/heads/master".to_string(), "1".repeat(40))]);
1376+
assert_eq!(
1377+
resolve_published_head(&refs, "refs/heads/main".to_string(), "refs/heads/main"),
1378+
"refs/heads/master"
1379+
);
1380+
}
1381+
13731382
#[test]
13741383
fn digest_from_key_strips_prefix() {
13751384
let k = format!("manifests/{}", "a".repeat(64));

‎crates/buzz-relay/src/api/git/transport.rs‎

Lines changed: 156 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,7 +1064,7 @@ pub async fn receive_pack(
10641064
state.config.bind_addr.port()
10651065
);
10661066
let hooks_dir = repo.path().join("hooks").display().to_string();
1067-
let hook_env = vec![
1067+
let mut hook_env = vec![
10681068
("BUZZ_HOOK_URL", hook_url),
10691069
(
10701070
"BUZZ_HOOK_SECRET",
@@ -1077,13 +1077,8 @@ pub async fn receive_pack(
10771077
auth.tenant.community().as_uuid().to_string(),
10781078
),
10791079
("BUZZ_PUSHER_PUBKEY", pusher_hex.clone()),
1080-
// Override any repo-local core.hooksPath setting; defense in
1081-
// depth even though the hydrated workspace has no inherited
1082-
// config.
1083-
("GIT_CONFIG_COUNT", "1".to_string()),
1084-
("GIT_CONFIG_KEY_0", "core.hooksPath".to_string()),
1085-
("GIT_CONFIG_VALUE_0", hooks_dir),
10861080
];
1081+
hook_env.extend(receive_pack_git_config(hooks_dir));
10871082

10881083
// Run receive-pack against the tempdir. Returns the *owned* subprocess
10891084
// output (PackOutput) — crucially NOT a Response, so the post-push
@@ -1111,6 +1106,23 @@ pub async fn receive_pack(
11111106
Ok(finalize_push(&state, ctx).await)
11121107
}
11131108

1109+
/// Per-process git configuration for the hydrated receive-pack workspace.
1110+
fn receive_pack_git_config(hooks_dir: String) -> Vec<(&'static str, String)> {
1111+
vec![
1112+
// Override any repo-local core.hooksPath setting; defense in depth
1113+
// even though the hydrated workspace has no inherited config.
1114+
("GIT_CONFIG_COUNT", "2".to_string()),
1115+
("GIT_CONFIG_KEY_0", "core.hooksPath".to_string()),
1116+
("GIT_CONFIG_VALUE_0", hooks_dir),
1117+
// A bare repository rejects deletion of its symbolic HEAD branch by
1118+
// default. Hydrated repositories are ephemeral, and cas_publish
1119+
// selects a surviving branch for the next manifest HEAD, so allow
1120+
// receive-pack to apply the deletion before that selection runs.
1121+
("GIT_CONFIG_KEY_1", "receive.denyDeleteCurrent".to_string()),
1122+
("GIT_CONFIG_VALUE_1", "ignore".to_string()),
1123+
]
1124+
}
1125+
11141126
/// Buffered output of a `git --stateless-rpc` subprocess.
11151127
///
11161128
/// The handler holds this as an owned value between subprocess completion
@@ -1921,11 +1933,148 @@ mod track_c_tests {
19211933
use buzz_core::CommunityId;
19221934
use nostr::{EventBuilder, Keys, Kind, Tag};
19231935
use std::collections::BTreeMap;
1936+
use std::io::Write;
1937+
use std::process::Output;
19241938

19251939
fn oid_sha1() -> String {
19261940
"cb09a769da1c01f458fa6959d4e8eded38fac8d3".to_string()
19271941
}
19281942

1943+
fn run_test_git(cwd: &Path, args: &[&str], extra_env: &[(&str, String)]) -> Output {
1944+
let mut cmd = std::process::Command::new("git");
1945+
cmd.current_dir(cwd)
1946+
.args(args)
1947+
.env_clear()
1948+
.env("PATH", std::env::var("PATH").unwrap_or_default())
1949+
.env("GIT_CONFIG_NOSYSTEM", "1")
1950+
.env("GIT_CONFIG_GLOBAL", "/dev/null")
1951+
.env("HOME", "/dev/null");
1952+
for (key, value) in extra_env {
1953+
cmd.env(key, value);
1954+
}
1955+
cmd.output().expect("run git")
1956+
}
1957+
1958+
fn run_test_receive_pack(repo: &Path, request: &[u8], extra_env: &[(&str, String)]) -> Output {
1959+
let mut cmd = std::process::Command::new("git");
1960+
cmd.arg("receive-pack")
1961+
.arg("--stateless-rpc")
1962+
.arg(repo)
1963+
.stdin(std::process::Stdio::piped())
1964+
.stdout(std::process::Stdio::piped())
1965+
.stderr(std::process::Stdio::piped())
1966+
.env_clear()
1967+
.env("PATH", std::env::var("PATH").unwrap_or_default())
1968+
.env("GIT_CONFIG_NOSYSTEM", "1")
1969+
.env("GIT_CONFIG_GLOBAL", "/dev/null")
1970+
.env("HOME", "/dev/null");
1971+
for (key, value) in extra_env {
1972+
cmd.env(key, value);
1973+
}
1974+
1975+
let mut child = cmd.spawn().expect("spawn receive-pack");
1976+
child
1977+
.stdin
1978+
.take()
1979+
.expect("receive-pack stdin")
1980+
.write_all(request)
1981+
.expect("write receive-pack request");
1982+
child.wait_with_output().expect("wait for receive-pack")
1983+
}
1984+
1985+
fn assert_git_success(output: Output, operation: &str) {
1986+
assert!(
1987+
output.status.success(),
1988+
"{operation} failed: {}",
1989+
String::from_utf8_lossy(&output.stderr)
1990+
);
1991+
}
1992+
1993+
#[test]
1994+
fn receive_pack_config_allows_deleting_current_branch() {
1995+
let root = tempfile::TempDir::new().expect("tempdir");
1996+
let remote = root.path().join("remote.git");
1997+
let source = root.path().join("source");
1998+
let remote_arg = remote.to_str().expect("utf-8 remote path");
1999+
let source_arg = source.to_str().expect("utf-8 source path");
2000+
2001+
assert_git_success(
2002+
run_test_git(
2003+
root.path(),
2004+
&["init", "--bare", "--initial-branch=main", remote_arg],
2005+
&[],
2006+
),
2007+
"initialize bare remote",
2008+
);
2009+
assert_git_success(
2010+
run_test_git(
2011+
root.path(),
2012+
&["init", "--initial-branch=main", source_arg],
2013+
&[],
2014+
),
2015+
"initialize source repository",
2016+
);
2017+
assert_git_success(
2018+
run_test_git(source.as_path(), &["config", "user.name", "Buzz Test"], &[]),
2019+
"configure user name",
2020+
);
2021+
assert_git_success(
2022+
run_test_git(
2023+
source.as_path(),
2024+
&["config", "user.email", "[email protected]"],
2025+
&[],
2026+
),
2027+
"configure user email",
2028+
);
2029+
std::fs::write(source.join("README.md"), "test\n").expect("write fixture");
2030+
assert_git_success(
2031+
run_test_git(source.as_path(), &["add", "README.md"], &[]),
2032+
"stage fixture",
2033+
);
2034+
assert_git_success(
2035+
run_test_git(source.as_path(), &["commit", "-m", "fixture"], &[]),
2036+
"commit fixture",
2037+
);
2038+
assert_git_success(
2039+
run_test_git(
2040+
source.as_path(),
2041+
&["push", remote_arg, "main:main", "main:master"],
2042+
&[],
2043+
),
2044+
"seed main and master",
2045+
);
2046+
2047+
let oid_output = run_test_git(remote.as_path(), &["rev-parse", "refs/heads/main"], &[]);
2048+
assert!(oid_output.status.success());
2049+
let old_oid = String::from_utf8(oid_output.stdout)
2050+
.expect("utf-8 oid")
2051+
.trim()
2052+
.to_string();
2053+
let command = format!(
2054+
"{old_oid} {} refs/heads/main\0report-status\n",
2055+
"0".repeat(40)
2056+
);
2057+
let mut request = format!("{:04x}", command.len() + 4).into_bytes();
2058+
request.extend_from_slice(command.as_bytes());
2059+
request.extend_from_slice(b"0000");
2060+
2061+
let git_config = receive_pack_git_config(remote.join("hooks").display().to_string());
2062+
let output = run_test_receive_pack(remote.as_path(), &request, &git_config);
2063+
assert!(
2064+
output.status.success(),
2065+
"receive-pack failed: {}",
2066+
String::from_utf8_lossy(&output.stderr)
2067+
);
2068+
assert!(
2069+
!receive_pack_report_rejected(&output.stdout),
2070+
"receive-pack rejected the deletion: {}",
2071+
String::from_utf8_lossy(&output.stdout)
2072+
);
2073+
2074+
assert!(!remote.join("refs/heads/main").exists());
2075+
assert!(remote.join("refs/heads/master").exists());
2076+
}
2077+
19292078
/// A gzip-encoded request body is transparently inflated before it
19302079
/// reaches the git subprocess. Git's smart-HTTP client gzips the
19312080
/// upload-pack/receive-pack request body past a size threshold (fires

0 commit comments

Comments
 (0)