Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Only a workspace admin puts a room in a room group
Petr Bauche6d631680ce0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6abafc11e..7404072a3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -109,9 +109,17 @@ version of their own to them without also giving them a release of their own.whole workspace and have no owner, so any member could rename, move ordelete one. Creating, changing and deleting a group, from the dashboard,the API or an agent's `create_room_group`, now needs a workspace admin (for- an agent, its owner). Anyone can still file a room they can write into an- existing group. Group room counts, and the rooms `get_room_group_detail`- lists, now leave out private rooms the caller cannot read.+ an agent, its owner). Group room counts, and the rooms+ `get_room_group_detail` lists, now leave out private rooms the caller+ cannot read.+- **Only a workspace admin puts a room in a room group.** A room's group can+ decide who may address an agent, since an addressing policy can admit+ everyone in a group's rooms, so any member who filed a room they could+ write into a group could address that group's agents. Putting a room in a+ group, whether when creating it, from the room's page, from the groups+ page or through an agent's `create_room`, now needs a workspace admin (for+ an agent, its owner). Taking a room out of its group still only needs+ write access to the room.#### Added- **The gateway says what the caller may change in a room.** Rooms, in thediff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 2916c21d1..85fda8067 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -719,12 +719,16 @@ groups nest under a parent to form a tree.(`member_rooms`), and its immediate `child_groups`.- **`create_room_group`** — provision a group. Only an agent whose owner is aworkspace admin may: groups are shared by the whole workspace. Anyone else- is refused, so file the room under an existing group or ask an admin.+ is refused; ask an admin.Required: `name`. Optional: `description`, `color`, `parent_group_name`(omit it for a top-level group). Creating a group does not move any roomsinto it; file rooms under it later by passing `group_name` to`create_room`. Missing parents are not created for you: create each levelfirst.+- **Filing a room in a group** (`group_name` on `create_room`) also needs an+ owner who is a workspace admin, because an agent's addressing policy can+ admit everyone in a group's rooms. Without one, create the room standalone+ and ask an admin to file it.Name a group by its **path**: the top-level group, then each child, separatedby `/`, e.g. `Fraud/Incidents`. The `path` that `list_room_groups` returnsdiff --git a/core/switch_core/authz.py b/core/switch_core/authz.pyindex 3494c3433..299500195 100644--- a/core/switch_core/authz.py+++ b/core/switch_core/authz.py@@ -208,6 +208,19 @@ def can_delete_room_document()+def require_group_filing(is_admin: bool) -> None:+ """Raise ``PermissionError`` unless a workspace admin is putting a room+ into a room group.++ A room's group is an input to agents' addressing policies (a rule can+ admit every room in a group), so filing a room into one can open agents+ to its members. Groups are admin-managed, and so is what goes in them.+ Taking a room out of a group only needs write access to the room.+ """+ if not is_admin:+ raise PermissionError("Only a workspace admin can put a room in a room group.")++def validate_visibility_pair(read_visibility: str, write_visibility: str) -> None:"""Validate a (read, write) visibility pair, raising ``ValueError`` if bad.diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex a0edfbbc2..b241b8a2f 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -974,6 +974,8 @@ async def create_room(Names match exactly. An ambiguous bare name errors with the pathof each match to retry with; an unknown path errors naming thefirst segment not found. Omit to leave the room standalone.+ Filing a room in a group needs an owner who is a workspace+ admin; anyone else is refused.roles: Optional room-roles to define at creation. Each entry is`{"name": "...", "instructions": "...", "exclusive": bool}`.Roles are assumable instruction bundles agents pick up withdiff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 32fb19cb4..c930bb611 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -34,7 +34,13 @@ from switch_core.agent_icon import ()from switch_core.aliases import check_alias_collisions, validate_alias_formatfrom switch_core.attachments import parse_attachment_group-from switch_core.authz import Action, Principal, require, require_manage+from switch_core.authz import (+ Action,+ Principal,+ require,+ require_group_filing,+ require_manage,+)from switch_core.bridges.agent.api.session_reporter import SessionReporterfrom switch_core.bridges.agent.api_key_cache import ApiKeyCachefrom switch_core.bridges.agent.mediation import MediationService@@ -2935,6 +2941,8 @@ class AgentCore:session, agent_id)group_id = await self._resolve_group_name(session, group_name)+ if group_id is not None:+ require_group_filing(owner_is_admin)owner = await session.get(User, agent.owner_id) if agent.owner_id else Noneif (reference_ids or package_ids) and agent.owner_id is None:raise ValueError(diff --git a/core/switch_core/gateway/room_groups.py b/core/switch_core/gateway/room_groups.pyindex c67c220f8..286f5098c 100644--- a/core/switch_core/gateway/room_groups.py+++ b/core/switch_core/gateway/room_groups.py@@ -6,7 +6,7 @@ from typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPException, Responsefrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.authz import Principal, require+from switch_core.authz import Principal, require, require_group_filingfrom switch_core.db.models import RoomGroup, Userfrom switch_core.db.stores.room_group_store import (RoomGroupNameTaken,@@ -154,10 +154,15 @@ async def assign_rooms_to_group(user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomGroupAssignResponse:- """Bulk-assign rooms into a group. Requires write access to each room;- unknown room ids are skipped."""+ """Bulk-assign rooms into a group. Requires a workspace admin (see+ `require_group_filing`) and write access to each room; unknown room ids+ are skipped."""if await room_group_store.get(session, group_id) is None:raise HTTPException(status_code=404, detail="Room group not found")+ try:+ require_group_filing(is_admin)+ except PermissionError as e:+ raise HTTPException(status_code=403, detail=str(e)) from eprincipal = Principal(user.id, is_admin)forbidden: list[str] = []diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex dba305ec7..f781b871b 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -15,6 +15,7 @@ from switch_core.authz import (Principal,can,can_unlink_from_room,+ require_group_filing,)from switch_core.bridges.agent.operations.agent_management import management_portfrom switch_core.bridges.agent.protocol.agent_core import AgentCore@@ -102,6 +103,13 @@ logger = logging.getLogger(__name__)router = APIRouter()+def _require_group_filing(is_admin: bool) -> None:+ try:+ require_group_filing(is_admin)+ except PermissionError as e:+ raise HTTPException(status_code=403, detail=str(e)) from e++async def _require_room_released(session: AsyncSession,room_store: RoomStore,@@ -408,6 +416,8 @@ async def create_room(is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:_validate_create(req)+ if req.group_id is not None:+ _require_group_filing(is_admin)config = RoomCreateConfig(name=req.name,description=req.description,@@ -1060,9 +1070,14 @@ async def put_room_group(user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- """Assign the room to a group, or make it standalone (`group_id=null`)."""+ """Assign the room to a group, or make it standalone (`group_id=null`).++ Taking a room out of its group needs write access to it; putting it in+ one also needs a workspace admin."""principal = Principal(user.id, is_admin)await authorize_room(session, room_store, room_id, principal, "write")+ if req.group_id is not None:+ _require_group_filing(is_admin)try:await room_store.set_group(session, room_id, req.group_id)except ValueError as e:diff --git a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.pyindex b6954ccee..7998ab767 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py@@ -129,3 +129,33 @@ class TestListRoomGroups:assert by_path["P / C"]["parent_group_id"] == parent.id# Sorted by path.assert [g["path"] for g in result] == ["P", "P / C"]+++class TestFilingNeedsAnAdminOwner:+ async def test_an_agent_of_a_non_admin_cannot_file_a_room_in_a_group(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _bare_service()+ svc.session_factory = session_factory # type: ignore[assignment]++ async def acting_as_member(session: AsyncSession, agent_id: str) -> Any:+ return SimpleNamespace(id=agent_id, owner_id="owner"), "owner", False++ svc._resolve_acting_identity = acting_as_member # type: ignore[method-assign]+ async with session_factory() as session:+ await RoomGroupStore().create(+ session, name="Eng", description=None, color=None, parent_group_id=None+ )+ await session.commit()++ with pytest.raises(PermissionError, match="workspace admin"):+ await svc.create_moderation_room(+ "agent-1",+ name="r",+ description="d",+ agent_names=[],+ user_names=None,+ channel_type=None,+ bridge_id=None,+ group_name="Eng",+ )diff --git a/core/tests/switch_core/gateway/test_room_groups_authz.py b/core/tests/switch_core/gateway/test_room_groups_authz.pyindex 03de7edb3..42578fd90 100644--- a/core/tests/switch_core/gateway/test_room_groups_authz.py+++ b/core/tests/switch_core/gateway/test_room_groups_authz.py@@ -1,4 +1,5 @@-"""Room groups are shared by the workspace: only an admin manages them."""+"""Room groups are shared by the workspace: only an admin manages them, or+puts a room in one."""from __future__ import annotations@@ -10,6 +11,7 @@ from switch_core.db.models import Room, Userfrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.gateway import rooms as rooms_routesfrom switch_core.gateway.room_groups import (assign_rooms_to_group,create_room_group,@@ -17,10 +19,13 @@ from switch_core.gateway.room_groups import (list_room_groups,patch_room_group,)+from switch_core.gateway.rooms import create_room, put_room_groupfrom switch_core.gateway.schemas import (+ RoomCreateRequest,RoomGroupAssignRequest,RoomGroupCreateRequest,RoomGroupUpdateRequest,+ RoomSetGroupRequest,)_GROUPS = RoomGroupStore()@@ -124,34 +129,121 @@ class TestManagingGroups:assert renamed.name == "Clients"- async def test_a_member_can_still_file_their_room_into_a_group(++class TestFilingRooms:+ """Putting a room in a group needs a workspace admin; taking it out needs+ write access to the room."""++ async def _setup(self, session: AsyncSession) -> tuple[User, User, Room, str]:+ member = await _add_user(session, name="member")+ admin = await _add_user(session, name="admin", role="admin")+ room = await _add_room(+ session, name="mine", owner_id=member.id, read_visibility="private"+ )+ group = await _GROUPS.create(+ session,+ name="Customers",+ description=None,+ color=None,+ parent_group_id=None,+ )+ await session.commit()+ return member, admin, room, group.id++ async def test_a_member_cannot_add_even_their_own_room_to_a_group(self, session_factory: async_sessionmaker[AsyncSession]) -> None:async with session_factory() as session:- member = await _add_user(session, name="member")- room = await _add_room(- session, name="mine", owner_id=member.id, read_visibility="private"- )- group = await _GROUPS.create(- session,- name="Customers",- description=None,- color=None,- parent_group_id=None,- )- await session.commit()+ member, _admin, room, group_id = await self._setup(session)++ with pytest.raises(HTTPException) as bulk:+ await assign_rooms_to_group(+ group_id,+ RoomGroupAssignRequest(room_ids=[room.id]),+ session,+ _GROUPS,+ _ROOMS,+ member,+ await _is_admin(session, member),+ )+ with pytest.raises(HTTPException) as single:+ await put_room_group(+ room.id,+ RoomSetGroupRequest(group_id=group_id),+ session,+ _ROOMS,+ None, # type: ignore[arg-type]+ None, # type: ignore[arg-type]+ None, # type: ignore[arg-type]+ member,+ await _is_admin(session, member),+ )++ assert bulk.value.status_code == single.value.status_code == 403+ assert (await _ROOMS.get(session, room.id)).group_id is None # type: ignore[union-attr]++ async def test_a_member_cannot_create_a_room_in_a_group(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ member, _admin, _room, group_id = await self._setup(session)++ with pytest.raises(HTTPException) as created:+ await create_room(+ RoomCreateRequest(+ name="new",+ description="d",+ agent_names=["a"],+ group_id=group_id,+ ),+ session,+ None, # type: ignore[arg-type]+ _ROOMS,+ None, # type: ignore[arg-type]+ None, # type: ignore[arg-type]+ None, # type: ignore[arg-type]+ member,+ await _is_admin(session, member),+ )++ assert created.value.status_code == 403++ async def test_an_admin_files_a_room_and_its_writer_takes_it_out(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ async def detail(_session: AsyncSession, room: Room, *_rest: object) -> Room:+ return room++ monkeypatch.setattr(rooms_routes, "_build_room_detail", detail)+ async with session_factory() as session:+ member, admin, room, group_id = await self._setup(session)response = await assign_rooms_to_group(- group.id,+ group_id,RoomGroupAssignRequest(room_ids=[room.id]),session,_GROUPS,_ROOMS,+ admin,+ await _is_admin(session, admin),+ )+ assert response.assigned == 1++ await put_room_group(+ room.id,+ RoomSetGroupRequest(group_id=None),+ session,+ _ROOMS,+ None, # type: ignore[arg-type]+ None, # type: ignore[arg-type]+ None, # type: ignore[arg-type]member,await _is_admin(session, member),)-- assert response.assigned == 1+ refreshed = await _ROOMS.get(session, room.id)+ assert refreshed is not None and refreshed.group_id is Noneclass TestRoomCounts:diff --git a/gateway/src/pages/rooms/GroupsPage.test.tsx b/gateway/src/pages/rooms/GroupsPage.test.tsxindex daefdadae..72180e765 100644--- a/gateway/src/pages/rooms/GroupsPage.test.tsx+++ b/gateway/src/pages/rooms/GroupsPage.test.tsx@@ -78,18 +78,22 @@ describe("GroupsPage", () => {expect(screen.queryByLabelText("Delete Customers")).toBeNull();});- it("files and unfiles only rooms the viewer may write to", async () => {- renderAs(false, [+ it("lets only an admin add rooms, and anyone take out a room they may write to", async () => {+ const rooms = [room("r1", "planning", "g1", true),room("r2", "leadership", "g1", false),room("r3", "retro", null, true),room("r4", "board", null, false),- ]);+ ];+ renderAs(false, rooms);fireEvent.click(screen.getByText("Customers"));-screen.getByRole("button", { name: "Remove planning from group" });expect(screen.queryByRole("button", { name: "Remove leadership from group" })).toBeNull();+ expect(screen.queryByRole("button", { name: /add rooms/i })).toBeNull();+ cleanup();+ renderAs(true, rooms);+ fireEvent.click(screen.getByText("Customers"));fireEvent.click(screen.getByRole("button", { name: "Add rooms" }));await screen.findByText("retro");expect(screen.queryByText("board")).toBeNull();diff --git a/gateway/src/pages/rooms/GroupsPage.tsx b/gateway/src/pages/rooms/GroupsPage.tsxindex f93aef22f..2faaf4734 100644--- a/gateway/src/pages/rooms/GroupsPage.tsx+++ b/gateway/src/pages/rooms/GroupsPage.tsx@@ -303,12 +303,15 @@ function MembershipPanel({group,byId,rooms,+ canAddRooms,onChanged,}: {selectedId: string | null;group: RoomGroupDetail | null;byId: Map<string, RoomGroupDetail>;rooms: RoomSummary[];+ /** Only a workspace admin may put rooms in a group. */+ canAddRooms: boolean;onChanged: () => void;}) {const [pickerOpen, setPickerOpen] = useState(false);@@ -391,7 +394,7 @@ function MembershipPanel({<Typography variant="h6" sx={{ flexGrow: 1 }} noWrap>{title}</Typography>- {!isStandalone && (+ {!isStandalone && canAddRooms && (<Buttonvariant="contained"size="small"@@ -407,8 +410,9 @@ function MembershipPanel({{isStandalone && (<Typography variant="body2" color="text.secondary">- These rooms aren't in any group. Select a group and use “Add rooms” to- organize them.+ {canAddRooms+ ? "These rooms aren't in any group. Select a group and use “Add rooms” to organize them."+ : "These rooms aren't in any group. A workspace admin can file them into one."}</Typography>)}@@ -564,6 +568,7 @@ export default function GroupsPage() {group={selectedGroup}byId={byId}rooms={roomList}+ canAddRooms={canManageGroups}onChanged={refetchAll}/></Paper>diff --git a/gateway/src/pages/rooms/RoomCreateFormBody.tsx b/gateway/src/pages/rooms/RoomCreateFormBody.tsxindex 0c8549afd..f697e96a6 100644--- a/gateway/src/pages/rooms/RoomCreateFormBody.tsx+++ b/gateway/src/pages/rooms/RoomCreateFormBody.tsx@@ -30,6 +30,7 @@ import { type RoomRoleSpec, createRoom } from "../../data/api";import { AccessSelect } from "../../components/AccessControls";import { type AccessLevel, fromAccessLevel } from "../../data/visibility";import { useAgents, useBridges, useBridgeUsers, useRoomGroups } from "../../data/hooks";+import { useAuth } from "../../data/AuthContext";import { flattenTree } from "./groupTree";import { ROOM_ACCESS_HELPERS, ROOM_ACCESS_OPTION_LABELS } from "./roomAccess";@@ -40,6 +41,8 @@ export default function RoomCreateFormBody() {const { data: agents } = useAgents();const { data: bridges } = useBridges();const { data: groups } = useRoomGroups();+ // Only a workspace admin may put a room in a group.+ const { canAdminTenant } = useAuth();const [name, setName] = useState("");const [description, setDescription] = useState("");@@ -258,7 +261,7 @@ export default function RoomCreateFormBody() {optionLabels={ROOM_ACCESS_OPTION_LABELS}/>- {(groups ?? []).length > 0 && (+ {canAdminTenant && (groups ?? []).length > 0 && (<TextFieldselectlabel="Group (optional)"diff --git a/gateway/src/pages/rooms/RoomDetailPage.tsx b/gateway/src/pages/rooms/RoomDetailPage.tsxindex d78357244..4541dd894 100644--- a/gateway/src/pages/rooms/RoomDetailPage.tsx+++ b/gateway/src/pages/rooms/RoomDetailPage.tsx@@ -120,7 +120,12 @@ export default function RoomDetailPage() {<Stack spacing={4}><RoomInfoSection room={room} /><Divider />- <GroupSection room={room} canWrite={canWrite} onChanged={refetch} />+ <GroupSection+ room={room}+ canWrite={canWrite}+ canFile={canAdminTenant}+ onChanged={refetch}+ /><Divider /><RolesSection room={room} canWrite={canWrite} onChanged={refetch} /><Divider />@@ -232,10 +237,13 @@ function InfoChip({function GroupSection({room,canWrite,+ canFile,onChanged,}: {room: RoomDetail;canWrite: boolean;+ /** May put the room in a group: a workspace admin. Anyone who can write may take it out. */+ canFile: boolean;onChanged: () => void;}) {const { data: groups, refetch: refetchGroups } = useRoomGroups();@@ -244,6 +252,13 @@ function GroupSection({const groupList = useMemo(() => groups ?? [], [groups]);const byId = useMemo(() => buildGroupIndex(groupList), [groupList]);+ const choices = useMemo(+ () =>+ flattenTree(groupList).filter(+ ({ group }) => canFile || group.id === room.group_id,+ ),+ [groupList, canFile, room.group_id],+ );const handleChange = useCallback(async (value: string) => {@@ -286,12 +301,16 @@ function GroupSection({label="Group"value={room.group_id ?? ""}onChange={(e) => handleChange(e.target.value)}- disabled={saving || !canWrite}+ disabled={saving || !canWrite || (!canFile && !room.group_id)}sx={{ width: 320 }}- helperText="Groups organise rooms in the list and colour them in the graph."+ helperText={+ canFile+ ? "Groups organise rooms in the list and colour them in the graph."+ : "Only a workspace admin can put a room in a group."+ }><MenuItem value="">Standalone (no group)</MenuItem>- {flattenTree(groupList).map(({ group, depth }) => (+ {choices.map(({ group, depth }) => (<MenuItem key={group.id} value={group.id}>{" ".repeat(depth)}{group.name}