Skip to content

Commit ca40fdf

Browse files
tlongwell-blocknpub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67dTyler Longwell
authored
fix(git): channel binding tooling + author remediation for unbound repos (#3626)
Closes #3527. Repos announced via vanilla NIP-34 (kind:30617 without a `buzz-channel` tag) 404 forever: the SEC-005 read gate requires a channel-membership ACL, and nothing tells the author why or how to fix it. Per the ruling in the originating thread, this ships **bind/rebind tooling plus a narrow author-only remediation carve-out** — the shelved owner-circle approach is intentionally absent. ## Relay - **`api/git/binding.rs` (new):** shared tri-state binding resolver — `Bound(uuid)` / `NotBound` / `Broken`. First-tag, fail-closed: a malformed `buzz-channel` tag is `Broken`, never conflated with "no tag". Both gates use it. - **Read gate (`transport.rs`):** a **never-bound** repo read by **its own announcement author** still returns 404 (status byte-identical to the generic denial) but the body carries remediation: `run: buzz repos bind --id <repo> --channel <channel-uuid> — …`. This leaks nothing — the author announced the repo, and only the author can rebind (30617 is keyed by `(author, d)`). `Broken` bindings stay generic-denial for everyone, including the author (revocation shape). Bound-to-nonexistent-channel stays generic (phase 1; ingest validation is phase 2). - **Push gate (`policy.rs`):** unbound denial now returns `GIT_NO_CHANNEL_BINDING_BODY`. A deploy-skew test pins that the body carries both the new token (`no_channel_binding`) and the legacy phrase (`"no channel binding"`) so already-shipped desktops keep matching. **(Review r1, blocker 2)** `Broken` no longer collapses into "unbound": it denies 403 `invalid channel binding` for *everyone — including the announcement owner —* **before** the owner short-circuit, matching the read gate's fail-closed posture. The remediation token stays NotBound-only. - **`ingest.rs`:** side-effect failure `warn!` → `error!` — prod runs `RUST_LOG=error`, so these failures were invisible during triage. ## Contract - **`buzz-core/git_perms.rs`:** `GIT_NO_CHANNEL_BINDING_TOKEN` / `GIT_NO_CHANNEL_BINDING_BODY` consts as the declared cross-component contract; relay tests and desktop matcher both build on them. ## CLI - **`buzz repos bind --id <repo> --channel <uuid>`** — rebinds an existing announcement, preserving other tags. - **(Review r1, blocker 1)** **`--channel` on `buzz repos create`** — optional; injects exactly one shape-validated `buzz-channel` tag at creation via a pure `build_create_announcement` builder, so the primary create command stops producing repos the relay 404s. UUID existence/membership stays the relay's authority at git-access time (same TOCTOU posture as `repos bind`). Overlaps with #3594 (open, head 6bbe384) — happy to reconcile whichever lands first; this branch also carries the bind path and tag preservation. ## Desktop - **Rust:** new `commands/project_git_merge_error.rs` (extracted from `project_git_workflow.rs` to respect the 1000-line ratchet); maps the token to a structured `no_channel_binding` error carrying the bind command. - **TS:** new `features/projects/lib/projectBranchErrors.ts` + tests — dual matcher (new token AND legacy spaced phrase); `ProjectBranchDialogs.tsx` uses it. ## Tests / verification (at head f914c70, base 25ad05a) - Workspace `cargo test` green; `clippy -D warnings` clean; desktop Rust 1859 pass; TS 3780 pass; tsc/biome/file-size checks pass. Pre-push hooks re-ran all suites at the pushed head. - Postgres-gated `sec005_read_gate_tests`: all 6 pass, including `read_gate_gives_author_of_unbound_repo_remediation_body` — asserts 404 status, `text/plain` content-type, and exact body bytes, distinguishing remediation from generic denial (a blind `is_err()` can't). - **New (review r1):** `buzz-cli` emitted-event tests — `create_with_channel_emits_exactly_one_binding_tag`, `create_without_channel_emits_no_binding_tag`, `create_rejects_malformed_channel_uuid` (266/266 pass). Postgres-gated `push_gate_denies_owner_through_broken_binding` — owner + malformed-first/valid-second binding → 403 generic body without the remediation token; never-bound control stays 200, pinning the denial to `Broken` specifically. - e2e git tests now bind announcements to a real channel via a `create_test_channel` helper. --------- Signed-off-by: Tyler Longwell <[email protected]> Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz> Co-authored-by: Tyler Longwell <[email protected]>
1 parent 8bf7a62 commit ca40fdf

15 files changed

Lines changed: 1069 additions & 258 deletions

File tree

‎crates/buzz-cli/src/commands/repos.rs‎

Lines changed: 235 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -83,35 +83,50 @@ fn build_protection_tag(
8383
Tag::parse(values).map_err(tag_error)
8484
}
8585

86-
enum ProtectionChange {
87-
Set(Box<Tag>),
88-
Remove(String),
86+
enum RepoChange {
87+
SetProtection(Box<Tag>),
88+
RemoveProtection(String),
89+
/// Bind (or rebind) the repo to a channel: replaces every existing
90+
/// `buzz-channel` tag with exactly one carrying the validated UUID.
91+
BindChannel(String),
8992
}
9093

9194
fn build_updated_repo_announcement(
9295
existing: &Event,
93-
change: ProtectionChange,
96+
change: RepoChange,
9497
) -> Result<EventBuilder, CliError> {
9598
let repo_id = repo_id_from_event(existing)?;
96-
let (pattern, replacement) = match change {
97-
ProtectionChange::Set(tag) => {
99+
// What to strip beyond `auth` (always stripped), and what to append.
100+
let (removed_pattern, removed_channel, replacement) = match change {
101+
RepoChange::SetProtection(tag) => {
98102
let pattern = protection_pattern(&tag)
99103
.ok_or_else(|| CliError::Other("replacement is not a protection tag".into()))?
100104
.to_string();
101-
(pattern, Some(*tag))
105+
(Some(pattern), false, Some(*tag))
102106
}
103-
ProtectionChange::Remove(pattern) => {
107+
RepoChange::RemoveProtection(pattern) => {
104108
RefPattern::parse(&pattern)
105109
.map_err(|error| CliError::Usage(format!("invalid ref pattern: {error}")))?;
106-
(pattern, None)
110+
(Some(pattern), false, None)
111+
}
112+
RepoChange::BindChannel(channel) => {
113+
crate::validate::validate_uuid(&channel)?;
114+
let tag = Tag::parse(["buzz-channel", channel.as_str()]).map_err(tag_error)?;
115+
(None, true, Some(tag))
107116
}
108117
};
109118

110119
let mut tags: Vec<Tag> = existing
111120
.tags
112121
.iter()
113122
.filter(|tag| {
114-
!has_tag_name(tag, "auth") && protection_pattern(tag) != Some(pattern.as_str())
123+
if has_tag_name(tag, "auth") {
124+
return false;
125+
}
126+
if removed_channel && has_tag_name(tag, "buzz-channel") {
127+
return false;
128+
}
129+
removed_pattern.is_none() || protection_pattern(tag) != removed_pattern.as_deref()
115130
})
116131
.cloned()
117132
.collect();
@@ -199,21 +214,30 @@ async fn submit_repo_update(client: &BuzzClient, builder: EventBuilder) -> Resul
199214
Ok(())
200215
}
201216

202-
pub async fn cmd_create_repo(
203-
client: &BuzzClient,
217+
/// Build the kind:30617 announcement for `repos create`, including the
218+
/// `buzz-channel` binding when requested.
219+
///
220+
/// Pure (no I/O) so the emitted tags are unit-testable. Exactly one
221+
/// validated `buzz-channel` tag is appended — the tag is the git ACL
222+
/// (issue #3527: without it the relay 404s every clone/fetch/push), so the
223+
/// UUID is shape-validated here and its existence/membership is the relay's
224+
/// authority at git-access time, same posture as `repos bind`.
225+
#[allow(clippy::too_many_arguments)]
226+
fn build_create_announcement(
204227
repo_id: &str,
205228
name: Option<&str>,
206229
description: Option<&str>,
207230
clone_urls: &[String],
208231
web_url: Option<&str>,
209232
relays: &[String],
210-
) -> Result<(), CliError> {
233+
channel: Option<&str>,
234+
) -> Result<EventBuilder, CliError> {
211235
validate_repo_id(repo_id)?;
212236

213237
let clone_refs: Vec<&str> = clone_urls.iter().map(|s| s.as_str()).collect();
214238
let relay_refs: Vec<&str> = relays.iter().map(|s| s.as_str()).collect();
215239

216-
let builder = buzz_sdk::build_repo_announcement(
240+
let mut builder = buzz_sdk::build_repo_announcement(
217241
repo_id,
218242
name,
219243
description,
@@ -223,6 +247,33 @@ pub async fn cmd_create_repo(
223247
)
224248
.map_err(|e| CliError::Other(format!("build_repo_announcement failed: {e}")))?;
225249

250+
if let Some(channel) = channel {
251+
crate::validate::validate_uuid(channel)?;
252+
builder = builder.tag(Tag::parse(["buzz-channel", channel]).map_err(tag_error)?);
253+
}
254+
Ok(builder)
255+
}
256+
257+
#[allow(clippy::too_many_arguments)]
258+
pub async fn cmd_create_repo(
259+
client: &BuzzClient,
260+
repo_id: &str,
261+
name: Option<&str>,
262+
description: Option<&str>,
263+
clone_urls: &[String],
264+
web_url: Option<&str>,
265+
relays: &[String],
266+
channel: Option<&str>,
267+
) -> Result<(), CliError> {
268+
let builder = build_create_announcement(
269+
repo_id,
270+
name,
271+
description,
272+
clone_urls,
273+
web_url,
274+
relays,
275+
channel,
276+
)?;
226277
let event = client.sign_event(builder)?;
227278
let resp = client.submit_event(event).await?;
228279
println!("{resp}");
@@ -320,7 +371,8 @@ async fn cmd_protect_set(
320371
require_patch,
321372
)?;
322373
let event = current_repo(client, repo_id).await?;
323-
let builder = build_updated_repo_announcement(&event, ProtectionChange::Set(Box::new(tag)))?;
374+
let builder =
375+
build_updated_repo_announcement(&event, RepoChange::SetProtection(Box::new(tag)))?;
324376
submit_repo_update(client, builder).await
325377
}
326378

@@ -341,8 +393,27 @@ async fn cmd_protect_remove(
341393
"repository {repo_id:?} has no protection rule for {ref_pattern:?}"
342394
)));
343395
}
396+
let builder = build_updated_repo_announcement(
397+
&event,
398+
RepoChange::RemoveProtection(ref_pattern.to_string()),
399+
)?;
400+
submit_repo_update(client, builder).await
401+
}
402+
403+
/// Bind (or rebind) a repository to a channel — the fix path for issue
404+
/// #3527's permanently-404 repos. Publishes a read-modify-write update of
405+
/// the caller's own kind:30617 with exactly one `buzz-channel` tag; all
406+
/// other metadata (protections, name, description, future tags) is
407+
/// preserved by the same machinery `repos protect` uses.
408+
///
409+
/// The UUID is validated for *shape* only — deliberately. Channel existence
410+
/// and the caller's membership are the relay's authority at git-access
411+
/// time; a CLI-side network pre-check would just be TOCTOU with extra
412+
/// latency.
413+
async fn cmd_bind_repo(client: &BuzzClient, repo_id: &str, channel: &str) -> Result<(), CliError> {
414+
let event = current_repo(client, repo_id).await?;
344415
let builder =
345-
build_updated_repo_announcement(&event, ProtectionChange::Remove(ref_pattern.to_string()))?;
416+
build_updated_repo_announcement(&event, RepoChange::BindChannel(channel.to_string()))?;
346417
submit_repo_update(client, builder).await
347418
}
348419

@@ -356,6 +427,7 @@ pub async fn dispatch(cmd: crate::ReposCmd, client: &BuzzClient) -> Result<(), C
356427
clone_urls,
357428
web,
358429
relays,
430+
channel,
359431
} => {
360432
cmd_create_repo(
361433
client,
@@ -365,11 +437,13 @@ pub async fn dispatch(cmd: crate::ReposCmd, client: &BuzzClient) -> Result<(), C
365437
&clone_urls,
366438
web.as_deref(),
367439
&relays,
440+
channel.as_deref(),
368441
)
369442
.await
370443
}
371444
ReposCmd::Get { id, owner } => cmd_get_repo(client, &id, owner.as_deref()).await,
372445
ReposCmd::List { owner, limit } => cmd_list_repos(client, owner.as_deref(), limit).await,
446+
ReposCmd::Bind { id, channel } => cmd_bind_repo(client, &id, &channel).await,
373447
ReposCmd::Protect(command) => match command {
374448
ReposProtectCmd::List { id } => cmd_protect_list(client, &id).await,
375449
ReposProtectCmd::Set {
@@ -403,8 +477,8 @@ mod tests {
403477
use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp};
404478

405479
use super::{
406-
build_protection_tag, build_updated_repo_announcement, protection_rules_json,
407-
validate_write_response, ProtectionChange,
480+
build_create_announcement, build_protection_tag, build_updated_repo_announcement,
481+
protection_rules_json, validate_write_response, RepoChange,
408482
};
409483

410484
fn signed_repo(tags: Vec<Tag>, content: &str, created_at: u64) -> nostr::Event {
@@ -439,7 +513,7 @@ mod tests {
439513

440514
let updated = build_updated_repo_announcement(
441515
&existing,
442-
ProtectionChange::Set(Box::new(replacement)),
516+
RepoChange::SetProtection(Box::new(replacement)),
443517
)
444518
.expect("build update")
445519
.sign_with_keys(&Keys::generate())
@@ -501,7 +575,7 @@ mod tests {
501575

502576
let updated = build_updated_repo_announcement(
503577
&existing,
504-
ProtectionChange::Remove("refs/heads/main".into()),
578+
RepoChange::RemoveProtection("refs/heads/main".into()),
505579
)
506580
.expect("build removal")
507581
.sign_with_keys(&Keys::generate())
@@ -538,7 +612,7 @@ mod tests {
538612

539613
let error = build_updated_repo_announcement(
540614
&existing,
541-
ProtectionChange::Set(Box::new(replacement)),
615+
RepoChange::SetProtection(Box::new(replacement)),
542616
)
543617
.expect_err("malformed existing rule must fail closed");
544618

@@ -564,7 +638,7 @@ mod tests {
564638

565639
let error = build_updated_repo_announcement(
566640
&existing,
567-
ProtectionChange::Set(Box::new(replacement)),
641+
RepoChange::SetProtection(Box::new(replacement)),
568642
)
569643
.expect_err("the 51st rule must be rejected");
570644

@@ -615,6 +689,145 @@ mod tests {
615689
.is_some_and(|error| error.contains("needs pattern + at least one rule")));
616690
}
617691

692+
#[test]
693+
fn bind_channel_replaces_duplicates_and_preserves_everything_else() {
694+
let channel = uuid::Uuid::new_v4().to_string();
695+
let existing = signed_repo(
696+
vec![
697+
tag(&["d", "demo"]),
698+
tag(&["name", "Demo"]),
699+
// Two stale bindings — e.g. from a buggy or vanilla client.
700+
tag(&["buzz-channel", "old-and-broken"]),
701+
tag(&["buzz-channel", &uuid::Uuid::new_v4().to_string()]),
702+
tag(&["auth", &"a".repeat(64), "kind=30617", &"b".repeat(128)]),
703+
tag(&["buzz-protect", "refs/heads/main", "push:admin"]),
704+
tag(&["future-metadata", "preserve-me"]),
705+
],
706+
"repository content",
707+
100,
708+
);
709+
710+
let updated =
711+
build_updated_repo_announcement(&existing, RepoChange::BindChannel(channel.clone()))
712+
.expect("build bind update")
713+
.sign_with_keys(&Keys::generate())
714+
.expect("sign bind update");
715+
716+
assert_eq!(updated.content, "repository content");
717+
assert_eq!(updated.created_at.as_secs(), 101);
718+
// Exactly one binding remains, and it is the requested one.
719+
let bindings: Vec<_> = updated
720+
.tags
721+
.iter()
722+
.filter(|tag| tag.as_slice().first().map(String::as_str) == Some("buzz-channel"))
723+
.collect();
724+
assert_eq!(bindings.len(), 1);
725+
assert_eq!(bindings[0].as_slice(), ["buzz-channel", channel.as_str()]);
726+
// Auth stripped (relay re-stamps); everything else preserved.
727+
assert!(!updated
728+
.tags
729+
.iter()
730+
.any(|tag| tag.as_slice().first().map(String::as_str) == Some("auth")));
731+
assert!(updated
732+
.tags
733+
.iter()
734+
.any(|tag| tag.as_slice() == ["buzz-protect", "refs/heads/main", "push:admin"]));
735+
assert!(updated
736+
.tags
737+
.iter()
738+
.any(|tag| tag.as_slice() == ["future-metadata", "preserve-me"]));
739+
assert!(updated
740+
.tags
741+
.iter()
742+
.any(|tag| tag.as_slice() == ["name", "Demo"]));
743+
}
744+
745+
#[test]
746+
fn bind_channel_adds_binding_to_unbound_repo() {
747+
let channel = uuid::Uuid::new_v4().to_string();
748+
let existing = signed_repo(vec![tag(&["d", "demo"])], "", 10);
749+
750+
let updated =
751+
build_updated_repo_announcement(&existing, RepoChange::BindChannel(channel.clone()))
752+
.expect("build bind update")
753+
.sign_with_keys(&Keys::generate())
754+
.expect("sign bind update");
755+
756+
assert!(updated
757+
.tags
758+
.iter()
759+
.any(|tag| tag.as_slice() == ["buzz-channel", channel.as_str()]));
760+
}
761+
762+
#[test]
763+
fn bind_channel_rejects_malformed_uuid() {
764+
let existing = signed_repo(vec![tag(&["d", "demo"])], "", 10);
765+
766+
let error =
767+
build_updated_repo_announcement(&existing, RepoChange::BindChannel("nope".into()))
768+
.expect_err("malformed channel id must not build an update");
769+
770+
assert!(matches!(error, crate::error::CliError::Usage(_)));
771+
}
772+
773+
/// Issue #3527: `repos create --channel` must emit exactly one
774+
/// `buzz-channel` tag so the primary create command stops producing
775+
/// repos the relay 404s forever.
776+
#[test]
777+
fn create_with_channel_emits_exactly_one_binding_tag() {
778+
let channel = uuid::Uuid::new_v4().to_string();
779+
let event = build_create_announcement(
780+
"demo",
781+
Some("Demo"),
782+
None,
783+
&["https://relay.example/git/owner/demo".to_string()],
784+
None,
785+
&[],
786+
Some(&channel),
787+
)
788+
.expect("build create announcement")
789+
.sign_with_keys(&Keys::generate())
790+
.expect("sign create announcement");
791+
792+
assert_eq!(event.kind, Kind::Custom(30617));
793+
let bindings: Vec<_> = event
794+
.tags
795+
.iter()
796+
.filter(|tag| tag.as_slice().first().map(String::as_str) == Some("buzz-channel"))
797+
.collect();
798+
assert_eq!(bindings.len(), 1, "exactly one buzz-channel tag");
799+
assert_eq!(bindings[0].as_slice(), ["buzz-channel", channel.as_str()]);
800+
// The standard metadata still rides along.
801+
assert!(event.tags.iter().any(|tag| tag.as_slice() == ["d", "demo"]));
802+
assert!(event
803+
.tags
804+
.iter()
805+
.any(|tag| tag.as_slice() == ["name", "Demo"]));
806+
}
807+
808+
#[test]
809+
fn create_without_channel_emits_no_binding_tag() {
810+
let event = build_create_announcement("demo", None, None, &[], None, &[], None)
811+
.expect("build create announcement")
812+
.sign_with_keys(&Keys::generate())
813+
.expect("sign create announcement");
814+
815+
assert!(
816+
!event
817+
.tags
818+
.iter()
819+
.any(|tag| tag.as_slice().first().map(String::as_str) == Some("buzz-channel")),
820+
"no --channel means no binding tag (vanilla NIP-34 stays possible)"
821+
);
822+
}
823+
824+
#[test]
825+
fn create_rejects_malformed_channel_uuid() {
826+
let error = build_create_announcement("demo", None, None, &[], None, &[], Some("nope"))
827+
.expect_err("malformed channel id must not build an announcement");
828+
assert!(matches!(error, crate::error::CliError::Usage(_)));
829+
}
830+
618831
#[test]
619832
fn duplicate_write_response_is_a_conflict() {
620833
let error = validate_write_response(

0 commit comments

Comments
 (0)