Skip to content

Commit 09331f2

Browse files
fix: address crossfire review — security, correctness, clarity
Crossfire round 1: codex 4/10, opus 8/10. All critical issues fixed: Security (critical): - Force channel_id=None for kind:1059 gift wraps — prevents channel-scoped storage that would bypass #p AUTH-gating (codex finding #1) Correctness: - NIP-50 pagination loop — keep fetching Typesense pages until limit met or result set exhausted, capped at MAX_SEARCH_PAGES=5 (codex finding #2) - Push authors/since/until to Typesense filter_by — post-filtering is now a correction step, not the primary filter (codex + opus suggestion) - NIP-10 root tag validation — reject events where client-supplied root diverges from server-resolved ancestry (codex finding #3) Clarity: - Consolidate #p gating into single P_GATED_KINDS check (opus suggestion #7) - filter.clone() → std::slice::from_ref(filter) (opus suggestion #1) - Remove no-op get_events_by_ids test, add debug_assert (opus #3, #5)
1 parent 473ca4d commit 09331f2

3 files changed

Lines changed: 127 additions & 112 deletions

File tree

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

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,7 @@ pub async fn get_events_by_ids(pool: &MySqlPool, ids: &[&[u8]]) -> Result<Vec<St
355355
if ids.is_empty() {
356356
return Ok(vec![]);
357357
}
358+
debug_assert!(ids.len() <= 500, "batch fetch should be bounded by caller");
358359

359360
let mut qb: QueryBuilder<sqlx::MySql> = QueryBuilder::new(
360361
"SELECT id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id \
@@ -575,17 +576,4 @@ pub(crate) fn uuid_from_bytes(bytes: &[u8]) -> Result<Uuid> {
575576
Uuid::from_slice(bytes).map_err(|e| DbError::InvalidData(format!("invalid UUID: {e}")))
576577
}
577578

578-
#[cfg(test)]
579-
mod tests {
580-
use super::*;
581-
582-
/// get_events_by_ids with an empty slice must return Ok([]) without hitting the DB.
583-
#[test]
584-
fn test_get_events_by_ids_empty_input() {
585-
// We can't call the async DB function without a pool, but we can verify
586-
// the early-return branch is correct by inspecting the logic directly.
587-
// The function returns Ok(vec![]) immediately when ids.is_empty().
588-
let ids: Vec<&[u8]> = vec![];
589-
assert!(ids.is_empty());
590-
}
591-
}
579+

