relay: refuse a reaction or deletion whose h names another channel (#9006)

## Summary

A reaction, or a deletion that targets a message, belongs to the target
message's channel. The relay works out that channel from the target and
stores the event there. But every read and every live delivery matches
the event's own channel (`h`) tags. So if a client puts a *different*
channel in the `h` tag, the event is stored in one channel and only ever
matches another:

- No one ever receives it.
- It still takes a slot when a client asks for "the latest N events" of
the real channel. A catch-up can then return fewer events than exist
while it looks complete, because the relay removes the stray event after
it applies the limit. This is one of the known gaps in
https://github.com/block/buzz-app/pull/2206.

The relay now refuses such an event. The rule:

| Event's `h` tags | Before | After |
|---|---|---|
| none | accepted | accepted |
| include the target's channel | accepted | accepted |
| only other channels | accepted, never delivered | refused |

The refusal uses the same "target not found" text as the existing
refusals for these kinds. So it tells the sender nothing about where the
target is.

No first-party client sends a mismatched `h`. buzz-app uses the target
message's channel, and desktop, mobile and the SDK send no `h` on
reactions. So no current client is affected.

### Details

- The check covers kind:7 reactions and kind:5 deletions that name their
target with an `e` tag. These are the two kinds whose channel comes from
a target. A kind:5 that names an addressable event (`a` tag) is not
affected.
- The check runs only when the target is in a channel, so a reaction to
a global event keeps any `h`. A tag must be the channel's UUID exactly
as the relay writes it (lowercase, hyphenated), the same way `#h`
filters match.
- The check runs after the token, membership and archive checks. If it
ran first, it would skip their database reads, and the response time
could tell someone who cannot read a private channel whether a guessed
`h` names the channel that holds a message.
- Events already stored with a stray `h` are not changed. They can still
take a slot under the limit.
- NOSTR.md now says that an optional `#h` on these kinds must name the
target's channel. It also says kind:5 takes its channel from its `#e`
target (the old text said it used `#h`).

### Related issue
None found. Follow-up to the known gaps listed in
https://github.com/block/buzz-app/pull/2206.

### Testing
- New `reaction_and_deletion_h_must_name_the_target_channel` test, as a
member of the target's channel. A reaction whose `h` names only another
channel is refused and not stored. A reaction with no `h`, or with both
channels, is accepted, and so is a reaction with any `h` on a global
event. A deletion of that reaction is refused and not stored with
another channel's `h`. It is accepted with the target's `h` or with no
`h`. A non-member's wrong guess still reaches the membership check. On a
private channel, a right guess and a wrong guess both end at the same
membership denial.
- I removed the check, and the test failed. I also moved it back before
the membership check, and the test failed.
- On a local relay over WebSocket: the same refusals and acceptances,
with the same messages, and a reaction to a global event keeps its `h`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)



Human test: Logan asked to take this to team review without a separate
hand test (2026-11-17).

buzz-review-completed

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
This commit is contained in:
Logan Johnson
2026-11-17 20:03:02 -05:00
committed by GitHub
parent 3876720c34
commit 4bf7d8a9b0
2 changed files with 183 additions and 3 deletions

View File

@@ -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.
---

View File

@@ -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<crate::state::AppState>,
tenant: TenantContext,
tracer: Arc<dyn buzz_conformance::Tracer>,
trace: Arc<VecTracer>,
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<dyn buzz_conformance::Tracer> = Arc::new(VecTracer::default());
let trace = Arc::new(VecTracer::default());
let tracer: Arc<dyn buzz_conformance::Tracer> = 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<IngestResult, IngestError>, 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).