Skip to content

Commit 4dea51f

Browse files
loganjLarry
andauthored
fix(relay): scope push matches with the read path's channel rule (#8507)
🤖 ## Summary This is a consistency and forward-compatibility fix. It does not change what users of current clients see. Mobile push notifications now decide which channels can notify a device with the same rule that reads use, with one exception that the protocol requires: system channels never push. Before this change, push and reads used two separate rules: - **Reads** (subscriptions, counts, search and the bridge) show only the original channel types (stream, forum, DM, workflow) unless the filter names the channel. - **Push** skipped only `system` channels. Today `system` is the only non-original type, so the two rules give the same result. But a channel type added later would be hidden from reads and would still send push notifications to every member. This PR removes that gap: push now calls the same function that reads use, so a future type gets the correct push behavior with no extra work. ## What changes - A channel of an original type pushes as before. Membership is still required. - A system channel never pushes, even when a push filter names it. NIP-CL says: "The relay MUST NOT send push notifications for system channels." This is the same as before. - A channel of a type added later pushes only to a push filter that names that channel with `#h` (the channel tag), as reads do. - A push filter that names one channel does not get pushes from other named-only channels. - Events that are not in a channel (for example gift wraps) match as before. Push filters cannot carry the `#t` or `#P` opt-in that reads accept, so for push, naming the channel means `#h` only. ## Impact on current clients: none - System channels still never push, and no current channel type is affected by the later-type rule. - The mobile app names channels by `#h` only for joined, unarchived DM channels (`mobile/lib/shared/push/push_subscription_provider.dart`). DMs are an original type. - Naming a channel cannot get around membership. A push filter that names a channel still gets nothing unless its owner is a member of that channel. - Database cost is unchanged: one per-batch query replaces another, on the same channel list, with no extra round trip. - The push docs (NIP-PL and the push suppression doc) do not mention channel types, so they need no update. ## Details - The push matcher loads the named-only channels in each batch and checks each lease filter with `filter_channel_scope`, the function REQ, COUNT, search and the bridge already use. Before that check, it rejects system channels outright. - This removes `system_channel_ids_among`, which push was the last caller of. ### Related issue Part of the system channels spec (§2, rule 5). Builds on #8181 and #8469. No duplicate PR found. ### Testing - A `match_job` unit test covers: unnamed filters on an original-type channel, on a channel-less event, on a system channel and on a later-type channel; a later-type channel named by `#h` (1 wake); a system channel named by `#h` (0 wakes); an unrelated `#h` (no widening); and non-members. Removing either the shared scope check or the system exception fails it. - Before this PR, no test covered the push channel filter, not even for `system`. --------- Signed-off-by: Logan Johnson <[email protected]> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
1 parent ce3fc78 commit 4dea51f

3 files changed

Lines changed: 132 additions & 45 deletions

File tree

‎crates/buzz-db/src/store/channel_members.rs‎

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1321,31 +1321,6 @@ pub async fn channel_type_of(
13211321
.await?)
13221322
}
13231323

1324-
/// The IDs in `channel_ids` that name system channels, deleted or not.
1325-
/// Push matching uses it to skip them.
1326-
pub async fn system_channel_ids_among(
1327-
pool: &PgPool,
1328-
community_id: CommunityId,
1329-
channel_ids: &[Uuid],
1330-
) -> Result<Vec<Uuid>> {
1331-
if channel_ids.is_empty() {
1332-
return Ok(Vec::new());
1333-
}
1334-
let mut connection = crate::observability::acquire_writer(
1335-
pool,
1336-
crate::observability::WriterOperation::Authorization,
1337-
)
1338-
.await?;
1339-
Ok(sqlx::query_scalar(
1340-
"SELECT id FROM channels \
1341-
WHERE community_id = $1 AND id = ANY($2) AND channel_type = 'system'",
1342-
)
1343-
.bind(community_id.as_uuid())
1344-
.bind(channel_ids)
1345-
.fetch_all(&mut *connection)
1346-
.await?)
1347-
}
1348-
13491324
/// The channels in `channel_ids` whose type is not a legacy type
13501325
/// ([`buzz_core::channel::LEGACY_CHANNEL_TYPES`]), deleted or not, each with
13511326
/// its type: system channels and any type added later. A filter reads them
@@ -2029,16 +2004,6 @@ impl Db {
20292004
channel_type_of(&self.pool, community_id, channel_id).await
20302005
}
20312006

