Skip to content

Commit 29368cf

Browse files
authored
Harden relay attack surfaces (#1369)
1 parent 2722ce4 commit 29368cf

20 files changed

Lines changed: 1228 additions & 200 deletions

File tree

‎.env.example‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,16 @@ RELAY_URL=ws://localhost:3000
5858
# {path}/{owner_hex}/{repo_id}.git/. Default: ./repos (relative to CWD).
5959
# Set an absolute path to keep repos stable across worktrees.
6060
# BUZZ_GIT_REPO_PATH=./repos
61+
# BUZZ_GIT_MAX_PACK_BYTES=524288000
62+
# BUZZ_GIT_MAX_REPO_BYTES=1048576000
63+
64+
# -----------------------------------------------------------------------------
65+
# Media Upload Admission
66+
# -----------------------------------------------------------------------------
67+
# Bound image/video parser and storage work admitted by one relay process.
68+
# BUZZ_MEDIA_MAX_CONCURRENT_UPLOADS=8
69+
# BUZZ_MEDIA_MAX_CONCURRENT_UPLOADS_PER_PUBKEY=2
70+
# BUZZ_MEDIA_UPLOADS_PER_MINUTE=30
6171

6272
# -----------------------------------------------------------------------------
6373
# Ephemeral Channels (TTL testing)

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

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use uuid::Uuid;
1111

1212
use buzz_core::kind::{
1313
event_kind_i32, is_ephemeral, is_parameterized_replaceable, KIND_AUTH, KIND_EVENT_REMINDER,
14+
KIND_HUDDLE_STARTED,
1415
};
1516
use buzz_core::{CommunityId, StoredEvent};
1617

@@ -105,6 +106,16 @@ impl EventQuery {
105106
/// anything beyond this is either a bug or abuse.
106107
pub const D_TAG_MAX_LEN: usize = 1024;
107108

109+
/// Maximum huddle-start content bytes considered by the parent-link lookup.
110+
///
111+
/// The canonical content is a small JSON object containing one UUID. Rejecting
112+
/// oversized candidates keeps a malformed lifecycle event from making audio
113+
/// admission pull large text rows into memory.
114+
const HUDDLE_LINK_CONTENT_MAX_BYTES: i64 = 512;
115+
/// Maximum candidate rows inspected after SQL prefiltering by parent, creator,
116+
/// kind, and UUID substring.
117+
const HUDDLE_LINK_CANDIDATE_LIMIT: i64 = 32;
118+
108119
/// Extract the `d_tag` value for storage.
109120
///
110121
/// For NIP-33 parameterized replaceable events (kind 30000–39999): returns the first
@@ -150,6 +161,62 @@ pub fn extract_not_before(event: &Event) -> Option<i64> {
150161
})
151162
}
152163

