Skip to content

Commit 49d977a

Browse files
committed
fix(workflows): preserve multi-channel listing semantics
Co-authored-by: Taylor Ho <[email protected]> Signed-off-by: Taylor Ho <[email protected]>
1 parent d8281b9 commit 49d977a

5 files changed

Lines changed: 292 additions & 44 deletions

File tree

‎crates/buzz-core/src/filter.rs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,28 @@ mod tests {
184184
));
185185
}
186186

187+
#[test]
188+
fn h_tag_multi_value_filter_matches_any_channel() {
189+
let channel_a = uuid::Uuid::new_v4();
190+
let channel_b = uuid::Uuid::new_v4();
191+
let stored = stored_with_tag(Tag::parse(["h", &channel_b.to_string()]).unwrap());
192+
let filter = Filter::new().custom_tags(
193+
nostr::SingleLetterTag::lowercase(nostr::Alphabet::H),
194+
[channel_a.to_string(), channel_b.to_string()],
195+
);
196+
197+
assert!(filters_match(&[filter], &stored));
198+
}
199+
200+
#[test]
201+
fn empty_h_tag_filter_matches_nothing() {
202+
let channel_id = uuid::Uuid::new_v4();
203+
let stored = stored_with_tag(Tag::parse(["h", &channel_id.to_string()]).unwrap());
204+
let filter: Filter = serde_json::from_value(serde_json::json!({ "#h": [] })).unwrap();
205+
206+
assert!(!filters_match(&[filter], &stored));
207+
}
208+
187209
#[test]
188210
fn h_tag_fallback_uses_stored_channel_id() {
189211
// Reactions (kind:7) and deletions (kind:5) don't carry h-tags —

‎crates/buzz-db/src/event.rs‎

Lines changed: 81 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,17 @@ pub struct EventQuery {
7070
/// Restrict results to events with an `e` tag referencing any of these event IDs (hex).
7171
/// Uses JSONB containment (`tags @> ...`) against the `tags` column.
7272
pub e_tags: Option<Vec<String>>,
73-
/// Restrict results to events in any of these channels, while retaining
74-
/// channel-less global events. Applied before SQL `LIMIT` so access-filtered
75-
/// historical pages have exact exhaustion semantics.
73+
/// Restrict results to events in any of these channels. By default,
74+
/// channel-less global events are retained so this can enforce a viewer's
75+
/// accessible-channel scope without hiding global events. Set
76+
/// [`EventQuery::channel_ids_include_global`] to `false` for an explicit
77+
/// multi-channel `#h` filter, which must match only requested channels.
78+
/// Applied before SQL `LIMIT` so access- and filter-scoped historical pages
79+
/// have exact exhaustion semantics.
7680
pub channel_ids: Option<Vec<uuid::Uuid>>,
81+
/// Whether [`EventQuery::channel_ids`] also retains channel-less global
82+
/// events. Defaults to `true` for access-scope queries.
83+
pub channel_ids_include_global: bool,
7784
/// Override the default page clamp ([`DEFAULT_MAX_PAGE_LIMIT`]). Used by
7885
/// the COUNT fallback path, which needs to fetch all matching events for
7986
/// post-filter counting. When None, the default clamp applies.
@@ -122,6 +129,7 @@ impl EventQuery {
122129
ids: None,
123130
e_tags: None,
124131
channel_ids: None,
132+
channel_ids_include_global: true,
125133
max_limit: None,
126134
shared_gated_reader: None,
127135
}
@@ -404,20 +412,24 @@ pub(crate) async fn query_events_on(
404412
qb.push(format!(" AND {col_prefix}channel_id IS NULL"));
405413
}
406414

407-
// Multi-channel IN pushdown: restrict to events in any of these channels
408-
// OR global events (channel_id IS NULL). Used by NIP-45 COUNT to enforce
409-
// channel access at the SQL level without fetching all rows.
415+
// Multi-channel IN pushdown. Access-scope queries retain global events;
416+
// explicit multi-value #h filters do not.
410417
//
411-
// SECURITY: Some(empty vec) means "user has access to NO channels" —
412-
// only global events (channel_id IS NULL) should be returned.
418+
// SECURITY: Some(empty vec) means "match no channels". Access-scope
419+
// queries still retain globals; explicit #h queries match nothing.
413420
if let Some(ref ch_ids) = q.channel_ids {
414421
if ch_ids.is_empty() {
415-
// No channel access — only global (non-channel) events visible.
416-
qb.push(format!(" AND {col_prefix}channel_id IS NULL"));
422+
if q.channel_ids_include_global {
423+
qb.push(format!(" AND {col_prefix}channel_id IS NULL"));
424+
} else {
425+
qb.push(" AND FALSE");
426+
}
417427
} else {
418-
qb.push(format!(
419-
" AND ({col_prefix}channel_id IS NULL OR {col_prefix}channel_id IN ("
420-
));
428+
qb.push(" AND (");
429+
if q.channel_ids_include_global {
430+
qb.push(format!("{col_prefix}channel_id IS NULL OR "));
431+
}
432+
qb.push(format!("{col_prefix}channel_id IN ("));
421433
let mut sep = qb.separated(", ");
422434
for ch in ch_ids {
423435
sep.push_bind(*ch);
@@ -670,15 +682,21 @@ pub(crate) async fn count_events_on(conn: &mut sqlx::PgConnection, q: &EventQuer
670682
qb.push(format!(" AND {col_prefix}channel_id IS NULL"));
671683
}
672684

673-
// Multi-channel IN pushdown for COUNT: restrict to accessible channels + global.
674-
// SECURITY: Some(empty vec) = no channel access → global events only.
685+
// Multi-channel IN pushdown for COUNT. Access-scope queries retain global
686+
// events; explicit multi-value #h filters do not.
675687
if let Some(ref ch_ids) = q.channel_ids {
676688
if ch_ids.is_empty() {
677-
qb.push(format!(" AND {col_prefix}channel_id IS NULL"));
689+
if q.channel_ids_include_global {
690+
qb.push(format!(" AND {col_prefix}channel_id IS NULL"));
691+
} else {
692+
qb.push(" AND FALSE");
693+
}
678694
} else {
679-
qb.push(format!(
680-
" AND ({col_prefix}channel_id IS NULL OR {col_prefix}channel_id IN ("
681-
));
695+
qb.push(" AND (");
696+
if q.channel_ids_include_global {
697+
qb.push(format!("{col_prefix}channel_id IS NULL OR "));
698+
}
699+
qb.push(format!("{col_prefix}channel_id IN ("));
682700
let mut sep = qb.separated(", ");
683701
for ch in ch_ids {
684702
sep.push_bind(*ch);
@@ -1878,6 +1896,50 @@ mod tests {
18781896
.expect("sign timestamped event")
18791897
}
18801898

1899+
#[tokio::test]
1900+
#[ignore = "requires Postgres"]
1901+
async fn explicit_multi_channel_scope_is_applied_before_historical_page_limit() {
1902+
let pool = setup_pool().await;
1903+
let community_uuid = make_test_community(&pool).await;
1904+
let community = CommunityId::from_uuid(community_uuid);
1905+
let channel_a = make_test_channel(&pool, community_uuid, None).await;
1906+
let channel_b = make_test_channel(&pool, community_uuid, None).await;
1907+
let unrelated_c = make_test_channel(&pool, community_uuid, None).await;
1908+
let base = 1_800_000_000;
1909+
1910+
let older_a = make_event_at(39_000, "older requested A", base + 1);
1911+
insert_event(&pool, community, &older_a, Some(channel_a))
1912+
.await
1913+
.expect("insert requested A candidate");
1914+
let requested_b = make_event_at(39_000, "requested B", base + 2);
1915+
insert_event(&pool, community, &requested_b, Some(channel_b))
1916+
.await
1917+
.expect("insert requested B candidate");
1918+
let newer_c = make_event_at(39_000, "newer unrelated C", base + 3);
1919+
insert_event(&pool, community, &newer_c, Some(unrelated_c))
1920+
.await
1921+
.expect("insert unrelated C candidate");
1922+
1923+
let events = query_events(
1924+
&pool,
1925+
&EventQuery {
1926+
kinds: Some(vec![39_000]),
1927+
channel_ids: Some(vec![channel_a, channel_b]),
1928+
channel_ids_include_global: false,
1929+
limit: Some(1),
1930+
..EventQuery::for_community(community)
1931+
},
1932+
)
1933+
.await
1934+
.expect("query explicit multi-channel page");
1935+
1936+
assert_eq!(events.len(), 1);
1937+
assert_eq!(
1938+
events[0].event.id, requested_b.id,
1939+
"newer unrelated channel C must not consume the requested A/B limit"
1940+
);
1941+
}
1942+
18811943
#[tokio::test]
18821944
#[ignore = "requires Postgres"]
18831945
async fn access_scope_is_applied_before_historical_page_limit() {

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

Lines changed: 126 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,12 @@ pub async fn handle_req(
288288
};
289289
let mut params =
290290
filter_to_query_params(filter, per_filter_channel, conn.tenant.community());
291-
apply_access_scope_to_query(&mut params, per_filter_channel, &accessible_channels);
291+
apply_channel_scope_to_query(
292+
&mut params,
293+
filter,
294+
per_filter_channel,
295+
&accessible_channels,
296+
);
292297
// Shared-gated visibility pushdown: set reader bytes so query_events
293298
// appends the SQL visibility clause before ORDER/LIMIT, preventing
294299
// newer private events from starving older shared ones off the page.
@@ -854,19 +859,20 @@ fn filters_are_nip43_membership_only(filters: &[Filter]) -> bool {
854859
})
855860
}
856861

857-
/// Extract a channel UUID from a single filter's `#h` tag.
862+
/// Extract the single channel UUID from a filter's `#h` tag.
863+
///
864+
/// A multi-value `#h` filter has NIP-01 OR semantics, so it cannot be reduced
865+
/// to one `EventQuery::channel_id` without dropping matches from the other
866+
/// channels. Return `None` in that case and let the caller apply the accessible
867+
/// channel set in SQL before the full filter is evaluated in Rust.
858868
fn extract_channel_id_from_filter(filter: &Filter) -> Option<uuid::Uuid> {
859-
for (tag_key, tag_values) in filter.generic_tags.iter() {
860-
let key = tag_key.to_string();
861-
if key == "h" {
862-
for val in tag_values {
863-
if let Ok(id) = val.parse::<uuid::Uuid>() {
864-
return Some(id);
865-
}
866-
}
867-
}
869+
let h_tag = nostr::SingleLetterTag::lowercase(nostr::Alphabet::H);
870+
let values = filter.generic_tags.get(&h_tag)?;
871+
if values.len() != 1 {
872+
return None;
868873
}
869-
None
874+
875+
values.iter().next()?.parse::<uuid::Uuid>().ok()
870876
}
871877

872878
/// Convert a single NIP-01 filter into an [`EventQuery`] for the database.
@@ -1002,6 +1008,37 @@ fn filter_to_query_params(
10021008
}
10031009
}
10041010

1011+
/// Push channel constraints into SQL before `LIMIT`.
1012+
///
1013+
/// A valid multi-value `#h` is narrowed to the requested channels the reader
1014+
/// may access. Invalid values are ignored, and an empty authorized result is an
1015+
/// explicit match-nothing scope rather than a global query. Filters without
1016+
/// `#h` retain the full accessible-channel scope plus global events.
1017+
fn apply_channel_scope_to_query(
1018+
query: &mut EventQuery,
1019+
filter: &Filter,
1020+
channel_id: Option<uuid::Uuid>,
1021+
accessible_channels: &[uuid::Uuid],
1022+
) {
1023+
if channel_id.is_some() {
1024+
return;
1025+
}
1026+
1027+
let h_tag = nostr::SingleLetterTag::lowercase(nostr::Alphabet::H);
1028+
if let Some(values) = filter.generic_tags.get(&h_tag) {
1029+
query.channel_ids = Some(
1030+
values
1031+
.iter()
1032+
.filter_map(|value| value.parse::<uuid::Uuid>().ok())
1033+
.filter(|requested| accessible_channels.contains(requested))
1034+
.collect(),
1035+
);
1036+
query.channel_ids_include_global = false;
1037+
} else {
1038+
query.channel_ids = Some(accessible_channels.to_vec());
1039+
}
1040+
}
1041+
10051042
/// Push the caller's authorized channel set into logically global historical
10061043
/// queries so SQL `LIMIT` counts visible rows. Channel-less events remain in
10071044
/// scope by `EventQuery::channel_ids` contract; an explicit single-channel
@@ -1551,6 +1588,83 @@ mod tests {
15511588
assert_eq!(extract_channel_id_from_filters(&filters), Some(channel_id));
15521589
}
15531590

1591+
#[test]
1592+
fn extract_channel_id_from_multi_value_filter_returns_none() {
1593+
let channel_a = uuid::Uuid::new_v4();
1594+
let channel_b = uuid::Uuid::new_v4();
1595+
let filter: Filter = serde_json::from_value(serde_json::json!({
1596+
"#h": [channel_a.to_string(), channel_b.to_string()],
1597+
}))
1598+
.unwrap();
1599+
1600+
assert_eq!(extract_channel_id_from_filter(&filter), None);
1601+
assert_eq!(
1602+
filter_to_query_params(
1603+
&filter,
1604+
extract_channel_id_from_filter(&filter),
1605+
buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()),
1606+
)
1607+
.channel_id,
1608+
None,
1609+
"multi-channel OR filters must not be narrowed to their first channel",
1610+
);
1611+
}
1612+
1613+
#[test]
1614+
fn multi_value_h_scope_intersects_access_before_limit() {
1615+
let channel_a = uuid::Uuid::new_v4();
1616+
let channel_b = uuid::Uuid::new_v4();
1617+
let unrelated_c = uuid::Uuid::new_v4();
1618+
let unauthorized = uuid::Uuid::new_v4();
1619+
let filter: Filter = serde_json::from_value(serde_json::json!({
1620+
"#h": [
1621+
channel_a.to_string(),
1622+
channel_b.to_string(),
1623+
unauthorized.to_string(),
1624+
"not-a-uuid"
1625+
],
1626+
"limit": 1
1627+
}))
1628+
.unwrap();
1629+
let mut query = filter_to_query_params(
1630+
&filter,
1631+
extract_channel_id_from_filter(&filter),
1632+
buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()),
1633+
);
1634+
1635+
apply_channel_scope_to_query(
1636+
&mut query,
1637+
&filter,
1638+
None,
1639+
&[channel_a, channel_b, unrelated_c],
1640+
);
1641+
1642+
let scoped_channels = query.channel_ids.expect("explicit channel scope");
1643+
assert_eq!(scoped_channels.len(), 2);
1644+
assert!(scoped_channels.contains(&channel_a));
1645+
assert!(scoped_channels.contains(&channel_b));
1646+
assert!(!query.channel_ids_include_global);
1647+
assert_eq!(query.limit, Some(1));
1648+
}
1649+
1650+
#[test]
1651+
fn empty_or_unauthorized_h_scope_matches_nothing() {
1652+
for values in [serde_json::json!([]), serde_json::json!(["not-a-uuid"])] {
1653+
let filter: Filter =
1654+
serde_json::from_value(serde_json::json!({ "#h": values })).unwrap();
1655+
let mut query = filter_to_query_params(
1656+
&filter,
1657+
None,
1658+
buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()),
1659+
);
1660+
1661+
apply_channel_scope_to_query(&mut query, &filter, None, &[uuid::Uuid::new_v4()]);
1662+
1663+
assert_eq!(query.channel_ids, Some(Vec::new()));
1664+
assert!(!query.channel_ids_include_global);
1665+
}
1666+
}
1667+
15541668
#[test]
15551669
fn test_extract_channel_id_mixed_channels_returns_none() {
15561670
let channel_a = uuid::Uuid::new_v4();

‎desktop/src-tauri/src/commands/workflows.rs‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,13 @@ pub async fn get_channel_workflows(
105105
///
106106
/// The Workflows overview screen previously issued one `get_channel_workflows`
107107
/// query per member channel (`Promise.all` fanout in `WorkflowsView`), i.e. N
108-
/// relay POSTs. A nostr `#h` filter matches ANY of its listed values, so one
109-
/// query with all channel ids returns the same set. Each `WorkflowWire` carries
110-
/// its own `channel_id` (from the event's `h` tag), so the frontend can still
111-
/// group results by channel. Neither this nor the per-channel command sets a
112-
/// `limit`, so batching does not change result completeness.
108+
/// relay POSTs. This sends N single-channel filters in one query request. Using
109+
/// one multi-value `#h` filter would be equivalent under NIP-01, but older
110+
/// relays incorrectly narrowed that shape to its first channel. Each
111+
/// `WorkflowWire` carries its own `channel_id` (from the event's `h` tag), so
112+
/// the frontend can still group results by channel. Neither this nor the
113+
/// per-channel command sets a `limit`, so batching does not change result
114+
/// completeness.
113115
#[tauri::command]
114116
pub async fn get_channels_workflows(
115117
channel_ids: Vec<String>,
@@ -119,18 +121,26 @@ pub async fn get_channels_workflows(
119121
return Ok(Vec::new());
120122
}
121123

122-
let events = query_relay(
123-
&state,
124-
&[serde_json::json!({
125-
"kinds": [30620],
126-
"#h": channel_ids,
127-
})],
128-
)
129-
.await?;
124+
let filters = channel_workflow_filters(channel_ids)?;
125+
let events = query_relay(&state, &filters).await?;
130126

131127
Ok(events.iter().map(workflow_from_event).collect())
132128
}
133129

130+
fn channel_workflow_filters(channel_ids: Vec<String>) -> Result<Vec<Value>, String> {
131+
channel_ids
132+
.into_iter()
133+
.map(|channel_id| {
134+
let channel_id = uuid::Uuid::parse_str(channel_id.trim())
135+
.map_err(|_| "invalid channel id".to_string())?;
136+
Ok(serde_json::json!({
137+
"kinds": [30620],
138+
"#h": [channel_id.to_string()],
139+
}))
140+
})
141+
.collect()
142+
}
143+
134144
#[tauri::command]
135145
pub async fn get_workflow(
136146
workflow_id: String,

0 commit comments

Comments
 (0)