2032-
/// The IDs in `channel_ids` that name system channels, deleted or not.
2033-
#[datastore_span(name = "system_channel_ids_among", system = "postgresql")]
2034-
pub async fn system_channel_ids_among(
2035-
&self,
2036-
community_id: CommunityId,
2037-
channel_ids: &[Uuid],
2038-
) -> Result<Vec<Uuid>> {
2039-
system_channel_ids_among(&self.pool, community_id, channel_ids).await
2040-
}
2041-
20422007
/// The channels in `channel_ids` whose type is not a legacy type, deleted
20432008
/// or not, each with its type.
20442009
#[datastore_span(name = "named_only_channels_among", system = "postgresql")]

‎crates/buzz-relay/src/handlers/system_channels.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ impl NamedOnlyChannels {
6767
&self.ids
6868
}
6969

70+
/// Whether `id` is a system channel.
71+
pub(crate) fn is_system(&self, id: &Uuid) -> bool {
72+
self.system.contains(id)
73+
}
74+
7075
pub(crate) fn is_empty(&self) -> bool {
7176
self.ids.is_empty()
7277
}

‎crates/buzz-relay/src/push_runtime.rs‎

Lines changed: 127 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,14 @@ use nostr::Filter;
1111
use serde::{Deserialize, Serialize};
1212
use tracing::{debug, error, warn};
1313

14-
use crate::{handlers::push_lease::Subscription, nip98::nip98_header, state::AppState};
14+
use crate::{
15+
handlers::{
16+
push_lease::Subscription,
17+
system_channels::{filter_channel_scope, NamedOnlyChannels},
18+
},
19+
nip98::nip98_header,
20+
state::AppState,
21+
};
1522

1623
// Dropping a SQLx transaction rolls it back; committed claims remain leased
1724
// until expiry. Dropping HTTP cannot recall requests already accepted by the
@@ -116,11 +123,13 @@ async fn matcher_loop(state: &AppState) {
116123
}
117124
}
118125

119-
/// Per-batch state shared by every job: the community's active leases and
120-
/// the exact (channel, lease author) membership pairs the jobs can consult.
126+
/// Per-batch state shared by every job: the community's active leases, the
127+
/// exact (channel, lease author) membership pairs the jobs can consult, and
128+
/// the batch's named-only channels (system channels and any type added later).
121129
struct MatchContext {
122130
leases: Vec<buzz_db::push::MatchLease>,
123131
memberships: std::collections::HashSet<(uuid::Uuid, Vec<u8>)>,
132+
named_only: NamedOnlyChannels,
124133
}
125134

