Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Enforce room group filing centrally, and for group templates

Petr Bauche7d5a80e58dc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7404072a3..1a2894b28 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -118,8 +118,10 @@ version of their own to them without also giving them a release of their own.
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.
+ an agent, its owner). Running a template that makes a room group now
+ needs a workspace admin too, and an agent cannot run one, since it runs
+ templates without its owner's admin reach. 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 the
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index 85fda8067..a004aac06 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -729,6 +729,10 @@ groups nest under a parent to form a tree.
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.
+- **Group templates** (a `group:` document, through `create_room_from_yaml`
+ or `run_template`) are refused for every agent, whoever its owner: a
+ template runs without your owner's admin reach. Nothing is created. Ask a
+ workspace admin to run it from the dashboard.
Name a group by its **path**: the top-level group, then each child, separated
by `/`, e.g. `Fraud/Incidents`. The `path` that `list_room_groups` returns
@@ -1118,7 +1122,7 @@ Every Switch tool you call in normal operation, one line each.
- `list_room_groups` — the group tree rooms are organised into.
- `get_room_group_detail` — one group's rooms and child groups.
- `create_room_group` — provision a new room group (workspace admin agents only).
-- `create_room_from_yaml` — provision a room or group from a YAML template.
+- `create_room_from_yaml` — provision a room from a YAML template (group templates are refused).
- `get_template_guide`: how to write a template, and the schema it is checked against.
- `list_templates`: the saved templates you can use.
- `get_template`: one template's document, inputs and agent slots.
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index b241b8a2f..4713639a1 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -19,7 +19,7 @@ from typing import Any
from switch_core.agent_refusals import AgentRefused, record_refusal
from switch_core.agent_template_ops import ActingFor, AgentTemplates
from switch_core.agent_templates import plan_template
-from switch_core.authz import Principal
+from switch_core.authz import Principal, require_group_filing
from switch_core.bridges.agent.api.handlers import parse_timestamp_ms
from switch_core.bridges.agent.operations.agent_management import (
management_permission,
@@ -1635,7 +1635,9 @@ async def create_room_from_yaml(
Args:
yaml: The template text. A top-level ``room:`` makes one room; a
``group:`` with a ``rooms:`` list (and optional ``links:``) makes
- a room group. Either may declare ``params:`` with defaults and
+ a room group, which an agent is refused: only a workspace admin
+ puts rooms in a group, and an agent acts without its owner's
+ admin reach. Either may declare ``params:`` with defaults and
descriptions; placeholders are filled in before provisioning.
inputs: Values for declared params. A required param with no default
must be supplied here, or provisioning fails naming it.
@@ -1754,6 +1756,9 @@ async def _provision_as_agent(
user_id=owner.id, name=owner.name, email=owner.email, text=yaml, inputs=inputs
)
parsed = rooms_yaml.parse_template(yaml, inputs=inputs, builtins=builtins)
+ if isinstance(parsed.spec, GroupSpec):
+ # Without the owner's admin reach, which filing rooms in a group needs.
+ require_group_filing(False)
await rooms_yaml.check_entity_params(parsed, reader=reader)
await rooms_yaml.check_bridges(parsed)
room_specs = (
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index c930bb611..5287ecec5 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -2940,9 +2940,11 @@ class AgentCore:
agent, _owner_id, owner_is_admin = await self._resolve_acting_identity(
session, agent_id
)
- group_id = await self._resolve_group_name(session, group_name)
- if group_id is not None:
+ # Before resolving the name: the lookup's errors would map the
+ # group tree for an agent that may not file into any of it.
+ if group_name is not None:
require_group_filing(owner_is_admin)
+ group_id = await self._resolve_group_name(session, group_name)
owner = await session.get(User, agent.owner_id) if agent.owner_id else None
if (reference_ids or package_ids) and agent.owner_id is None:
raise ValueError(
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index 365e011cb..76b641a88 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -18,6 +18,7 @@ from sqlalchemy import tuple_ as sa_tuple
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.authz import require_group_filing
from switch_core.chats import MEMBER_CLIENT_TYPE
from switch_core.db.id_lists import any_of
from switch_core.db.models import (
@@ -933,12 +934,24 @@ class RoomStore:
await session.flush()
async def set_group(
- self, session: AsyncSession, room_id: str, group_id: str | None
+ self,
+ session: AsyncSession,
+ room_id: str,
+ group_id: str | None,
+ *,
+ acting_is_admin: bool,
) -> None:
- """Assign the room to a group, or make it standalone (`group_id=None`)."""
+ """Assign the room to a group, or make it standalone (`group_id=None`).
+
+ Putting the room in a group it is not already in needs a workspace
+ admin (`require_group_filing`, raising ``PermissionError``); making
+ it standalone, or leaving it where it is, does not. Authorizing the
+ room itself is the caller's job."""
room = await session.get(Room, room_id)
if room is None:
raise ValueError(f"Room not found: {room_id}")
+ if group_id is not None and group_id != room.group_id:
+ require_group_filing(acting_is_admin)
if group_id is not None:
group = await session.get(RoomGroup, group_id)
if group is None:
@@ -947,13 +960,21 @@ class RoomStore:
await session.flush()
async def set_group_bulk(
- self, session: AsyncSession, room_ids: list[str], group_id: str | None
+ self,
+ session: AsyncSession,
+ room_ids: list[str],
+ group_id: str | None,
+ *,
+ acting_is_admin: bool,
) -> int:
"""Assign many rooms to a group (or `None` for standalone) in one UPDATE.
- The caller is responsible for validating the group and authorizing the
- rooms. Returns the number of rows updated.
+ Putting rooms in a group needs a workspace admin
+ (`require_group_filing`). The caller is responsible for validating the
+ group and authorizing the rooms. Returns the number of rows updated.
"""
+ if group_id is not None:
+ require_group_filing(acting_is_admin)
if not room_ids:
return 0
result = await session.execute(
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 6dd91859b..7b0968a23 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -21,6 +21,7 @@ from switch_core.authz import (
Principal,
can_unlink_from_room,
require,
+ require_group_filing,
)
from switch_core.config import SwitchConfig
from switch_core.db.audit import AuditAction, record_audit_event
@@ -1297,3 +1298,11 @@ async def readable_room_ids(
session, user.id, is_admin=is_admin, include_archived=True
)
return {r.id for r in rooms}
+
+
+def require_group_filing_or_403(is_admin: bool) -> None:
+ """`authz.require_group_filing` as HTTP 403, for gateway routes."""
+ try:
+ require_group_filing(is_admin)
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
diff --git a/core/switch_core/gateway/room_groups.py b/core/switch_core/gateway/room_groups.py
index 286f5098c..dd257a12d 100644
--- a/core/switch_core/gateway/room_groups.py
+++ b/core/switch_core/gateway/room_groups.py
@@ -6,14 +6,18 @@ from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Response
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.authz import Principal, require, require_group_filing
+from switch_core.authz import Principal, require
from switch_core.db.models import RoomGroup, User
from switch_core.db.stores.room_group_store import (
RoomGroupNameTaken,
RoomGroupStore,
)
from switch_core.db.stores.room_store import RoomStore
-from switch_core.gateway.auth import get_current_user, get_tenant_is_admin
+from switch_core.gateway.auth import (
+ get_current_user,
+ get_tenant_is_admin,
+ require_group_filing_or_403,
+)
from switch_core.gateway.dependencies import (
current_telemetry,
get_room_group_store,
@@ -157,12 +161,11 @@ async def assign_rooms_to_group(
"""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."""
+ # Before the lookup: whether a group exists is not for someone who may
+ # not file into it.
+ require_group_filing_or_403(is_admin)
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 e
principal = Principal(user.id, is_admin)
forbidden: list[str] = []
@@ -184,7 +187,9 @@ async def assign_rooms_to_group(
detail=f"No write access to rooms: {', '.join(forbidden)}",
)
- assigned = await room_store.set_group_bulk(session, allowed, group_id)
+ assigned = await room_store.set_group_bulk(
+ session, allowed, group_id, acting_is_admin=is_admin
+ )
await session.commit()
return RoomGroupAssignResponse(assigned=assigned)
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index f781b871b..af870ec6c 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -15,7 +15,6 @@ from switch_core.authz import (
Principal,
can,
can_unlink_from_room,
- require_group_filing,
)
from switch_core.bridges.agent.operations.agent_management import management_port
from switch_core.bridges.agent.protocol.agent_core import AgentCore
@@ -38,6 +37,7 @@ from switch_core.gateway.auth import (
authorize_room,
get_current_user,
get_tenant_is_admin,
+ require_group_filing_or_403,
takes_part_in_room,
)
from switch_core.gateway.dependencies import (
@@ -103,13 +103,6 @@ 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,
@@ -417,7 +410,7 @@ async def create_room(
) -> RoomDetail:
_validate_create(req)
if req.group_id is not None:
- _require_group_filing(is_admin)
+ require_group_filing_or_403(is_admin)
config = RoomCreateConfig(
name=req.name,
description=req.description,
@@ -434,6 +427,8 @@ async def create_room(
group_id=req.group_id,
created_by=user.id,
owner_id=user.id,
+ acting_user_id=user.id,
+ acting_is_admin=is_admin,
read_visibility=req.read_visibility,
write_visibility=req.write_visibility,
roles=([RoleSpec(**r.model_dump()) for r in req.roles] if req.roles else None),
@@ -1072,14 +1067,16 @@ async def put_room_group(
) -> RoomDetail:
"""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."""
+ Taking a room out of its group, or leaving it where it is, needs write
+ access to it; putting it in another 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)
+ await room_store.set_group(
+ session, room_id, req.group_id, acting_is_admin=is_admin
+ )
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
except ValueError as e:
# Missing room → 404; missing group → 400.
detail = str(e)
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index 37a21b76c..0a96782b1 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -23,7 +23,12 @@ from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.aliases import validate_alias_format, validate_alias_map
-from switch_core.authz import Principal, can, validate_visibility_pair
+from switch_core.authz import (
+ Principal,
+ can,
+ require_group_filing,
+ validate_visibility_pair,
+)
from switch_core.bridges.collaboration.models import (
ChannelCreationUnsupported,
ChannelType,
@@ -555,8 +560,10 @@ class RoomService:
for alias in (config.aliases or {}).values():
validate_alias_format(alias)
# Validate the group up front so a bad id fails before we provision a
- # room / external channel.
+ # room / external channel. Filing a room in a group needs a workspace
+ # admin; checked first, so a refusal does not reveal which groups exist.
if config.group_id is not None:
+ require_group_filing(config.acting_is_admin)
async with self._session_factory() as session:
if await session.get(RoomGroup, config.group_id) is None:
raise ValueError(f"Room group not found: {config.group_id}")
@@ -691,7 +698,12 @@ class RoomService:
async with self._session_factory() as session:
await self._room_store.create(session, room)
if config.group_id is not None:
- await self._room_store.set_group(session, room.id, config.group_id)
+ await self._room_store.set_group(
+ session,
+ room.id,
+ config.group_id,
+ acting_is_admin=config.acting_is_admin,
+ )
if agent_ids:
await self._room_store.add_agents(
session,
diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.py
index daf227eba..8fb79027c 100644
--- a/core/switch_core/rooms_yaml.py
+++ b/core/switch_core/rooms_yaml.py
@@ -40,7 +40,7 @@ import yaml
from pydantic import BaseModel, Field, TypeAdapter, ValidationError, model_validator
from switch_core.agent_runs import AgentOrigin, kickoff_fingerprint
-from switch_core.authz import Principal, can
+from switch_core.authz import Principal, can, require_group_filing
from switch_core.bridges.collaboration.models import ChannelType
from switch_core.bridges.resource.registry import validate_reference_value
from switch_core.clients.actor import SystemActor
@@ -1153,7 +1153,12 @@ class RoomYamlService:
any, posted as it is created) → links by name. A room that fails is
reported in ``errors`` and the rest still go ahead; nothing is rolled
back, so the caller sees exactly what exists.
+
+ Creating a group and filing rooms into it both need a workspace admin
+ (`require_group_filing`), so a non-admin is refused before anything
+ is made.
"""
+ require_group_filing(is_admin)
async with self._session_factory() as session:
group = await self._room_groups.create(
session,
diff --git a/core/tests/switch_core/bridges/agent/operations/test_agent_template_tools.py b/core/tests/switch_core/bridges/agent/operations/test_agent_template_tools.py
index ea6e1844e..22f456204 100644
--- a/core/tests/switch_core/bridges/agent/operations/test_agent_template_tools.py
+++ b/core/tests/switch_core/bridges/agent/operations/test_agent_template_tools.py
@@ -552,27 +552,22 @@ def test_a_team_template_with_a_group_fills_every_room():
@pytest.mark.asyncio
-async def test_run_a_team_template_that_makes_a_group(tools):
+async def test_a_team_template_that_makes_a_group_is_refused(tools):
template_id = await _stored(
tools, tools["user_id"], "blue team", GROUP_TEAM_TEMPLATE, kind="group"
)
- result = await _as(
- tools["agent_id"],
- run_template,
- template_id=template_id,
- inputs={"team": "blue"},
- agents={"blue-lead": "claude-code.alice", "blue-helper": "claude-code.bob"},
- )
+ with pytest.raises(PermissionError, match="workspace admin"):
+ await _as(
+ tools["agent_id"],
+ run_template,
+ template_id=template_id,
+ inputs={"team": "blue"},
+ agents={"blue-lead": "claude-code.alice", "blue-helper": "claude-code.bob"},
+ )
- assert result["errors"] == []
- assert {r["room_name"] for r in result["rooms"]} == {"blue-lobby", "blue-work"}
async with tools["session_factory"]() as session:
- names = {
- r.template_name
- for r in (await session.execute(select(Room))).scalars().all()
- }
- assert names == {"blue team"}
+ assert (await session.execute(select(Room))).scalars().all() == []
def test_a_slot_reached_through_a_param_is_swapped_too():
diff --git a/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py b/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py
index 0d43d0a04..4feea7667 100644
--- a/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py
+++ b/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py
@@ -21,7 +21,6 @@ from switch_core.bridges.agent.operations.definitions import create_room_from_ya
from switch_core.db.models import (
Room,
RoomGroup,
- RoomLink,
)
SINGLE_ROOM_YAML = """\
@@ -97,16 +96,14 @@ async def test_single_room_with_params_and_creator_builtin(env):
@pytest.mark.asyncio
-async def test_group_provisioned_with_links(env):
- result = await _call(env["agent_id"], yaml=GROUP_YAML, inputs={"team": "alpha"})
- assert result["group_name"] == "alpha group"
- assert {r["room_name"] for r in result["rooms"]} == {"alpha main", "alpha support"}
- assert result["errors"] == []
+async def test_a_group_document_is_refused_and_makes_nothing(env):
+ """An agent acts without its owner's admin reach, and only a workspace
+ admin puts rooms in a group."""
+ with pytest.raises(PermissionError, match="workspace admin"):
+ await _call(env["agent_id"], yaml=GROUP_YAML, inputs={"team": "alpha"})
async with env["session_factory"]() as session:
- group = await session.get(RoomGroup, result["group_id"])
- assert group is not None
- links = (await session.execute(select(RoomLink))).scalars().all()
- assert [link.label for link in links] == ["support"]
+ assert (await session.execute(select(RoomGroup))).scalars().all() == []
+ assert (await session.execute(select(Room))).scalars().all() == []
KICKOFF_YAML = """\
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.py
index 7998ab767..59241c381 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
@@ -118,7 +118,7 @@ class TestListRoomGroups:
session,
Room(transport_room_id="!r:test", name="r", description="d"),
)
- await rooms.set_group(session, room.id, child.id)
+ await rooms.set_group(session, room.id, child.id, acting_is_admin=True)
await session.commit()
result = await svc.list_room_groups("agent-x")
@@ -159,3 +159,26 @@ class TestFilingNeedsAnAdminOwner:
bridge_id=None,
group_name="Eng",
)
+
+ async def test_the_refusal_comes_before_the_group_lookup(
+ 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]
+
+ 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="No/Such/Group",
+ )
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py
index f6f9d3b32..dd09a450e 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py
@@ -124,7 +124,7 @@ class TestGetRoomGroupDetail:
room = await rooms.create(
session, Room(transport_room_id="!r:test", name="r1", description="d")
)
- await rooms.set_group(session, room.id, parent["id"])
+ await rooms.set_group(session, room.id, parent["id"], acting_is_admin=True)
await session.commit()
room_id, room_name = room.id, room.name
@@ -188,7 +188,9 @@ class TestRoomGroupsForNonAdmins:
),
)
for room in (own_room, hidden_room):
- await rooms.set_group(session, room.id, group["id"])
+ await rooms.set_group(
+ session, room.id, group["id"], acting_is_admin=True
+ )
await session.commit()
own_id, mine_id = own_room.id, mine.id
diff --git a/core/tests/switch_core/db/stores/test_room_group_store.py b/core/tests/switch_core/db/stores/test_room_group_store.py
index f5eeb31d9..08e72e3e2 100644
--- a/core/tests/switch_core/db/stores/test_room_group_store.py
+++ b/core/tests/switch_core/db/stores/test_room_group_store.py
@@ -22,7 +22,7 @@ async def _make_room(
Room(transport_room_id=f"!{name}:test", name=name, description=f"{name} desc"),
)
if group_id is not None:
- await rooms.set_group(session, room.id, group_id)
+ await rooms.set_group(session, room.id, group_id, acting_is_admin=True)
return room
@@ -74,7 +74,7 @@ class TestRoomGroupStore:
assert counts == {g.id: 1}
# Clearing the group makes the room standalone.
- await rooms.set_group(session, r.id, None)
+ await rooms.set_group(session, r.id, None, acting_is_admin=True)
await session.commit()
assert await store.get_room_counts(session) == {}
refreshed = await rooms.get(session, r.id)
@@ -88,7 +88,53 @@ class TestRoomGroupStore:
r = await _make_room(rooms, session, "room-b")
await session.commit()
with pytest.raises(ValueError, match="Room group not found"):
- await rooms.set_group(session, r.id, "nope")
+ await rooms.set_group(session, r.id, "nope", acting_is_admin=True)
+
+ async def test_only_an_admin_files_a_room(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = GroupStore()
+ rooms = Rooms()
+ async with session_factory() as session:
+ g = await store.create(
+ session, name="G", description=None, color=None, parent_group_id=None
+ )
+ r = await _make_room(rooms, session, "room-c")
+ await session.commit()
+ with pytest.raises(PermissionError, match="workspace admin"):
+ await rooms.set_group(session, r.id, g.id, acting_is_admin=False)
+ with pytest.raises(PermissionError, match="workspace admin"):
+ await rooms.set_group_bulk(session, [r.id], g.id, acting_is_admin=False)
+ refreshed = await rooms.get(session, r.id)
+ assert refreshed is not None and refreshed.group_id is None
+
+ async def test_a_non_admin_keeps_or_clears_the_current_group(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = GroupStore()
+ rooms = Rooms()
+ async with session_factory() as session:
+ g = await store.create(
+ session, name="G", description=None, color=None, parent_group_id=None
+ )
+ r = await _make_room(rooms, session, "room-d", group_id=g.id)
+ await session.commit()
+
+ await rooms.set_group(session, r.id, g.id, acting_is_admin=False)
+ await rooms.set_group(session, r.id, None, acting_is_admin=False)
+ await session.commit()
+ refreshed = await rooms.get(session, r.id)
+ assert refreshed is not None and refreshed.group_id is None
+
+ async def test_a_non_admin_is_refused_before_the_group_lookup(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ rooms = Rooms()
+ async with session_factory() as session:
+ r = await _make_room(rooms, session, "room-e")
+ await session.commit()
+ with pytest.raises(PermissionError):
+ await rooms.set_group(session, r.id, "nope", acting_is_admin=False)
async def test_reparent_rejects_self_and_cycles(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -286,13 +332,17 @@ class TestRoomGroupStore:
r2 = await _make_room(rooms, session, "r2")
await session.commit()
- assigned = await rooms.set_group_bulk(session, [r1.id, r2.id], g.id)
+ assigned = await rooms.set_group_bulk(
+ session, [r1.id, r2.id], g.id, acting_is_admin=True
+ )
await session.commit()
assert assigned == 2
assert await store.get_room_counts(session) == {g.id: 2}
# Bulk clear (group_id=None) makes them standalone again.
- cleared = await rooms.set_group_bulk(session, [r1.id, r2.id], None)
+ cleared = await rooms.set_group_bulk(
+ session, [r1.id, r2.id], None, acting_is_admin=True
+ )
await session.commit()
assert cleared == 2
assert await store.get_room_counts(session) == {}
@@ -302,7 +352,9 @@ class TestRoomGroupStore:
) -> None:
rooms = Rooms()
async with session_factory() as session:
- assert await rooms.set_group_bulk(session, [], None) == 0
+ assert (
+ await rooms.set_group_bulk(session, [], None, acting_is_admin=True) == 0
+ )
async def _group(
diff --git a/core/tests/switch_core/gateway/test_room_groups_authz.py b/core/tests/switch_core/gateway/test_room_groups_authz.py
index 42578fd90..f13e2be97 100644
--- a/core/tests/switch_core/gateway/test_room_groups_authz.py
+++ b/core/tests/switch_core/gateway/test_room_groups_authz.py
@@ -182,6 +182,53 @@ class TestFilingRooms:
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_is_refused_before_the_group_lookup(
+ 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 bulk:
+ await assign_rooms_to_group(
+ "no-such-group",
+ RoomGroupAssignRequest(room_ids=[room.id]),
+ session,
+ _GROUPS,
+ _ROOMS,
+ member,
+ await _is_admin(session, member),
+ )
+
+ assert bulk.value.status_code == 403
+
+ async def test_a_member_may_put_the_room_back_in_its_current_group(
+ 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)
+ await _ROOMS.set_group(session, room.id, group_id, acting_is_admin=True)
+ await session.commit()
+
+ 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),
+ )
+ refreshed = await _ROOMS.get(session, room.id)
+ assert refreshed is not None and refreshed.group_id == group_id
+
async def test_a_member_cannot_create_a_room_in_a_group(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -267,7 +314,7 @@ class TestRoomCounts:
session, name="priv", owner_id=other.id, read_visibility="private"
)
for room in (public, private):
- await _ROOMS.set_group(session, room.id, group.id)
+ await _ROOMS.set_group(session, room.id, group.id, acting_is_admin=True)
await session.commit()
async def count_for(user: User) -> int:
diff --git a/core/tests/switch_core/test_room_service_group_filing.py b/core/tests/switch_core/test_room_service_group_filing.py
new file mode 100644
index 000000000..f2b8ec991
--- /dev/null
+++ b/core/tests/switch_core/test_room_service_group_filing.py
@@ -0,0 +1,54 @@
+"""`RoomService.create_room` puts a room in a group only for a workspace
+admin, whichever front door the request came through."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Room
+from switch_core.db.stores.room_store import RoomStore
+from switch_core.room_service import RoomCreateConfig, RoomService
+
+
+class _NeverProvisioned:
+ def __getattr__(self, name: str) -> Any:
+ raise AssertionError(f"provisioning reached: {name}")
+
+
+def _service(session_factory: async_sessionmaker[AsyncSession]) -> RoomService:
+ never: Any = _NeverProvisioned()
+ return RoomService(
+ provisioning=never,
+ room_store=RoomStore(),
+ agent_store=never,
+ client_lifecycle=never,
+ collab_lifecycle=never,
+ collab_bridge_store=never,
+ resource_service=never,
+ session_factory=session_factory,
+ room_cache=never,
+ )
+
+
[email protected]("group_id", ["no-such-group", "any"])
+async def test_a_non_admin_cannot_create_a_room_in_a_group(
+ session_factory: async_sessionmaker[AsyncSession], group_id: str
+) -> None:
+ with pytest.raises(PermissionError, match="workspace admin"):
+ await _service(session_factory).create_room(
+ RoomCreateConfig(
+ name="filed",
+ description="d",
+ agent_names=[],
+ group_id=group_id,
+ acting_user_id="member",
+ acting_is_admin=False,
+ )
+ )
+
+ async with session_factory() as session:
+ assert (await session.execute(select(Room))).scalars().all() == []
diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.py
index a3f1e4159..2954d85aa 100644
--- a/core/tests/switch_core/test_rooms_yaml.py
+++ b/core/tests/switch_core/test_rooms_yaml.py
@@ -16,6 +16,7 @@ from typing import Any
import pytest
import pytest_asyncio
import yaml
+from fastapi import HTTPException
from sqlalchemy import insert, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
@@ -2294,7 +2295,7 @@ async def test_provision_group_two_rooms_linked(env):
svc = _svc(env)
spec = _group(env, GROUP_TEMPLATE, {"newcomer": "dana"})
- result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=False)
+ result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=True)
assert result.group_name == "Onboarding"
assert [r.room_name for r in result.rooms] == ["dana lobby", "dana workroom"]
@@ -2315,6 +2316,18 @@ async def test_provision_group_two_rooms_linked(env):
assert link.label == "workroom"
+async def test_provision_group_needs_a_workspace_admin(env):
+ svc = _svc(env)
+ spec = _group(env, GROUP_TEMPLATE, {"newcomer": "dana"})
+
+ with pytest.raises(PermissionError, match="workspace admin"):
+ await svc.provision_group(spec, user_id=env["user_id"], is_admin=False)
+
+ async with env["session_factory"]() as session:
+ assert (await session.execute(select(RoomGroup))).scalars().all() == []
+
+
@pytest.mark.asyncio
async def test_provision_group_reports_a_failed_room_and_keeps_the_rest(env):
svc = _svc(env)
@@ -2336,7 +2349,7 @@ links:
label: next
""",
)
- result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=False)
+ result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=True)
assert [r.room_name for r in result.rooms] == ["safe room"]
assert result.errors[0]["room_name"] == "boom room"
@@ -2370,7 +2383,7 @@ rooms:
""",
)
await svc.provision_group(
- spec, user_id=env["user_id"], is_admin=False, creator_name="alice"
+ spec, user_id=env["user_id"], is_admin=True, creator_name="alice"
)
assert posted == [("A", "start A")]
@@ -2399,7 +2412,7 @@ rooms:
@pytest.mark.asyncio
async def test_endpoint_json_body_group(env):
- """The /from-yaml endpoint provisions a group document."""
+ """The /from-yaml endpoint provisions a group document, for an admin."""
import json
from unittest.mock import AsyncMock
@@ -2415,7 +2428,10 @@ async def test_endpoint_json_body_group(env):
).encode()
async with env["session_factory"]() as session:
- result = await create_room_from_yaml(request, session, svc, user, False)
+ with pytest.raises(HTTPException) as refused:
+ await create_room_from_yaml(request, session, svc, user, False)
+ assert refused.value.status_code == 403
+ result = await create_room_from_yaml(request, session, svc, user, True)
assert result.group_name == "Onboarding"
assert [r.room_name for r in result.rooms] == ["frank lobby", "frank workroom"]
@@ -2436,7 +2452,7 @@ rooms:
claude-code.alice: greeter
""",
)
- result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=False)
+ result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=True)
room_id = result.rooms[0].room_id
# FakeRoomService does not seed aliases; write the row the real one would.
async with env["session_factory"]() as session:
diff --git a/gateway/src/pages/rooms/GroupsPage.tsx b/gateway/src/pages/rooms/GroupsPage.tsx
index 2faaf4734..312f051d5 100644
--- a/gateway/src/pages/rooms/GroupsPage.tsx
+++ b/gateway/src/pages/rooms/GroupsPage.tsx
@@ -465,7 +465,8 @@ function MembershipPanel({
export default function GroupsPage() {
const navigate = useNavigate();
// Groups are shared by the workspace, so only an admin creates, edits or
- // deletes them; anyone may file rooms they can write into one.
+ // deletes them, or puts rooms in one; anyone who can write to a room may
+ // take it out.
const { canAdminTenant: canManageGroups } = useAuth();
const { data: groups, loading, refetch } = useRoomGroups();
const { data: rooms, refetch: refetchRooms } = useRooms();
diff --git a/gateway/src/pages/rooms/RoomDetailPage.test.tsx b/gateway/src/pages/rooms/RoomDetailPage.test.tsx
index da0f5faa0..7a2cc331d 100644
--- a/gateway/src/pages/rooms/RoomDetailPage.test.tsx
+++ b/gateway/src/pages/rooms/RoomDetailPage.test.tsx
@@ -10,6 +10,10 @@ vi.mock("react-router", () => ({
useParams: () => ({ roomId: "r1" }),
}));
+vi.mock("../../data/AuthContext", () => ({
+ useAuth: () => ({ canAdminTenant: false }),
+}));
+
vi.mock("../../data/hooks", () => ({
useAgents: vi.fn(),
useBridgeUsers: vi.fn(),
diff --git a/gateway/src/pages/rooms/RoomDetailPage.tsx b/gateway/src/pages/rooms/RoomDetailPage.tsx
index 4541dd894..078826ea5 100644
--- a/gateway/src/pages/rooms/RoomDetailPage.tsx
+++ b/gateway/src/pages/rooms/RoomDetailPage.tsx
@@ -19,7 +19,6 @@ import {
Divider,
FormControlLabel,
IconButton,
- MenuItem,
Stack,
Switch,
TextField,
@@ -42,12 +41,12 @@ import {
deleteRoomRole,
removeRoomAgent,
setRoomAgentJoinEvents,
- setRoomGroup,
unarchiveRoom,
updateRoom,
updateRoomRole,
} from "../../data/api";
-import { useAgents, useBridgeUsers, useRoom, useRoomGroups } from "../../data/hooks";
+import { useAgents, useBridgeUsers, useRoom } from "../../data/hooks";
+import { useAuth } from "../../data/AuthContext";
import { AccessChip, AccessSelect } from "../../components/AccessControls";
import { type AccessLevel, fromAccessLevel, toAccessLevel } from "../../data/visibility";
import {
@@ -57,7 +56,7 @@ import {
formatDateTime,
titleCase,
} from "../../theme/hootFormat";
-import { effectiveColor, buildGroupIndex, flattenTree } from "./groupTree";
+import RoomGroupSection from "./RoomGroupSection";
import RoomGraphView from "./RoomGraphView";
import RoomLinkedRoomsSection from "./RoomLinkedRoomsSection";
import RoomResourcesSection from "./RoomResourcesSection";
@@ -67,6 +66,7 @@ import { ROOM_ACCESS_HELPERS, ROOM_ACCESS_OPTION_LABELS } from "./roomAccess";
export default function RoomDetailPage() {
const { roomId } = useParams<{ roomId: string }>();
const navigate = useNavigate();
+ const { canAdminTenant } = useAuth();
const { data: room, loading, error, refetch } = useRoom(roomId);
const [exportOpen, setExportOpen] = useState(false);
@@ -120,7 +120,7 @@ export default function RoomDetailPage() {
<Stack spacing={4}>
<RoomInfoSection room={room} />
<Divider />
- <GroupSection
+ <RoomGroupSection
room={room}
canWrite={canWrite}
canFile={canAdminTenant}
@@ -232,96 +232,6 @@ function InfoChip({
);
}
-// ── Group ─────────────────────────────────────────────────────────────────────
-
-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();
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- 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) => {
- setSaving(true);
- setError(null);
- try {
- await setRoomGroup(room.id, value || null);
- refetchGroups();
- onChanged();
- } catch (err) {
- setError(err instanceof Error ? err.message : "Failed to update group");
- } finally {
- setSaving(false);
- }
- },
- [room.id, onChanged, refetchGroups],
- );
-
- return (
- <Stack spacing={1.5}>
- <Typography variant="overline" sx={{ color: "text.secondary", display: "block" }}>
- Group
- </Typography>
- {error && <Alert severity="error">{error}</Alert>}
- <Stack direction="row" spacing={1.5} alignItems="center">
- {room.group_id && (
- <Box
- sx={{
- width: 12,
- height: 12,
- borderRadius: "50%",
- bgcolor: effectiveColor(room.group_id, byId),
- flexShrink: 0,
- }}
- />
- )}
- <TextField
- select
- size="small"
- label="Group"
- value={room.group_id ?? ""}
- onChange={(e) => handleChange(e.target.value)}
- disabled={saving || !canWrite || (!canFile && !room.group_id)}
- sx={{ width: 320 }}
- 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>
- {choices.map(({ group, depth }) => (
- <MenuItem key={group.id} value={group.id}>
- {"  ".repeat(depth)}
- {group.name}
- </MenuItem>
- ))}
- </TextField>
- </Stack>
- </Stack>
- );
-}
-
// ── Roles ─────────────────────────────────────────────────────────────────────
function RolesSection({
diff --git a/gateway/src/pages/rooms/RoomGroupSection.test.tsx b/gateway/src/pages/rooms/RoomGroupSection.test.tsx
new file mode 100644
index 000000000..c2fa03ae7
--- /dev/null
+++ b/gateway/src/pages/rooms/RoomGroupSection.test.tsx
@@ -0,0 +1,92 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { type RoomDetail, type RoomGroupDetail, setRoomGroup } from "../../data/api";
+import * as hooks from "../../data/hooks";
+import RoomGroupSection from "./RoomGroupSection";
+
+vi.mock("../../data/api", () => ({
+ setRoomGroup: vi.fn(async () => {}),
+}));
+
+vi.mock("../../data/hooks", () => ({
+ useRoomGroups: vi.fn(),
+}));
+
+const group: RoomGroupDetail = {
+ id: "g1",
+ name: "Customers",
+ description: null,
+ color: null,
+ parent_group_id: null,
+ room_count: 1,
+ created_at: "2026-01-01",
+};
+
+function renderSection(opts: {
+ groupId: string | null;
+ canFile: boolean;
+ canWrite: boolean;
+ groups: RoomGroupDetail[];
+}) {
+ vi.mocked(hooks.useRoomGroups).mockReturnValue({
+ data: opts.groups,
+ loading: false,
+ error: null,
+ refetch: vi.fn(),
+ });
+ const room = { id: "r1", group_id: opts.groupId, group_name: null } as RoomDetail;
+ render(
+ <RoomGroupSection
+ room={room}
+ canWrite={opts.canWrite}
+ canFile={opts.canFile}
+ onChanged={vi.fn()}
+ />,
+ );
+}
+
+describe("RoomGroupSection", () => {
+ afterEach(() => {
+ cleanup();
+ vi.mocked(setRoomGroup).mockClear();
+ });
+
+ it("gives an admin the group picker", () => {
+ renderSection({ groupId: null, canFile: true, canWrite: true, groups: [group] });
+ expect(screen.getByLabelText("Group")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /remove from group/i })).toBeNull();
+ });
+
+ it("shows anyone else the current group and lets a writer take the room out", async () => {
+ renderSection({ groupId: "g1", canFile: false, canWrite: true, groups: [group] });
+ expect(screen.queryByLabelText("Group")).toBeNull();
+ expect(screen.getByText("Customers")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: /remove from group/i }));
+ await waitFor(() => expect(setRoomGroup).toHaveBeenCalledWith("r1", null));
+ });
+
+ it("names a group missing from the loaded list", () => {
+ renderSection({ groupId: "hidden", canFile: false, canWrite: true, groups: [] });
+ expect(screen.getByText("A group not in your list")).toBeTruthy();
+ expect(screen.getByRole("button", { name: /remove from group/i })).toBeTruthy();
+ });
+
+ it("falls back to the group name the room carries", () => {
+ vi.mocked(hooks.useRoomGroups).mockReturnValue({
+ data: [],
+ loading: false,
+ error: null,
+ refetch: vi.fn(),
+ });
+ const room = { id: "r1", group_id: "g9", group_name: "Partners" } as RoomDetail;
+ render(<RoomGroupSection room={room} canWrite={true} canFile={false} onChanged={vi.fn()} />);
+ expect(screen.getByText("Partners")).toBeTruthy();
+ });
+
+ it("offers no removal without write access", () => {
+ renderSection({ groupId: "g1", canFile: false, canWrite: false, groups: [group] });
+ expect(screen.getByText("Customers")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /remove from group/i })).toBeNull();
+ });
+});
diff --git a/gateway/src/pages/rooms/RoomGroupSection.tsx b/gateway/src/pages/rooms/RoomGroupSection.tsx
new file mode 100644
index 000000000..341ba8de5
--- /dev/null
+++ b/gateway/src/pages/rooms/RoomGroupSection.tsx
@@ -0,0 +1,104 @@
+import { Alert, Box, Button, MenuItem, Stack, TextField, Typography } from "@mui/material";
+import { useCallback, useMemo, useState } from "react";
+import { type RoomDetail, setRoomGroup } from "../../data/api";
+import { useRoomGroups } from "../../data/hooks";
+import { buildGroupIndex, effectiveColor, flattenTree } from "./groupTree";
+
+/** The room's group. A workspace admin puts the room in any group; anyone
+ * else who can write to the room sees its group and may take it out. */
+export default function RoomGroupSection({
+ 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();
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const groupList = useMemo(() => groups ?? [], [groups]);
+ const byId = useMemo(() => buildGroupIndex(groupList), [groupList]);
+ const choices = useMemo(() => flattenTree(groupList), [groupList]);
+ const currentName = room.group_id
+ ? (byId.get(room.group_id)?.name ?? room.group_name ?? "A group not in your list")
+ : "Standalone (no group)";
+
+ const handleChange = useCallback(
+ async (value: string) => {
+ setSaving(true);
+ setError(null);
+ try {
+ await setRoomGroup(room.id, value || null);
+ refetchGroups();
+ onChanged();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Failed to update group");
+ } finally {
+ setSaving(false);
+ }
+ },
+ [room.id, onChanged, refetchGroups],
+ );
+
+ return (
+ <Stack spacing={1.5}>
+ <Typography variant="overline" sx={{ color: "text.secondary", display: "block" }}>
+ Group
+ </Typography>
+ {error && <Alert severity="error">{error}</Alert>}
+ <Stack direction="row" spacing={1.5} alignItems="center">
+ {room.group_id && (
+ <Box
+ sx={{
+ width: 12,
+ height: 12,
+ borderRadius: "50%",
+ bgcolor: effectiveColor(room.group_id, byId),
+ flexShrink: 0,
+ }}
+ />
+ )}
+ {canFile ? (
+ <TextField
+ select
+ size="small"
+ label="Group"
+ value={room.group_id ?? ""}
+ onChange={(e) => handleChange(e.target.value)}
+ disabled={saving || !canWrite}
+ sx={{ width: 320 }}
+ helperText="Groups organise rooms in the list and colour them in the graph."
+ >
+ <MenuItem value="">Standalone (no group)</MenuItem>
+ {choices.map(({ group, depth }) => (
+ <MenuItem key={group.id} value={group.id}>
+ {" ".repeat(depth)}
+ {group.name}
+ </MenuItem>
+ ))}
+ </TextField>
+ ) : (
+ <>
+ <Typography variant="body2">{currentName}</Typography>
+ {room.group_id && canWrite && (
+ <Button size="small" disabled={saving} onClick={() => handleChange("")}>
+ Remove from group
+ </Button>
+ )}
+ </>
+ )}
+ </Stack>
+ {!canFile && (
+ <Typography variant="caption" sx={{ color: "text.secondary" }}>
+ Only a workspace admin can put a room in a group.
+ </Typography>
+ )}
+ </Stack>
+ );
+}