Skip to content

Commit 3c9bb09

Browse files
tlongwell-blocknpub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d
andauthored
fix(relay): allow open relays to set their NIP-11 workspace icon (kind:9033) (#3998)
## Problem The desktop deliberately shows the workspace icon editor on open relays (#2640, gate: `canEditIcon` in `desktop/src/features/communities/ui/EditCommunityDialog.tsx`) and defers to the relay-side kind:9033 check — which required an admin/owner row in `relay_members`. For a community with **no admin/owner row at all** (the `ensure_configured_community` path, which never writes an owner), every 9033 was refused and the icon was permanently unsettable. **Correction from review (thanks @dawn):** the original version of this PR claimed nobody holds a role on an open relay. That's false — `main.rs` bootstraps `RELAY_OWNER_PUBKEY` as owner regardless of `BUZZ_REQUIRE_RELAY_MEMBERSHIP`, so a production open relay like bb-block *does* have an owner row, and the old gate was refusing everyone except that owner. The first revision of this diff would have silently widened that owner-only control to any NIP-42-authenticated sender. ## Fix — steward-wins `may_set_workspace_profile(sender_role, membership_enforced, community_has_steward)`: | Relay mode | Community has admin/owner row? | Who may set the icon | |---|---|---| | Closed (`require_relay_membership=true`) | any | admin or owner (unchanged) | | Open | yes (e.g. bb-block) | admin or owner (unchanged posture) | | Open | no (genuinely rosterless) | any NIP-42-authenticated sender | - New DB helper `has_admin_or_owner(community)` (`crates/buzz-db/src/relay_members.rs`); the call site only queries it on open relays. - The rosterless admit logs a `warn!` with the sender pubkey — 9033 writes no audit row and publishes no announcement event (unlike 9030/9031), so this is the only durable attribution. - Kinds 9030–9032, NIP-42 auth, `AdminUsers` scope, ban gate, and icon validation are all untouched. - Doc comment fixed: cited nonexistent `canEditCommunityProfile`; real symbol is `canEditIcon`. ## Test coverage — closing the mutation gap Dawn's mutation testing showed the original unit tests pinned only the helper's truth table: inverting the flag at the call site or deleting the gate entirely survived the full suite. - Unit tests now cover the 3-arg truth table (closed steward-independent, open-with-steward stays steward-only, rosterless-open admits). - Two `#[ignore]`d Postgres integration tests drive `handle_relay_admin_event` with a real `AppState` (open rosterless admit → steward appears → roleless refused again; closed relay member refused). Wired into the Backend Integration CI job as a dedicated nextest step. - **Both of Dawn's mutants verified killed** at this head: flag inversion fails 1 unit test; gate deletion fails both integration tests (`Ok(())` where `Rejected` expected). ## CI wrinkle found and fixed: pre-existing schema drift The first Backend Integration run of the new 9033 tests failed with `column "icon" of relation "communities" does not exist` — migration `0003_community_icon.sql` added the column, but `schema/schema.sql` (the desired-state file that CI job applies via pgschema) was never updated. Pre-existing drift, invisible until a test in that job actually wrote the column. Fixed in `297148f62` (3-line addition to `schema/schema.sql`). ## Receipts (at `1b4b52db8` code / `297148f62` head) - `cargo test -p buzz-relay`: 835 pass, 1 fail — `api::mesh_demo::tests::demo_join_forwarded_arm_round_trips_echo`, pre-existing (fails identically at the old base and on clean main); `telemetry::trace_context_lookup_does_not_enable_callsites` is a known order-dependent flake, passes in isolation. - `cargo test -p buzz-db`: 94 pass. - Both ignored integration tests pass live against local Postgres. - `cargo fmt --all -- --check`: clean. - Live-local pass per TESTING.md at this head (release build, relay on :3199, real WS + NIP-42 via nak): - open rosterless: roleless key sets icon → NIP-11 serves it; `warn!` with sender pubkey in the relay log - open + owner row inserted: fresh roleless key refused ("must be admin or owner"); owner sets icon - closed relay (owner bootstrapped, `BUZZ_RELAY_PRIVATE_KEY` set): plain member refused, owner sets icon, `javascript:` URL rejected, empty icon clears (NIP-11 → null) --------- Signed-off-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz> Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
1 parent 7604005 commit 3c9bb09

5 files changed

Lines changed: 343 additions & 2 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,18 @@ jobs:
692692
--run-ignored ignored-only
693693
env:
694694
DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz
695+
- name: Workspace profile (kind:9033) gate tests
696+
# Call-site integration for the 9033 authorization gate: open relay
697+
# rosterless/steward transitions and the closed-relay admin/owner rule,
698+
# against real Postgres. #[ignore]d in the default suite, selected
699+
# explicitly here — see handlers::relay_admin::tests.
700+
run: |
701+
cargo nextest run \
702+
--archive-file target/ci/backend-integration-tests.tar.zst \
703+
-E 'package(buzz-relay) and test(/handlers::relay_admin::tests/)' \
704+
--run-ignored ignored-only
705+
env:
706+
DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz
695707
- name: NIP-ER reminder e2e
696708
# Feature e2e for NIP-ER (Event Reminders, kind:30300): write-path
697709
# validation, author-only read filtering, and scheduler delivery against

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4096,6 +4096,12 @@ impl Db {
40964096
relay_members::bootstrap_owner(&self.pool, community, owner_pubkey).await
40974097
}
40984098

4099+
/// Returns `true` if any member of `community` holds the `admin` or
4100+
/// `owner` role.
4101+
pub async fn has_admin_or_owner(&self, community: CommunityId) -> Result<bool> {
4102+
relay_members::has_admin_or_owner(&self.pool, community).await
4103+
}
4104+
40994105
/// Atomically transfers ownership of `community` to `new_owner_pubkey`,
41004106
/// demoting the previous owner(s) to `member`. Verifies
41014107
/// `expected_owner_pubkey` matches the current owner inside the same

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,21 @@ pub async fn is_relay_member(pool: &PgPool, community: CommunityId, pubkey: &str
3737
Ok(row.is_some())
3838
}
3939

40+
/// Returns `true` if any member of `community` holds the `admin` or `owner`
41+
/// role. Open relays don't *enforce* the roster, but startup
42+
/// (`bootstrap_owner`) and operator provisioning still populate it — this is
43+
/// how the workspace-profile gate detects whether a steward exists.
44+
pub async fn has_admin_or_owner(pool: &PgPool, community: CommunityId) -> Result<bool> {
45+
let row = sqlx::query(
46+
"SELECT 1 FROM relay_members \
47+
WHERE community_id = $1 AND role IN ('admin', 'owner') LIMIT 1",
48+
)
49+
.bind(community.as_uuid())
50+
.fetch_optional(pool)
51+
.await?;
52+
Ok(row.is_some())
53+
}
54+
4055
/// Returns the relay member record for `pubkey` in `community`, or `None`.
4156
pub async fn get_relay_member(
4257
pool: &PgPool,

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

Lines changed: 307 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
//! | 9030 | Add member | admin or owner |
1111
//! | 9031 | Remove member | admin or owner |
1212
//! | 9032 | Change role | owner only |
13-
//! | 9033 | Set workspace profile (icon) | admin or owner |
13+
//! | 9033 | Set workspace profile (icon) | admin or owner; on an open relay whose community has no admin/owner row at all, any authenticated sender (see [`may_set_workspace_profile`]) |
1414
1515
use std::sync::Arc;
1616

@@ -94,6 +94,35 @@ fn validate_workspace_icon(icon: &str) -> Result<(), String> {
9494
Ok(())
9595
}
9696

97+
/// Whether `sender_role` may set the workspace profile (kind:9033).
98+
///
99+
/// Closed relays (`membership_enforced == true`) require an `admin`/`owner`
100+
/// row in `relay_members` — the enforced roster is the authority. Open relays
101+
/// don't *enforce* the roster, but the data can still exist: startup
102+
/// bootstraps `RELAY_OWNER_PUBKEY` as `owner` regardless of the flag
103+
/// (`main.rs`), as does operator provisioning. So the rule is steward-wins:
104+
///
105+
/// - a steward (any admin/owner row) exists → admin/owner only, exactly like
106+
/// a closed relay. An open relay with a configured owner keeps its icon
107+
/// owner-controlled instead of last-write-wins for every authenticated key.
108+
/// - genuinely rosterless (e.g. a community created by
109+
/// `ensure_configured_community`, which writes no owner row) → any
110+
/// NIP-42-authenticated sender may set the icon, mirroring how open relays
111+
/// gate every other write. Without this the icon is permanently unsettable:
112+
/// the desktop deliberately shows the icon editor on open relays (see
113+
/// `canEditIcon` in `EditCommunityDialog.tsx`, #2640) and defers to this
114+
/// relay-side check, which used to always say no.
115+
fn may_set_workspace_profile(
116+
sender_role: &str,
117+
membership_enforced: bool,
118+
community_has_steward: bool,
119+
) -> bool {
120+
if !membership_enforced && !community_has_steward {
121+
return true;
122+
}
123+
sender_role == "admin" || sender_role == "owner"
124+
}
125+
97126
/// A relay-admin command failure, carrying the *category* of the failure so
98127
/// the ingest seam can map it to the right NIP-01 prefix and HTTP status.
99128
///
@@ -230,9 +259,33 @@ async fn execute_relay_admin_command(
230259
// kind:9033 — Set workspace profile (icon). Handled before p-tag
231260
// extraction: it targets the relay itself, not a member pubkey.
232261
if kind == RELAY_ADMIN_SET_WORKSPACE_PROFILE {
233-
if sender_role != "admin" && sender_role != "owner" {
262+
// Steward detection only matters on open relays (closed relays gate on
263+
// the sender's own role either way), so skip the extra query there.
264+
let community_has_steward = if state.config.require_relay_membership {
265+
true
266+
} else {
267+
state
268+
.db
269+
.has_admin_or_owner(tenant.community())
270+
.await
271+
.map_err(|e| format!("database error: {e}"))?
272+
};
273+
if !may_set_workspace_profile(
274+
sender_role,
275+
state.config.require_relay_membership,
276+
community_has_steward,
277+
) {
234278
return Err("actor not authorized: must be admin or owner".to_string());
235279
}
280+
if sender_role != "admin" && sender_role != "owner" {
281+
// Rosterless-open-relay admit: 9033 writes no audit row and
282+
// publishes no announcement event (unlike 9030/9031), so this warn
283+
// is the only durable attribution of who changed the icon.
284+
warn!(
285+
sender = %sender_hex,
286+
"workspace profile change admitted without a roster role (open relay, no steward)"
287+
);
288+
}
236289

237290
// Empty or missing icon tag clears the workspace icon.
238291
let icon = extract_tag_value(event, "icon").unwrap_or_default();
@@ -562,6 +615,46 @@ mod tests {
562615
assert!(validate_workspace_icon("").is_ok());
563616
}
564617

618+
/// Closed relay (membership enforced): only an admin/owner row in
619+
/// `relay_members` may set the workspace profile — a plain member, or a
620+
/// pubkey with no row at all (empty role), must be refused. The steward
621+
/// flag is irrelevant when membership is enforced (call sites pass `true`,
622+
/// but the rule must not depend on it).
623+
#[test]
624+
fn closed_relay_requires_admin_or_owner_for_workspace_profile() {
625+
for steward in [true, false] {
626+
assert!(may_set_workspace_profile("owner", true, steward));
627+
assert!(may_set_workspace_profile("admin", true, steward));
628+
assert!(!may_set_workspace_profile("member", true, steward));
629+
assert!(!may_set_workspace_profile("", true, steward));
630+
}
631+
}
632+
633+
/// Open relay with a steward: startup bootstraps `RELAY_OWNER_PUBKEY` as
634+
/// `owner` regardless of `require_relay_membership`, so an open relay's
635+
/// community can hold admin/owner rows. When one exists, the icon stays
636+
/// steward-only — the fix must not widen an owner-controlled icon to
637+
/// every authenticated key.
638+
#[test]
639+
fn open_relay_with_steward_keeps_workspace_profile_steward_only() {
640+
assert!(may_set_workspace_profile("owner", false, true));
641+
assert!(may_set_workspace_profile("admin", false, true));
642+
assert!(!may_set_workspace_profile("member", false, true));
643+
assert!(!may_set_workspace_profile("", false, true));
644+
}
645+
646+
/// Open relay, genuinely rosterless (no admin/owner row anywhere): any
647+
/// authenticated sender may set the icon — including the roleless (empty
648+
/// role) case, which is *every* sender there. This is the bug being
649+
/// fixed: the desktop shows the icon editor on open relays (#2640) but
650+
/// the relay refused every 9033.
651+
#[test]
652+
fn rosterless_open_relay_admits_any_authenticated_sender_for_workspace_profile() {
653+
assert!(may_set_workspace_profile("", false, false));
654+
assert!(may_set_workspace_profile("member", false, false));
655+
assert!(may_set_workspace_profile("owner", false, false));
656+
}
657+
565658
#[test]
566659
fn workspace_icon_https_ok() {
567660
assert!(validate_workspace_icon("https://example.com/icon.png").is_ok());
@@ -591,4 +684,216 @@ mod tests {
591684
let long_data = format!("data:image/png;base64,{}", "A".repeat(98_304));
592685
assert!(validate_workspace_icon(&long_data).is_err());
593686
}
687+
688+
// ─── Call-site integration: the 9033 gate wired to real config + DB ────
689+
//
690+
// The unit tests above pin `may_set_workspace_profile`'s truth table, but
691+
// not its wiring: mutation-testing showed that inverting
692+
// `state.config.require_relay_membership` at the call site — an exact
693+
// inversion of the security contract — survives the default suite. These
694+
// tests drive `handle_relay_admin_event` with a real `AppState` against
695+
// Postgres, on both relay modes, so the wiring itself is pinned. Selected
696+
// explicitly in CI's Backend Integration job; requires local Postgres
697+
// (and hard-fails rather than skipping when it is unreachable).
698+
699+
const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1
700+
701+
/// Build a real `AppState` + tenant for a fresh community on `host`, with
702+
/// `require_relay_membership` set as given. Mirrors
703+
/// `api::invites::tests::invite_test_state`.
704+
async fn workspace_profile_test_state(
705+
host: &str,
706+
require_relay_membership: bool,
707+
) -> (Arc<AppState>, TenantContext) {
708+
let mut config = crate::config::Config::from_env().expect("config from env");
709+
let database_url = std::env::var("BUZZ_TEST_DATABASE_URL")
710+
.or_else(|_| std::env::var("DATABASE_URL"))
711+
.unwrap_or_else(|_| TEST_DB_URL.to_string());
712+
config.database_url = database_url.clone();
713+
config.redis_url = "redis://127.0.0.1:1".to_string();
714+
config.relay_url = format!("wss://{host}");
715+
config.require_relay_membership = require_relay_membership;
716+
717+
let pool = sqlx::PgPool::connect(&database_url)
718+
.await
719+
.expect("requires reachable Postgres");
720+
let db = buzz_db::Db::from_pool(pool.clone());
721+
let record = db
722+
.ensure_configured_community(host)
723+
.await
724+
.expect("ensure community");
725+
let tenant = TenantContext::resolved(record.id, host);
726+
727+
let redis_pool = deadpool_redis::Config::from_url(&config.redis_url)
728+
.create_pool(Some(deadpool_redis::Runtime::Tokio1))
729+
.expect("redis pool config");
730+
let pubsub = Arc::new(
731+
buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone())
732+
.await
733+
.expect("pubsub manager"),
734+
);
735+
let audit = buzz_audit::AuditService::new(pool.clone());
736+
let auth = buzz_auth::AuthService::new(config.auth.clone());
737+
let search = buzz_search::SearchService::new(pool.clone());
738+
let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new(
739+
db.clone(),
740+
buzz_workflow::WorkflowConfig::default(),
741+
));
742+
let media_storage = buzz_media::MediaStorage::new(&config.media).expect("media storage");
743+
let (state, _audit_shutdown) = AppState::new(
744+
config,
745+
db,
746+
redis_pool,
747+
audit,
748+
pubsub,
749+
auth,
750+
search,
751+
workflow_engine,
752+
Keys::generate(),
753+
media_storage,
754+
);
755+
(Arc::new(state), tenant)
756+
}
757+
758+
/// Sign a fresh kind:9033 with `icon` and run it through the real
759+
/// admission + command path.
760+
async fn submit_9033(
761+
state: &Arc<AppState>,
762+
tenant: &TenantContext,
763+
keys: &Keys,
764+
icon: &str,
765+
) -> Result<(), RelayAdminError> {
766+
let event = EventBuilder::new(Kind::Custom(9033), "")
767+
.tags(vec![Tag::parse(["icon", icon]).expect("icon tag")])
768+
.sign_with_keys(keys)
769+
.expect("sign 9033");
770+
handle_relay_admin_event(tenant, state, &event).await
771+
}
772+
773+
async fn stored_icon(state: &Arc<AppState>, tenant: &TenantContext) -> Option<String> {
774+
state
775+
.db
776+
.get_community_icon(tenant.community())
777+
.await
778+
.expect("read icon")
779+
}
780+
781+
/// Open relay (`require_relay_membership = false`): a rosterless
782+
/// community admits any authenticated sender, but the moment a steward
783+
/// (admin/owner row) exists the gate reverts to steward-only.
784+
///
785+
/// Discriminating: fails if the call site inverts or drops
786+
/// `require_relay_membership`, or stops consulting `has_admin_or_owner`.
787+
#[tokio::test]
788+
#[ignore = "requires Postgres"]
789+
async fn open_relay_9033_admits_roleless_only_until_a_steward_exists() {
790+
let host = format!("icon-gate-open-{}.example", uuid::Uuid::new_v4().simple());
791+
let (state, tenant) = workspace_profile_test_state(&host, false).await;
792+
let roleless = Keys::generate();
793+
let owner = Keys::generate();
794+
795+
// Rosterless: the roleless sender may set the icon.
796+
submit_9033(&state, &tenant, &roleless, "https://example.com/open.png")
797+
.await
798+
.expect("rosterless open relay must admit an authenticated sender");
799+
assert_eq!(
800+
stored_icon(&state, &tenant).await.as_deref(),
801+
Some("https://example.com/open.png"),
802+
"icon must actually be stored"
803+
);
804+
805+
// Seed a steward — the same roleless sender must now be refused, and
806+
// the previously stored icon must survive the refused attempt.
807+
state
808+
.db
809+
.add_relay_member(
810+
tenant.community(),
811+
&owner.public_key().to_hex(),
812+
"owner",
813+
None,
814+
)
815+
.await
816+
.expect("seed owner");
817+
let refused = submit_9033(&state, &tenant, &roleless, "https://evil.example/pwn.png").await;
818+
assert_eq!(
819+
refused,
820+
Err(RelayAdminError::Rejected(
821+
"actor not authorized: must be admin or owner".to_string()
822+
)),
823+
"an open relay with a steward must refuse a roleless sender"
824+
);
825+
assert_eq!(
826+
stored_icon(&state, &tenant).await.as_deref(),
827+
Some("https://example.com/open.png"),
828+
"refused attempt must not mutate the icon"
829+
);
830+
831+
// The steward still can.
832+
submit_9033(&state, &tenant, &owner, "https://example.com/owner.png")
833+
.await
834+
.expect("the steward must retain icon control");
835+
assert_eq!(
836+
stored_icon(&state, &tenant).await.as_deref(),
837+
Some("https://example.com/owner.png")
838+
);
839+
}
840+
841+
/// Closed relay (`require_relay_membership = true`): admin/owner only —
842+
/// a plain member and a roleless key are refused even though the
843+
/// community also *looks* rosterless-then-stewarded to the open-relay
844+
/// branch. Together with the open-relay test this kills the inverted-flag
845+
/// mutant: no assignment of the flag satisfies both.
846+
#[tokio::test]
847+
#[ignore = "requires Postgres"]
848+
async fn closed_relay_9033_still_requires_admin_or_owner() {
849+
let host = format!("icon-gate-closed-{}.example", uuid::Uuid::new_v4().simple());
850+
let (state, tenant) = workspace_profile_test_state(&host, true).await;
851+
let roleless = Keys::generate();
852+
let member = Keys::generate();
853+
let admin = Keys::generate();
854+
state
855+
.db
856+
.add_relay_member(
857+
tenant.community(),
858+
&member.public_key().to_hex(),
859+
"member",
860+
None,
861+
)
862+
.await
863+
.expect("seed member");
864+
state
865+
.db
866+
.add_relay_member(
867+
tenant.community(),
868+
&admin.public_key().to_hex(),
869+
"admin",
870+
None,
871+
)
872+
.await
873+
.expect("seed admin");
874+
875+
for (keys, label) in [(&roleless, "roleless"), (&member, "member")] {
876+
let refused = submit_9033(&state, &tenant, keys, "https://evil.example/pwn.png").await;
877+
assert_eq!(
878+
refused,
879+
Err(RelayAdminError::Rejected(
880+
"actor not authorized: must be admin or owner".to_string()
881+
)),
882+
"closed relay must refuse a {label} sender"
883+
);
884+
}
885+
assert_eq!(
886+
stored_icon(&state, &tenant).await,
887+
None,
888+
"refused attempts must not set an icon"
889+
);
890+
891+
submit_9033(&state, &tenant, &admin, "https://example.com/closed.png")
892+
.await
893+
.expect("closed-relay admin must set the icon");
894+
assert_eq!(
895+
stored_icon(&state, &tenant).await.as_deref(),
896+
Some("https://example.com/closed.png")
897+
);
898+
}
594899
}

0 commit comments

Comments
 (0)