Files
buzz/crates/buzz-relay/src/api/git/binding.rs
Tyler 788b3c002b 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
6bbe38459) — 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 f914c7066, base 581baa625)
- 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 <tlongwell@block.xyz>
Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
Co-authored-by: Tyler Longwell <tlongwell@block.xyz>
2026-07-29 20:07:55 -04:00

129 lines
5.0 KiB
Rust

//! Repo → channel binding resolution, shared by the read gate and push policy.
//!
//! The `buzz-channel` tag on a kind:30617 announcement IS the git ACL: the
//! read gate (SEC-005, `transport::authorize_git_read`) and the push policy
//! endpoint (`policy::hook_callback`) both authorize against membership in
//! the bound channel. Before this module they each parsed the tag with their
//! own code that agreed only by coincidence; the resolver makes the
//! agreement structural.
//!
//! # First-tag, fail-closed semantics
//!
//! Only the *first* `buzz-channel` tag is considered, and it must carry a
//! valid UUID. A malformed first binding resolves to [`RepoBinding::Broken`]
//! even if a later duplicate tag is valid — an ambiguous announcement must
//! fail closed, not silently resolve to whichever duplicate happens to
//! parse. If this ever became "find the first *parseable* tag", an author
//! who can append a second `buzz-channel` tag would pick the channel.
//!
//! # What this deliberately does NOT do
//!
//! No DB access. A well-formed UUID that names a nonexistent or deleted
//! channel still resolves to [`RepoBinding::Bound`]; each gate's own
//! membership lookup then denies (`get_member_role` joins
//! `channels … deleted_at IS NULL`, so a dead channel is indistinguishable
//! from a non-member — the info-leak-safe posture). Likewise each gate keeps
//! its own archived-channel policy: push denies on archived channels, read
//! does not, and this resolver must not unify that asymmetry as a side
//! effect.
use uuid::Uuid;
/// How a kind:30617 announcement binds (or fails to bind) a channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepoBinding {
/// No `buzz-channel` tag at all. The announcement author (the only
/// identity that can rebind — 30617 is keyed by `(author, d)`) may be
/// offered remediation; everyone else gets the generic denial.
NotBound,
/// First `buzz-channel` tag carries a valid UUID.
Bound(Uuid),
/// First `buzz-channel` tag exists but its value is not a UUID.
/// Fail closed with the generic denial — never remediation, which
/// would leak that the repo exists.
Broken,
}
/// Resolve the channel binding of a kind:30617 announcement from its tags.
pub fn resolve_repo_binding(event: &nostr::Event) -> RepoBinding {
let Some(first) = event
.tags
.iter()
.find(|t| t.as_slice().first().map(String::as_str) == Some("buzz-channel"))
else {
return RepoBinding::NotBound;
};
match first.as_slice().get(1).map(|v| Uuid::parse_str(v)) {
Some(Ok(id)) => RepoBinding::Bound(id),
_ => RepoBinding::Broken,
}
}
#[cfg(test)]
mod tests {
use nostr::{EventBuilder, Keys, Kind, Tag};
use super::{resolve_repo_binding, RepoBinding};
fn announcement(tags: Vec<Tag>) -> nostr::Event {
EventBuilder::new(Kind::Custom(30617), "")
.tags(tags)
.sign_with_keys(&Keys::generate())
.expect("sign 30617")
}
#[test]
fn extracts_valid_uuid() {
let ch = uuid::Uuid::new_v4();
let event = announcement(vec![
Tag::parse(["d", "repo"]).unwrap(),
Tag::parse(["buzz-channel", &ch.to_string()]).unwrap(),
]);
assert_eq!(resolve_repo_binding(&event), RepoBinding::Bound(ch));
}
#[test]
fn absent_tag_is_not_bound() {
let event = announcement(vec![Tag::parse(["d", "repo"]).unwrap()]);
assert_eq!(resolve_repo_binding(&event), RepoBinding::NotBound);
}
#[test]
fn malformed_and_empty_values_are_broken_not_absent() {
let malformed = announcement(vec![
Tag::parse(["d", "repo"]).unwrap(),
Tag::parse(["buzz-channel", "not-a-uuid"]).unwrap(),
]);
assert_eq!(resolve_repo_binding(&malformed), RepoBinding::Broken);
let empty = announcement(vec![
Tag::parse(["d", "repo"]).unwrap(),
Tag::parse(["buzz-channel"]).unwrap(),
]);
assert_eq!(resolve_repo_binding(&empty), RepoBinding::Broken);
}
#[test]
fn fails_closed_on_ambiguous_duplicate_bindings() {
let ch = uuid::Uuid::new_v4();
let other = uuid::Uuid::new_v4();
// Malformed first + valid second: the ambiguity denies; the valid
// duplicate must NOT win, or the duplicate picks the channel.
let malformed_first = announcement(vec![
Tag::parse(["d", "repo"]).unwrap(),
Tag::parse(["buzz-channel", "not-a-uuid"]).unwrap(),
Tag::parse(["buzz-channel", &ch.to_string()]).unwrap(),
]);
assert_eq!(resolve_repo_binding(&malformed_first), RepoBinding::Broken);
// Valid first + different second: first wins deterministically.
let valid_first = announcement(vec![
Tag::parse(["d", "repo"]).unwrap(),
Tag::parse(["buzz-channel", &ch.to_string()]).unwrap(),
Tag::parse(["buzz-channel", &other.to_string()]).unwrap(),
]);
assert_eq!(resolve_repo_binding(&valid_first), RepoBinding::Bound(ch));
}
}