Skip to content

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

Hide private rooms behind existing links too

Petr Bauch536c5f8ce104
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 157a6474e..1964102c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -93,8 +93,10 @@ version of their own to them without also giving them a release of their own.
The room link graph, the rooms a document, package or reference is attached
to, and an agent's `list_all_rooms` now show only rooms the caller may read
(an agent also sees the rooms it is in). Linking a room to another now
- needs read access to the target, whose name the link shows. An agent can
- list a room's participants only from inside the room.
+ needs read access to the target, whose name the link shows, including
+ links an agent's `create_room` makes. A room's links, outbound and inbound,
+ leave out rooms the caller cannot read, for people and agents alike. An
+ agent can list a room's participants only from inside the room.
- **Only a workspace admin manages room groups.** Groups are shared by the
whole workspace and have no owner, so any member could rename, move or
delete one. Creating, changing and deleting a group, from the dashboard,
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index 8063c450b..d1e0ca777 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -409,7 +409,8 @@ them. Each entry carries `target_room_id` (pass it to `connect_to_room`),
rooms are related, and an `access` field — `"member"` means you may connect,
`"not_member"` means the call will fail and you should ask the room's operator
(the human user, typically) to add you rather than trying; such an entry also
-carries an `access_note` saying so.
+carries an `access_note` saying so. A link to a room you may not see (one
+your owner cannot read and you are not in) is left out.
They are metadata, not access. Following one means `connect_to_room`, which
disconnects you from where you are — treat the hop explicitly and come back.
@@ -689,7 +690,8 @@ Surface that error rather than retrying.
`create_room` accepts `reference_ids`, `package_ids` and `linked_rooms` to
seed a room at creation time. Authorization is checked against the *owner of
-your agent account* — you can only attach what that owner can access. Bad ids
+your agent account* — you can only attach what that owner can access, and
+link only to rooms that owner can read. Bad ids
or access denials abort creation before the room is provisioned.
Race-time attachment failures (rare) do not abort the room; they come back in
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 488bf592d..52357001d 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -445,14 +445,25 @@ async def _decorate_linked_rooms(
``"member"`` if the calling agent is assigned to the target room,
``"not_member"`` otherwise. For ``not_member`` rows, also include a
human-readable ``access_note`` warning that ``connect_to_room`` will
- fail until the agent is added by an operator."""
+ fail until the agent is added by an operator.
+
+ A link whose target the agent may not see (see `list_all_rooms`) is left
+ out: it would show a private room's name and description."""
if not linked_rooms:
return []
async with protocol.session_factory() as session:
agent_rooms = await protocol.room_store.get_rooms_for_agent(session, agent_id)
+ visible_ids = {
+ r.id
+ for r in await protocol.rooms_visible_to(
+ session, agent_id, include_archived=True
+ )
+ }
member_ids = {r.id for r in agent_rooms}
out: list[dict[str, Any]] = []
for entry in linked_rooms:
+ if entry["target_room_id"] not in visible_ids:
+ continue
is_member = entry["target_room_id"] in member_ids
decorated = {
**entry,
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index f972b8a3c..79eee228f 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -3773,7 +3773,7 @@ class AgentCore:
last = rooms[-1]
return rooms, _encode_room_cursor(last.created_at, last.id)
- async def _rooms_visible_to(
+ async def rooms_visible_to(
self, session: AsyncSession, agent_id: str, *, include_archived: bool
) -> list[Room]:
"""The rooms the agent's owner may read, plus those the agent is in."""
@@ -3799,7 +3799,7 @@ class AgentCore:
async with self.session_factory() as session:
result = await session.execute(select(RoomGroup))
groups = list(result.scalars().all())
- visible = await self._rooms_visible_to(
+ visible = await self.rooms_visible_to(
session, agent_id, include_archived=True
)
counts = Counter(r.group_id for r in visible if r.group_id is not None)
@@ -3910,7 +3910,7 @@ class AgentCore:
member_rooms = [
{"id": r.id, "name": r.name}
- for r in await self._rooms_visible_to(
+ for r in await self.rooms_visible_to(
session, agent_id, include_archived=True
)
if r.group_id == group_id
diff --git a/core/switch_core/gateway/room_links.py b/core/switch_core/gateway/room_links.py
index 98939eebe..83596263d 100644
--- a/core/switch_core/gateway/room_links.py
+++ b/core/switch_core/gateway/room_links.py
@@ -11,6 +11,7 @@ from switch_core.db.stores.room_store import RoomStore
from switch_core.gateway.auth import (
get_current_user,
get_tenant_is_admin,
+ readable_room_ids,
require_room_access,
)
from switch_core.gateway.dependencies import (
@@ -54,7 +55,10 @@ async def list_linked_rooms(
) -> list[LinkedRoomDetail]:
await require_room_access(session, room_store, room_id, user, "read", is_admin)
rows = await resource_service.list_linked_rooms_for_room(session, room_id)
- return [LinkedRoomDetail(**row) for row in rows]
+ readable = await readable_room_ids(session, room_store, user, is_admin)
+ return [
+ LinkedRoomDetail(**row) for row in rows if row["target_room_id"] in readable
+ ]
@router.get("/rooms/{room_id}/linked-rooms/inbound")
@@ -68,7 +72,12 @@ async def list_inbound_linked_rooms(
) -> list[InboundLinkedRoomDetail]:
await require_room_access(session, room_store, room_id, user, "read", is_admin)
rows = await resource_service.list_inbound_linked_rooms(session, room_id)
- return [InboundLinkedRoomDetail(**row) for row in rows]
+ readable = await readable_room_ids(session, room_store, user, is_admin)
+ return [
+ InboundLinkedRoomDetail(**row)
+ for row in rows
+ if row["source_room_id"] in readable
+ ]
@router.post("/rooms/{room_id}/linked-rooms", status_code=201)
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index d8d663647..37a21b76c 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -352,6 +352,13 @@ class RoomService:
target = await self._room_store.get(session, link.target_room_id)
if target is None:
raise ValueError(f"Linked room not found: {link.target_room_id}")
+ # A link shows its target's name and description in the new
+ # room, so linking needs read access to the target.
+ if not can(principal, "read", target):
+ raise PermissionError(
+ f"User {config.acting_user_id} cannot link to room "
+ f"{link.target_room_id}"
+ )
if not link.label.strip():
raise ValueError("Linked room label must not be empty")
diff --git a/core/tests/switch_core/bridges/agent/operations/test_linked_rooms_visibility.py b/core/tests/switch_core/bridges/agent/operations/test_linked_rooms_visibility.py
new file mode 100644
index 000000000..57a9a3545
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/operations/test_linked_rooms_visibility.py
@@ -0,0 +1,54 @@
+"""An agent is not shown a linked room it may not see: the link would name a
+private room."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.agent.operations.definitions import _decorate_linked_rooms
+
+
+class _Session:
+ async def __aenter__(self) -> _Session:
+ return self
+
+ async def __aexit__(self, *exc: object) -> bool:
+ return False
+
+
+def _link(room_id: str) -> dict[str, Any]:
+ return {
+ "target_room_id": room_id,
+ "target_room_name": room_id,
+ "target_room_description": "",
+ "label": "see also",
+ }
+
+
+async def test_links_to_rooms_the_agent_may_not_see_are_left_out() -> None:
+ async def rooms_for_agent(_session: object, _agent_id: str) -> list[Any]:
+ return [SimpleNamespace(id="joined")]
+
+ async def visible(
+ _session: object, _agent_id: str, *, include_archived: bool
+ ) -> list[Any]:
+ assert include_archived
+ return [SimpleNamespace(id="joined"), SimpleNamespace(id="public")]
+
+ protocol = SimpleNamespace(
+ session_factory=_Session,
+ room_store=SimpleNamespace(get_rooms_for_agent=rooms_for_agent),
+ rooms_visible_to=visible,
+ )
+
+ out = await _decorate_linked_rooms(
+ protocol, # type: ignore[arg-type]
+ "agent-1",
+ [_link("joined"), _link("public"), _link("hidden")],
+ )
+
+ assert [(e["target_room_id"], e["access"]) for e in out] == [
+ ("joined", "member"),
+ ("public", "not_member"),
+ ]
diff --git a/core/tests/switch_core/gateway/test_room_resource_read_authz.py b/core/tests/switch_core/gateway/test_room_resource_read_authz.py
index 15941bfce..4ef614b37 100644
--- a/core/tests/switch_core/gateway/test_room_resource_read_authz.py
+++ b/core/tests/switch_core/gateway/test_room_resource_read_authz.py
@@ -31,7 +31,11 @@ from switch_core.gateway.documents import (
)
from switch_core.gateway.packages import detach_package_from_room
from switch_core.gateway.references import detach_reference_from_room
-from switch_core.gateway.room_links import get_room_link_graph
+from switch_core.gateway.room_links import (
+ get_room_link_graph,
+ list_inbound_linked_rooms,
+ list_linked_rooms,
+)
_ROOM_STORE = RoomStore()
_USER_STORE = UserStore()
@@ -265,6 +269,45 @@ class TestRoomListingsHidePrivateRooms:
assert await graph_for(other) == ({public.id}, 0)
assert await graph_for(owner) == ({public.id, private.id}, 1)
+ async def test_a_rooms_links_leave_out_unreadable_rooms_on_either_end(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await _add_user(session, name="owner")
+ other = await _add_user(session, name="other")
+ public = await _add_room(
+ session, name="pub", owner_id=owner.id, read_visibility="public"
+ )
+ private = await _add_room(
+ session, name="priv", owner_id=owner.id, read_visibility="private"
+ )
+ svc = _svc(session_factory)
+ await svc.attach_linked_room(
+ session,
+ source_room_id=public.id,
+ target_room_id=private.id,
+ label="out",
+ )
+ await svc.attach_linked_room(
+ session, source_room_id=private.id, target_room_id=public.id, label="in"
+ )
+
+ async def links_for(user: User) -> tuple[set[str], set[str]]:
+ is_admin = await _is_admin(session, user)
+ outbound = await list_linked_rooms(
+ public.id, session, svc, _ROOM_STORE, user, is_admin
+ )
+ inbound = await list_inbound_linked_rooms(
+ public.id, session, svc, _ROOM_STORE, user, is_admin
+ )
+ return (
+ {r.target_room_id for r in outbound},
+ {r.source_room_id for r in inbound},
+ )
+
+ assert await links_for(other) == (set(), set())
+ assert await links_for(owner) == ({private.id}, {private.id})
+
async def test_rooms_for_document_leaves_out_unreadable_rooms(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/test_room_create_link_access.py b/core/tests/switch_core/test_room_create_link_access.py
new file mode 100644
index 000000000..18a250db6
--- /dev/null
+++ b/core/tests/switch_core/test_room_create_link_access.py
@@ -0,0 +1,54 @@
+"""Creating a room with links needs read access to each link's target, whose
+name and description the link shows. Real Postgres."""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Room, User
+from switch_core.db.stores.room_store import RoomStore
+from switch_core.room_service import LinkedRoomSpec, RoomCreateConfig, RoomService
+
+
+def _service(session_factory: async_sessionmaker[AsyncSession]) -> RoomService:
+ # `_validate_attachments` only reads rooms; refs and packages are not used.
+ svc = object.__new__(RoomService)
+ svc._session_factory = session_factory # type: ignore[attr-defined]
+ svc._room_store = RoomStore() # type: ignore[attr-defined]
+ return svc
+
+
+def _config(target_id: str, user_id: str) -> RoomCreateConfig:
+ return RoomCreateConfig(
+ name="new",
+ description="d",
+ linked_rooms=[LinkedRoomSpec(target_room_id=target_id, label="see also")],
+ acting_user_id=user_id,
+ acting_is_admin=False,
+ )
+
+
+async def test_linking_to_a_private_room_one_cannot_read_is_refused(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ owner = User(name="owner", email="[email protected]", role="user")
+ other = User(name="other", email="[email protected]", role="user")
+ session.add_all([owner, other])
+ await session.flush()
+ private = Room(
+ transport_room_id="!priv:test",
+ name="priv",
+ description="secret",
+ owner_id=owner.id,
+ read_visibility="private",
+ write_visibility="private",
+ )
+ session.add(private)
+ await session.commit()
+
+ svc = _service(session_factory)
+ with pytest.raises(PermissionError, match="cannot link"):
+ await svc._validate_attachments(_config(private.id, other.id))
+ await svc._validate_attachments(_config(private.id, owner.id))