Skip to content

Commit f580efc

Browse files
authored
fix(git): make project branch workflows reliable (#2213)
1 parent e7e2197 commit f580efc

22 files changed

Lines changed: 604 additions & 124 deletions

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

Lines changed: 50 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,34 @@ async fn snapshot_workspace_state(
352352
Ok((refs, head))
353353
}
354354

355+
fn resolve_published_head(
356+
refs: &BTreeMap<String, String>,
357+
observed_head: String,
358+
parent_head: &str,
359+
) -> String {
360+
let is_published_branch =
361+
|name: &str| name.starts_with("refs/heads/") && refs.contains_key(name);
362+
if is_published_branch(&observed_head) {
363+
return observed_head;
364+
}
365+
if is_published_branch(parent_head) {
366+
return parent_head.to_string();
367+
}
368+
for preferred in ["refs/heads/main", "refs/heads/master"] {
369+
if refs.contains_key(preferred) {
370+
return preferred.to_string();
371+
}
372+
}
373+
if let Some(branch) = refs.keys().find(|name| name.starts_with("refs/heads/")) {
374+
return branch.clone();
375+
}
376+
if !observed_head.is_empty() {
377+
observed_head
378+
} else {
379+
parent_head.to_string()
380+
}
381+
}
382+
355383
fn digest_from_pack_key(key: &str) -> Result<String, CasError> {
356384
key.strip_prefix("packs/")
357385
.filter(|digest| digest.len() == 64 && digest.chars().all(|c| c.is_ascii_hexdigit()))
@@ -1014,16 +1042,10 @@ async fn cas_publish_inner(
10141042
// below uses them as the "negative" set to produce the delta pack.
10151043
let (refs_after, head_observed) = snapshot_workspace_state(repo_path, scratch_dir).await?;
10161044

1017-
// HEAD fallback: a bare repo serving pushes shouldn't have detached
1018-
// HEAD, but if `git symbolic-ref` failed (or returned empty), inherit
1019-
// the parent's HEAD rather than installing an empty one. `validate()`
1020-
// below rejects "empty after fallback" — that's the first-push +
1021-
// detached-HEAD case where the writer must declare a HEAD.
1022-
let head = if head_observed.is_empty() {
1023-
parent_state.parent.head.clone()
1024-
} else {
1025-
head_observed
1026-
};
1045+
// Fresh bare repositories can inherit Git's environment-dependent
1046+
// `master` symref even when the first push creates `main`. Publish a real
1047+
// branch whenever one exists so HEAD never advertises a phantom branch.
1048+
let head = resolve_published_head(&refs_after, head_observed, &parent_state.parent.head);
10271049

10281050
let packs_before = parent_state.parent.packs.len();
10291051
let mut compaction_failure = None;
@@ -1330,6 +1352,24 @@ mod tests {
13301352
assert!(digest_from_pack_key(&format!("packs/{}", "g".repeat(64))).is_err());
13311353
}
13321354

1355+
#[test]
1356+
fn published_head_ignores_dangling_master_when_main_exists() {
1357+
let refs = BTreeMap::from([("refs/heads/main".to_string(), "1".repeat(40))]);
1358+
assert_eq!(
1359+
resolve_published_head(&refs, "refs/heads/master".to_string(), ""),
1360+
"refs/heads/main"
1361+
);
1362+
}
1363+
1364+
#[test]
1365+
fn published_head_preserves_an_existing_nonstandard_branch() {
1366+
let refs = BTreeMap::from([("refs/heads/release".to_string(), "1".repeat(40))]);
1367+
assert_eq!(
1368+
resolve_published_head(&refs, "refs/heads/release".to_string(), "refs/heads/main"),
1369+
"refs/heads/release"
1370+
);
1371+
}
1372+
13331373
#[test]
13341374
fn digest_from_key_strips_prefix() {
13351375
let k = format!("manifests/{}", "a".repeat(64));

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

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,11 @@ pub async fn load_manifest_for_read(
178178
.map(|(_etag, _digest, manifest)| manifest))
179179
}
180180

181+
async fn init_bare_repo(path: &Path) -> Result<(), HydrateError> {
182+
run_git(path, &["init", "--bare", "--quiet"]).await?;
183+
run_git(path, &["symbolic-ref", "HEAD", "refs/heads/main"]).await
184+
}
185+
181186
/// Hydrate a bare repo for write (`receive-pack`) and return the
182187
/// `ParentState` the workspace was hydrated from.
183188
///
@@ -190,10 +195,10 @@ pub async fn load_manifest_for_read(
190195
/// workspace was hydrated from.
191196
///
192197
/// First-push case (pointer absent): returns `(empty bare repo,
193-
/// ParentState::fresh())`. The empty bare repo is a fresh `git init --bare`
194-
/// with no refs and no objects; `receive-pack` will accept the first push
195-
/// and create whatever refs the client sends, and `cas_publish` will CAS
196-
/// the pointer with `If-None-Match: *`.
198+
/// ParentState::fresh())`. The empty bare repo has HEAD initialized to `main`
199+
/// but no refs or objects; `receive-pack` will accept the first push and create
200+
/// whatever refs the client sends, and `cas_publish` will CAS the pointer with
201+
/// `If-None-Match: *`.
197202
///
198203
/// Any below-pointer failure (manifest 404 under non-empty pointer, digest
199204
/// mismatch, malformed pointer body) is a hard error — never silently
@@ -220,7 +225,7 @@ pub async fn hydrate_for_write(
220225
HydrateError::Hydrate(format!("tempdir in {:?}: {e}", options.scratch_dir))
221226
})?;
222227
let path = tempdir.path().to_path_buf();
223-
run_git(&path, &["init", "--bare", "--quiet"]).await?;
228+
init_bare_repo(&path).await?;
224229
Ok((
225230
HydratedRepo {
226231
_tempdir: tempdir,
@@ -294,7 +299,7 @@ async fn materialize_manifest(
294299
let tempdir = TempDir::new_in(options.scratch_dir)
295300
.map_err(|e| HydrateError::Hydrate(format!("tempdir in {:?}: {e}", options.scratch_dir)))?;
296301
let path = tempdir.path().to_path_buf();
297-
run_git(&path, &["init", "--bare", "--quiet"]).await?;
302+
init_bare_repo(&path).await?;
298303

299304
// Phase 1: fetch, write, and index one pack at a time. Keeping only one
300305
// verified pack body resident avoids a manifest with many historical packs
@@ -500,6 +505,21 @@ mod tests {
500505
assert!(!is_hex_oid(""));
501506
}
502507

508+
#[tokio::test]
509+
async fn fresh_bare_repo_defaults_head_to_main() {
510+
let scratch = TempDir::new().expect("scratch");
511+
init_bare_repo(scratch.path())
512+
.await
513+
.expect("initialize bare repo");
514+
assert_eq!(
515+
tokio::fs::read_to_string(scratch.path().join("HEAD"))
516+
.await
517+
.expect("read HEAD")
518+
.trim(),
519+
"ref: refs/heads/main"
520+
);
521+
}
522+
503523
#[tokio::test]
504524
async fn generated_idx_size_is_bounded() {
505525
let scratch = TempDir::new().expect("scratch");

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

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
//!
66
//! 1. Validates HMAC signature + 30s TTL (fail-closed)
77
//! 2. Resolves kind:30617 → protection rules
8-
//! 3. Resolves pusher's channel role via buzz-channel binding
9-
//! 4. Promotes Bot → Member (bots in a channel push as members)
10-
//! 5. Calls `buzz_core::git_perms::evaluate_push()`
11-
//! 6. Returns 200 (allow) or 403 (deny with reasons)
8+
//! 3. Grants owner authority to the repo key or its verified managed-agent owner
9+
//! 4. Otherwise resolves the pusher's channel role via buzz-channel binding
10+
//! 5. Promotes Bot → Member (bots in a channel push as members)
11+
//! 6. Calls `buzz_core::git_perms::evaluate_push()`
12+
//! 7. Returns 200 (allow) or 403 (deny with reasons)
1213
//!
1314
//! # Bot Role Model
1415
//!
@@ -252,7 +253,7 @@ pub async fn hook_policy_check(
252253
};
253254
let query = EventQuery {
254255
kinds: Some(vec![30617]),
255-
pubkey: Some(owner_bytes),
256+
pubkey: Some(owner_bytes.clone()),
256257
d_tag: Some(req.repo_id.clone()),
257258
global_only: true,
258259
limit: Some(1),
@@ -316,9 +317,34 @@ pub async fn hook_policy_check(
316317
}
317318
}
318319

319-
// 7. Resolve pusher's role.
320+
// 7. Resolve pusher's role. A cryptographically verified managed-agent
321+
// owner has the same repository authority as the agent key itself.
320322
let repo_owner_hex = hex::encode(repo_event.event.pubkey.to_bytes());
321-
let role = if req.pusher_pubkey == repo_owner_hex {
323+
let pusher_bytes = match hex::decode(&req.pusher_pubkey) {
324+
Ok(bytes) if bytes.len() == 32 => bytes,
325+
_ => return (StatusCode::FORBIDDEN, "invalid pusher pubkey").into_response(),
326+
};
327+
let is_repo_owner = req.pusher_pubkey == repo_owner_hex;
328+
let is_managed_agent_owner = if is_repo_owner {
329+
false
330+
} else {
331+
match state
332+
.db
333+
.is_agent_owner(community, &owner_bytes, &pusher_bytes)
334+
.await
335+
{
336+
Ok(is_owner) => is_owner,
337+
Err(error) => {
338+
error!(
339+
repo = %req.repo_id,
340+
error = %error,
341+
"hook callback: managed-agent owner lookup failed"
342+
);
343+
return (StatusCode::FORBIDDEN, "internal error").into_response();
344+
}
345+
}
346+
};
347+
let role = if is_repo_owner || is_managed_agent_owner {
322348
MemberRole::Owner
323349
} else {
324350
match channel_id {
@@ -327,12 +353,6 @@ pub async fn hook_policy_check(
327353
return (StatusCode::FORBIDDEN, "no channel binding").into_response();
328354
}
329355
Some(ch_id) => {
330-
let pusher_bytes = match hex::decode(&req.pusher_pubkey) {
331-
Ok(b) if b.len() == 32 => b,
332-
_ => {
333-
return (StatusCode::FORBIDDEN, "invalid pusher pubkey").into_response();
334-
}
335-
};
336356
match state
337357
.db
338358
.get_member_role(community, ch_id, &pusher_bytes)

‎desktop/src-tauri/src/commands/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ mod project_git;
3838
mod project_git_branches;
3939
mod project_git_diff;
4040
mod project_git_exec;
41+
mod project_git_push;
4142
mod project_git_workflow;
4243
mod project_repo_paths;
4344
mod project_terminal;

‎desktop/src-tauri/src/commands/project_git.rs‎

Lines changed: 39 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use super::project_git_exec::{
22
build_git_auth_config, clean_branch, run_git, validate_workspace_clone_url, GitAuthConfig,
33
};
4+
use super::project_git_push::push_project_local_repository_blocking;
45
use super::project_repo_paths::{canonical_repos_roots, find_local_repo_dir};
56
use crate::app_state::AppState;
67
use serde::Serialize;
@@ -52,6 +53,7 @@ pub struct ProjectLocalRepoInfo {
5253
pub struct ProjectRepoSyncStatusInfo {
5354
pub local_path: Option<String>,
5455
pub local_branch: Option<String>,
56+
pub local_branches: Vec<String>,
5557
pub local_head: Option<String>,
5658
pub local_short_head: Option<String>,
5759
pub remote_branch: Option<String>,
@@ -492,7 +494,7 @@ pub(crate) fn normalize_branch_option(branch: Option<&str>) -> Option<String> {
492494
clean_branch(branch.map(str::to_string))
493495
}
494496

495-
fn compare_local_remote_status(
497+
pub(crate) fn compare_local_remote_status(
496498
repo_dir: &std::path::Path,
497499
clone_url: &str,
498500
branch_name: Option<&str>,
@@ -502,6 +504,23 @@ fn compare_local_remote_status(
502504
let local_branch = run_git(&["branch", "--show-current"], Some(repo_dir), auth)
503505
.ok()
504506
.and_then(|output| first_output_line(&output));
507+
let local_branches = run_git(
508+
&[
509+
"for-each-ref",
510+
"--count=200",
511+
"--format=%(refname:short)",
512+
"refs/heads/",
513+
],
514+
Some(repo_dir),
515+
auth,
516+
)
517+
.map(|output| {
518+
output
519+
.lines()
520+
.filter_map(|branch| normalize_branch_option(Some(branch)))
521+
.collect()
522+
})
523+
.unwrap_or_default();
505524
// The local checkout's branch name is attacker-influencable (a hostile
506525
// remote can point HEAD at a flag-shaped refname), so it must pass the
507526
// same `clean_branch` validation as relay-supplied names before it is
@@ -549,6 +568,17 @@ fn compare_local_remote_status(
549568
)
550569
.ok()
551570
.and_then(|output| first_output_line(&output));
571+
// A legacy empty clone may have an unborn local `master` while the project
572+
// declares `main`. Permit that mismatch only when the remote has no branch
573+
// refs at all; any lookup failure is treated as non-empty (fail closed).
574+
let remote_has_branches = run_git(
575+
&["ls-remote", "--heads", "--end-of-options", "origin"],
576+
Some(repo_dir),
577+
auth,
578+
)
579+
.map(|output| !output.trim().is_empty())
580+
.unwrap_or(true);
581+
let is_first_publish = remote_head.is_none() && !remote_has_branches;
552582
let merge_base = base_branch.as_deref().and_then(|base_branch| {
553583
run_git(
554584
&[
@@ -596,7 +626,7 @@ fn compare_local_remote_status(
596626

597627
let push_block_reason = if local_head.is_none() {
598628
Some("No local commits to push.".to_string())
599-
} else if local_branch.as_deref() != Some(branch.as_str()) {
629+
} else if local_branch.as_deref() != Some(branch.as_str()) && !is_first_publish {
600630
Some(format!(
601631
"Local checkout is on a different branch than {branch}."
602632
))
@@ -634,6 +664,7 @@ fn compare_local_remote_status(
634664
ProjectRepoSyncStatusInfo {
635665
local_path: Some(repo_dir.display().to_string()),
636666
local_branch,
667+
local_branches,
637668
local_head: local_head.clone(),
638669
local_short_head: local_head.as_deref().map(short_hash),
639670
remote_branch: Some(branch),
@@ -832,6 +863,7 @@ pub async fn get_project_repo_sync_status(
832863
return Ok(ProjectRepoSyncStatusInfo {
833864
local_path: None,
834865
local_branch: None,
866+
local_branches: Vec::new(),
835867
local_head: None,
836868
local_short_head: None,
837869
remote_branch: branch_name
@@ -881,44 +913,13 @@ pub async fn push_project_local_repository(
881913
else {
882914
return Err("No local checkout found.".to_string());
883915
};
884-
let status = compare_local_remote_status(
916+
push_project_local_repository_blocking(
885917
&repo_dir,
886-
&clone_url,
887-
branch_name.as_deref(),
888-
base_branch.as_deref(),
918+
clone_url,
919+
branch_name,
920+
base_branch,
889921
&auth,
890-
);
891-
if !status.can_push {
892-
return Err(status
893-
.push_block_reason
894-
.unwrap_or_else(|| "Local checkout cannot be pushed.".to_string()));
895-
}
896-
let branch = status
897-
.remote_branch
898-
.clone()
899-
.ok_or_else(|| "No branch selected for push.".to_string())?;
900-
let commit = status
901-
.local_head
902-
.clone()
903-
.ok_or_else(|| "No local commit selected for push.".to_string())?;
904-
run_git(
905-
&[
906-
"push",
907-
"--end-of-options",
908-
"origin",
909-
format!("HEAD:{branch}").as_str(),
910-
],
911-
Some(&repo_dir),
912-
&auth,
913-
)?;
914-
915-
Ok(ProjectRepoPushResult {
916-
pushed: true,
917-
message: format!("Pushed {branch} to remote."),
918-
branch,
919-
commit,
920-
merge_base: status.merge_base,
921-
})
922+
)
922923
})
923924
.await
924925
.map_err(|error| format!("repo push task failed: {error}"))?

0 commit comments

Comments
 (0)