164+
fn huddle_started_content_links(content: &str, ephemeral_channel_id: Uuid) -> bool {
165+
serde_json::from_str::<serde_json::Value>(content)
166+
.ok()
167+
.and_then(|value| {
168+
value
169+
.get("ephemeral_channel_id")
170+
.and_then(serde_json::Value::as_str)
171+
.and_then(|id| Uuid::parse_str(id).ok())
172+
})
173+
.is_some_and(|id| id == ephemeral_channel_id)
174+
}
175+
176+
/// Return whether `parent_channel_id` has a creator-signed huddle-start event
177+
/// that links to `ephemeral_channel_id`.
178+
///
179+
/// The creator constraint matters: a member of some unrelated channel can post
180+
/// their own kind:48100 event there, but they cannot sign as the creator of the
181+
/// target ephemeral channel.
182+
pub async fn huddle_started_link_exists(
183+
pool: &PgPool,
184+
community_id: CommunityId,
185+
parent_channel_id: Uuid,
186+
ephemeral_channel_id: Uuid,
187+
creator_pubkey: &[u8],
188+
) -> Result<bool> {
189+
let uuid_needle = format!("%{}%", ephemeral_channel_id);
190+
let candidates: Vec<String> = sqlx::query_scalar(
191+
r#"
192+
SELECT content
193+
FROM events
194+
WHERE deleted_at IS NULL
195+
AND community_id = $1
196+
AND channel_id = $2
197+
AND kind = $3
198+
AND pubkey = $4
199+
AND octet_length(content) <= $5
200+
AND content ILIKE $6
201+
ORDER BY created_at DESC, id ASC
202+
LIMIT $7
203+
"#,
204+
)
205+
.bind(community_id.as_uuid())
206+
.bind(parent_channel_id)
207+
.bind(KIND_HUDDLE_STARTED as i32)
208+
.bind(creator_pubkey)
209+
.bind(HUDDLE_LINK_CONTENT_MAX_BYTES)
210+
.bind(uuid_needle)
211+
.bind(HUDDLE_LINK_CANDIDATE_LIMIT)
212+
.fetch_all(pool)
213+
.await?;
214+
215+
Ok(candidates
216+
.iter()
217+
.any(|content| huddle_started_content_links(content, ephemeral_channel_id)))
218+
}
219+
153220
/// Insert a Nostr event. Rejects AUTH and ephemeral kinds.
154221
///
155222
/// Returns `(StoredEvent, was_inserted)` — `was_inserted` is `false` on duplicate.
@@ -1709,4 +1776,21 @@ mod tests {
17091776
"A/X must be reclaimable after its own release"
17101777
);
17111778
}
1779+
1780+
#[test]
1781+
fn huddle_started_content_requires_matching_ephemeral_field() {
1782+
let channel_id = Uuid::new_v4();
1783+
let matching = serde_json::json!({
1784+
"ephemeral_channel_id": channel_id.to_string(),
1785+
})
1786+
.to_string();
1787+
assert!(huddle_started_content_links(&matching, channel_id));
1788+
1789+
let wrong_field = serde_json::json!({
1790+
"other": channel_id.to_string(),
1791+
})
1792+
.to_string();
1793+
assert!(!huddle_started_content_links(&wrong_field, channel_id));
1794+
assert!(!huddle_started_content_links("not-json", channel_id));
1795+
}
17121796
}

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,25 @@ impl Db {
413413
event::count_events(&self.pool, q).await
414414
}
415415

416+
/// Return whether a creator-signed huddle-start event links a parent
417+
/// channel to an ephemeral huddle channel.
418+
pub async fn huddle_started_link_exists(
419+
&self,
420+
community_id: CommunityId,
421+
parent_channel_id: Uuid,
422+
ephemeral_channel_id: Uuid,
423+
creator_pubkey: &[u8],
424+
) -> Result<bool> {
425+
event::huddle_started_link_exists(
426+
&self.pool,
427+
community_id,
428+
parent_channel_id,
429+
ephemeral_channel_id,
430+
creator_pubkey,
431+
)
432+
.await
433+
}
434+
416435
/// Fetch the latest replaceable event for a (kind, pubkey) pair.
417436
///
418437
/// Uses canonical NIP-16 ordering: `created_at DESC, id ASC`.
@@ -1542,6 +1561,31 @@ impl Db {
15421561
.await
15431562
}
15441563

