Skip to content

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

fix(db): drop the unfiltered fallback a rebind already outgrew (CHOO-2623)

Wojciech Wojtyniak6c46a1b31a54
diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.py
index 5b2c6dba6..160d655d4 100644
--- a/core/switch_core/clients/admin_client.py
+++ b/core/switch_core/clients/admin_client.py
@@ -22,6 +22,7 @@ from switch_core.clients.mentions import (
unique_mention_tokens,
)
from switch_core.clients.room_meta import RoomMeta
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.agent_session_store import AgentSessionStore
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.document_store import DocumentStore
@@ -261,7 +262,7 @@ class AdminClient(ClientBase[ClientConfig]):
async def _resolve_room_meta(self, matrix_room_id: str) -> RoomMeta | None:
if matrix_room_id in self._room_meta_cache:
return self._room_meta_cache[matrix_room_id]
- async with self.session_factory() as session:
+ async with tenant_session(self.session_factory, self.tenant_id) as session:
room = await self._room_store.get_by_matrix_room_id(session, matrix_room_id)
if room is None:
logger.error("Room not found for matrix room ID: %s", matrix_room_id)
diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.py
index 401018720..6f703c3a8 100644
--- a/core/switch_core/clients/agent_client.py
+++ b/core/switch_core/clients/agent_client.py
@@ -808,7 +808,7 @@ class AgentClient(ClientBase[ClientConfig]):
if matrix_room_id in self._room_meta:
return self._room_meta[matrix_room_id]
- async with self.session_factory() as session:
+ async with tenant_session(self.session_factory, self.tenant_id) as session:
room = await self._room_store.get_by_matrix_room_id(session, matrix_room_id)
if room is None:
logger.error("Room not found for matrix room ID: %s", matrix_room_id)
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index f46bca10b..65c135aaa 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -11,9 +11,9 @@ from switch_core.db.models import (
ClientRoom,
Room,
RoomGroup,
+ require_tenant_id,
room_agents,
)
-from switch_core.tenant_context import current_tenant_id
class RoomStore:
@@ -52,27 +52,28 @@ class RoomStore:
async def get_by_matrix_room_id(
self, session: AsyncSession, matrix_room_id: str
) -> Room | None:
- """Resolve a room by its Matrix room id, scoped to the bound tenant
- when one is bound.
+ """Resolve a room by its Matrix room id within the bound tenant.
+ Scoped explicitly rather than left to row-level security:
`matrix_room_id` is unique per tenant
- (`uq_rooms_tenant_matrix_room_id`), not globally, so a caller that
- already knows its tenant must not match another tenant's room of the
- same transport id — that read is filtered explicitly here rather than
- left to row-level security, which is inert against the owner
- connection every environment uses today.
-
- A caller with nothing bound gets the unfiltered search instead of an
- error: `_resolve_room_and_tenant` (`transport/postgres.py`) is exactly
- this lookup used to discover *which* tenant a transport-side id
- belongs to, deliberately with no tenant bound yet, and forcing one
- would make that bootstrap impossible.
+ (`uq_rooms_tenant_matrix_room_id`), not globally, so the moment a
+ second tenant has a room bound to the same transport id, an unfiltered
+ read here matches both rows and raises `MultipleResultsFound` out of
+ every inbound-event path that resolves a room this way (provisioning,
+ the Postgres transport, admin commands). Every caller that reaches
+ this by now already knows its tenant — `PostgresTransport` and the
+ two `ClientBase` subclasses carry it on the row they were built from,
+ and `PostgresProvisioning` is only ever called from `room_service`
+ inside a `tenant_scope` bound to the room it is acting on — so there
+ is no bootstrap case left that needs an unfiltered fallback, the same
+ as `ClientStore.get_by_matrix_user_id`.
"""
- conditions = [Room.matrix_room_id == matrix_room_id]
- tenant_id = current_tenant_id()
- if tenant_id is not None:
- conditions.append(Room.tenant_id == tenant_id)
- result = await session.execute(select(Room).where(*conditions))
+ result = await session.execute(
+ select(Room).where(
+ Room.tenant_id == require_tenant_id(),
+ Room.matrix_room_id == matrix_room_id,
+ )
+ )
return result.scalar_one_or_none()
async def get_all(
diff --git a/core/tests/switch_core/db/stores/test_room_store.py b/core/tests/switch_core/db/stores/test_room_store.py
index 7e1942c09..423d8be72 100644
--- a/core/tests/switch_core/db/stores/test_room_store.py
+++ b/core/tests/switch_core/db/stores/test_room_store.py
@@ -2,9 +2,10 @@ from __future__ import annotations
import uuid
+import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.db.models import Room, Tenant
+from switch_core.db.models import Room, Tenant, TenantNotBoundError
from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.room_store import RoomStore
@@ -63,3 +64,46 @@ class TestGetByMatrixRoomIdMultiTenant:
result = await store.get_by_matrix_room_id(verify, shared_matrix_room_id)
assert result is not None
assert result.id == other_id
+
+
+class TestGetByMatrixRoomIdRequiresATenant:
+ """No caller left reaches `get_by_matrix_room_id` with nothing bound
+ (CHOO-2623): `PostgresTransport` and the two `ClientBase` subclasses carry
+ their own tenant, and `PostgresProvisioning` is only ever invoked from
+ inside a `tenant_scope` bound to the room it acts on. An unfiltered
+ fallback for "nothing bound" therefore has no legitimate caller left to
+ serve — only a forgotten bind, which two tenants sharing a
+ `matrix_room_id` turn into `MultipleResultsFound` instead of `Room | None`.
+ Refusing outright, the same as `ClientStore.get_by_matrix_user_id`, turns
+ that into a clear, immediate error instead.
+ """
+
+ @pytest.mark.no_ambient_tenant
+ async def test_raises_rather_than_matching_two_tenants_rooms(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = RoomStore()
+ tenant_a = f"tenant-{uuid.uuid4().hex[:8]}"
+ tenant_b = f"tenant-{uuid.uuid4().hex[:8]}"
+ shared_matrix_room_id = "!shared-unbound:switch.local"
+
+ async with session_factory() as session:
+ session.add_all(
+ [
+ Tenant(id=tenant_a, slug=tenant_a, name=tenant_a),
+ Tenant(id=tenant_b, slug=tenant_b, name=tenant_b),
+ ]
+ )
+ await session.commit()
+
+ async with tenant_session(session_factory, tenant_a) as session:
+ await _make_room(session, shared_matrix_room_id)
+ await session.commit()
+
+ async with tenant_session(session_factory, tenant_b) as session:
+ await _make_room(session, shared_matrix_room_id)
+ await session.commit()
+
+ async with session_factory() as verify:
+ with pytest.raises(TenantNotBoundError):
+ await store.get_by_matrix_room_id(verify, shared_matrix_room_id)