Skip to content

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

Tighten authorization on subagent parents and room listings

Petr Bauch9325840b9012
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b264908fb..de9b8348e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -84,6 +84,18 @@ version of their own to them without also giving them a release of their own.
the runner the room existed and could write its name into their new room.
Now a room the runner cannot read reads as missing.
+- **Registering an agent under a parent requires owning the parent.** The
+ agent API's `register-known` and `register-known-bulk` accepted any agent as
+ `parent_agent_id`, copying its name and settings to the new child. They now
+ refuse a parent the registering user does not own, as the dashboard's own
+ subagent registration already did.
+- **Private rooms stay out of room listings for people who cannot read them.**
+ 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.
+
#### Added
- **An agent controller can send its agents' operations on its socket.**
Every operation a controller's agents call was an HTTP request of its own,
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index cae164886..ef0536d7c 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -424,9 +424,10 @@ none of it is needed to take part in a conversation.
### Inspecting the instance
-- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on the
- instance (not just the ones you are in), and fetch a room's members, channel
- type and admin mode. `list_all_rooms` answers a page at a time,
+- **`list_all_rooms`** / **`get_room_detail`** — enumerate the rooms on the
+ instance you may see (not just the ones you are in: every room your owner
+ can read, plus your own), and fetch a room's members, channel type and
+ admin mode. `list_all_rooms` answers a page at a time,
`{rooms, next_cursor}`: pass `next_cursor` back as `cursor` for the next page
(null on the last), `limit` for its size (default 100, at most 500), and
`name_contains` to match a name in any case. `get_room_detail` also returns the room's assumable
@@ -1087,7 +1088,7 @@ Every Switch tool you call in normal operation, one line each.
- `edit_role` — change a role's instructions or exclusivity.
- `delete_role` — remove a role and any lease on it.
- `list_linked_rooms` — refresh this room's outbound pointers.
-- `list_all_rooms` — every room on the instance, not just yours, a page at a time.
+- `list_all_rooms` — every room your owner can read, not just yours, a page at a time.
- `get_room_detail` — one room's members, channel type, roles, aliases.
- `list_bridges` — the collaboration bridges available for new rooms.
- `create_room` — provision a room. Confirm with the user first.
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index 953e48d52..9b0be5e6f 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -296,12 +296,36 @@ async def _register_known(
return result.agent_id, result.api_key
+async def _require_own_parent(
+ session: AsyncSession, protocol: AgentCore, parent_agent_id: str, owner_id: str
+) -> Agent:
+ """Load the parent a registration names, refusing one the registering
+ user does not own: a child inherits its parent's name and settings, so
+ naming someone else's agent would read and impersonate it."""
+ parent = await protocol.agent_store.get(session, parent_agent_id)
+ if parent is None:
+ raise HTTPException(
+ status_code=404, detail=f"Parent agent not found: {parent_agent_id}"
+ )
+ if parent.owner_id != owner_id:
+ raise HTTPException(
+ status_code=403,
+ detail="Only the parent agent's owner can register agents under it.",
+ )
+ return parent
+
+
@router.post("/register-known")
async def register_known_agent_endpoint(
req: RegisterKnownAgentRequest,
owner_id: Annotated[str, Depends(_resolve_registration_user_id)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
+ session: Annotated[AsyncSession, Depends(get_session)],
) -> RegisterAgentResponse:
+ if req.parent_agent_id is not None:
+ await _require_own_parent(session, protocol, req.parent_agent_id, owner_id)
+ # Not held across registration, which opens its own session.
+ await session.commit()
agent_id, api_key = await _register_known(
agent_type=req.agent_type,
name=req.name,
@@ -334,11 +358,7 @@ async def register_known_agents_bulk_endpoint(
if not req.subagents:
raise HTTPException(status_code=400, detail="No subagents provided")
- parent = await protocol.agent_store.get(session, req.parent_agent_id)
- if parent is None:
- raise HTTPException(
- status_code=404, detail=f"Parent agent not found: {req.parent_agent_id}"
- )
+ parent = await _require_own_parent(session, protocol, req.parent_agent_id, owner_id)
# Subagents inherit the parent's operational settings unless the caller
# overrides them: they should run in the same channels mode and use the
@@ -1743,13 +1763,16 @@ async def get_room_history(
@router.get("/rooms/{room_id}/participants")
async def list_participants(
room_id: str,
- _agent: Annotated[Agent, Depends(get_agent_from_scope)],
+ agent: Annotated[Agent, Depends(get_agent_from_scope)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
) -> ParticipantsResponse:
try:
+ await protocol.require_room_member(agent.id, room_id)
participants_desc = await protocol.list_participants(room_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
participants = [
ParticipantInfo(
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 2002eff5b..9ad6f91a6 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -1473,9 +1473,11 @@ async def list_all_rooms(
limit: int = 100,
cursor: str | None = None,
) -> dict[str, Any]:
- """List every room on this Switch instance (not just rooms this agent
- is a member of), a page at a time, oldest first. Use `list_rooms` instead
- to see only the rooms this agent is assigned to.
+ """List the rooms on this Switch instance this agent may see, a page at
+ a time, oldest first: every room its owner can read (public rooms and
+ ones the owner takes part in; all rooms for a workspace admin) plus the
+ rooms it is a member of. Use `list_rooms` instead to see only the rooms
+ this agent is assigned to.
Args:
include_archived: When false (default), archived rooms are omitted.
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index a1d0ae800..2dcd9bea3 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -3698,10 +3698,12 @@ class AgentCore:
) -> dict[str, Any]:
"""Create a directed link from source_room_id → target_room_id.
- Requires write access to the source room.
+ Requires write access to the source room and read access to the
+ target, whose name and description the link shows.
"""
async with self.session_factory() as session:
await self._require_room_action(session, agent_id, source_room_id, "write")
+ await self._require_room_action(session, agent_id, target_room_id, "read")
result = await self.resource_service.attach_linked_room(
session,
source_room_id=source_room_id,
@@ -3744,18 +3746,25 @@ class AgentCore:
limit: int,
cursor: str | None,
) -> tuple[list[Room], str | None]:
- """One page of every room, oldest first, and the cursor for the next
- page (None on the last). Archived rooms are excluded unless
+ """One page of the rooms the agent may see, oldest first, and the
+ cursor for the next page (None on the last): every room its owner may
+ read, plus those it is a member of. Archived rooms are excluded unless
`include_archived` is set."""
if not 1 <= limit <= LIST_ALL_ROOMS_MAX:
raise ValueError(f"limit must be between 1 and {LIST_ALL_ROOMS_MAX}")
async with self.session_factory() as session:
+ _agent, owner_id, owner_is_admin = await self._resolve_acting_identity(
+ session, agent_id
+ )
rooms = await self.room_store.page_all(
session,
include_archived=include_archived,
name_contains=name_contains,
limit=limit + 1,
after=_decode_room_cursor(cursor) if cursor is not None else None,
+ reader_id=owner_id,
+ reader_is_admin=owner_is_admin,
+ member_agent_id=agent_id,
)
if len(rooms) <= limit:
return rooms, None
diff --git a/core/switch_core/bridges/resource/service.py b/core/switch_core/bridges/resource/service.py
index e1eb8f2e2..d33a9af15 100644
--- a/core/switch_core/bridges/resource/service.py
+++ b/core/switch_core/bridges/resource/service.py
@@ -728,25 +728,33 @@ class ResourceService:
for rid, name, desc, label in rows
]
- async def get_room_link_graph(self, session: AsyncSession) -> dict[str, Any]:
- """Return every room + every directed link in a single payload, for
- the full-graph view in the frontend.
+ async def get_room_link_graph(
+ self, session: AsyncSession, readable_rooms: list[Room]
+ ) -> dict[str, Any]:
+ """Return `readable_rooms` and the directed links between them in a
+ single payload, for the full-graph view in the frontend. A link with
+ either end outside `readable_rooms` is left out, so the graph says
+ nothing about rooms the caller cannot read.
Each room carries its `group_id`, and the flattened group tree is
returned under `groups` so the frontend can colour rooms by their
top-level ancestor group.
"""
- result = await session.execute(
- select(Room.id, Room.name, Room.description, Room.group_id)
- )
rooms = [
- {"id": rid, "name": name, "description": desc, "group_id": gid}
- for rid, name, desc, gid in result.all()
+ {
+ "id": r.id,
+ "name": r.name,
+ "description": r.description,
+ "group_id": r.group_id,
+ }
+ for r in readable_rooms
]
+ readable_ids = {r.id for r in readable_rooms}
link_rows = await self._room_links.list_all(session)
links = [
{"source_room_id": s, "target_room_id": t, "label": lbl}
for s, t, lbl in link_rows
+ if s in readable_ids and t in readable_ids
]
group_result = await session.execute(
select(
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index a59994ba7..2854df78a 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -266,10 +266,29 @@ class RoomStore:
name_contains: str | None,
limit: int,
after: tuple[datetime, str] | None,
+ reader_id: str | None,
+ reader_is_admin: bool,
+ member_agent_id: str,
) -> list[Room]:
"""Up to `limit` rooms after the `(created_at, id)` position `after`,
- oldest first, whose name contains `name_contains` (any case)."""
+ oldest first, whose name contains `name_contains` (any case).
+
+ Only rooms an agent may see are returned: those its owner `reader_id`
+ may read (as `list_readable`; every room for a workspace admin) and
+ those `member_agent_id` is in. An agent with no owner sees public
+ rooms and its own."""
stmt = select(Room)
+ if not reader_is_admin:
+ visible = [
+ Room.read_visibility == "public",
+ exists().where(
+ room_agents.c.room_id == Room.id,
+ room_agents.c.agent_id == member_agent_id,
+ ),
+ ]
+ if reader_id is not None:
+ visible.append(involves(reader_id))
+ stmt = stmt.where(or_(*visible))
if not include_archived:
stmt = stmt.where(Room.archived_at.is_(None))
if name_contains:
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 0a14bde84..f4f7c0e97 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -1204,3 +1204,17 @@ async def require_room_access(
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e)) from e
return room
+
+
+async def readable_room_ids(
+ session: AsyncSession, room_store: RoomStore, user: User, is_admin: bool
+) -> set[str]:
+ """Ids of every room `user` may read, archived ones included.
+
+ For endpoints that list rooms reached through something else (a document,
+ a package, a reference) so they do not name rooms the caller cannot see.
+ """
+ rooms = await room_store.list_readable(
+ session, user.id, is_admin=is_admin, include_archived=True
+ )
+ return {r.id for r in rooms}
diff --git a/core/switch_core/gateway/documents.py b/core/switch_core/gateway/documents.py
index 93a7dd362..159ecec24 100644
--- a/core/switch_core/gateway/documents.py
+++ b/core/switch_core/gateway/documents.py
@@ -13,6 +13,7 @@ from switch_core.db.stores.user_store import UserStore
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 (
@@ -284,6 +285,7 @@ async def list_rooms_for_document(
document_id: str,
session: Annotated[AsyncSession, Depends(get_session)],
resource_service: Annotated[ResourceService, Depends(get_resource_service)],
+ room_store: Annotated[RoomStore, Depends(get_room_store)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[ResourceRoom]:
@@ -296,7 +298,12 @@ async def list_rooms_for_document(
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e)) from e
rows = await resource_service.list_rooms_for_document(session, document_id)
- return [ResourceRoom(room_id=rid, room_name=name) for rid, name in rows]
+ readable = await readable_room_ids(session, room_store, user, is_admin)
+ return [
+ ResourceRoom(room_id=rid, room_name=name)
+ for rid, name in rows
+ if rid in readable
+ ]
@router.get("/rooms/{room_id}/documents")
diff --git a/core/switch_core/gateway/packages.py b/core/switch_core/gateway/packages.py
index 4521f6d71..5e8f0d4e5 100644
--- a/core/switch_core/gateway/packages.py
+++ b/core/switch_core/gateway/packages.py
@@ -13,6 +13,7 @@ from switch_core.db.stores.user_store import UserStore
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 (
@@ -218,6 +219,7 @@ async def list_rooms_for_package(
package_id: str,
session: Annotated[AsyncSession, Depends(get_session)],
resource_service: Annotated[ResourceService, Depends(get_resource_service)],
+ room_store: Annotated[RoomStore, Depends(get_room_store)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[ResourceRoom]:
@@ -233,7 +235,12 @@ async def list_rooms_for_package(
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e)) from e
rows = await resource_service.list_rooms_for_package(session, package_id)
- return [ResourceRoom(room_id=rid, room_name=name) for rid, name in rows]
+ readable = await readable_room_ids(session, room_store, user, is_admin)
+ return [
+ ResourceRoom(room_id=rid, room_name=name)
+ for rid, name in rows
+ if rid in readable
+ ]
# ── Membership ────────────────────────────────────────────────────────────
diff --git a/core/switch_core/gateway/references.py b/core/switch_core/gateway/references.py
index c78b6e7d8..179716238 100644
--- a/core/switch_core/gateway/references.py
+++ b/core/switch_core/gateway/references.py
@@ -18,6 +18,7 @@ from switch_core.db.stores.user_store import UserStore
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 (
@@ -414,6 +415,7 @@ async def list_rooms_for_reference(
reference_id: str,
session: Annotated[AsyncSession, Depends(get_session)],
resource_service: Annotated[ResourceService, Depends(get_resource_service)],
+ room_store: Annotated[RoomStore, Depends(get_room_store)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[ResourceRoom]:
@@ -429,7 +431,12 @@ async def list_rooms_for_reference(
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e)) from e
rows = await resource_service.list_rooms_for_reference(session, reference_id)
- return [ResourceRoom(room_id=rid, room_name=name) for rid, name in rows]
+ readable = await readable_room_ids(session, room_store, user, is_admin)
+ return [
+ ResourceRoom(room_id=rid, room_name=name)
+ for rid, name in rows
+ if rid in readable
+ ]
@router.get("/rooms/{room_id}/references")
diff --git a/core/switch_core/gateway/room_links.py b/core/switch_core/gateway/room_links.py
index 3c2e18a14..98939eebe 100644
--- a/core/switch_core/gateway/room_links.py
+++ b/core/switch_core/gateway/room_links.py
@@ -32,9 +32,14 @@ router = APIRouter()
async def get_room_link_graph(
session: Annotated[AsyncSession, Depends(get_session)],
resource_service: Annotated[ResourceService, Depends(get_resource_service)],
- _user: Annotated[User, Depends(get_current_user)],
+ room_store: Annotated[RoomStore, Depends(get_room_store)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> RoomGraphResponse:
- payload = await resource_service.get_room_link_graph(session)
+ readable = await room_store.list_readable(
+ session, user.id, is_admin=is_admin, include_archived=True
+ )
+ payload = await resource_service.get_room_link_graph(session, readable)
return RoomGraphResponse(**payload)
@@ -77,6 +82,10 @@ async def create_linked_room(
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> LinkedRoomDetail:
await require_room_access(session, room_store, room_id, user, "write", is_admin)
+ # The link shows the target's name and description, so it must be readable.
+ await require_room_access(
+ session, room_store, req.target_room_id, user, "read", is_admin
+ )
try:
row = await resource_service.attach_linked_room(
session,
diff --git a/core/tests/switch_core/bridges/agent/api/test_register_known_parent_owner.py b/core/tests/switch_core/bridges/agent/api/test_register_known_parent_owner.py
new file mode 100644
index 000000000..f7bf42458
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/api/test_register_known_parent_owner.py
@@ -0,0 +1,100 @@
+"""Registering under a parent agent requires owning that parent."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import HTTPException
+
+from switch_core.bridges.agent.api.handlers import (
+ register_known_agent_endpoint,
+ register_known_agents_bulk_endpoint,
+)
+from switch_core.bridges.agent.api.schemas import (
+ BulkSubagentSpec,
+ RegisterKnownAgentBulkRequest,
+ RegisterKnownAgentRequest,
+)
+
+
+def _protocol_with_parent(owner_id: str | None) -> AsyncMock:
+ protocol = AsyncMock()
+ parent = (
+ None
+ if owner_id is None
+ else SimpleNamespace(
+ id="parent-1", name="main", owner_id=owner_id, metadata_={}
+ )
+ )
+ protocol.agent_store.get = AsyncMock(return_value=parent)
+ return protocol
+
+
+def _single_request() -> RegisterKnownAgentRequest:
+ return RegisterKnownAgentRequest(
+ agent_type="claude-code",
+ name="main.reviewer",
+ description="Reviews diffs",
+ parent_agent_id="parent-1",
+ )
+
+
+def _bulk_request() -> RegisterKnownAgentBulkRequest:
+ return RegisterKnownAgentBulkRequest(
+ agent_type="claude-code",
+ parent_agent_id="parent-1",
+ subagents=[BulkSubagentSpec(subagent_name="reviewer", description="Reviews")],
+ )
+
+
+async def test_single_refuses_someone_elses_parent() -> None:
+ protocol = _protocol_with_parent("alice")
+
+ with pytest.raises(HTTPException) as exc:
+ await register_known_agent_endpoint(
+ _single_request(), "mallory", protocol, AsyncMock()
+ )
+
+ assert exc.value.status_code == 403
+ protocol.register_agent.assert_not_awaited()
+
+
+async def test_single_refuses_a_missing_parent() -> None:
+ protocol = _protocol_with_parent(None)
+
+ with pytest.raises(HTTPException) as exc:
+ await register_known_agent_endpoint(
+ _single_request(), "alice", protocol, AsyncMock()
+ )
+
+ assert exc.value.status_code == 404
+ protocol.register_agent.assert_not_awaited()
+
+
+async def test_bulk_refuses_someone_elses_parent() -> None:
+ protocol = _protocol_with_parent("alice")
+
+ with pytest.raises(HTTPException) as exc:
+ await register_known_agents_bulk_endpoint(
+ _bulk_request(), "mallory", protocol, AsyncMock()
+ )
+
+ assert exc.value.status_code == 403
+ protocol.register_agent.assert_not_awaited()
+
+
+async def test_bulk_registers_under_own_parent() -> None:
+ protocol = _protocol_with_parent("alice")
+ protocol.agent_store.get_by_name = AsyncMock(return_value=None)
+ protocol.register_agent = AsyncMock(
+ return_value=SimpleNamespace(agent_id="child-1", api_key="key")
+ )
+
+ response = await register_known_agents_bulk_endpoint(
+ _bulk_request(), "alice", protocol, AsyncMock()
+ )
+
+ assert [r.name for r in response.results] == ["main.reviewer"]
+ assert protocol.register_agent.await_args.kwargs["owner_id"] == "alice"
diff --git a/core/tests/switch_core/bridges/agent/api/test_room_visibility.py b/core/tests/switch_core/bridges/agent/api/test_room_visibility.py
new file mode 100644
index 000000000..b83d1f353
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/api/test_room_visibility.py
@@ -0,0 +1,68 @@
+"""An agent sees only the rooms its owner may read or that it belongs to."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import HTTPException
+
+from switch_core.bridges.agent.api.handlers import list_participants
+from switch_core.bridges.agent.protocol.agent_core import AgentCore
+
+
+async def test_participants_of_a_room_the_agent_is_not_in_are_refused() -> None:
+ protocol = AsyncMock()
+ protocol.require_room_member = AsyncMock(
+ side_effect=PermissionError("Agent is not a member of this room")
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await list_participants("room-1", SimpleNamespace(id="agent-1"), protocol)
+
+ assert exc.value.status_code == 403
+ protocol.list_participants.assert_not_awaited()
+
+
+class _FakeSession:
+ async def __aenter__(self) -> _FakeSession:
+ return self
+
+ async def __aexit__(self, *exc: object) -> bool:
+ return False
+
+ async def get(self, model: Any, ident: str) -> Any:
+ return SimpleNamespace(id=ident)
+
+
+def _room(room_id: str, *, owner_id: str, read_visibility: str) -> Any:
+ return SimpleNamespace(
+ id=room_id,
+ owner_id=owner_id,
+ read_visibility=read_visibility,
+ write_visibility="private",
+ )
+
+
+async def test_list_all_rooms_hides_private_rooms_of_other_users() -> None:
+ own = _room("own", owner_id="alice", read_visibility="private")
+ public = _room("public", owner_id="bob", read_visibility="public")
+ joined = _room("joined", owner_id="bob", read_visibility="private")
+ hidden = _room("hidden", owner_id="bob", read_visibility="private")
+
+ svc = object.__new__(AgentCore)
+ svc.session_factory = _FakeSession # type: ignore[assignment]
+ svc.agent_store = SimpleNamespace( # type: ignore[assignment]
+ get=AsyncMock(return_value=SimpleNamespace(id="agent-1", owner_id="alice"))
+ )
+ svc.user_store = SimpleNamespace(administers=AsyncMock(return_value=False)) # type: ignore[assignment]
+ svc.room_store = SimpleNamespace( # type: ignore[assignment]
+ get_rooms_for_agent=AsyncMock(return_value=[joined]),
+ get_all=AsyncMock(return_value=[own, public, joined, hidden]),
+ )
+
+ rooms = await svc.list_all_rooms("agent-1")
+
+ assert [r.id for r in rooms] == ["own", "public", "joined"]
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 720fd60b3..15941bfce 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
@@ -14,7 +14,7 @@ from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.resource.service import ResourceService
-from switch_core.db.models import Room, User
+from switch_core.db.models import Document, Room, User
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.document_store import DocumentStore
from switch_core.db.stores.package_store import PackageStore
@@ -27,9 +27,11 @@ from switch_core.gateway.documents import (
detach_document_from_room,
get_room_document,
list_room_documents,
+ list_rooms_for_document,
)
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
_ROOM_STORE = RoomStore()
_USER_STORE = UserStore()
@@ -218,3 +220,90 @@ class TestRoomResourceReadAuthz:
await _is_admin(session, owner),
)
assert exc.value.status_code == 404
+
+
+async def _add_room(
+ session: AsyncSession, *, name: str, owner_id: str, read_visibility: str
+) -> Room:
+ room = Room(
+ transport_room_id=f"!{name}:test",
+ name=name,
+ description=f"{name} desc",
+ owner_id=owner_id,
+ read_visibility=read_visibility,
+ write_visibility="private",
+ )
+ session.add(room)
+ await session.flush()
+ return room
+
+
+class TestRoomListingsHidePrivateRooms:
+ async def test_link_graph_leaves_out_unreadable_rooms_and_their_links(
+ 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="x"
+ )
+
+ async def graph_for(user: User) -> tuple[set[str], int]:
+ graph = await get_room_link_graph(
+ session, svc, _ROOM_STORE, user, await _is_admin(session, user)
+ )
+ return {r.id for r in graph.rooms}, len(graph.links)
+
+ assert await graph_for(other) == ({public.id}, 0)
+ assert await graph_for(owner) == ({public.id, private.id}, 1)
+
+ async def test_rooms_for_document_leaves_out_unreadable_rooms(
+ 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"
+ )
+ doc = Document(
+ owner_id=owner.id,
+ read_visibility="public",
+ write_visibility="private",
+ name="doc",
+ description="d",
+ instructions="",
+ content="c",
+ )
+ session.add(doc)
+ await session.flush()
+ svc = _svc(session_factory)
+ for room in (public, private):
+ await svc.attach_document_to_room(
+ session, room.id, doc.id, user_id=owner.id
+ )
+
+ async def rooms_for(user: User) -> set[str]:
+ rows = await list_rooms_for_document(
+ doc.id,
+ session,
+ svc,
+ _ROOM_STORE,
+ user,
+ await _is_admin(session, user),
+ )
+ return {r.room_id for r in rows}
+
+ assert await rooms_for(other) == {public.id}
+ assert await rooms_for(owner) == {public.id, private.id}
diff --git a/core/tests/switch_core/gateway/test_room_write_authz.py b/core/tests/switch_core/gateway/test_room_write_authz.py
index f27bf6d75..276ff90b5 100644
--- a/core/tests/switch_core/gateway/test_room_write_authz.py
+++ b/core/tests/switch_core/gateway/test_room_write_authz.py
@@ -277,6 +277,31 @@ class TestCreateLinkedRoomWriteAuthz:
links = await svc.list_linked_rooms_for_room(session, source.id)
assert [link["target_room_id"] for link in links] == [target.id]
+ async def test_cannot_link_to_a_private_room_one_cannot_read(
+ 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")
+ source = await _add_room(session, name="src", owner_id=other.id)
+ target = await _add_room(session, name="tgt", owner_id=owner.id)
+ svc = _resource_service(session_factory)
+ req = LinkedRoomCreateRequest(target_room_id=target.id, label="rel")
+
+ with pytest.raises(HTTPException) as exc:
+ await create_linked_room(
+ source.id,
+ req,
+ session,
+ svc,
+ _ROOM_STORE,
+ other,
+ await _is_admin(session, other),
+ )
+
+ assert exc.value.status_code == 403
+ assert await svc.list_linked_rooms_for_room(session, source.id) == []
+
class TestDeleteLinkedRoomWriteAuthz:
async def test_non_owner_cannot_delete_link(