1564+
/// Insert or update a workflow using its NIP-33 `d`-tag UUID.
1565+
#[allow(clippy::too_many_arguments)]
1566+
pub async fn upsert_workflow(
1567+
&self,
1568+
community_id: CommunityId,
1569+
id: Uuid,
1570+
channel_id: Option<Uuid>,
1571+
owner_pubkey: &[u8],
1572+
name: &str,
1573+
definition_json: &str,
1574+
definition_hash: &[u8],
1575+
) -> Result<()> {
1576+
workflow::upsert_workflow(
1577+
&self.pool,
1578+
community_id,
1579+
id,
1580+
channel_id,
1581+
owner_pubkey,
1582+
name,
1583+
definition_json,
1584+
definition_hash,
1585+
)
1586+
.await
1587+
}
1588+
15451589
/// Fetch a single workflow by ID, scoped to its community.
15461590
pub async fn get_workflow(
15471591
&self,
@@ -1679,6 +1723,16 @@ impl Db {
16791723
workflow::delete_workflow(&self.pool, community_id, id).await
16801724
}
16811725

1726+
/// Delete a workflow only when it belongs to the provided owner.
1727+
pub async fn delete_workflow_for_owner(
1728+
&self,
1729+
community_id: CommunityId,
1730+
id: Uuid,
1731+
owner_pubkey: &[u8],
1732+
) -> Result<()> {
1733+
workflow::delete_workflow_for_owner(&self.pool, community_id, id, owner_pubkey).await
1734+
}
1735+
16821736
/// Find a workflow by owner pubkey and name within a community. Used for
16831737
/// NIP-09 a-tag deletion where the d-tag is the workflow name (not UUID).
16841738
pub async fn find_workflow_by_owner_and_name(

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

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,56 @@ pub async fn create_workflow(
301301
Ok(id)
302302
}
303303

304+
/// Insert or update a workflow at the caller-supplied NIP-33 `d`-tag UUID.
305+
///
306+
/// Updates are allowed only when the existing row has the same owner and
307+
/// channel. That keeps a learned workflow UUID from becoming a cross-user or
308+
/// cross-channel overwrite primitive while still making retries idempotent.
309+
#[allow(clippy::too_many_arguments)]
310+
pub async fn upsert_workflow(
311+
pool: &PgPool,
312+
community_id: CommunityId,
313+
id: Uuid,
314+
channel_id: Option<Uuid>,
315+
owner_pubkey: &[u8],
316+
name: &str,
317+
definition_json: &str,
318+
definition_hash: &[u8],
319+
) -> Result<()> {
320+
let row = sqlx::query(
321+
r#"
322+
INSERT INTO workflows
323+
(community_id, id, name, owner_pubkey, channel_id, definition, definition_hash, status, enabled)
324+
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, 'active', TRUE)
325+
ON CONFLICT (community_id, id) DO UPDATE
326+
SET name = EXCLUDED.name,
327+
definition = EXCLUDED.definition,
328+
definition_hash = EXCLUDED.definition_hash,
329+
updated_at = NOW()
330+
WHERE workflows.owner_pubkey = EXCLUDED.owner_pubkey
331+
AND workflows.channel_id IS NOT DISTINCT FROM EXCLUDED.channel_id
332+
RETURNING id
333+
"#,
334+
)
335+
.bind(community_id.as_uuid())
336+
.bind(id)
337+
.bind(name)
338+
.bind(owner_pubkey)
339+
.bind(channel_id)
340+
.bind(definition_json)
341+
.bind(definition_hash)
342+
.fetch_optional(pool)
343+
.await?;
344+
345+
if row.is_none() {
346+
return Err(DbError::AccessDenied(format!(
347+
"workflow {id} belongs to a different owner or channel"
348+
)));
349+
}
350+
351+
Ok(())
352+
}
353+
304354
/// Fetch a single workflow by ID, scoped to its community.
305355
///
306356
/// `workflows` is keyed `(community_id, id)`; the same workflow UUID can exist
@@ -656,6 +706,34 @@ pub async fn delete_workflow(pool: &PgPool, community_id: CommunityId, id: Uuid)
656706
Ok(())
657707
}
658708

