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): scope agent-name, client and room lookups to the bound tenant (CHOO-2623)

Wojciech Wojtyniakb72014c257c1
diff --git a/core/switch_core/db/stores/agent_store.py b/core/switch_core/db/stores/agent_store.py
index 9265ab4a0..af2e65e2b 100644
--- a/core/switch_core/db/stores/agent_store.py
+++ b/core/switch_core/db/stores/agent_store.py
@@ -1,7 +1,14 @@
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import Agent, ClientRoom, Model, Tool, room_agents
+from switch_core.db.models import (
+ Agent,
+ ClientRoom,
+ Model,
+ Tool,
+ require_tenant_id,
+ room_agents,
+)
class AgentStore:
@@ -15,19 +22,36 @@ class AgentStore:
return await session.get(Agent, agent_id)
async def get_by_name(self, session: AsyncSession, name: str) -> Agent | None:
- result = await session.execute(select(Agent).where(Agent.name == name))
+ """Resolve an agent by name within the bound tenant.
+
+ Scoped explicitly rather than left to row-level security: `name` is
+ unique per tenant (`uq_agents_tenant_name`), not globally, so the
+ moment a second tenant has an agent of the same name, an unfiltered
+ read here matches both rows and raises `MultipleResultsFound` out of
+ every caller that resolves an agent by name — mention routing,
+ registration, and the gateway's agent lookup among them.
+ """
+ result = await session.execute(
+ select(Agent).where(
+ Agent.tenant_id == require_tenant_id(), Agent.name == name
+ )
+ )
return result.scalar_one_or_none()
async def get_by_name_insensitive(
self, session: AsyncSession, name: str
) -> Agent | None:
- """Resolve an agent by name, case-insensitively.
+ """Resolve an agent by name, case-insensitively, within the bound tenant.
Mirrors how `@name` mentions are matched (case-insensitive), so a tagged
- token resolves to the same agent the router would address.
+ token resolves to the same agent the router would address. Scoped for
+ the same reason as `get_by_name`.
"""
result = await session.execute(
- select(Agent).where(func.lower(Agent.name) == name.lower())
+ select(Agent).where(
+ Agent.tenant_id == require_tenant_id(),
+ func.lower(Agent.name) == name.lower(),
+ )
)
return result.scalar_one_or_none()
diff --git a/core/switch_core/db/stores/client_store.py b/core/switch_core/db/stores/client_store.py
index 3e35ecb35..fe8e74b74 100644
--- a/core/switch_core/db/stores/client_store.py
+++ b/core/switch_core/db/stores/client_store.py
@@ -1,7 +1,7 @@
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import Client
+from switch_core.db.models import Client, require_tenant_id
class ClientStore:
@@ -15,8 +15,21 @@ class ClientStore:
async def get_by_matrix_user_id(
self, session: AsyncSession, matrix_user_id: str
) -> Client | None:
+ """Resolve a client by its Matrix user id within the bound tenant.
+
+ Scoped explicitly rather than left to row-level security:
+ `matrix_user_id` is unique per tenant
+ (`uq_clients_tenant_matrix_user_id`), not globally, so the moment a
+ second tenant has a client with the same puppet id, an unfiltered read
+ here matches both rows and raises `MultipleResultsFound` out of
+ message routing and provisioning, which resolve the sending client
+ from an inbound event this way.
+ """
result = await session.execute(
- select(Client).where(Client.matrix_user_id == matrix_user_id)
+ select(Client).where(
+ Client.tenant_id == require_tenant_id(),
+ Client.matrix_user_id == matrix_user_id,
+ )
)
return result.scalar_one_or_none()
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index 49f441c4f..f46bca10b 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -13,6 +13,7 @@ from switch_core.db.models import (
RoomGroup,
room_agents,
)
+from switch_core.tenant_context import current_tenant_id
class RoomStore:
@@ -51,9 +52,27 @@ class RoomStore:
async def get_by_matrix_room_id(
self, session: AsyncSession, matrix_room_id: str
) -> Room | None:
- result = await session.execute(
- select(Room).where(Room.matrix_room_id == matrix_room_id)
- )
+ """Resolve a room by its Matrix room id, scoped to the bound tenant
+ when one is bound.
+
+ `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.
+ """
+ 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))
return result.scalar_one_or_none()
async def get_all(
diff --git a/core/tests/switch_core/db/stores/test_agent_store.py b/core/tests/switch_core/db/stores/test_agent_store.py
index c7e617716..eaac37b96 100644
--- a/core/tests/switch_core/db/stores/test_agent_store.py
+++ b/core/tests/switch_core/db/stores/test_agent_store.py
@@ -1,26 +1,35 @@
from __future__ import annotations
+import uuid
+
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.db.models import Agent, ApiKey, Client, Room, Task, User
+from switch_core.db.models import Agent, ApiKey, Client, Room, Task, Tenant, User
from switch_core.db.stores.agent_store import AgentStore
+from switch_core.tenant_context import tenant_scope
+
+async def _make_agent(session: AsyncSession, name: str, *, unique: str = "") -> Agent:
+ """Minimal User → ApiKey → Client → Agent chain.
-async def _make_agent(session: AsyncSession, name: str) -> Agent:
- """Minimal User → ApiKey → Client → Agent chain."""
- user = User(name=name, email=f"{name}@test", role="user", password_hash="x")
+ `unique` disambiguates the user email / api-key hash / client matrix id —
+ each globally unique columns — when two agents share `name` across
+ tenants, since `name` itself is only unique per tenant.
+ """
+ slug = f"{name}-{unique}" if unique else name
+ user = User(name=name, email=f"{slug}@test", role="user", password_hash="x")
session.add(user)
await session.flush()
api_key = ApiKey(
user_id=user.id,
- key_hash=f"hash-{name}",
+ key_hash=f"hash-{slug}",
encrypted_key="enc",
label=name,
type="agent",
)
client = Client(
- matrix_user_id=f"@{name}:test",
+ matrix_user_id=f"@{slug}:test",
display_name=name,
type="agent",
)
@@ -40,6 +49,18 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:
return agent
+async def _make_agent_for_tenant(
+ session: AsyncSession, tenant_id: str, name: str
+) -> Agent:
+ """An agent named `name`, filed under `tenant_id` rather than the ambient
+ tenant. The underlying user/api-key/client identifiers stay globally
+ unique (suffixed with a fresh uuid) regardless of tenant — only `name`
+ is meant to collide with another tenant's agent here."""
+ unique = uuid.uuid4().hex[:8]
+ with tenant_scope(tenant_id):
+ return await _make_agent(session, name, unique=unique)
+
+
async def _make_room(session: AsyncSession, name: str) -> Room:
room = Room(matrix_room_id=f"!{name}:test", name=name, description=f"{name} desc")
session.add(room)
@@ -111,3 +132,61 @@ class TestDeleteAgentWithTasks:
)
assert remaining.scalars().first() is None
assert await verify.get(Agent, performer_id) is not None
+
+
+class TestGetByNameMultiTenant:
+ """`Agent.name` is unique per tenant (`uq_agents_tenant_name`), not
+ globally — two tenants may each have an agent of the same name. Before
+ scoping the read, an unfiltered `get_by_name`/`get_by_name_insensitive`
+ matched both rows and raised `MultipleResultsFound` out of every caller
+ that resolves an agent by name (mention routing, registration, the
+ gateway).
+ """
+
+ async def test_get_by_name_returns_the_bound_tenants_agent(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = AgentStore()
+ other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+
+ async with session_factory() as session:
+ session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant))
+ await session.flush()
+ own = await _make_agent(session, "shared-name")
+ other = await _make_agent_for_tenant(session, other_tenant, "shared-name")
+ await session.commit()
+
+ async with session_factory() as verify:
+ result = await store.get_by_name(verify, "shared-name")
+ assert result is not None
+ assert result.id == own.id
+
+ async with session_factory() as verify:
+ with tenant_scope(other_tenant):
+ result = await store.get_by_name(verify, "shared-name")
+ assert result is not None
+ assert result.id == other.id
+
+ async def test_get_by_name_insensitive_returns_the_bound_tenants_agent(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = AgentStore()
+ other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+
+ async with session_factory() as session:
+ session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant))
+ await session.flush()
+ own = await _make_agent(session, "SharedName")
+ other = await _make_agent_for_tenant(session, other_tenant, "sharedname")
+ await session.commit()
+
+ async with session_factory() as verify:
+ result = await store.get_by_name_insensitive(verify, "sharedname")
+ assert result is not None
+ assert result.id == own.id
+
+ async with session_factory() as verify:
+ with tenant_scope(other_tenant):
+ result = await store.get_by_name_insensitive(verify, "sharedname")
+ assert result is not None
+ assert result.id == other.id
diff --git a/core/tests/switch_core/db/stores/test_client_store.py b/core/tests/switch_core/db/stores/test_client_store.py
new file mode 100644
index 000000000..264d00e3a
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_client_store.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+import uuid
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Client, Tenant
+from switch_core.db.stores.client_store import ClientStore
+from switch_core.tenant_context import tenant_scope
+
+
+async def _make_client(session: AsyncSession, matrix_user_id: str) -> Client:
+ client = Client(
+ matrix_user_id=matrix_user_id,
+ display_name=matrix_user_id,
+ type="agent",
+ )
+ session.add(client)
+ await session.flush()
+ return client
+
+
+async def _make_client_for_tenant(
+ session: AsyncSession, tenant_id: str, matrix_user_id: str
+) -> Client:
+ """A client filed under `tenant_id` rather than the ambient tenant."""
+ with tenant_scope(tenant_id):
+ return await _make_client(session, matrix_user_id)
+
+
+class TestGetByMatrixUserIdMultiTenant:
+ """`Client.matrix_user_id` is unique per tenant
+ (`uq_clients_tenant_matrix_user_id`), not globally — two tenants may each
+ puppet the same Matrix user id. Before scoping the read, an unfiltered
+ `get_by_matrix_user_id` matched both rows and raised
+ `MultipleResultsFound` out of message routing and provisioning, which
+ resolve the sending client from an inbound event this way.
+ """
+
+ async def test_returns_the_bound_tenants_client(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ClientStore()
+ other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+ shared_matrix_user_id = "@shared:switch.local"
+
+ async with session_factory() as session:
+ session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant))
+ await session.flush()
+ own = await _make_client(session, shared_matrix_user_id)
+ other = await _make_client_for_tenant(
+ session, other_tenant, shared_matrix_user_id
+ )
+ await session.commit()
+
+ async with session_factory() as verify:
+ result = await store.get_by_matrix_user_id(verify, shared_matrix_user_id)
+ assert result is not None
+ assert result.id == own.id
+
+ async with session_factory() as verify:
+ with tenant_scope(other_tenant):
+ result = await store.get_by_matrix_user_id(
+ verify, shared_matrix_user_id
+ )
+ assert result is not None
+ assert result.id == other.id
diff --git a/core/tests/switch_core/db/stores/test_room_store.py b/core/tests/switch_core/db/stores/test_room_store.py
new file mode 100644
index 000000000..73c583c77
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_room_store.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+import uuid
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Room, Tenant
+from switch_core.db.stores.room_store import RoomStore
+from switch_core.tenant_context import tenant_scope
+
+
+async def _make_room(session: AsyncSession, matrix_room_id: str) -> Room:
+ room = Room(
+ matrix_room_id=matrix_room_id,
+ name=matrix_room_id,
+ description="test room",
+ )
+ session.add(room)
+ await session.flush()
+ return room
+
+
+async def _make_room_for_tenant(
+ session: AsyncSession, tenant_id: str, matrix_room_id: str
+) -> Room:
+ """A room filed under `tenant_id` rather than the ambient tenant."""
+ with tenant_scope(tenant_id):
+ return await _make_room(session, matrix_room_id)
+
+
+class TestGetByMatrixRoomIdMultiTenant:
+ """`Room.matrix_room_id` is unique per tenant
+ (`uq_rooms_tenant_matrix_room_id`), not globally — two tenants may each
+ have a room bound to the same transport room id. Before scoping the read,
+ an unfiltered `get_by_matrix_room_id` matched both rows and raised
+ `MultipleResultsFound` out of every inbound-event path that resolves the
+ room this way (provisioning, the Postgres transport, admin commands).
+ """
+
+ async def test_returns_the_bound_tenants_room(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = RoomStore()
+ other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+ shared_matrix_room_id = "!shared:switch.local"
+
+ async with session_factory() as session:
+ session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant))
+ await session.flush()
+ own = await _make_room(session, shared_matrix_room_id)
+ other = await _make_room_for_tenant(
+ session, other_tenant, shared_matrix_room_id
+ )
+ await session.commit()
+
+ async with session_factory() as verify:
+ result = await store.get_by_matrix_room_id(verify, shared_matrix_room_id)
+ assert result is not None
+ assert result.id == own.id
+
+ async with session_factory() as verify:
+ with tenant_scope(other_tenant):
+ result = await store.get_by_matrix_room_id(
+ verify, shared_matrix_room_id
+ )
+ assert result is not None
+ assert result.id == other.id