Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(channels): channel participant rename channel (#6596)

Will Hutchinson9c932e21f7d1
diff --git a/.sqlx/query-6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64.json b/.sqlx/query-6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64.json
deleted file mode 100644
index 531266f154..0000000000
--- a/.sqlx/query-6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants\n WHERE channel_id = $1\n AND user_id = $2\n AND role IN (\n 'admin'::comms_participant_role,\n 'owner'::comms_participant_role\n )\n ) AS \"exists!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64"
-}
diff --git a/.sqlx/query-8b8bf65a87d7dbc7689a0e8e3d85a425805ffc2cdac1a78032f1f8737c372b4c.json b/.sqlx/query-8b8bf65a87d7dbc7689a0e8e3d85a425805ffc2cdac1a78032f1f8737c372b4c.json
new file mode 100644
index 0000000000..714728306d
--- /dev/null
+++ b/.sqlx/query-8b8bf65a87d7dbc7689a0e8e3d85a425805ffc2cdac1a78032f1f8737c372b4c.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants\n WHERE channel_id = $1\n AND user_id = $2\n AND left_at IS NULL\n AND (\n role IN (\n 'admin'::comms_participant_role,\n 'owner'::comms_participant_role\n )\n OR (\n NOT $3\n AND role = 'member'::comms_participant_role\n )\n )\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "8b8bf65a87d7dbc7689a0e8e3d85a425805ffc2cdac1a78032f1f8737c372b4c"
+}
diff --git a/apps/docs/AI/mcp/tools/rename-channel.mdx b/apps/docs/AI/mcp/tools/rename-channel.mdx
index 7e11e03296..e455f0cf65 100644
--- a/apps/docs/AI/mcp/tools/rename-channel.mdx
+++ b/apps/docs/AI/mcp/tools/rename-channel.mdx
@@ -1,11 +1,11 @@
---
title: RenameChannel
-description: "Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel."
+description: "Rename an existing channel. Requires the current user to be an active channel participant. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel."
---
# RenameChannel
-Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.
+Rename an existing channel. Requires the current user to be an active channel participant. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.
## Parameters
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index 8192b3a357..c2ab7bd9b8 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -187,10 +187,6 @@ function NewTop(props: { channelId: string }) {
tab.value === 'call' ? { ...tab, label: <CallTabLabel /> } : tab
);
- // The generic rename op is gated on the document block-load signals, which
- // the channel block never sets — so the menu offers a channel-local rename
- // built from the channels context instead. The action's own gate keeps it
- // off DMs and channels the user does not own.
const channelEntity = () => {
const ch = channel();
if (!ch) return undefined;
@@ -200,6 +196,11 @@ function NewTop(props: { channelId: string }) {
blockName: 'channel',
channelType: ch.channel_type,
ownerId: ch.owner_id,
+ isParticipant: participantsQuery.isSuccess
+ ? (participantsQuery.data ?? []).some(
+ (participant) => participant.user_id === userId()
+ )
+ : undefined,
});
};
diff --git a/apps/web/src/features/entity/tests/buildEntityData.test.ts b/apps/web/src/features/entity/tests/buildEntityData.test.ts
index 58b4a48641..609cf09706 100644
--- a/apps/web/src/features/entity/tests/buildEntityData.test.ts
+++ b/apps/web/src/features/entity/tests/buildEntityData.test.ts
@@ -114,6 +114,21 @@ describe('buildEntityData', () => {
});
expect(e).toEqual({ ...base, type: 'channel', channelType: 'team' });
});
+
+ it('passes isParticipant through when provided', () => {
+ const e = buildEntityData({
+ ...base,
+ blockName: 'channel',
+ channelType: 'team',
+ isParticipant: false,
+ });
+ expect(e).toEqual({
+ ...base,
+ type: 'channel',
+ channelType: 'team',
+ isParticipant: false,
+ });
+ });
});
describe('email', () => {
diff --git a/apps/web/src/features/entity/utils/buildEntityData.ts b/apps/web/src/features/entity/utils/buildEntityData.ts
index 8938ad89a4..912c896138 100644
--- a/apps/web/src/features/entity/utils/buildEntityData.ts
+++ b/apps/web/src/features/entity/utils/buildEntityData.ts
@@ -23,6 +23,7 @@ export type BuildEntityDataArgs = {
fileType?: string;
isCompleted?: boolean;
channelType?: ChannelEntity['channelType'];
+ isParticipant?: boolean;
cron?: string;
enabled?: boolean;
channelId?: string;
@@ -138,6 +139,9 @@ export function buildEntityData(
...base,
type: 'channel',
channelType: args.channelType,
+ ...(args.isParticipant === undefined
+ ? {}
+ : { isParticipant: args.isParticipant }),
};
})
.with(
diff --git a/apps/web/src/features/next-soup/actions/make-rename-action.test.ts b/apps/web/src/features/next-soup/actions/make-rename-action.test.ts
new file mode 100644
index 0000000000..6e8ea45c1a
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/make-rename-action.test.ts
@@ -0,0 +1,94 @@
+import type { EntityData } from '@entity';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@app/features/entity/bulk-edit/BulkEditEntityModal', () => ({
+ openBulkEditModal: vi.fn(),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: vi.fn(), failure: vi.fn(), dismiss: vi.fn() },
+}));
+vi.mock('../utils', () => ({
+ restoreSoupFocus: vi.fn(),
+}));
+
+import { makeRenameAction } from './make-rename-action';
+
+const ME = 'macro|[email protected]';
+const OTHER = 'macro|[email protected]';
+
+const entity = (
+ type: EntityData['type'],
+ overrides: Partial<EntityData> = {}
+) =>
+ ({ type, id: 'e1', name: 'Thing', ownerId: ME, ...overrides }) as EntityData;
+
+const channel = (
+ overrides: Partial<Extract<EntityData, { type: 'channel' }>> = {}
+) =>
+ entity('channel', {
+ channelType: 'private',
+ ...overrides,
+ });
+
+const { canExecute } = makeRenameAction({ userId: () => ME });
+
+describe('makeRenameAction.canExecute', () => {
+ it('allows the owner of a private channel to rename it', () => {
+ expect(canExecute(channel({ channelType: 'private', ownerId: ME }))).toBe(
+ true
+ );
+ });
+
+ it('allows the owner of a team channel to rename it', () => {
+ expect(canExecute(channel({ channelType: 'team', ownerId: ME }))).toBe(
+ true
+ );
+ });
+
+ it('allows a non-owner participant to rename a channel', () => {
+ expect(
+ canExecute(
+ channel({
+ ownerId: OTHER,
+ isParticipant: true,
+ })
+ )
+ ).toBe(true);
+ });
+
+ it('treats a missing isParticipant flag as joined', () => {
+ expect(canExecute(channel({ ownerId: OTHER }))).toBe(true);
+ });
+
+ it('refuses a team channel the viewer has not joined', () => {
+ expect(
+ canExecute(
+ channel({
+ channelType: 'team',
+ isParticipant: false,
+ })
+ )
+ ).toBe(false);
+ });
+
+ it('refuses direct messages', () => {
+ expect(
+ canExecute(channel({ channelType: 'direct_message', ownerId: ME }))
+ ).toBe(false);
+ });
+
+ it('allows renaming a document the caller owns', () => {
+ expect(canExecute(entity('document'))).toBe(true);
+ });
+
+ it('refuses a document owned by someone else', () => {
+ expect(canExecute(entity('document', { ownerId: OTHER }))).toBe(false);
+ });
+
+ it('refuses channel messages, threads, email, and foreign rows', () => {
+ expect(canExecute(entity('channel_message'))).toBe(false);
+ expect(canExecute(entity('channel_thread'))).toBe(false);
+ expect(canExecute(entity('email'))).toBe(false);
+ expect(canExecute(entity('foreign'))).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/next-soup/actions/make-rename-action.ts b/apps/web/src/features/next-soup/actions/make-rename-action.ts
index b467f0e957..8f407e86de 100644
--- a/apps/web/src/features/next-soup/actions/make-rename-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-rename-action.ts
@@ -20,7 +20,7 @@ export const makeRenameAction = (options: MakeRenameOptions) => {
if (entity.type === 'channel') {
if (entity.channelType === 'direct_message') return false;
- return entity.ownerId === userId();
+ return entity.isParticipant !== false;
}
return entity.ownerId === userId();
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index eb70658322..5e76843479 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -5510,7 +5510,7 @@ export interface ReadSpreadsheet {
includeStyles?: boolean | null;
}
/**
- * Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.
+ * Rename an existing channel. Requires the current user to be an active channel participant. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.
*/
export interface RenameChannel {
/**
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index dd1560523f..b76cab9fd3 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -4046,7 +4046,7 @@ export const removeParticipantsBody = zod
.describe('Request to remove participants.');
/**
- * @summary Set a channel or group chat profile picture. Requires rename permission.
+ * @summary Set a channel or group chat profile picture. Requires channel admin or owner access.
*/
export const setChannelPictureParams = zod.object({
channel_id: zod.uuid().describe('Channel ID'),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 9fdae3135c..489ecc05ae 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -4253,7 +4253,7 @@
"/channels/{channel_id}/profile_picture": {
"put": {
"tags": ["channels::inbound::axum_router::profile_picture"],
- "summary": "Set a channel or group chat profile picture. Requires rename permission.",
+ "summary": "Set a channel or group chat profile picture. Requires channel admin or owner access.",
"operationId": "set_channel_picture",
"parameters": [
{
diff --git a/crates/channels/src/domain/entity_mutation.rs b/crates/channels/src/domain/entity_mutation.rs
index 3de2a579b6..de5296eae1 100644
--- a/crates/channels/src/domain/entity_mutation.rs
+++ b/crates/channels/src/domain/entity_mutation.rs
@@ -1,7 +1,7 @@
//! Unified entity-mutation capability impls for channels.
use entity_access::domain::models::{
- AdminParticipantRole, EntityAccessReceipt, OwnerParticipantRole, RequiredPermission,
+ EntityAccessReceipt, MemberParticipantRole, OwnerParticipantRole, RequiredPermission,
};
use entity_mutation::{
DeleteEntityPermanently, EntityMutationEffect, EntityMutationErrorCode, RenameEntity,
@@ -49,7 +49,7 @@ impl<R, E, P, M, F> RenameEntity for ChannelServiceImpl<R, E, P, M, F>
where
Self: ChannelService,
{
- type Receipt = AdminParticipantRole;
+ type Receipt = MemberParticipantRole;
async fn rename_entity(
&self,
@@ -57,11 +57,8 @@ where
receipt: EntityAccessReceipt<Self::Receipt>,
display_name: String,
) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {
- let channel_id = channel_uuid(&entity)?;
- let sender = sender_from_receipt(&receipt)?;
self.patch_channel(
- sender,
- channel_id,
+ receipt,
PatchChannelRequest {
channel_name: Some(display_name),
convert_to_team_channel: None,
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index bdaec8395b..57e9e4e435 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -790,10 +790,12 @@ pub trait ChannelService: Send + Sync + 'static {
}
/// Patch a channel.
+ ///
+ /// Name-only updates are allowed for any member receipt. Converting a
+ /// channel or changing auto-join still requires channel admin access.
fn patch_channel(
&self,
- _actor: Sender,
- _channel_id: Uuid,
+ _access: EntityAccessReceipt<MemberParticipantRole>,
_req: PatchChannelRequest,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
async move {
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index 7ab97a944d..eda4870652 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -23,7 +23,9 @@ use crate::domain::{
use bot_id::BotIdStr;
use bot_id::cowlike::CowLike;
use channel_sender::ChannelSender;
-use entity_access::domain::models::{EntityAccessReceipt, EntityType, MemberParticipantRole};
+use entity_access::domain::models::{
+ AdminParticipantRole, EntityAccessReceipt, EntityType, MemberParticipantRole,
+};
use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::models::{PatchMessageNotificationPolicy, SimpleMention};
use models_pagination::{CreatedAt, PaginateOn, Query};
@@ -531,11 +533,10 @@ where
.await
}
- #[tracing::instrument(err, skip(self, req))]
+ #[tracing::instrument(err, skip(self, access, req))]
async fn patch_channel(
&self,
- actor: Sender,
- channel_id: Uuid,
+ access: EntityAccessReceipt<MemberParticipantRole>,
mut req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
if req.channel_name.is_none()
@@ -545,7 +546,28 @@ where
return Ok(());
}
- let actor = require_user_actor(&actor)?;
+ if (req.convert_to_team_channel.is_some() || req.auto_join_team.is_some())
+ && !access
+ .entity_permission()
+ .satisfies::<AdminParticipantRole>()
+ {
+ return Err(ChannelMutationErr::Forbidden(
+ "converting a channel or changing auto-join requires channel admin access"
+ .to_string(),
+ ));
+ }
+
+ if access.entity().entity_type != EntityType::Channel {
+ return Err(ChannelMutationErr::BadRequest(
+ "channel access receipt required".into(),
+ ));
+ }
+ let actor = access
+ .get_authenticated_user()
+ .cloned()
+ .map_err(|_| ChannelMutationErr::Unauthorized("authenticated user required".into()))?;
+ let channel_id = Uuid::parse_str(&access.entity().entity_id)
+ .map_err(|error| ChannelMutationErr::BadRequest(error.to_string()))?;
let info = self
.repo
.get_channel_info(channel_id)
@@ -2057,11 +2079,10 @@ where
async fn patch_channel(
&self,
- actor: Sender,
- channel_id: Uuid,
+ access: EntityAccessReceipt<MemberParticipantRole>,
req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
- ChannelServiceImpl::patch_channel(self, actor, channel_id, req).await
+ ChannelServiceImpl::patch_channel(self, access, req).await
}
async fn delete_channel(
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index cc463bede2..fda6e5914d 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -20,6 +20,7 @@ use crate::domain::{
};
use channel_sender::ChannelSender;
use chrono::Utc;
+use entity_access::domain::models::ParticipantRole as AccessRole;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use std::{
collections::HashMap,
@@ -993,6 +994,23 @@ fn sender(user_id: &str) -> Sender {
Sender::new_from_user(macro_id(user_id))
}
+fn patch_receipt(
+ user_id: &str,
+ channel_id: Uuid,
+ role: AccessRole,
+) -> EntityAccessReceipt<MemberParticipantRole> {
+ use entity_access::domain::models::{Entity, EntityPermission};
+ EntityAccessReceipt::<MemberParticipantRole>::try_new_authenticated_user(
+ macro_id(user_id),
+ Entity {
+ entity_id: channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ },
+ EntityPermission::ChannelRole { role },
+ )
+ .unwrap()
+}
+
#[tokio::test]
async fn post_message_emits_message_posted_event_and_updates_share_permissions() {
let channel_id = Uuid::new_v4();
@@ -2843,8 +2861,7 @@ async fn patch_channel_dispatches_channel_updated() {
let svc = mutation_service(repo, events.clone(), FakeReferenceSharing::default());
svc.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Member),
PatchChannelRequest {
channel_name: Some("Renamed".to_string()),
convert_to_team_channel: None,
@@ -2874,8 +2891,7 @@ async fn noop_patch_channel_dispatches_nothing() {
);
svc.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Member),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: None,
@@ -2904,8 +2920,7 @@ async fn patch_channel_conversion_uses_the_users_team() {
);
svc.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Admin),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: Some(true),
@@ -2942,8 +2957,7 @@ async fn patch_channel_conversion_names_an_unnamed_private_channel() {
);
svc.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Admin),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: Some(true),
@@ -2978,8 +2992,7 @@ async fn patch_team_channel_conversion_to_private_clears_team_settings() {
);
svc.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Admin),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: Some(false),
@@ -3012,8 +3025,7 @@ async fn patch_channel_conversion_requires_the_user_to_have_a_team() {
let err = svc
.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Admin),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: Some(true),
@@ -3041,8 +3053,7 @@ async fn patch_channel_rejects_enabling_auto_join_on_a_non_team_channel() {
let err = svc
.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Admin),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: None,
@@ -3075,8 +3086,7 @@ async fn patch_team_channel_auto_join_uses_its_existing_team() {
);
svc.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Admin),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: None,
@@ -3104,8 +3114,7 @@ async fn patch_channel_allows_disabling_auto_join_without_a_team() {
);
svc.patch_channel(
- sender("macro|[email protected]"),
- channel_id,
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Admin),
PatchChannelRequest {
channel_name: None,
convert_to_team_channel: None,
@@ -3122,6 +3131,89 @@ async fn patch_channel_allows_disabling_auto_join_without_a_team() {
assert_eq!(state.channel_patches[0].0.auto_join_team, Some(false));
}
+#[tokio::test]
+async fn patch_channel_member_can_rename() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_channel(
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Member),
+ PatchChannelRequest {
+ channel_name: Some("Member Name".to_string()),
+ convert_to_team_channel: None,
+ auto_join_team: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.channel_patches.len(), 1);
+ assert_eq!(
+ state.channel_patches[0].0.channel_name.as_deref(),
+ Some("Member Name")
+ );
+ assert_eq!(state.channel_patches[0].0.convert_to_team_channel, None);
+ assert_eq!(state.channel_patches[0].0.auto_join_team, None);
+ let events = events.events.lock().unwrap();
+ assert!(matches!(
+ events.as_slice(),
+ [ChannelEvent::ChannelUpdated { channel_name: Some(name), .. }]
+ if name == "Member Name"
+ ));
+}
+
+#[tokio::test]
+async fn patch_channel_member_cannot_convert_or_change_auto_join() {
+ let requests = [
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(true),
+ auto_join_team: None,
+ },
+ PatchChannelRequest {
+ channel_name: Some("Still Member".to_string()),
+ convert_to_team_channel: None,
+ auto_join_team: Some(false),
+ },
+ ];
+ for req in requests {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().user_team_id = Some(Uuid::new_v4());
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ let err = svc
+ .patch_channel(
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Member),
+ req,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ ChannelMutationErr::Forbidden(message)
+ if message == "converting a channel or changing auto-join requires channel admin access"
+ ));
+ let state = repo.state.lock().unwrap();
+ assert!(state.channel_patches.is_empty());
+ assert_eq!(state.user_team_id_lookups, 0);
+ assert!(events.events.lock().unwrap().is_empty());
+ }
+}
+
#[tokio::test]
async fn remove_participants_dispatches_participants_removed() {
let channel_id = Uuid::new_v4();
diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rs
index 2e8f08686a..6acc3e25d4 100644
--- a/crates/channels/src/inbound/axum_router.rs
+++ b/crates/channels/src/inbound/axum_router.rs
@@ -38,8 +38,8 @@ use chrono::{DateTime, Utc};
use entity_access::{
domain::{
models::{
- AccessError, AccessLevel, AdminParticipantRole, EntityAccessReceipt, EntityType,
- MemberParticipantRole, OwnerParticipantRole, RequiredPermission, ViewOnly,
+ AccessError, AccessLevel, EntityAccessReceipt, EntityType, MemberParticipantRole,
+ OwnerParticipantRole, RequiredPermission, ViewOnly,
},
ports::EntityAccessService,
},
@@ -523,12 +523,13 @@ pub async fn patch_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Json(req): Json<PatchChannelRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
- let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
- let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
- state.service.patch_channel(actor, channel_id, req).await?;
+ state
+ .service
+ .patch_channel(access.entity_access_receipt, req)
+ .await?;
Ok((StatusCode::OK, "patched channel".to_string()))
}
diff --git a/crates/channels/src/inbound/axum_router/profile_picture.rs b/crates/channels/src/inbound/axum_router/profile_picture.rs
index 9904e7f863..7ba0074e68 100644
--- a/crates/channels/src/inbound/axum_router/profile_picture.rs
+++ b/crates/channels/src/inbound/axum_router/profile_picture.rs
@@ -1,4 +1,5 @@
use super::*;
+use entity_access::domain::models::AdminParticipantRole;
/// Replace a channel's picture, or remove it by sending a null file id.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
@@ -7,7 +8,7 @@ pub struct SetChannelPictureRequest {
pub profile_picture_id: Option<Uuid>,
}
-/// Set a channel or group chat profile picture. Requires rename permission.
+/// Set a channel or group chat profile picture. Requires channel admin or owner access.
#[utoipa::path(
put,
path = "/channels/{channel_id}/profile_picture",
diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rs
index 2fa3e0c206..14d414e275 100644
--- a/crates/channels/src/inbound/axum_router/test.rs
+++ b/crates/channels/src/inbound/axum_router/test.rs
@@ -18,8 +18,8 @@ use axum::{
use entity_access::domain::models::TeamRole;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotAccessScope, BotId, Entity, EntityAccessReceipt,
- EntityPermission, EntityType, MemberParticipantRole,
+ AccessError, AccessLevel, AdminParticipantRole, BotAccessScope, BotId, Entity,
+ EntityAccessReceipt, EntityPermission, EntityType, MemberParticipantRole,
ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
@@ -865,8 +865,7 @@ impl ChannelService for RecordingMutationService {
async fn patch_channel(
&self,
- _actor: Sender,
- _channel_id: Uuid,
+ _access: EntityAccessReceipt<MemberParticipantRole>,
_req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
Ok(())
diff --git a/crates/channels/src/inbound/toolset.rs b/crates/channels/src/inbound/toolset.rs
index e2c9a0b4d4..bd3c2fbaaa 100644
--- a/crates/channels/src/inbound/toolset.rs
+++ b/crates/channels/src/inbound/toolset.rs
@@ -23,8 +23,8 @@ use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};
use bot_id::BotId;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, AdminParticipantRole, BotAccessScope, EntityAccessReceipt,
- EntityType, MemberParticipantRole, RequiredPermission,
+ AccessError, AccessLevel, BotAccessScope, EntityAccessReceipt, EntityType,
+ MemberParticipantRole, RequiredPermission,
},
ports::EntityAccessService,
};
@@ -131,13 +131,13 @@ where
.map_err(channel_access_error)
}
- /// Mint the same admin receipt HTTP uses before renaming a channel.
- pub async fn require_channel_admin(
+ /// Mint a member receipt before renaming a channel.
+ pub async fn require_channel_rename(
&self,
request_context: &RequestContext,
channel_id: Uuid,
- ) -> Result<EntityAccessReceipt<AdminParticipantRole>, ToolCallError> {
- self.channel_receipt(request_context, channel_id, ChannelReceiptKind::Admin)
+ ) -> Result<EntityAccessReceipt<MemberParticipantRole>, ToolCallError> {
+ self.channel_receipt(request_context, channel_id, ChannelReceiptKind::Rename)
.await
}
@@ -171,7 +171,7 @@ where
#[derive(Clone, Copy)]
enum ChannelReceiptKind {
- Admin,
+ Rename,
Member,
}
@@ -196,19 +196,16 @@ fn channel_access_error(err: AccessError) -> ToolCallError {
fn channel_receipt_error(kind: ChannelReceiptKind, err: AccessError) -> ToolCallError {
let description = match (kind, &err) {
(
- ChannelReceiptKind::Admin,
+ ChannelReceiptKind::Rename,
AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),
- ) => "you need channel admin access to rename this channel",
+ ) => "you must be a member of the channel to rename it",
(
ChannelReceiptKind::Member,
AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),
) => "you must be a member of the channel to change its participants",
(_, AccessError::NotFound(_)) => "channel not found",
(_, AccessError::BadRequest(_)) => "invalid channel id",
- (ChannelReceiptKind::Admin, AccessError::Unavailable(_) | AccessError::Internal(_)) => {
- "failed to verify channel admin access"
- }
- (ChannelReceiptKind::Member, AccessError::Unavailable(_) | AccessError::Internal(_)) => {
+ (_, AccessError::Unavailable(_) | AccessError::Internal(_)) => {
"failed to verify channel membership"
}
};
diff --git a/crates/channels/src/inbound/toolset/rename_channel.rs b/crates/channels/src/inbound/toolset/rename_channel.rs
index c47684603d..964c807a6b 100644
--- a/crates/channels/src/inbound/toolset/rename_channel.rs
+++ b/crates/channels/src/inbound/toolset/rename_channel.rs
@@ -1,4 +1,4 @@
-use super::{ChannelToolContext, channel_mutation_error, channel_name, user_sender};
+use super::{ChannelToolContext, channel_mutation_error, channel_name};
use crate::domain::models::PatchChannelRequest;
use crate::domain::ports::ChannelService;
use ai_toolset::{
@@ -29,7 +29,7 @@ pub struct RenameChannelResponse {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "RenameChannel",
- description = "Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel."
+ description = "Rename an existing channel. Requires the current user to be an active channel participant. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel."
)]
pub struct RenameChannel {
/// Channel to rename.
@@ -64,9 +64,8 @@ where
) -> ToolResult<Self::Output> {
let name = channel_name(&self.name)?;
let receipt = service_context
- .require_channel_admin(&request_context, self.channel_id)
+ .require_channel_rename(&request_context, self.channel_id)
.await?;
- let actor = user_sender(&receipt)?;
let previous_name = service_context
.service
.get_channel_metadata(self.channel_id, request_context.user_id.clone())
@@ -77,8 +76,7 @@ where
service_context
.service
.patch_channel(
- actor,
- self.channel_id,
+ receipt,
PatchChannelRequest {
channel_name: Some(name.clone()),
convert_to_team_channel: None,
diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rs
index 471fb42a26..2e15f456e9 100644
--- a/crates/channels/src/inbound/toolset/test.rs
+++ b/crates/channels/src/inbound/toolset/test.rs
@@ -22,7 +22,8 @@ use bot_id::BotId;
use entity_access::domain::{
models::{
AccessError, AccessLevel, BotAccessScope, CallChannelInfo, EntityAccessReceipt,
- EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo,
+ EntityPermission, EntityType, MemberParticipantRole, RequiredPermission, TeamRole,
+ UserTeamInfo,
},
ports::{EntityAccessService, NoOpEntityAccessService},
};
@@ -297,13 +298,19 @@ impl ChannelService for ToolTestChannelService {
async fn patch_channel(
&self,
- actor: Sender,
- channel_id: Uuid,
+ access: EntityAccessReceipt<MemberParticipantRole>,
req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
if let Some(message) = &self.patch_error {
return Err(ChannelMutationErr::BadRequest(message.clone()));
}
+ let actor = Sender::new_from_user(
+ access
+ .get_authenticated_user()
+ .cloned()
+ .expect("authenticated user"),
+ );
+ let channel_id = Uuid::parse_str(&access.entity().entity_id).expect("channel id");
self.patches
.lock()
.expect("patch lock")
@@ -557,7 +564,8 @@ fn rename_channel_schema_is_valid() {
assert!(result.is_ok(), "{result:?}");
let validated = result.unwrap();
assert_eq!(validated.name, "RenameChannel");
- assert!(validated.description.contains("Rename"));
+ assert!(validated.description.contains("participant"));
+ assert!(!validated.description.to_lowercase().contains("admin"));
}
#[test]
@@ -839,7 +847,7 @@ async fn create_channel_surfaces_domain_errors() {
}
#[tokio::test]
-async fn rename_channel_requires_admin_and_patches_only_the_name() {
+async fn rename_channel_requires_member_and_patches_only_the_name() {
let channel_id = Uuid::new_v4();
let service = ToolTestChannelService {
metadata_name: Some("Old Name".to_string()),
@@ -856,7 +864,7 @@ async fn rename_channel_requires_admin_and_patches_only_the_name() {
}
.call(ServiceContext(context), RequestContext::new(user_id()))
.await
- .expect("admin can rename");
+ .expect("member can rename");
assert_eq!(response.name, "New Name");
assert_eq!(response.previous_name.as_deref(), Some("Old Name"));
@@ -870,7 +878,7 @@ async fn rename_channel_requires_admin_and_patches_only_the_name() {
}
#[tokio::test]
-async fn rename_channel_rejects_non_admins() {
+async fn rename_channel_rejects_non_members() {
let context = ChannelToolContext::new(
Arc::new(RecordingMessages::default()),
ToolTestChannelService::default(),
@@ -886,11 +894,11 @@ async fn rename_channel_rejects_non_admins() {
}
.call(ServiceContext(context), RequestContext::new(user_id()))
.await
- .expect_err("non-admin");
+ .expect_err("non-member");
assert_eq!(
error.description,
- "you need channel admin access to rename this channel"
+ "you must be a member of the channel to rename it"
);
}
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index 7fd01c3f22..6847435643 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -3091,6 +3091,8 @@ impl ChannelRepo for PgChannelsRepo {
anyhow::bail!("team id is required to patch team channel settings");
}
+ let requires_admin = convert_to_team_channel.is_some() || auto_join_team.is_some();
+
let mut transaction = self.pool.begin().await?;
let row = sqlx::query_as!(
ExistsRow,
@@ -3100,22 +3102,35 @@ impl ChannelRepo for PgChannelsRepo {
FROM comms_channel_participants
WHERE channel_id = $1
AND user_id = $2
- AND role IN (
- 'admin'::comms_participant_role,
- 'owner'::comms_participant_role
+ AND left_at IS NULL
+ AND (
+ role IN (
+ 'admin'::comms_participant_role,
+ 'owner'::comms_participant_role
+ )
+ OR (
+ NOT $3
+ AND role = 'member'::comms_participant_role
+ )
)
) AS "exists!"
"#,
channel_id,
user_id,
+ requires_admin,
)
.fetch_one(&mut *transaction)
.await
.context("failed to check user authorization")?;
if !row.exists {
+ if requires_admin {
+ anyhow::bail!(
+ "User is not authorized to perform this action, to patch channel settings you must be an admin or owner"
+ );
+ }
anyhow::bail!(
- "User is not authorized to perform this action, to patch a channel you must be an admin or owner"
+ "User is not authorized to perform this action, to rename a channel you must be a member"
);
}
diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rs
index 3eb0549c78..f1d7cfc753 100644
--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs
@@ -554,6 +554,60 @@ async fn patch_channel_rename_advances_updated_at(pool: Pool<Postgres>) {
assert!(after.updated_at > before.updated_at);
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_channel_rename_allows_a_member(pool: Pool<Postgres>) {
+ let repo = repo(pool.clone());
+
+ repo.patch_channel(
+ CH1,
+ USER_C.to_string(),
+ None,
+ PatchChannelRequest {
+ channel_name: Some("member-renamed".to_string()),
+ convert_to_team_channel: None,
+ auto_join_team: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let after = sqlx::query!("SELECT name FROM comms_channels WHERE id = $1", CH1)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(after.name.as_deref(), Some("member-renamed"));
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_channel_settings_reject_a_member(pool: Pool<Postgres>) {
+ let repo = repo(pool);
+
+ let err = repo
+ .patch_channel(
+ CH1,
+ USER_C.to_string(),
+ None,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: None,
+ auto_join_team: Some(false),
+ },
+ )
+ .await
+ .expect_err("member cannot change auto-join");
+
+ assert!(
+ err.to_string()
+ .contains("to patch channel settings you must be an admin or owner")
+ );
+}
+
#[sqlx::test(
fixtures(path = "../../../fixtures", scripts("channels_repo")),
migrator = "MACRO_DB_MIGRATIONS"
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 2dd5a4f4d1..95f9662f13 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -333,9 +333,10 @@ message or acknowledgement and verify that it does not pull you to latest.
## Channel pictures
-Channels and group chats can have a custom picture. Admins and owners (the same
-people who can rename a channel) can open the title menu. Beside `Rename`,
-choose `Set channel picture` to add or replace a picture. Select a PNG, JPG,
+Channels and group chats can have a custom picture. Any active participant can
+`Rename` a named channel from the title menu. Direct messages cannot be renamed.
+Only admins and owners also get `Set channel picture` and `Remove channel
+picture`. Choose `Set channel picture` to add or replace a picture. Select a PNG, JPG,
WebP, or GIF up to 16 MB. The upload must finish before the picture is saved;
the server accepts only supported images uploaded by the person setting the
picture. An error leaves the previous picture in place. When a picture is set, the menu also offers
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index a14508e7ff..183a9a840a 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -715,7 +715,7 @@ export class Sdk extends HeyApiClient {
}
/**
- * Set a channel or group chat profile picture. Requires rename permission.
+ * Set a channel or group chat profile picture. Requires channel admin or owner access.
*/
public setChannelPicture<ThrowOnError extends boolean = false>(options: Options<SetChannelPictureData, ThrowOnError>): RequestResult<SetChannelPictureResponses, SetChannelPictureErrors, ThrowOnError> {
return (options.client ?? this.client).put<SetChannelPictureResponses, SetChannelPictureErrors, ThrowOnError>({
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 9fdae3135c..489ecc05ae 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -4253,7 +4253,7 @@
"/channels/{channel_id}/profile_picture": {
"put": {
"tags": ["channels::inbound::axum_router::profile_picture"],
- "summary": "Set a channel or group chat profile picture. Requires rename permission.",
+ "summary": "Set a channel or group chat profile picture. Requires channel admin or owner access.",
"operationId": "set_channel_picture",
"parameters": [
{