126135
async fn load_match_context(
@@ -138,22 +147,22 @@ async fn load_match_context(
138147
let mut authors: Vec<Vec<u8>> = leases.iter().map(|lease| lease.author.clone()).collect();
139148
authors.sort_unstable();
140149
authors.dedup();
141-
// System channels never push: drop their membership pairs, so a channel
142-
// event there matches no lease (channel events require membership).
143-
let system = state
144-
.db
145-
.system_channel_ids_among(batch.community, &channels)
146-
.await?;
147150
let memberships = state
148151
.db
149152
.membership_pairs(batch.community, &channels, &authors)
150153
.await?
151154
.into_iter()
152-
.filter(|(channel, _)| !system.contains(channel))
153155
.collect();
156+
let named_only = NamedOnlyChannels::from_typed(
157+
state
158+
.db
159+
.named_only_channels_among(batch.community, &channels)
160+
.await?,
161+
);
154162
Ok(MatchContext {
155163
leases,
156164
memberships,
165+
named_only,
157166
})
158167
}
159168

@@ -301,6 +310,7 @@ fn match_job(
301310
let filter: Filter =
302311
serde_json::from_value(serde_json::Value::Object(sub.filter.clone()))?;
303312
if !push_filter_authorized_for_event(&filter, &job.event.event, &author_hex)
313+
|| !push_filter_reads_channel(&filter, job.event.channel_id, &context.named_only)
304314
|| !filters_match(std::slice::from_ref(&filter), &job.event)
305315
{
306316
continue;
@@ -346,6 +356,29 @@ fn match_job(
346356
Ok(wakes)
347357
}
348358

359+
/// Whether a lease filter may push an event in `channel`, by the same rule as
360+
/// REQ: a legacy-type channel is in every filter's scope (membership is
361+
/// checked separately), and a named-only channel is in scope only when the
362+
/// filter names it (see [`crate::handlers::system_channels`]). Lease filters
363+
/// cannot carry `#t` or `#P`, so for push "names it" means `#h`. The one
364+
/// exception: NIP-CL forbids push for system channels, even when named.
365+
fn push_filter_reads_channel(
366+
filter: &Filter,
367+
channel: Option<uuid::Uuid>,
368+
named_only: &NamedOnlyChannels,
369+
) -> bool {
370+
let Some(channel) = channel else {
371+
return true;
372+
};
373+
if !named_only.ids().contains(&channel) {
374+
return true;
375+
}
376+
if named_only.is_system(&channel) {
377+
return false;
378+
}
379+
filter_channel_scope(filter, &[], named_only).contains(&channel)
380+
}
381+
349382
/// Match-time counterpart of REQ's filter-level `#p` authorization gate.
350383
/// Kind 1059 is globally stored and leaks recipient activity through wake
351384
/// timing, so a lease may only match gift wraps addressed to its own author.
@@ -764,6 +797,90 @@ mod tests {
764797
));
765798
}
766799

800+
#[test]
801+
fn named_only_channel_pushes_only_to_a_filter_that_names_it() {
802+
let member = nostr::Keys::generate();
803+
let outsider = nostr::Keys::generate();
804+
let sender = nostr::Keys::generate();
805+
let legacy = uuid::Uuid::new_v4();
806+
let system = uuid::Uuid::new_v4();
807+
let future = uuid::Uuid::new_v4();
808+
let author = |keys: &nostr::Keys| keys.public_key().to_bytes().to_vec();
809+
let context = |keys: &nostr::Keys, filter: Value| MatchContext {
810+
leases: vec![buzz_db::push::MatchLease {
811+
author: author(keys),
812+
installation_id: "phone".into(),
813+
generation: 1,
814+
subscriptions: serde_json::json!([{"filter": filter, "class": "default"}]),
815+
expires_at: Utc::now().timestamp() + 3600,
816+
}],
817+
memberships: [legacy, system, future]
818+
.into_iter()
819+
.map(|channel| (channel, author(&member)))
820+
.collect(),
821+
named_only: NamedOnlyChannels::from_typed([
822+
(system, "system".to_owned()),
823+
(future, "later-type".to_owned()),
824+
]),
825+
};
826+
let job = |channel: Option<uuid::Uuid>| {
827+
let mut event = EventBuilder::new(Kind::Custom(9), "hi");
828+
if let Some(channel) = channel {
829+
event = event.tag(Tag::parse(["h", &channel.to_string()]).unwrap());
830+
}
831+
buzz_db::push::BatchedMatch {
832+
event: buzz_core::StoredEvent::new(event.sign_with_keys(&sender).unwrap(), channel),
833+
attempt: 1,
834+
}
835+
};
836+
let wakes = |keys: &nostr::Keys, filter: Value, channel| {
837+
match_job(&job(channel), &context(keys, filter))
838+
.unwrap()
839+
.len()
840+
};
841+
let names =
842+
|channel: uuid::Uuid| serde_json::json!({"kinds": [9], "#h": [channel.to_string()]});
843+
let broad = serde_json::json!({"kinds": [9]});
844+
845+
// A filter that names no channel reads legacy-type channels and
846+
// channel-less events, but no named-only channel.
847+
assert_eq!(wakes(&member, broad.clone(), Some(legacy)), 1, "legacy");
848+
assert_eq!(wakes(&member, broad.clone(), None), 1, "no channel");
849+
assert_eq!(
850+
wakes(&member, broad.clone(), Some(system)),
851+
0,
852+
"unnamed system"
853+
);
854+
assert_eq!(wakes(&member, broad, Some(future)), 0, "unnamed later type");
855+
856+
// Naming a later-type channel by #h reads it, as in REQ.
857+
assert_eq!(
858+
wakes(&member, names(future), Some(future)),
859+
1,
860+
"named later type"
861+
);
862+
// NIP-CL: a system channel never pushes, even when named.
863+
assert_eq!(
864+
wakes(&member, names(system), Some(system)),
865+
0,
866+
"named system"
867+
);
868+
// Naming one channel does not widen the filter to another.
869+
let other = uuid::Uuid::new_v4();
870+
assert_eq!(wakes(&member, names(other), Some(future)), 0, "other #h");
871+
// Membership is still required.
872+
assert_eq!(
873+
wakes(&outsider, names(future), Some(future)),
874+
0,
875+
"non-member"
876+
);
877+
assert_eq!(
878+
wakes(&outsider, names(legacy), Some(legacy)),
879+
0,
880+
"non-member legacy"
881+
);
882+
}
883+
767884
async fn capture(
768885
State(seen): State<Arc<Mutex<Vec<Value>>>>,
769886
OriginalUri(uri): OriginalUri,

0 commit comments

Comments
 (0)