‎crates/sprout-relay/src/handlers/event.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,11 @@ pub async fn handle_event(event: Event, conn: Arc<ConnectionState>, state: Arc<A
297297
return;
298298
}
299299
}
300+
} else if is_gift_wrap {
301+
// NIP-17 gift wraps are always global (channel_id = None).
302+
// A client-supplied h-tag is ignored — storing gift wraps channel-scoped
303+
// would let any channel subscriber read them, bypassing #p gating.
304+
None
300305
} else {
301306
extract_channel_id(&event)
302307
};
@@ -844,8 +849,8 @@ async fn resolve_nip10_thread_meta(
844849
chrono::DateTime::from_timestamp(parent_event.event.created_at.as_u64() as i64, 0)
845850
.unwrap_or_else(Utc::now);
846851

847-
// Validate root hex (effective root is resolved from parent metadata below).
848-
hex::decode(&root_hex).map_err(|_| "invalid root event ID hex".to_string())?;
852+
let client_root_bytes =
853+
hex::decode(&root_hex).map_err(|_| "invalid root event ID hex".to_string())?;
849854

850855
let parent_meta = state
851856
.db
@@ -856,6 +861,11 @@ async fn resolve_nip10_thread_meta(
856861
let (final_root_bytes, root_created, depth) = match parent_meta {
857862
Some(meta) => {
858863
let effective_root = meta.root_event_id.unwrap_or_else(|| parent_bytes.clone());
864+
// Reject if client-supplied root diverges from server-resolved root.
865+
// This prevents stored thread_metadata from contradicting wire-visible e-tags.
866+
if client_root_bytes != effective_root {
867+
return Err("root tag does not match thread ancestry".to_string());
868+
}
859869
let root_ts = if let Ok(Some(root_ev)) =
860870
state.db.get_event_by_id(&effective_root).await
861871
{
@@ -867,7 +877,11 @@ async fn resolve_nip10_thread_meta(
867877
(effective_root, root_ts, meta.depth + 1)
868878
}
869879
None => {
870-
// Parent has no thread metadata — it is the root.
880+
// Parent has no thread metadata — parent is the root.
881+
// For direct replies, client_root == parent is expected.
882+
if client_root_bytes != parent_bytes {
883+
return Err("root tag does not match thread ancestry".to_string());
884+
}
871885
(parent_bytes.clone(), parent_created, 1)
872886
}
873887
};

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

Lines changed: 108 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -89,47 +89,34 @@ pub async fn handle_req(
8989
// #h presence to prevent mixed-filter bypass: a client could send
9090
// [{#h:..., kinds:[44100]}, {authors:[...]}] which resolves to global scope
9191
// but would skip the #p check if we only looked at per-filter #h tags.
92+
// Kinds that are globally stored and require #p = authed pubkey.
93+
// Without this, a client could subscribe to another user's membership
94+
// notifications or gift-wrapped DMs.
95+
const P_GATED_KINDS: [u32; 3] = [
96+
KIND_MEMBER_ADDED_NOTIFICATION,
97+
KIND_MEMBER_REMOVED_NOTIFICATION,
98+
KIND_GIFT_WRAP,
99+
];
100+
92101
if channel_id.is_none() {
93102
let authed_pubkey_hex = hex::encode(&pubkey_bytes);
94103
let p_tag = nostr::SingleLetterTag::lowercase(nostr::Alphabet::P);
95104

96105
for filter in &filters {
97-
// Membership notifications (kind:44100/44101) require #p = authed pubkey.
98-
let can_match_membership = filter.kinds.as_ref().is_none_or(|ks| {
99-
ks.iter().any(|k| {
100-
let ku = k.as_u16() as u32;
101-
ku == KIND_MEMBER_ADDED_NOTIFICATION || ku == KIND_MEMBER_REMOVED_NOTIFICATION
102-
})
106+
let can_match_p_gated = filter.kinds.as_ref().is_none_or(|ks| {
107+
ks.iter()
108+
.any(|k| P_GATED_KINDS.contains(&(k.as_u16() as u32)))
103109
});
104-
if can_match_membership {
110+
if can_match_p_gated {
105111
// ALL #p values must match the authenticated pubkey — prevents
106-
// a client from sneaking in a victim's pubkey alongside their own
107-
// (e.g. #p:[my_key, victim_key]) to receive the victim's notifications.
108-
let has_matching_p = filter.generic_tags.get(&p_tag).is_some_and(|values| {
109-
!values.is_empty() && values.iter().all(|v| *v == authed_pubkey_hex)
110-
});
111-
if !has_matching_p {
112-
conn.send(RelayMessage::closed(
113-
&sub_id,
114-
"restricted: membership notifications require #p matching your pubkey",
115-
));
116-
return;
117-
}
118-
}
119-
120-
// NIP-17 gift wraps (kind:1059) require #p = authed pubkey.
121-
// Same pattern as membership notifications — prevents reading others' DMs.
122-
let can_match_gift_wrap = filter.kinds.as_ref().is_none_or(|ks| {
123-
ks.iter().any(|k| k.as_u16() as u32 == KIND_GIFT_WRAP)
124-
});
125-
if can_match_gift_wrap {
112+
// a client from sneaking in a victim's pubkey alongside their own.
126113
let has_matching_p = filter.generic_tags.get(&p_tag).is_some_and(|values| {
127114
!values.is_empty() && values.iter().all(|v| *v == authed_pubkey_hex)
128115
});
129116
if !has_matching_p {
130117
conn.send(RelayMessage::closed(
131118
&sub_id,
132-
"restricted: gift-wrap events require #p matching your pubkey",
119+
"restricted: p-gated events require #p matching your pubkey",
133120
));
134121
return;
135122
}
@@ -235,6 +222,9 @@ pub async fn handle_req(
235222

236223
/// Handle a NIP-50 search REQ: query Typesense, fetch full events, deliver results, EOSE.
237224
/// Search subscriptions are one-shot — no persistent subscription is registered.
225+
/// Maximum Typesense pages to fetch per filter (prevents unbounded loops).
226+
const MAX_SEARCH_PAGES: u32 = 5;
227+
238228
async fn handle_search_req(
239229
sub_id: &str,
240230
filters: &[Filter],
@@ -247,7 +237,6 @@ async fn handle_search_req(
247237
return;
248238
}
249239

250-
// Build channel scope filter for Typesense
251240
let channel_filter = {
252241
let ids: Vec<String> = accessible_channels.iter().map(|id| id.to_string()).collect();
253242
format!("channel_id:=[{}]", ids.join(","))
@@ -266,7 +255,8 @@ async fn handle_search_req(
266255
.map(|l| (l as u32).min(MAX_HISTORICAL_LIMIT as u32))
267256
.unwrap_or(MAX_HISTORICAL_LIMIT as u32);
268257

269-
// Build Typesense filter_by — channel scope + optional kind constraint
258+
// Push as many NIP-01 constraints into Typesense as possible so
259+
// post-filtering is a correction step, not the primary filter.
270260
let mut filter_parts = vec![channel_filter.clone()];
271261
if let Some(ref kinds) = filter.kinds {
272262
if !kinds.is_empty() {
@@ -275,85 +265,108 @@ async fn handle_search_req(
275265
filter_parts.push(format!("kind:=[{}]", kind_vals.join(",")));
276266
}
277267
}
278-
279-
let search_query = sprout_search::SearchQuery {
280-
q: search_text,
281-
filter_by: Some(filter_parts.join(" && ")),
282-
sort_by: None, // Typesense default = relevance (text_match score)
283-
page: 1,
284-
per_page: limit,
285-
};
286-
287-
let search_result = match state.search.search(&search_query).await {
288-
Ok(r) => r,
289-
Err(e) => {
290-
warn!(sub_id = %sub_id, "NIP-50 search failed: {e}");
291-
continue;
268+
if let Some(ref authors) = filter.authors {
269+
if !authors.is_empty() {
270+
let author_vals: Vec<String> = authors.iter().map(|a| a.to_hex()).collect();
271+
filter_parts.push(format!("pubkey:=[{}]", author_vals.join(",")));
292272
}
293-
};
294-
295-
// Collect event IDs from search hits (skip hits with no channel_id)
296-
let hit_ids: Vec<Vec<u8>> = search_result
297-
.hits
298-
.iter()
299-
.filter(|h| h.channel_id.is_some())
300-
.filter_map(|h| hex::decode(&h.event_id).ok())
301-
.filter(|bytes| bytes.len() == 32)
302-
.collect();
303-
304-
if hit_ids.is_empty() {
305-
continue;
273+
}
274+
if let Some(since) = filter.since {
275+
filter_parts.push(format!("created_at:>={}", since.as_u64()));
276+
}
277+
if let Some(until) = filter.until {
278+
filter_parts.push(format!("created_at:<={}", until.as_u64()));
306279
}
307280

308-
// Batch-fetch full events from DB
309-
let id_refs: Vec<&[u8]> = hit_ids.iter().map(|b| b.as_slice()).collect();
310-
let events = match state.db.get_events_by_ids(&id_refs).await {
311-
Ok(evs) => evs,
312-
Err(e) => {
313-
warn!(sub_id = %sub_id, "NIP-50 batch fetch failed: {e}");
314-
continue;
281+
let filter_by = filter_parts.join(" && ");
282+
283+
// Paginate: keep fetching pages until we've emitted `limit` results
284+
// or exhausted the search result set. This ensures post-filtering
285+
// doesn't silently reduce the result count below the requested limit.
286+
let mut emitted: u32 = 0;
287+
let per_page = limit.min(100); // Typesense max per_page is typically 250
288+
289+
for page in 1..=MAX_SEARCH_PAGES {
290+
if emitted >= limit {
291+
break;
315292
}
316-
};
317293

318-
// Build a lookup map for preserving Typesense relevance order
319-
let event_map: std::collections::HashMap<[u8; 32], &sprout_core::StoredEvent> = events
320-
.iter()
321-
.map(|ev| (ev.event.id.to_bytes(), ev))
322-
.collect();
323-
324-
// Deliver in Typesense relevance order
325-
for hit_id in &hit_ids {
326-
let id_array: [u8; 32] = match hit_id.as_slice().try_into() {
327-
Ok(a) => a,
328-
Err(_) => continue,
294+
let search_query = sprout_search::SearchQuery {
295+
q: search_text.clone(),
296+
filter_by: Some(filter_by.clone()),
297+
sort_by: None, // Typesense default = relevance (text_match score)
298+
page,
299+
per_page,
329300
};
330301

331-
let stored = match event_map.get(&id_array) {
332-
Some(ev) => ev,
333-
None => continue, // Deleted between search and fetch
302+
let search_result = match state.search.search(&search_query).await {
303+
Ok(r) => r,
304+
Err(e) => {
305+
warn!(sub_id = %sub_id, "NIP-50 search failed: {e}");
306+
break;
307+
}
334308
};
335309

336-
if !seen_ids.insert(stored.event.id) {
337-
continue; // Cross-filter dedup
338-
}
310+
let page_empty = search_result.hits.is_empty();
311+
let exhausted = (page as u64) * (per_page as u64) >= search_result.found;
312+
313+
let hit_ids: Vec<Vec<u8>> = search_result
314+
.hits
315+
.into_iter()
316+
.filter(|h| h.channel_id.is_some())
317+
.filter_map(|h| hex::decode(&h.event_id).ok())
318+
.filter(|bytes| bytes.len() == 32)
319+
.collect();
320+
321+
if !hit_ids.is_empty() {
322+
let id_refs: Vec<&[u8]> = hit_ids.iter().map(|b| b.as_slice()).collect();
323+
let events = match state.db.get_events_by_ids(&id_refs).await {
324+
Ok(evs) => evs,
325+
Err(e) => {
326+
warn!(sub_id = %sub_id, "NIP-50 batch fetch failed: {e}");
327+
break;
328+
}
329+
};
339330

340-
// NIP-01 post-filtering: check ids, since, until, generic tags against THIS filter.
341-
// Use single-element slice so we match against only this filter's constraints,
342-
// not the OR of all filters (which could let a hit from filter A pass filter B's
343-
// non-search fields).
344-
if !filters_match(&[filter.clone()], stored) {
345-
continue;
346-
}
331+
let event_map: std::collections::HashMap<[u8; 32], &sprout_core::StoredEvent> =
332+
events
333+
.iter()
334+
.map(|ev| (ev.event.id.to_bytes(), ev))
335+
.collect();
347336

348-
// Access check (belt and suspenders — Typesense already filtered by channel)
349-
if let Some(ch_id) = stored.channel_id {
350-
if !accessible_channels.contains(&ch_id) {
351-
continue;
337+
for hit_id in &hit_ids {
338+
if emitted >= limit {
339+
break;
340+
}
341+
let id_array: [u8; 32] = match hit_id.as_slice().try_into() {
342+
Ok(a) => a,
343+
Err(_) => continue,
344+
};
345+
let stored = match event_map.get(&id_array) {
346+
Some(ev) => ev,
347+
None => continue,
348+
};
349+
if !seen_ids.insert(stored.event.id) {
350+
continue;
351+
}
352+
// NIP-01 post-filtering against THIS filter only (not OR of all filters).
353+
if !filters_match(std::slice::from_ref(filter), stored) {
354+
continue;
355+
}
356+
if let Some(ch_id) = stored.channel_id {
357+
if !accessible_channels.contains(&ch_id) {
358+
continue;
359+
}
360+
}
361+
if !conn.send(RelayMessage::event(sub_id, &stored.event)) {
362+
return;
363+
}
364+
emitted += 1;
352365
}
353366
}
354367

355-
if !conn.send(RelayMessage::event(sub_id, &stored.event)) {
356-
return; // Connection closed
368+
if page_empty || exhausted {
369+
break;
357370
}
358371
}
359372
}

0 commit comments

Comments
 (0)