709+
/// Delete a workflow only when it belongs to `owner_pubkey`.
710+
///
711+
/// Used by event-driven deletion paths where the workflow UUID is attacker
712+
/// controlled. Keeping the owner predicate in the DELETE statement avoids a
713+
/// check-then-delete race and ensures a caller cannot delete another user's
714+
/// workflow just by learning its UUID.
715+
pub async fn delete_workflow_for_owner(
716+
pool: &PgPool,
717+
community_id: CommunityId,
718+
id: Uuid,
719+
owner_pubkey: &[u8],
720+
) -> Result<()> {
721+
let affected = sqlx::query(
722+
"DELETE FROM workflows WHERE community_id = $1 AND id = $2 AND owner_pubkey = $3",
723+
)
724+
.bind(community_id.as_uuid())
725+
.bind(id)
726+
.bind(owner_pubkey)
727+
.execute(pool)
728+
.await?
729+
.rows_affected();
730+
731+
if affected == 0 {
732+
return Err(DbError::NotFound(format!("workflow {id}")));
733+
}
734+
Ok(())
735+
}
736+
659737
// -- Workflow Run CRUD --------------------------------------------------------
660738

661739
/// Insert a new workflow run. Returns the new run's UUID.

‎crates/buzz-media/src/error.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ pub enum MediaError {
5656
TokenRevoked,
5757
#[error("pubkey mismatch")]
5858
PubkeyMismatch,
59+
#[error("upload rate limit exceeded")]
60+
UploadRateLimitExceeded,
61+
#[error("upload concurrency limit reached")]
62+
UploadConcurrencyLimitReached,
5963
/// Video codec is not H.264 (avc1).
6064
#[error("unsupported video codec: only H.264 (avc1) is accepted")]
6165
WrongCodec,
@@ -133,6 +137,9 @@ impl IntoResponse for MediaError {
133137
}
134138
Self::InsufficientScope => (StatusCode::FORBIDDEN, self.to_string()),
135139
Self::RelayMembershipRequired => (StatusCode::FORBIDDEN, self.to_string()),
140+
Self::UploadRateLimitExceeded | Self::UploadConcurrencyLimitReached => {
141+
(StatusCode::TOO_MANY_REQUESTS, self.to_string())
142+
}
136143
Self::UnsupportedContainer => (StatusCode::UNSUPPORTED_MEDIA_TYPE, self.to_string()),
137144
Self::WrongCodec
138145
| Self::DurationTooLong

‎crates/buzz-relay/src/api/bridge.rs‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -740,10 +740,16 @@ pub async fn count_events(
740740
} else {
741741
// Fallback: query + post-filter for non-pushable constraints.
742742
let mut q = query;
743-
q.limit = Some(100_000);
744-
q.max_limit = Some(100_000);
743+
crate::handlers::req::apply_count_fallback_limit(&mut q);
745744
match state.db.query_events(&q).await {
746745
Ok(stored_events) => {
746+
if crate::handlers::req::count_fallback_exceeded(stored_events.len()) {
747+
metrics::counter!("buzz_count_fallback_rejections_total").increment(1);
748+
return Err(api_error(
749+
StatusCode::BAD_REQUEST,
750+
"count filter requires narrower constraints",
751+
));
752+
}
747753
for se in stored_events {
748754
if !buzz_core::filter::filters_match(std::slice::from_ref(filter), &se)
749755
{
@@ -790,11 +796,17 @@ pub async fn count_events(
790796
}
791797
}
792798
} else {
793-
// Fallback: query with high limit + post-filter for correctness.
794-
query.limit = Some(100_000);
795-
query.max_limit = Some(100_000);
799+
// Fallback: query a bounded candidate set + post-filter.
800+
crate::handlers::req::apply_count_fallback_limit(&mut query);
796801
match state.db.query_events(&query).await {
797802
Ok(stored_events) => {
803+
if crate::handlers::req::count_fallback_exceeded(stored_events.len()) {
804+
metrics::counter!("buzz_count_fallback_rejections_total").increment(1);
805+
return Err(api_error(
806+
StatusCode::BAD_REQUEST,
807+
"count filter requires narrower constraints",
808+
));
809+
}
798810
for se in stored_events {
799811
if !buzz_core::filter::filters_match(std::slice::from_ref(filter), &se)
800812
{

0 commit comments

Comments
 (0)