Skip to content

Commit 516946f

Browse files
tlongwell-blocknpub1jmc9dt2lyvzu3h0kxlwxt5zg4fxp9476awyxw6gwxn72g6cw7exqs64whmTyler Longwell
authored
fix(security): enforce durable community ban on NIP-43 relay-admin kinds 9030-9033 (#3128)
## Summary `ingest_event`'s durable write-path restriction gate exempts NIP-43 relay-admin kinds **9030–9033**, so that a *timed-out* admin keeps administrative capability. That exemption was ban-blind, and `handle_relay_admin_event` performed no restriction check of its own. A **banned** admin or owner could still add members, remove members, change member roles, and set the workspace icon by posting a signed NIP-98 request to `POST /events`. No open WebSocket required. Reported externally by **Bilal Syed** (also filed publicly as #3020 before he read `SECURITY.md`). Verified true, reproduced live, and found slightly worse than reported. Same class as BUZZ-SEC-007, which PR #1915 closed for moderation command kinds 9040–9044. That fix was never extended to the 9030 range. ## Why it worked - `handlers/ingest.rs:1639` skipped the restriction check when `is_relay_admin_kind(kind)` was true. - `handlers/relay_admin.rs` did a freshness check and a role lookup only — zero restriction reads in the file. - A ban does not remove the role: `ban_member` (`buzz-db/src/moderation.rs:314`) writes only `community_bans`, so the `relay_members` admin row survives. - The HTTP path never consulted ban state — `enforce_relay_membership` is a bare `SELECT 1 FROM relay_members`. - The ban was enforced only at the NIP-42 auth seam, which an HTTP request never crosses. **Worse than reported:** the report covered remove (9031) and icon (9033). Add (**9030**) works too, so a banned admin can *plant* new members. That matters because `moderation_authz.rs:163-170` derives "an admin cannot ban an owner or fellow admin" from `relay_members` — the very table 9030/9031 mutate. A banned admin could seed accomplices into the roster the ban was meant to stop them touching. Also of note: `moderation_authz.rs:158-165` already asserts in a comment that *"The command handler separately rejects a banned actor on every transport."* `relay_admin.rs` was the one command handler not holding that invariant. ## The fix Enforce the durable ban **inside `handle_relay_admin_event`** — the reporter's own suggested shape, and the `moderation_commands.rs:99-108` precedent. Deliberately **not** the one-token alternative of dropping `&& !is_relay_admin_kind(kind_u32)` at `ingest.rs:1639`: that would also start blocking *timed-out* admins, silently changing policy. Bans are refused; timeouts still administer, which is the entire reason the exemption exists. `handle_relay_admin_event` becomes a thin admission wrapper around an unchanged `execute_relay_admin_command` body, so no future early return inside that body can precede the check. The check therefore also necessarily precedes the freshness check. **The refusal category is part of the security contract**, so this returns a typed `RelayAdminError` rather than a string. A `blocked:` string would have kept the right wire text but returned **400** instead of **403** (`api/bridge.rs:845` vs `:858`), and would have reported a restriction-DB outage as a client error: | Variant | Ingest | Wire | HTTP | |---|---|---|---| | `Banned` | `AuthFailed` | `blocked: you are banned from this community` | **403** | | `Rejected(..)` | `Rejected` | `invalid: …` | 400 (unchanged) | | `Internal(..)` | `Internal` | `error: …` (sanitized) | **500** | ## Verification Live over real HTTP against an isolated relay, all four exempt kinds refused, DB checked after each for non-mutation: ``` [banned] 9031 remove -> 403 blocked: you are banned from this community [banned] 9030 add -> 403 blocked: you are banned from this community [banned] 9032 change role -> 403 blocked: you are banned from this community [banned] 9033 set icon -> 403 blocked: you are banned from this community ``` Victim still `member`, planted key absent, role target unchanged, icon still NULL. 9032 required a banned **owner** to be a real test, since it is owner-only. - **Mutation-tested.** The admission decision is the pure `admits_relay_admin_command(&RestrictionState)`, covered by the *default* suite. Neutering it fails `banned_actor_is_not_admitted_to_a_relay_admin_command`. The first version of this patch would have stayed green if someone deleted the check — that gap is closed. The unit test does not prove handler *wiring*; the `#[ignore]`d live E2E is what checks linkage. - **Fail-closed proven empirically**, by manual fault injection rather than assertion: renaming `community_bans.banned` out from under the running relay yields 500, no mutation, and no schema detail leaked to the client. - Negative/positive controls: timed-out admin still administers *and* is still content-write-blocked; clean admin unaffected with mutation confirmed; non-admin still gets `invalid:`/400. - Reviewed iteratively by **@mari** over three rounds; final approval at 9/10+ on minimalness, elegance, and correctness. She also ran an independent deep regression pass on an isolated stack (odd port 44391) covering channel lifecycle, membership, messages/replies/search/edit/delete, reactions, canvas, DMs, and moderation transitions — no regressions. - `cargo fmt --all --check`, `cargo clippy -p buzz-relay --all-targets -D warnings`, `buzz-core` 229/229, `buzz-cli` 250/250, `run-tests.sh unit` all five packages green. - `buzz-relay --lib`: **756 passed / 1 failed**. The sole failure `api::mesh_demo::tests::demo_join_forwarded_arm_round_trips_echo` (504 vs 200) is **pre-existing** — reproduced identically in a detached worktree at merge base `79f439b`. ## Notes for the reviewer - Merged `origin/main` in as a merge commit rather than rebasing, per instruction. No conflicts; the eight incoming commits touch none of the three files here. Closest neighbour is `79f439b` (kind:9000 NIP-29 *channel* role authz) — disjoint from this NIP-43 *relay-admin* fix. - **This does not close the class.** Two separate items remain open, deliberately excluded to keep an externally-known security fix reviewable: 1. **Command kinds dispatch before the gate.** `is_command_kind` fires at `ingest.rs:1561`, ~80 lines *before* the restriction gate, and `command_executor.rs` has no restriction read. Measured live: a banned member can still open a DM (41010 → 200). 41011/41012/30620/46030/46031 unprobed. Needs per-kind semantics enumerated first (reports allowed while banned; moderation commands allow timeouts but reject bans; ordinary writes reject both). 2. **`moderation_commands.rs` maps its own restriction-DB failure to 400, not 500**, and leaks the raw Postgres message to the client. - One correction for the public issue: its repro step 1 says `kind:9041`, which is **unban**. The ban is **9040** (`KIND_MODERATION_BAN`, `buzz-core/src/kind.rs:298`). Following the steps verbatim yields a false negative. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]> --------- Signed-off-by: Tyler Longwell <[email protected]> Co-authored-by: npub1jmc9dt2lyvzu3h0kxlwxt5zg4fxp9476awyxw6gwxn72g6cw7exqs64whm <96f056ad5f2305c8ddf637dc65d048aa4c12d7daeb8867690e34fca46b0ef64c@buzz.block.builderlab.xyz> Co-authored-by: Tyler Longwell <[email protected]>
1 parent e868381 commit 516946f

3 files changed

Lines changed: 583 additions & 5 deletions

File tree

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

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,19 @@ pub enum IngestError {
183183
Internal(String),
184184
}
185185

186+
fn map_relay_admin_error(error: super::relay_admin::RelayAdminError) -> IngestError {
187+
use super::relay_admin::RelayAdminError;
188+
match error {
189+
// Same wire prefix and HTTP status (403) as every other durable
190+
// restriction refusal — see the write-path gate below and `auth.rs`.
191+
RelayAdminError::Banned => {
192+
IngestError::AuthFailed("blocked: you are banned from this community".to_string())
193+
}
194+
RelayAdminError::Rejected(reason) => IngestError::Rejected(format!("invalid: {reason}")),
195+
RelayAdminError::Internal(reason) => IngestError::Internal(format!("error: {reason}")),
196+
}
197+
}
198+
186199
fn map_push_accept_error(error: super::push_lease::AcceptError) -> IngestError {
187200
match error {
188201
super::push_lease::AcceptError::Validation(reason) => {
@@ -1624,7 +1637,10 @@ async fn ingest_event_inner(
16241637
// is the durable backstop the fan-out's best-effort delivery relies on.
16251638
// Moderation commands enforce bans inside their handler and remain exempt
16261639
// here only so timeouts do not disarm the tool used to lift them. Relay-admin
1627-
// commands retain their separate authorization policy.
1640+
// commands (9030–9033) are exempt for the same reason — a timed-out admin
1641+
// must still be able to administer the roster — and likewise enforce the
1642+
// durable ban inside `relay_admin::handle_relay_admin_event`. Any kind added
1643+
// to this exemption owes the same handler-local ban check.
16281644
//
16291645
// Scope: this gate checks the *authoring* pubkey only, with no NIP-OA
16301646
// owner→agent cascade. That cascade lives at the auth seam for bans, where
@@ -1831,10 +1847,13 @@ async fn ingest_event_inner(
18311847
}
18321848

18331849
// Handled directly — these mutate relay_members and do NOT get stored.
1850+
// The handler enforces the durable community ban itself: the write-path
1851+
// gate above exempts relay-admin kinds so timed-out admins keep their
1852+
// administrative capability, which leaves bans to the handler.
18341853
if is_relay_admin_kind(event.kind.as_u16() as u32) {
18351854
crate::handlers::relay_admin::handle_relay_admin_event(tenant, state, &event)
18361855
.await
1837-
.map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?;
1856+
.map_err(map_relay_admin_error)?;
18381857
return Ok(IngestResult {
18391858
event_id: event_id_hex,
18401859
accepted: true,
@@ -2542,6 +2561,62 @@ mod tests {
25422561
};
25432562
use nostr::{EventBuilder, Kind};
25442563

2564+
/// A banned relay admin must be refused with the same wire prefix and
2565+
/// transport status as every other durable-restriction refusal:
2566+
/// `blocked:` and (via `bridge.rs`'s `AuthFailed` arm) HTTP 403 — never
2567+
/// `invalid:`/400, which reads as "your request was malformed" and lets a
2568+
/// client retry-loop against an authorization decision.
2569+
#[test]
2570+
fn relay_admin_ban_maps_to_blocked_auth_failure() {
2571+
let mapped = map_relay_admin_error(super::super::relay_admin::RelayAdminError::Banned);
2572+
match mapped {
2573+
IngestError::AuthFailed(msg) => {
2574+
assert_eq!(msg, "blocked: you are banned from this community");
2575+
}
2576+
other => panic!("banned admin must map to AuthFailed (HTTP 403), got {other:?}"),
2577+
}
2578+
}
2579+
2580+
/// Validation/authorization failures keep the pre-existing `invalid:`
2581+
/// prefix and 400 status — this is the arm the whole 9030-series relied on
2582+
/// before the ban category existed, so it must not regress.
2583+
#[test]
2584+
fn relay_admin_rejection_keeps_invalid_prefix() {
2585+
let mapped = map_relay_admin_error(super::super::relay_admin::RelayAdminError::Rejected(
2586+
"actor not authorized: must be admin or owner".to_string(),
2587+
));
2588+
match mapped {
2589+
IngestError::Rejected(msg) => {
2590+
assert_eq!(
2591+
msg, "invalid: actor not authorized: must be admin or owner",
2592+
"existing relay-admin rejections must keep their exact wire text"
2593+
);
2594+
}
2595+
other => panic!("validation failure must map to Rejected, got {other:?}"),
2596+
}
2597+
}
2598+
2599+
/// A restriction-lookup outage is a server fault, not a client one. It
2600+
/// must fail closed as `error:`/500 so a Postgres blip can neither admit a
2601+
/// banned admin nor be reported to an innocent one as a bad request.
2602+
#[test]
2603+
fn relay_admin_internal_maps_to_error_not_client_fault() {
2604+
let mapped = map_relay_admin_error(super::super::relay_admin::RelayAdminError::Internal(
2605+
"internal error checking restriction state: pool timed out".to_string(),
2606+
));
2607+
match mapped {
2608+
IngestError::Internal(msg) => {
2609+
assert!(
2610+
msg.starts_with("error: "),
2611+
"internal failures need the `error:` NIP-01 prefix, got {msg:?}"
2612+
);
2613+
}
2614+
other => {
2615+
panic!("restriction DB failure must map to Internal (HTTP 500), got {other:?}")
2616+
}
2617+
}
2618+
}
2619+
25452620
#[derive(Debug, Default)]
25462621
struct VecTracer {
25472622
steps: Mutex<Vec<TraceStep>>,

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

Lines changed: 129 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,18 +94,104 @@ fn validate_workspace_icon(icon: &str) -> Result<(), String> {
9494
Ok(())
9595
}
9696

97+
/// A relay-admin command failure, carrying the *category* of the failure so
98+
/// the ingest seam can map it to the right NIP-01 prefix and HTTP status.
99+
///
100+
/// The category is part of the security contract, not cosmetics: a ban must
101+
/// surface as `blocked:` / HTTP 403 (like every other durable-restriction
102+
/// refusal), and a restriction-lookup outage must surface as a 500 rather than
103+
/// a client-side 400 that reads as "your request was malformed". Mirrors
104+
/// [`super::push_lease::AcceptError`] and its `map_push_accept_error` seam.
105+
#[derive(Debug, PartialEq, Eq)]
106+
pub(super) enum RelayAdminError {
107+
/// Sender is under a durable community ban — `blocked:` / HTTP 403.
108+
Banned,
109+
/// Legacy command rejection — `invalid:` / HTTP 400. This is whatever
110+
/// [`execute_relay_admin_command`] returned as a `String`, which is mostly
111+
/// validation and authorization but also still includes that function's own
112+
/// DB failures. Categorizing those is deliberately out of scope for the ban
113+
/// fix, so this arm claims no stronger invariant than "the command body said
114+
/// no".
115+
Rejected(String),
116+
/// Admission could not be decided because the restriction lookup failed —
117+
/// `error:` / HTTP 500.
118+
Internal(String),
119+
}
120+
121+
/// Decide whether a durable restriction state admits a relay-admin command.
122+
///
123+
/// Ban only, deliberately: a timeout is a write-block on *content*, and
124+
/// `ingest_event` exempts relay-admin kinds from its durable write-path gate
125+
/// precisely so restricted-but-not-banned admins retain their administrative
126+
/// capability. Mirrors `moderation_commands::ensure_actor_not_banned`.
127+
///
128+
/// Split out as a pure function so the admission rule itself is unit-testable
129+
/// without a live relay: the end-to-end HTTP test proves the transport, this
130+
/// proves the decision.
131+
fn admits_relay_admin_command(
132+
restriction: &buzz_db::moderation::RestrictionState,
133+
) -> Result<(), RelayAdminError> {
134+
if restriction.banned {
135+
return Err(RelayAdminError::Banned);
136+
}
137+
Ok(())
138+
}
139+
97140
/// Validate and execute a relay admin command (kinds 9030–9033).
98141
///
142+
/// Admission: rejects a sender under a durable community ban before any
143+
/// command runs. The command itself is executed by
144+
/// [`execute_relay_admin_command`].
145+
///
146+
/// Returns `Ok(())` on success, or a categorized [`RelayAdminError`].
147+
pub(super) async fn handle_relay_admin_event(
148+
tenant: &TenantContext,
149+
state: &Arc<AppState>,
150+
event: &Event,
151+
) -> Result<(), RelayAdminError> {
152+
// A ban is an admission boundary, not only a WebSocket-auth check. HTTP
153+
// NIP-98 requests and already-authenticated sockets reach this handler
154+
// without passing through a fresh NIP-42 challenge, and `ingest_event`
155+
// exempts relay-admin kinds from its durable write-path gate so a *timed
156+
// out* admin can still administer the roster. That exemption is ban-blind,
157+
// so the ban must be enforced here or not at all: a banned admin otherwise
158+
// keeps mutating `relay_members` — the very table `moderation_authz`
159+
// derives moderator capability from — until someone manually deletes the
160+
// row. Mirrors `moderation_commands.rs`, which defends the same boundary
161+
// for 9040–9044, and holds that file's stated invariant that a direct
162+
// command handler rejects a banned actor on every transport.
163+
//
164+
// This gate wraps execution rather than opening it so no future early
165+
// return inside the command body can precede it.
166+
let restriction = state
167+
.db
168+
.moderation_restriction_state(tenant.community(), &event.pubkey.to_bytes())
169+
.await
170+
// Fail closed: a DB blip must never admit a banned admin.
171+
.map_err(|e| {
172+
RelayAdminError::Internal(format!("internal error checking restriction state: {e}"))
173+
})?;
174+
admits_relay_admin_command(&restriction)?;
175+
176+
execute_relay_admin_command(tenant, state, event)
177+
.await
178+
.map_err(RelayAdminError::Rejected)
179+
}
180+
181+
/// Execute an already-admitted relay admin command.
182+
///
99183
/// The handler:
100184
/// 1. Extracts the target pubkey from the `["p", ...]` tag.
101185
/// 2. Extracts the role from the `["role", ...]` tag (kinds 9030 and 9032).
102186
/// 3. Looks up the sender's current role in `relay_members`.
103187
/// 4. Enforces the permission matrix.
104188
/// 5. Applies the change via the DB.
105189
///
106-
/// Returns `Ok(())` on success. Returns `Err(msg)` — where `msg` is a
107-
/// human-readable rejection reason — on any validation failure.
108-
pub async fn handle_relay_admin_event(
190+
/// Returns `Ok(())` on success. Returns `Err(msg)` — where `msg` is the
191+
/// legacy rejection reason — on any failure. This body does not distinguish
192+
/// validation failures from execution DB failures; both surface as `Err(msg)`
193+
/// and are categorised by the caller as [`RelayAdminError::Rejected`].
194+
async fn execute_relay_admin_command(
109195
tenant: &TenantContext,
110196
state: &Arc<AppState>,
111197
event: &Event,
@@ -349,6 +435,46 @@ mod tests {
349435
use super::*;
350436
use nostr::{EventBuilder, Keys, Kind, Tag};
351437

438+
/// The vulnerability this file's ban gate closes: `ingest_event` exempts
439+
/// relay-admin kinds 9030–9033 from its durable write-path restriction
440+
/// gate, so a **banned** admin could add/remove relay members and change
441+
/// the workspace icon over signed NIP-98 `POST /events`. Deleting the
442+
/// admission check must fail here, in the default (non-ignored) suite.
443+
#[test]
444+
fn banned_actor_is_not_admitted_to_a_relay_admin_command() {
445+
let banned = buzz_db::moderation::RestrictionState {
446+
banned: true,
447+
muted_until: None,
448+
};
449+
assert_eq!(
450+
admits_relay_admin_command(&banned),
451+
Err(RelayAdminError::Banned),
452+
"a durably banned admin must never reach a relay-admin command"
453+
);
454+
}
455+
456+
/// The counter-invariant, and the reason the ingest exemption exists at
457+
/// all: a timeout restricts *content* writes, not administrative
458+
/// capability. Widening this gate to timeouts would silently change policy.
459+
#[test]
460+
fn timed_out_actor_is_still_admitted() {
461+
let timed_out = buzz_db::moderation::RestrictionState {
462+
banned: false,
463+
muted_until: Some(chrono::Utc::now() + chrono::Duration::minutes(5)),
464+
};
465+
assert!(
466+
admits_relay_admin_command(&timed_out).is_ok(),
467+
"a timed-out admin must still administer the roster"
468+
);
469+
}
470+
471+
#[test]
472+
fn unrestricted_actor_is_admitted() {
473+
assert!(
474+
admits_relay_admin_command(&buzz_db::moderation::RestrictionState::default()).is_ok()
475+
);
476+
}
477+
352478
/// Build a minimal signed Event with the given kind and tags.
353479
/// The pubkey will be randomly generated — sufficient for tag extraction tests.
354480
fn make_test_event(kind: u16, tags: Vec<Vec<&'static str>>) -> Event {

0 commit comments

Comments
 (0)