Skip to content

Commit 27b5a29

Browse files
ARTclaude
andcommitted
fix(relay): bound HTTP typing by serialized size; test the write fence
The 1 KiB cap summed content and tag values only, so an event with an h tag plus many empty tags counted as a few bytes while its JSON could reach the HTTP body limit. Measure the serialized event instead (2 KiB, which leaves room for id, pubkey and sig on a ~600-byte real indicator). The oversize test now covers content, one large tag value, and 10k empty tags. Add a test for the community write fence on the HTTP typing path. Over HTTP a quiescing community's host no longer binds, so the test binds the tenant first and then quiesces, which is the window the fence guards. Update comments and docs that said HTTP rejects every ephemeral kind; only typing (kind:20002) is accepted. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: ART <ea39c1c8acf57180161ef4ba4ed68abf8589f5291956b909a5aa991fc66664ca@buzz.block.builderlab.xyz>
1 parent 2603c7b commit 27b5a29

7 files changed

Lines changed: 109 additions & 29 deletions

File tree

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,8 @@ fn current_working_directory() -> Result<String> {
9696

9797
/// Publish a kind:20001 presence update event via the WebSocket connection.
9898
///
99-
/// Ephemeral kinds (20000-29999) are rejected by the HTTP bridge, so presence
100-
/// updates must be routed through the WS path.
99+
/// The HTTP bridge rejects presence (kind:20001); typing (kind:20002) is the
100+
/// only ephemeral kind it accepts. Presence updates must use the WS path.
101101
///
102102
/// Content is a bare status string (`"online"`, `"away"`, `"offline"`) matching
103103
/// the desktop client's format. The relay stores this in Redis and synthesizes

‎crates/buzz-cli/TESTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ buzz users presence --pubkeys "$MY_PUBKEY" | jq .
333333
buzz users set-presence --status online | jq .
334334
buzz users set-presence --status away | jq .
335335
buzz users set-presence --status offline | jq .
336-
# Note: set-presence may fail — kind:20001 is ephemeral and rejected by the HTTP bridge
336+
# Note: set-presence may fail — the HTTP bridge accepts kind:20001 (presence) only via WebSocket
337337

338338
# users set-status — NIP-38 kind:30315 on the d:general coordinate
339339
buzz users set-status --text "reviewing PRs" --emoji "🔍" | jq .

‎crates/buzz-cli/src/client.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1174,7 +1174,8 @@ impl BuzzClient {
11741174

11751175
/// Publish an ephemeral event via WebSocket with NIP-42 authentication.
11761176
///
1177-
/// The relay rejects ephemeral kinds (20000–29999) over HTTP. Delegates to
1177+
/// The relay accepts only typing (kind:20002) of the ephemeral kinds
1178+
/// (20000–29999) over HTTP. Delegates to
11781179
/// `buzz_ws_client::publish_event` which handles connect, NIP-42 auth,
11791180
/// EVENT send, OK wait, and graceful close.
11801181
pub async fn publish_ephemeral_event(&self, event: nostr::Event) -> Result<String, CliError> {

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

Lines changed: 92 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -207,17 +207,99 @@ async fn typing_without_channel_is_rejected() {
207207
#[ignore = "requires Postgres and Redis"]
208208
async fn oversized_typing_is_rejected() {
209209
let f = Fixture::new().await;
210-
let event = EventBuilder::new(Kind::Custom(20002), "x".repeat(2048))
211-
.tags([Tag::parse(["h".to_string(), f.channel.to_string()]).unwrap()])
212-
.sign_with_keys(&f.member)
210+
let h = || Tag::parse(["h".to_string(), f.channel.to_string()]).unwrap();
211+
let empty = || Tag::parse([String::new()]).unwrap();
212+
let cases = [
213+
("content", "x".repeat(2048), vec![h()]),
214+
(
215+
"tag value",
216+
String::new(),
217+
vec![
218+
h(),
219+
Tag::parse(["e".to_string(), "x".repeat(2048)]).unwrap(),
220+
],
221+
),
222+
(
223+
"empty tags",
224+
String::new(),
225+
std::iter::once(h())
226+
.chain(std::iter::repeat_with(empty).take(10_000))
227+
.collect(),
228+
),
229+
];
230+
for (case, content, tags) in cases {
231+
let event = EventBuilder::new(Kind::Custom(20002), content)
232+
.tags(tags)
233+
.sign_with_keys(&f.member)
234+
.unwrap();
235+
let (status, body) = f.post(&f.member, &event).await;
236+
assert_eq!(
237+
status,
238+
axum::http::StatusCode::BAD_REQUEST,
239+
"{case}: {body}"
240+
);
241+
assert!(
242+
body["error"]
243+
.as_str()
244+
.unwrap_or_default()
245+
.contains("too large"),
246+
"{case}: {body}"
247+
);
248+
}
249+
}
250+
251+
#[tokio::test]
252+
#[ignore = "requires Postgres and Redis"]
253+
async fn fenced_community_typing_is_rejected() {
254+
use futures::StreamExt;
255+
let f = Fixture::new().await;
256+
// Over HTTP a quiescing community's host no longer binds (404), so the
257+
// fence only matters when quiescing starts after the request has bound its
258+
// tenant. Reproduce that order: bind first, then quiesce, then publish.
259+
let tenant = crate::tenant::bind_community(&f.state.db, &f.host)
260+
.await
213261
.unwrap();
214-
let (status, body) = f.post(&f.member, &event).await;
215-
assert_eq!(status, axum::http::StatusCode::BAD_REQUEST, "{body}");
262+
// Enter the deletion executor's transaction scope in this disposable
263+
// fixture; the DB rejects unfenced ad-hoc state changes.
264+
let mut tx = f.pool.begin().await.unwrap();
265+
sqlx::query("SELECT set_config('buzz.deletion_executor_community', $1, true), set_config('buzz.deletion_fence_generation', '0', true)")
266+
.bind(f.community.to_string())
267+
.execute(&mut *tx)
268+
.await
269+
.unwrap();
270+
sqlx::query("UPDATE communities SET deletion_state = 'quiescing' WHERE id = $1")
271+
.bind(f.community.as_uuid())
272+
.execute(&mut *tx)
273+
.await
274+
.unwrap();
275+
tx.commit().await.unwrap();
276+
277+
let topic = buzz_pubsub::EventTopicKey {
278+
community_id: f.community,
279+
topic: buzz_pubsub::EventTopic::Channel(f.channel),
280+
}
281+
.redis_channel();
282+
let client = redis::Client::open(f.state.config.redis_url.as_str()).unwrap();
283+
let mut pubsub = client.get_async_pubsub().await.unwrap();
284+
pubsub.subscribe(&topic).await.unwrap();
285+
286+
let err = crate::handlers::event::publish_http_typing(
287+
&f.state,
288+
&tenant,
289+
f.typing(&f.member, Some(f.channel)),
290+
f.member.public_key(),
291+
)
292+
.await
293+
.unwrap_err();
216294
assert!(
217-
body["error"]
218-
.as_str()
219-
.unwrap_or_default()
220-
.contains("too large"),
221-
"{body}"
295+
matches!(&err, IngestError::Rejected(msg) if msg == "restricted: community writes are fenced"),
296+
"{err:?}"
297+
);
298+
let mut messages = pubsub.into_on_message();
299+
assert!(
300+
tokio::time::timeout(std::time::Duration::from_millis(500), messages.next())
301+
.await
302+
.is_err(),
303+
"fenced typing indicator must not be published"
222304
);
223305
}

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

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,11 +1056,13 @@ async fn publish_channel_ephemeral(
10561056
Ok(())
10571057
}
10581058

1059-
/// Upper bound on content plus tag values for an HTTP typing indicator.
1060-
/// Real indicators carry empty content and at most three short tags (`h`,
1061-
/// root `e`, reply `e`, roughly 250 bytes). Without a cap a member could post
1062-
/// up to the HTTP body limit and have it fanned out to every subscriber.
1063-
const MAX_HTTP_TYPING_BYTES: usize = 1024;
1059+
/// Upper bound on the serialized JSON of an HTTP typing indicator. Real
1060+
/// indicators carry empty content and at most three short tags (`h`, root
1061+
/// `e`, reply `e`), about 600 bytes with id, pubkey and sig. Measuring the
1062+
/// serialized event, not just content and tag values, also counts tag
1063+
/// structure, so many empty tags cannot slip a near-body-limit event past the
1064+
/// cap and into fan-out to every subscriber.
1065+
const MAX_HTTP_TYPING_BYTES: usize = 2048;
10641066

10651067
/// Publishes a typing indicator (kind:20002) submitted through HTTP
10661068
/// `POST /events`, for clients that sign but hold no WebSocket, such as
@@ -1081,16 +1083,9 @@ pub(crate) async fn publish_http_typing(
10811083
let ch_id = super::ingest::extract_channel_id(&event).ok_or_else(|| {
10821084
IngestError::Rejected("invalid: typing indicator needs a channel UUID h tag".into())
10831085
})?;
1084-
let size = event.content.len()
1085-
+ event
1086-
.tags
1087-
.iter()
1088-
.flat_map(|tag| tag.as_slice())
1089-
.map(String::len)
1090-
.sum::<usize>();
1091-
if size > MAX_HTTP_TYPING_BYTES {
1086+
if nostr::JsonUtil::as_json(&event).len() > MAX_HTTP_TYPING_BYTES {
10921087
return Err(IngestError::Rejected(format!(
1093-
"invalid: typing indicator too large (max {MAX_HTTP_TYPING_BYTES} bytes of content and tags)"
1088+
"invalid: typing indicator too large (max {MAX_HTTP_TYPING_BYTES} bytes serialized)"
10941089
)));
10951090
}
10961091
let event_clone = event.clone();

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2390,6 +2390,8 @@ async fn ingest_event_inner(
23902390
));
23912391
}
23922392

2393+
// Typing indicators (kind:20002) never reach this gate: the HTTP bridge
2394+
// routes them to `publish_http_typing` before ingest.
23932395
if auth.is_http() && (kind_u32 == KIND_GIFT_WRAP || kind_u32 == KIND_PRESENCE_UPDATE) {
23942396
return Err(IngestError::Rejected(format!(
23952397
"invalid: kind {kind_u32} is only accepted via WebSocket"

‎desktop/src-tauri/src/managed_agents/nest_skill.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ buzz messages send --channel <UUID> \
122122
## Gotchas
123123

124124
1. **`feed get` sorts newest-first** — every other list command sorts oldest-first. Don't assume consistent sort order.
125-
2. **`users set-presence` is broken** — sends ephemeral kind:20001 via HTTP POST; relay rejects ephemeral kinds over HTTP. Will fail until WebSocket support is added.
125+
2. **`users set-presence` is broken** — sends ephemeral kind:20001 via HTTP POST; relay accepts presence only over WebSocket (typing, kind:20002, is the one ephemeral kind HTTP accepts). Will fail until WebSocket support is added.
126126
3. **`workflow runs` always returns `[]`** — run history lives in the relay's database, not as Nostr events.
127127
4. **`dms open` returns `dm_id`** — use this value as `--channel` for subsequent `messages send/get` commands on that DM.
128128
5. **Content max 65,536 bytes** (exit 1 if exceeded). Diffs auto-truncate at 61,440 bytes at a hunk boundary.

0 commit comments

Comments
 (0)