Skip to content

Commit f914c70

Browse files
npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67dTyler Longwell
andcommitted
fix(git): address review blockers — --channel on create, Broken denies before owner short-circuit
Blocker 1: ReposCmd::Create gains --channel; build_create_announcement is extracted pure so the emitted kind:30617 event is unit-testable. Exactly one shape-validated buzz-channel tag is appended; existence/membership stays the relay's authority (same TOCTOU posture as repos bind). Blocker 2: hook_policy_check no longer collapses Broken|NotBound. Broken now denies 403 "invalid channel binding" for everyone — including the announcement owner — before owner resolution, matching the read gate's fail-closed posture. The remediation token stays NotBound-only. New Postgres-gated test push_gate_denies_owner_through_broken_binding pins owner + malformed-first/valid-second → 403 generic body, with a never-bound control staying 200. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent ede1065 commit f914c70

3 files changed

Lines changed: 290 additions & 13 deletions

File tree

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

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -214,21 +214,30 @@ async fn submit_repo_update(client: &BuzzClient, builder: EventBuilder) -> Resul
214214
Ok(())
215215
}
216216

217-
pub async fn cmd_create_repo(
218-
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(
219227
repo_id: &str,
220228
name: Option<&str>,
221229
description: Option<&str>,
222230
clone_urls: &[String],
223231
web_url: Option<&str>,
224232
relays: &[String],
225-
) -> Result<(), CliError> {
233+
channel: Option<&str>,
234+
) -> Result<EventBuilder, CliError> {
226235
validate_repo_id(repo_id)?;
227236

228237
let clone_refs: Vec<&str> = clone_urls.iter().map(|s| s.as_str()).collect();
229238
let relay_refs: Vec<&str> = relays.iter().map(|s| s.as_str()).collect();
230239

231-
let builder = buzz_sdk::build_repo_announcement(
240+
let mut builder = buzz_sdk::build_repo_announcement(
232241
repo_id,
233242
name,
234243
description,
@@ -238,6 +247,33 @@ pub async fn cmd_create_repo(
238247
)
239248
.map_err(|e| CliError::Other(format!("build_repo_announcement failed: {e}")))?;
240249

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+
)?;
241277
let event = client.sign_event(builder)?;
242278
let resp = client.submit_event(event).await?;
243279
println!("{resp}");
@@ -391,6 +427,7 @@ pub async fn dispatch(cmd: crate::ReposCmd, client: &BuzzClient) -> Result<(), C
391427
clone_urls,
392428
web,
393429
relays,
430+
channel,
394431
} => {
395432
cmd_create_repo(
396433
client,
@@ -400,6 +437,7 @@ pub async fn dispatch(cmd: crate::ReposCmd, client: &BuzzClient) -> Result<(), C
400437
&clone_urls,
401438
web.as_deref(),
402439
&relays,
440+
channel.as_deref(),
403441
)
404442
.await
405443
}
@@ -439,8 +477,8 @@ mod tests {
439477
use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp};
440478

441479
use super::{
442-
build_protection_tag, build_updated_repo_announcement, protection_rules_json,
443-
validate_write_response, RepoChange,
480+
build_create_announcement, build_protection_tag, build_updated_repo_announcement,
481+
protection_rules_json, validate_write_response, RepoChange,
444482
};
445483

446484
fn signed_repo(tags: Vec<Tag>, content: &str, created_at: u64) -> nostr::Event {
@@ -732,6 +770,64 @@ mod tests {
732770
assert!(matches!(error, crate::error::CliError::Usage(_)));
733771
}
734772

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+
735831
#[test]
736832
fn duplicate_write_response_is_a_conflict() {
737833
let error = validate_write_response(

‎crates/buzz-cli/src/lib.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,6 +1129,11 @@ pub enum ReposCmd {
11291129
/// Preferred Nostr relay(s) for repo discovery — can be specified multiple times
11301130
#[arg(long = "nostr-relay")]
11311131
relays: Vec<String>,
1132+
/// Channel UUID to bind the repo to. The `buzz-channel` tag is the
1133+
/// git ACL: without it the relay 404s every clone/fetch/push until
1134+
/// the author runs `buzz repos bind` (issue #3527).
1135+
#[arg(long)]
1136+
channel: Option<String>,
11321137
},
11331138
/// Get a repository announcement
11341139
Get {

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

Lines changed: 183 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -302,15 +302,26 @@ pub async fn hook_policy_check(
302302

303303
// 6. Resolve channel binding via the shared resolver (same first-tag,
304304
// fail-closed semantics as the read gate) and check archived state
305-
// (applies to ALL pushers including owner). On the push side, NotBound
306-
// and Broken collapse into the same bucket — both historically produced
307-
// the "no channel binding" denial for non-owners, and a pusher is past
308-
// NIP-98 auth so the body leaks nothing new. Only the read gate
309-
// distinguishes them (author remediation is NotBound-only).
305+
// (applies to ALL pushers including owner).
306+
//
307+
// `Broken` denies HERE, before owner resolution: a malformed or
308+
// ambiguous first binding fails closed for *everyone*, exactly like the
309+
// read gate. Letting it fall through as "unbound" would hand the owner
310+
// short-circuit below a push path through a binding the read gate
311+
// refuses to honor — the tri-state exists precisely so Broken and
312+
// NotBound cannot collapse. Only genuinely-NotBound repos proceed, and
313+
// only they may earn the remediation-token denial.
310314
let channel_id = match crate::api::git::binding::resolve_repo_binding(&repo_event.event) {
311315
crate::api::git::binding::RepoBinding::Bound(id) => Some(id),
312-
crate::api::git::binding::RepoBinding::NotBound
313-
| crate::api::git::binding::RepoBinding::Broken => None,
316+
crate::api::git::binding::RepoBinding::NotBound => None,
317+
crate::api::git::binding::RepoBinding::Broken => {
318+
warn!(repo = %req.repo_id, "hook callback: broken buzz-channel binding");
319+
// Deliberately NOT the no_channel_binding token body: the
320+
// remediation contract is NotBound-only. A broken binding is
321+
// ambiguity, and ambiguity gets a generic denial (matching the
322+
// read gate's posture for the same announcement).
323+
return (StatusCode::FORBIDDEN, "invalid channel binding").into_response();
324+
}
314325
};
315326

316327
if let Some(ch_id) = channel_id {
@@ -808,4 +819,169 @@ printf '%s' "$HMAC_INPUT" | openssl dgst -sha256 -hmac "{secret}" -hex 2>/dev/nu
808819
"Single-ref HMAC mismatch!\n Rust: {rust_sig}\n Bash: {bash_sig}"
809820
);
810821
}
822+
823+
// ── hook_policy_check binding gate (requires Postgres) ──────────────
824+
825+
const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1
826+
827+
async fn policy_test_state() -> Arc<AppState> {
828+
let mut config = crate::config::Config::from_env().expect("default config loads");
829+
config.require_relay_membership = false;
830+
config.redis_url = "redis://127.0.0.1:1".to_string();
831+
config.database_url = std::env::var("BUZZ_TEST_DATABASE_URL")
832+
.or_else(|_| std::env::var("DATABASE_URL"))
833+
.unwrap_or_else(|_| TEST_DB_URL.to_string());
834+
let pool = sqlx::PgPool::connect(&config.database_url)
835+
.await
836+
.expect("connect test DB");
837+
let db = buzz_db::Db::from_pool(pool.clone());
838+
let redis_pool = deadpool_redis::Config::from_url(&config.redis_url)
839+
.create_pool(Some(deadpool_redis::Runtime::Tokio1))
840+
.expect("redis pool");
841+
let pubsub = Arc::new(
842+
buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone())
843+
.await
844+
.expect("pubsub manager"),
845+
);
846+
let audit = buzz_audit::AuditService::new(pool.clone());
847+
let auth = buzz_auth::AuthService::new(config.auth.clone());
848+
let search = buzz_search::SearchService::new(pool.clone());
849+
let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new(
850+
db.clone(),
851+
buzz_workflow::WorkflowConfig::default(),
852+
));
853+
let media_storage = buzz_media::MediaStorage::new(&config.media).expect("media storage");
854+
let (state, _audit_shutdown) = AppState::new(
855+
config,
856+
db,
857+
redis_pool,
858+
audit,
859+
pubsub,
860+
auth,
861+
search,
862+
workflow_engine,
863+
nostr::Keys::generate(),
864+
media_storage,
865+
);
866+
Arc::new(state)
867+
}
868+
869+
/// Announce `repo_id` with the given tags, then push to it as its own
870+
/// announcement author and return the response.
871+
async fn owner_push_response(
872+
state: &Arc<AppState>,
873+
community: buzz_core::CommunityId,
874+
keys: &nostr::Keys,
875+
repo_id: &str,
876+
binding_tags: Vec<nostr::Tag>,
877+
) -> axum::response::Response {
878+
use nostr::{EventBuilder, Kind, Tag};
879+
880+
let mut tags = vec![Tag::parse(["d", repo_id]).unwrap()];
881+
tags.extend(binding_tags);
882+
let event = EventBuilder::new(Kind::Custom(30617), "")
883+
.tags(tags)
884+
.sign_with_keys(keys)
885+
.expect("sign 30617");
886+
state
887+
.db
888+
.insert_event(community, &event, None)
889+
.await
890+
.expect("insert 30617");
891+
892+
let owner_hex = keys.public_key().to_hex();
893+
let mut req = HookCallbackRequest {
894+
repo_id: repo_id.to_string(),
895+
repo_owner: owner_hex.clone(),
896+
community_id: community.as_uuid().to_string(),
897+
pusher_pubkey: owner_hex,
898+
ref_updates: vec![HookRefUpdate {
899+
old_oid: "0".repeat(40),
900+
new_oid: "2".repeat(40),
901+
ref_name: "refs/heads/main".to_string(),
902+
is_ancestor: false,
903+
}],
904+
timestamp: SystemTime::now()
905+
.duration_since(UNIX_EPOCH)
906+
.unwrap()
907+
.as_secs(),
908+
signature: String::new(),
909+
};
910+
let secret = state.config.git_hook_hmac_secret.clone();
911+
sign_request(&mut req, secret.as_bytes());
912+
hook_policy_check(State(Arc::clone(state)), Json(req)).await
913+
}
914+
915+
async fn body_string(response: axum::response::Response) -> (StatusCode, String) {
916+
let status = response.status();
917+
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
918+
.await
919+
.expect("read body");
920+
(status, String::from_utf8(bytes.to_vec()).expect("utf-8"))
921+
}
922+
923+
/// The tri-state trap the resolver exists to prevent: a broken (malformed
924+
/// or ambiguous-first) binding must fail closed for EVERYONE on push —
925+
/// including the announcement author — *before* the owner short-circuit
926+
/// grants `MemberRole::Owner`. Collapsing `Broken` into "unbound" hands
927+
/// the owner a push path through a binding the read gate refuses to
928+
/// honor. The remediation token stays reserved for genuinely NotBound.
929+
#[tokio::test]
930+
#[ignore = "requires Postgres"]
931+
async fn push_gate_denies_owner_through_broken_binding() {
932+
use nostr::{Keys, Tag};
933+
934+
let state = policy_test_state().await;
935+
let host = format!("policy-{}.example", uuid::Uuid::new_v4().simple());
936+
let community = state
937+
.db
938+
.ensure_configured_community(&host)
939+
.await
940+
.expect("community")
941+
.id;
942+
let keys = Keys::generate();
943+
944+
// Malformed first + valid-looking second: the ambiguity must deny,
945+
// and the parseable duplicate must not rescue the push.
946+
let response = owner_push_response(
947+
&state,
948+
community,
949+
&keys,
950+
&format!("repo-{}", uuid::Uuid::new_v4().simple()),
951+
vec![
952+
Tag::parse(["buzz-channel", "not-a-uuid"]).unwrap(),
953+
Tag::parse(["buzz-channel", &uuid::Uuid::new_v4().to_string()]).unwrap(),
954+
],
955+
)
956+
.await;
957+
let (status, body) = body_string(response).await;
958+
assert_eq!(status, StatusCode::FORBIDDEN);
959+
assert_eq!(
960+
body, "invalid channel binding",
961+
"owner pushing through a broken binding must be denied generically"
962+
);
963+
assert!(
964+
!body.contains(buzz_core::git_perms::GIT_NO_CHANNEL_BINDING_TOKEN),
965+
"remediation token is NotBound-only; Broken must never earn it"
966+
);
967+
968+
// Control: the same owner pushing a genuinely NEVER-BOUND repo is
969+
// allowed (owner authority over an unbound announcement is the
970+
// long-standing push semantics). This pins the denial above to
971+
// Broken specifically, not to some broader regression.
972+
let response = owner_push_response(
973+
&state,
974+
community,
975+
&keys,
976+
&format!("repo-{}", uuid::Uuid::new_v4().simple()),
977+
vec![],
978+
)
979+
.await;
980+
let (status, body) = body_string(response).await;
981+
assert_eq!(
982+
status,
983+
StatusCode::OK,
984+
"owner push to a never-bound repo must remain allowed (got body: {body})"
985+
);
986+
}
811987
}

0 commit comments

Comments
 (0)