diff --git a/NOSTR.md b/NOSTR.md index 3ee50488bb..c3265bfabb 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -611,8 +611,8 @@ but only admins/owners can set it. Full spec: - **Pubkey allowlist is fail-closed.** DB errors deny the connection. - **API token users bypass the allowlist.** The allowlist only gates pubkey-only NIP-42. - **kind:9 requires `#h` tag.** Messages without a channel-scoped `#h` tag are rejected. -- **kind:7 derives channel from target.** Reactions look up the target event's channel via `#e` — client-supplied `#h` tags are ignored. Reactions to unknown events are rejected (fail-closed). -- **kind:5 uses `#h` if present, but doesn't require it.** Deletions validate author-match against target events via `#e` tags. Only self-authored events can be deleted (admin deletions use kind:9005). +- **kind:7 derives channel from target.** Reactions look up the target event's channel via `#e`. An `#h` tag is optional. When the target is in a channel and the reaction has `#h` tags, one must be that channel's UUID exactly as the relay writes it (lowercase, hyphenated), or the reaction is refused as if its target were missing. A reaction to a global event is not checked. Reactions to unknown events are rejected (fail-closed). +- **kind:5 derives channel from its `#e` target.** Deletions validate author-match against target events via `#e` tags. An `#h` follows the same rule as on a reaction; a deletion that names its target with an `#a` tag is not checked. Only self-authored events can be deleted (admin deletions use kind:9005). - **Client-submitted kind:44100/44101 rejected.** Membership notifications can only be signed by the relay keypair. --- diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 2f2ce7257c..e0a13a840f 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -3158,6 +3158,27 @@ async fn ingest_event_inner( } } + // An event that takes its channel from its target is stored in that + // channel, but every read and fan-out matches its own `h` tags. One whose + // `h` names another channel would never be delivered, yet it would use a + // slot under the channel's history LIMIT, so a replay cut by the limit + // could look complete. Refuse it with the kind's not-found denial. This + // runs after the token, membership and archive gates: an earlier refusal + // would skip their reads, and its timing would show a sender who cannot + // read the target's channel whether a guessed `h` names it. + if let (Some(reason), Some(target_channel)) = (target_denial, channel_id) { + let target_channel = target_channel.to_string(); + let mut h_tags = event + .tags + .iter() + .filter(|t| t.kind().to_string() == "h") + .peekable(); + if h_tags.peek().is_some() && !h_tags.any(|t| t.content() == Some(target_channel.as_str())) + { + return Err(target_denied(reason)); + } + } + // Artifact revisions passed the same home-channel write gates as kind 9 // above; they are stored and published without conversation side effects. if kind_u32 == buzz_core::kind::KIND_ARTIFACT { @@ -7675,6 +7696,7 @@ mod postgres_tests { state: Arc, tenant: TenantContext, tracer: Arc, + trace: Arc, author: nostr::Keys, sender: nostr::Keys, target_channel: Uuid, @@ -7695,7 +7717,8 @@ mod postgres_tests { .expect("ensure community") .id; let tenant = TenantContext::resolved(community, &host); - let tracer: Arc = Arc::new(VecTracer::default()); + let trace = Arc::new(VecTracer::default()); + let tracer: Arc = trace.clone(); let (author, sender) = (nostr::Keys::generate(), nostr::Keys::generate()); let mut channels = Vec::new(); for creator in [&author, &sender] { @@ -7741,6 +7764,7 @@ mod postgres_tests { state, tenant, tracer, + trace, author, sender, target_channel: channels[0], @@ -7837,6 +7861,162 @@ mod postgres_tests { .expect("in-scope token reacts to the message"); } + /// A reaction, or a deletion of one, is stored in its target's channel. An + /// `h` tag naming only another channel is refused like a missing target, + /// and nothing is stored: such an event would never be delivered, yet it + /// would use a slot under the channel's history LIMIT. No `h` tag, or the + /// target's own among them, is accepted, and so is any `h` on a reaction + /// to a global event. A sender's guess still passes the membership gate + /// before the refusal, so its cost does not show whether it was right. + /// Mutations: drop the `h` check → RED; move it before the membership + /// gate → RED (no AuthCheck for the guess). + #[tokio::test] + #[ignore = "requires Postgres"] + async fn reaction_and_deletion_h_must_name_the_target_channel() { + let f = ScopedTargetFixture::new("stray-h").await; + // The author is a member of the target's channel, so only the h check + // can refuse its events. Each reaction has its own emoji: a repeated + // one is a duplicate the relay accepts without storing. + let send = |keys: &nostr::Keys, kind: u32, content: &str, target_id: &str, h: &[&Uuid]| { + let mut tags = vec![nostr::Tag::parse(["e", target_id]).unwrap()]; + tags.extend( + h.iter() + .map(|h| nostr::Tag::parse(["h", &h.to_string()]).unwrap()), + ); + let event = EventBuilder::new(Kind::Custom(kind as u16), content) + .tags(tags) + .sign_with_keys(keys) + .expect("sign"); + let auth = IngestAuth::Nip42 { + pubkey: keys.public_key(), + scopes: vec![Scope::MessagesWrite], + channel_ids: None, + conn_id: Uuid::new_v4(), + }; + (event.id.to_hex(), f.submit(event, auth)) + }; + let refused = |result: Result, expected: &str| match result { + Err(IngestError::Rejected(msg)) => assert_eq!(msg, format!("invalid: {expected}")), + Err(other) => panic!("expected refusal, got {other:?}"), + Ok(result) => panic!("expected refusal, accepted: {}", result.message), + }; + async fn stored(f: &ScopedTargetFixture, id: String) -> bool { + f.state + .db + .get_event_by_id_including_deleted_for_event_write( + f.tenant.community(), + &hex::decode(id).expect("hex id"), + ) + .await + .expect("read event") + .is_some() + } + let (target, other) = (&f.target_channel, &f.other_channel); + let (live, global) = (f.live.id.to_hex(), f.global.id.to_hex()); + let a = &f.author; + + let (id, result) = send(a, KIND_REACTION, "+", &live, &[other]); + refused(result.await, REACTION_TARGET_NOT_FOUND); + assert!(!stored(&f, id).await, "a refused reaction is not stored"); + let (plain, result) = send(a, KIND_REACTION, "+", &live, &[]); + result.await.expect("a reaction with no h is accepted"); + let (reaction, result) = send(a, KIND_REACTION, "-", &live, &[other, target]); + result + .await + .expect("a reaction with the target's channel among its h tags is accepted"); + send(a, KIND_REACTION, "+", &global, &[other]) + .1 + .await + .expect("a reaction to a global event keeps any h"); + + let (id, result) = send(a, KIND_DELETION, "", &reaction, &[other]); + refused( + result.await, + crate::handlers::side_effects::DELETION_TARGET_DENIED, + ); + assert!(!stored(&f, id).await, "a refused deletion is not stored"); + send(a, KIND_DELETION, "", &reaction, &[target]) + .1 + .await + .expect("a deletion whose h names the target's channel is accepted"); + send(a, KIND_DELETION, "", &plain, &[]) + .1 + .await + .expect("a deletion with no h is accepted"); + + // The sender is not a member of the target's channel. Its guess at the + // wrong channel must still reach the membership gate. + f.trace.steps.lock().expect("trace lock").clear(); + refused( + send(&f.sender, KIND_REACTION, "+", &live, &[other]).1.await, + REACTION_TARGET_NOT_FOUND, + ); + assert!( + f.trace + .steps + .lock() + .expect("trace lock") + .iter() + .any(|step| matches!(step.action, TraceAction::AuthCheck { .. })), + "a wrong h must not be refused before the membership gate" + ); + + // In a private channel the sender cannot read, a right guess and a + // wrong guess both end at the same membership denial. + let private = Uuid::new_v4(); + f.state + .db + .create_channel_with_id( + f.tenant.community(), + private, + &format!("stray-h-private-{}", private.simple()), + buzz_db::channel::ChannelType::Stream, + buzz_db::channel::ChannelVisibility::Private, + None, + a.public_key().to_bytes().as_slice(), + None, + ) + .await + .expect("create private channel"); + let hidden = EventBuilder::new(Kind::Custom(9), "hidden") + .tags([nostr::Tag::parse(["h", &private.to_string()]).unwrap()]) + .sign_with_keys(a) + .expect("sign"); + let auth = IngestAuth::Http { + pubkey: a.public_key(), + scopes: vec![Scope::MessagesWrite], + auth_method: HttpAuthMethod::Nip98, + }; + ingest_event_inner(&f.state, &f.tracer, &f.tenant, hidden.clone(), auth) + .await + .expect("store private target"); + let hidden = hidden.id.to_hex(); + for guess in [&private, other] { + f.trace.steps.lock().expect("trace lock").clear(); + refused( + send(&f.sender, KIND_REACTION, "+", &hidden, &[guess]) + .1 + .await, + REACTION_TARGET_NOT_FOUND, + ); + assert!( + f.trace + .steps + .lock() + .expect("trace lock") + .iter() + .any(|step| matches!( + step.action, + TraceAction::AuthCheck { + verdict: Verdict::Deny, + .. + } + )), + "a guess at a private channel must end at the membership denial" + ); + } + } + // ── Owner-aware ban/timeout coverage ───────────────────────────────────── /// Fresh community plus an agent owned by `owner` (users.agent_owner_pubkey).