Skip to content

Commit 4355db1

Browse files
loganjLarry
andcommitted
fix(relay): scope push matches with the read path's channel rule
Push skipped only `system` channels, while REQ, COUNT, search and the bridge keep only legacy channel types unless a filter names the channel. A channel type added later would have pushed to every member. The matcher now loads the batch's named-only channels and scopes each lease filter with `filter_channel_scope`, the same function reads use. A named-only channel (system or later type) pushes only to a lease filter that names it by `#h`. Removes the now-unused `system_channel_ids_among`. Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Signed-off-by: Logan Johnson <[email protected]>
1 parent fcdabcf commit 4355db1

2 files changed

Lines changed: 93 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/push_runtime.rs‎

Lines changed: 93 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,25 @@ fn match_job(
346356
Ok(wakes)
347357
}
348358

359+
/// Whether a lease filter may read 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`.
364+
fn push_filter_reads_channel(
365+
filter: &Filter,
366+
channel: Option<uuid::Uuid>,
367+
named_only: &NamedOnlyChannels,
368+
) -> bool {
369+
let Some(channel) = channel else {
370+
return true;
371+
};
372+
if !named_only.ids().contains(&channel) {
373+
return true;
374+
}
375+
filter_channel_scope(filter, &[], named_only).contains(&channel)
376+
}
377+
349378
/// Match-time counterpart of REQ's filter-level `#p` authorization gate.
350379
/// Kind 1059 is globally stored and leaks recipient activity through wake
351380
/// timing, so a lease may only match gift wraps addressed to its own author.
@@ -764,6 +793,60 @@ mod tests {
764793
));
765794
}
766795

796+
#[test]
797+
fn named_only_channel_pushes_only_to_a_filter_that_names_it() {
798+
let member = nostr::Keys::generate();
799+
let sender = nostr::Keys::generate();
800+
let legacy = uuid::Uuid::new_v4();
801+
let system = uuid::Uuid::new_v4();
802+
let future = uuid::Uuid::new_v4();
803+
let author = member.public_key().to_bytes().to_vec();
804+
let lease = |filter: Value| buzz_db::push::MatchLease {
805+
author: author.clone(),
806+
installation_id: "phone".into(),
807+
generation: 1,
808+
subscriptions: serde_json::json!([{"filter": filter, "class": "default"}]),
809+
expires_at: Utc::now().timestamp() + 3600,
810+
};
811+
let context = |filter: Value| MatchContext {
812+
leases: vec![lease(filter)],
813+
memberships: [legacy, system, future]
814+
.into_iter()
815+
.map(|channel| (channel, author.clone()))
816+
.collect(),
817+
named_only: NamedOnlyChannels::from_typed([
818+
(system, "system".to_owned()),
819+
(future, "later-type".to_owned()),
820+
]),
821+
};
822+
let job = |channel: uuid::Uuid| buzz_db::push::BatchedMatch {
823+
event: buzz_core::StoredEvent::new(
824+
EventBuilder::new(Kind::Custom(9), "hi")
825+
.tag(Tag::parse(["h", &channel.to_string()]).unwrap())
826+
.sign_with_keys(&sender)
827+
.unwrap(),
828+
Some(channel),
829+
),
830+
attempt: 1,
831+
};
832+
let wakes = |filter: Value, channel| match_job(&job(channel), &context(filter)).unwrap();
833+
834+
// A filter that names no channel reads only legacy-type channels.
835+
let broad = serde_json::json!({"kinds": [9]});
836+
assert_eq!(wakes(broad.clone(), legacy).len(), 1);
837+
assert!(wakes(broad.clone(), system).is_empty());
838+
assert!(wakes(broad, future).is_empty());
839+
840+
// Naming a named-only channel by #h reads it, as in REQ.
841+
for channel in [system, future] {
842+
let named = serde_json::json!({"kinds": [9], "#h": [channel.to_string()]});
843+
assert_eq!(wakes(named, channel).len(), 1);
844+
}
845+
// Naming one channel does not widen the filter to another.
846+
let other = serde_json::json!({"kinds": [9], "#h": [system.to_string()]});
847+
assert!(wakes(other, future).is_empty());
848+
}
849+
767850
async fn capture(
768851
State(seen): State<Arc<Mutex<Vec<Value>>>>,
769852
OriginalUri(uri): OriginalUri,

0 commit comments

Comments
 (0)