Skip to content

Commit 453fc26

Browse files
fix(channels): restrict private-channel invitations (#4612)
This change requires an active owner or administrator for third-party additions to private channels. The relay validator and transactional database authority enforce the same rule, including removed-member reactivation and role-change paths. Idempotent self-target behavior remains available, while ordinary members can no longer extend private-channel access to another identity. ## Testing - `git diff --check origin/main...codex/security-private-channel-invite-authority` - Rebased onto `origin/main` at `049080e` - Full CI pending Originating Buzz thread: `buzz://message?channel=3928fe05-df61-4b5d-b9c7-d623b9b10ea1&id=3c6c02312f763fbe0d2bfc33a6c1a362f91d0354f3d18b039cf7a0558c1439d1` --------- Signed-off-by: Jordan Mecom <[email protected]> Signed-off-by: Eli Foster <[email protected]> Co-authored-by: Eli Foster <[email protected]>
1 parent cf6ccee commit 453fc26

19 files changed

Lines changed: 858 additions & 190 deletions

File tree

‎VISION.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ The relay enforces all access control. Channel membership is the only gate.
3939
| Type | Visibility | Join | Create |
4040
|------|-----------|------|--------|
4141
| **Open channels** | Searchable by all members | Self-join | Any member |
42-
| **Private channels** | Hidden, invite-only | Invited by member | Any member |
42+
| **Private channels** | Hidden, invite-only | Invited by an owner/admin | Any member |
4343
| **DMs** | Participants only | N/A (up to 9) | Any member |
4444
| **Guests** | Scoped to specific channels | Invited | N/A |
4545

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

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,9 @@ async fn acquire_channel_membership_lock(
371371
/// Role enforcement:
372372
/// - Open channels: `invited_by` is optional; role is forced to `Member` regardless of
373373
/// what the caller passes — callers cannot self-assign elevated roles.
374-
/// - Private channels: requires an `invited_by` who is an active owner/admin.
374+
/// - Private channels: requires an `invited_by` who is an active owner/admin, the channel
375+
/// creator bootstrapping their own first membership, or the target adding themselves
376+
/// (idempotent re-add — an active member's *role* still cannot change this way).
375377
/// - Elevated roles (`Owner`, `Admin`) may only be granted by an existing owner/admin,
376378
/// even on open channels.
377379
///
@@ -419,10 +421,14 @@ pub async fn add_member(
419421
DbError::InvalidData(format!("invalid role in database: {inviter_role_str}"))
420422
})?;
421423

422-
// Any member can invite others, but only owners/admins may grant elevated roles.
423-
if role.is_elevated() && !inviter_role.is_elevated() {
424+
// Only owners/admins may extend private-channel access to another
425+
// identity. `inviter == pubkey` keeps a member's own idempotent
426+
// re-add working; it is not a role-escalation hole, because the
427+
// active-role-change guard below still rejects a self-targeted
428+
// promotion from any non-elevated caller.
429+
if !inviter_role.is_elevated() && inviter != pubkey {
424430
return Err(DbError::AccessDenied(
425-
"only owners/admins may grant elevated roles".to_string(),
431+
"only owners/admins may add private-channel members".to_string(),
426432
));
427433
}
428434
}

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

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -355,28 +355,28 @@ pub async fn validate_admin_event(
355355
.iter()
356356
.find(|m| m.pubkey == actor_bytes)
357357
.and_then(|m| m.role.parse().ok());
358-
359-
// PUT_USER: open channels allow any authenticated user; private channels
360-
// require the actor to be an existing member (any role can invite).
361-
if channel.visibility == "private" {
362-
if actor_role.is_none() {
363-
return Err(anyhow::anyhow!("actor not authorized"));
364-
}
365-
366-
// Only owners/admins may grant elevated roles.
367-
if requested_role.is_some_and(|r| r.is_elevated())
368-
&& !actor_role.is_some_and(|r| r.is_elevated())
369-
{
370-
return Err(anyhow::anyhow!(
371-
"only owners/admins may grant elevated roles"
372-
));
373-
}
374-
}
375-
376-
// Extract target pubkey from p tag
377358
let target_pubkey =
378359
extract_p_tag(event).ok_or_else(|| anyhow::anyhow!("missing p tag"))?;
379360

361+
// PUT_USER: open channels allow any authenticated user. Private
362+
// channels only let owners/admins add another identity; otherwise
363+
// any compromised member could extend access to channel history.
364+
//
365+
// A self-targeted add skips this check so an idempotent re-add
366+
// still works. That is not a way into a private channel: ingest's
367+
// `check_channel_membership` rejects a non-member (and a
368+
// soft-removed member) before this validator runs, and `add_member`
369+
// independently requires the self-inviter to hold an active role.
370+
// Self-promotion is caught by the role-change guard below.
371+
if channel.visibility == "private"
372+
&& target_pubkey != actor_bytes
373+
&& !actor_role.is_some_and(|r| r.is_elevated())
374+
{
375+
return Err(anyhow::anyhow!(
376+
"only owners/admins may add private-channel members"
377+
));
378+
}
379+
380380
// Changing an ACTIVE existing member's role is privileged in both
381381
// directions, on every visibility. `get_members` filters
382382
// `removed_at IS NULL`, so a soft-removed row is deliberately not an

‎crates/buzz-test-client/tests/e2e_relay.rs‎

Lines changed: 74 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2201,6 +2201,10 @@ async fn create_private_channel_ws(client: &mut BuzzTestClient, keys: &Keys) ->
22012201
}
22022202

22032203
/// Submit a kind:9000 PUT_USER event over WebSocket.
2204+
///
2205+
/// `allow_self_tagging` keeps self-targeted adds working: EventBuilder otherwise
2206+
/// drops a `p` tag matching the signer (nostr-0.44.3 builder.rs:435-449) and the
2207+
/// event fails as "missing p tag" instead of exercising the authority check.
22042208
async fn add_member_ws(
22052209
client: &mut BuzzTestClient,
22062210
channel_id: &str,
@@ -2210,6 +2214,7 @@ async fn add_member_ws(
22102214
let h_tag = Tag::parse(["h", channel_id]).unwrap();
22112215
let p_tag = Tag::parse(["p", target_pubkey_hex]).unwrap();
22122216
let event = EventBuilder::new(Kind::Custom(9000), "")
2217+
.allow_self_tagging()
22132218
.tags([h_tag, p_tag])
22142219
.sign_with_keys(signer)
22152220
.unwrap();
@@ -2219,6 +2224,8 @@ async fn add_member_ws(
22192224
}
22202225

22212226
/// Submit a kind:9000 PUT_USER event with a role tag over WebSocket.
2227+
///
2228+
/// See [`add_member_ws`] for why `allow_self_tagging` is required.
22222229
async fn add_member_with_role_ws(
22232230
client: &mut BuzzTestClient,
22242231
channel_id: &str,
@@ -2230,6 +2237,7 @@ async fn add_member_with_role_ws(
22302237
let p_tag = Tag::parse(["p", target_pubkey_hex]).unwrap();
22312238
let role_tag = Tag::parse(["role", role]).unwrap();
22322239
let event = EventBuilder::new(Kind::Custom(9000), "")
2240+
.allow_self_tagging()
22332241
.tags([h_tag, p_tag, role_tag])
22342242
.sign_with_keys(signer)
22352243
.unwrap();
@@ -2241,10 +2249,10 @@ async fn add_member_with_role_ws(
22412249
(ok.accepted, ok.message)
22422250
}
22432251

2244-
/// Any member of a private channel can invite another user (Slack model).
2252+
/// Only owners/admins can add another identity to a private channel.
22452253
#[tokio::test]
22462254
#[ignore]
2247-
async fn test_private_channel_any_member_can_invite() {
2255+
async fn test_private_channel_member_cannot_invite() {
22482256
let url = relay_url();
22492257
let owner_keys = Keys::generate();
22502258
let member_keys = Keys::generate();
@@ -2271,23 +2279,85 @@ async fn test_private_channel_any_member_can_invite() {
22712279
.await
22722280
.expect("connect as member");
22732281

2274-
// Regular member invites a third user — this should succeed.
2282+
// Regular member tries to invite a third user.
22752283
let (accepted, msg) = add_member_ws(
22762284
&mut member_client,
22772285
&channel_id,
22782286
&invitee_keys.public_key().to_hex(),
22792287
&member_keys,
22802288
)
22812289
.await;
2290+
assert!(
2291+
!accepted,
2292+
"regular member must not add another private-channel identity: {msg}"
2293+
);
2294+
assert!(
2295+
msg.contains("owners/admins"),
2296+
"rejection should name the owner/admin requirement, got: {msg}"
2297+
);
2298+
2299+
// The same member re-adding *themselves* stays idempotent — the huddle
2300+
// bot-add and kind:9021 paths depend on a self-targeted PUT_USER working.
2301+
let (accepted, msg) = add_member_ws(
2302+
&mut member_client,
2303+
&channel_id,
2304+
&member_keys.public_key().to_hex(),
2305+
&member_keys,
2306+
)
2307+
.await;
22822308
assert!(
22832309
accepted,
2284-
"regular member should be able to invite to private channel, got: {msg}"
2310+
"self-targeted re-add must stay idempotent, got: {msg}"
22852311
);
22862312

22872313
owner_client.disconnect().await.expect("disconnect owner");
22882314
member_client.disconnect().await.expect("disconnect member");
22892315
}
22902316

2317+
/// An admin — not just the owner — can still add to a private channel.
2318+
#[tokio::test]
2319+
#[ignore]
2320+
async fn test_private_channel_admin_can_invite() {
2321+
let url = relay_url();
2322+
let owner_keys = Keys::generate();
2323+
let admin_keys = Keys::generate();
2324+
let invitee_keys = Keys::generate();
2325+
2326+
let mut owner_client = BuzzTestClient::connect(&url, &owner_keys)
2327+
.await
2328+
.expect("connect as owner");
2329+
let channel_id = create_private_channel_ws(&mut owner_client, &owner_keys).await;
2330+
2331+
let (accepted, msg) = add_member_with_role_ws(
2332+
&mut owner_client,
2333+
&channel_id,
2334+
&admin_keys.public_key().to_hex(),
2335+
"admin",
2336+
&owner_keys,
2337+
)
2338+
.await;
2339+
assert!(accepted, "owner should add an admin, got: {msg}");
2340+
2341+
let mut admin_client = BuzzTestClient::connect(&url, &admin_keys)
2342+
.await
2343+
.expect("connect as admin");
2344+
2345+
let (accepted, msg) = add_member_ws(
2346+
&mut admin_client,
2347+
&channel_id,
2348+
&invitee_keys.public_key().to_hex(),
2349+
&admin_keys,
2350+
)
2351+
.await;
2352+
assert!(
2353+
accepted,
2354+
"admin should be able to add to a private channel, got: {msg}"
2355+
);
2356+
2357+
owner_client.disconnect().await.expect("disconnect owner");
2358+
admin_client.disconnect().await.expect("disconnect admin");
2359+
}
2360+
22912361
/// A non-member cannot invite someone to a private channel.
22922362
#[tokio::test]
22932363
#[ignore]

‎desktop/src/features/channels/hooks.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ import type {
3232
SetChannelTopicInput,
3333
UpdateChannelInput,
3434
} from "@/shared/api/types";
35+
import { useIdentityQuery } from "@/shared/api/hooks";
3536
import { useCommunities } from "@/features/communities/useCommunities";
37+
import { canAddChannelMembers } from "@/features/channels/lib/channelMemberAdmission";
3638
import {
3739
readChannelSnapshot,
3840
writeChannelSnapshot,
@@ -501,6 +503,32 @@ export function useDeleteChannelMutation(channelId: string | null) {
501503
});
502504
}
503505

506+
/**
507+
* Whether the signed-in identity may add *another* identity to this channel,
508+
* per {@link canAddChannelMembers}. Both queries are the ones the channel UI
509+
* already holds, so this shares their cache rather than fetching again.
510+
*/
511+
export function useCanAddChannelMembers(channelId: string | null) {
512+
const channelsQuery = useChannelsQuery();
513+
const membersQuery = useChannelMembersQuery(channelId);
514+
const identityQuery = useIdentityQuery();
515+
516+
const channel =
517+
channelsQuery.data?.find((candidate) => candidate.id === channelId) ?? null;
518+
const selfPubkey = identityQuery.data?.pubkey ?? null;
519+
const selfRole = selfPubkey
520+
? (membersQuery.data?.find(
521+
(member) => member.pubkey.toLowerCase() === selfPubkey.toLowerCase(),
522+
)?.role ?? null)
523+
: null;
524+
525+
return canAddChannelMembers({
526+
channelType: channel?.channelType,
527+
visibility: channel?.visibility,
528+
selfRole,
529+
});
530+
}
531+
504532
export function useAddChannelMembersMutation(channelId: string | null) {
505533
const queryClient = useQueryClient();
506534

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { strict as assert } from "node:assert";
2+
import test from "node:test";
3+
4+
import { canAddChannelMembers } from "./channelMemberAdmission.ts";
5+
6+
test("open channels accept adds from anyone, member or not", () => {
7+
assert.equal(
8+
canAddChannelMembers({
9+
channelType: "stream",
10+
visibility: "open",
11+
selfRole: null,
12+
}),
13+
true,
14+
);
15+
assert.equal(
16+
canAddChannelMembers({
17+
channelType: "stream",
18+
visibility: "open",
19+
selfRole: "member",
20+
}),
21+
true,
22+
);
23+
});
24+
25+
test("private channels accept adds only from owners/admins", () => {
26+
for (const selfRole of ["owner", "admin"]) {
27+
assert.equal(
28+
canAddChannelMembers({
29+
channelType: "stream",
30+
visibility: "private",
31+
selfRole,
32+
}),
33+
true,
34+
`${selfRole} should be able to add`,
35+
);
36+
}
37+
38+
for (const selfRole of ["member", "bot", "guest", null]) {
39+
assert.equal(
40+
canAddChannelMembers({
41+
channelType: "stream",
42+
visibility: "private",
43+
selfRole,
44+
}),
45+
false,
46+
`${selfRole} must not be able to add`,
47+
);
48+
}
49+
});
50+
51+
test("DMs never accept adds, even from an owner", () => {
52+
assert.equal(
53+
canAddChannelMembers({
54+
channelType: "dm",
55+
visibility: "private",
56+
selfRole: "owner",
57+
}),
58+
false,
59+
);
60+
assert.equal(
61+
canAddChannelMembers({
62+
channelType: "dm",
63+
visibility: "open",
64+
selfRole: "owner",
65+
}),
66+
false,
67+
);
68+
});
69+
70+
test("unknown visibility fails closed for non-elevated callers", () => {
71+
assert.equal(
72+
canAddChannelMembers({ channelType: "stream", selfRole: "member" }),
73+
false,
74+
);
75+
assert.equal(
76+
canAddChannelMembers({ channelType: "stream", selfRole: "owner" }),
77+
true,
78+
);
79+
});
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Client mirror of the relay's kind:9000 authority for adding *another*
3+
* identity to a channel (`validate_admin_event` + `buzz_db::channel::add_member`):
4+
*
5+
* - DMs: nobody — membership is fixed at creation.
6+
* - Open channels: anyone, member or not.
7+
* - Private channels: owners/admins only. A plain member extending access to
8+
* channel history is exactly what the relay now rejects, so the affordance
9+
* must not be offered.
10+
*
11+
* Unknown visibility fails closed — the relay is the authority and a hidden
12+
* button is cheaper than an opaque rejection.
13+
*/
14+
export function canAddChannelMembers({
15+
channelType,
16+
visibility,
17+
selfRole,
18+
}: {
19+
channelType?: string | null;
20+
visibility?: string | null;
21+
selfRole?: string | null;
22+
}): boolean {
23+
if (channelType === "dm") {
24+
return false;
25+
}
26+
27+
if (visibility === "open") {
28+
return true;
29+
}
30+
31+
return selfRole === "owner" || selfRole === "admin";
32+
}
33+
34+
/** Explains a denied add so the user isn't left guessing at a missing button. */
35+
export const PRIVATE_CHANNEL_ADD_DENIED_MESSAGE =
36+
"Only channel owners and admins can add people to a private channel.";

0 commit comments

Comments
 (0)