Skip to content

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

feat(db): enforce tenant isolation with row-level security (CHOO-2623)

Wojciech Wojtyniak5da0376bce1a
diff --git a/core/pyproject.toml b/core/pyproject.toml
index 6b55dd3a4..013a0f0cc 100644
--- a/core/pyproject.toml
+++ b/core/pyproject.toml
@@ -87,6 +87,7 @@ asyncio_mode = "auto"
addopts = "-m 'not integration'"
markers = [
"integration: boots real Postgres + Tuwunel via testcontainers (slow; excluded from the default run — use `just test-integration`)",
+ "no_ambient_tenant: opt out of session_factory's default tenant-zero binding, for tests asserting what is or is not bound",
]
[tool.mypy]
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index d90c99663..dfce0c420 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -28,6 +28,7 @@ from switch_core.db.notify_ddl import (
CREATE_NOTIFY_TRIGGER,
DROP_NOTIFY_TRIGGER,
)
+from switch_core.db.rls_ddl import attach_row_level_security
from switch_core.tenant_context import current_tenant_id
@@ -88,23 +89,44 @@ class TenantMember(Base):
TENANT_ZERO_ID = "00000000-0000-0000-0000-000000000000"
+class TenantNotBoundError(RuntimeError):
+ """A scoped row was constructed with no tenant bound to write it under.
+
+ Raised from Python, before the row ever reaches the database, so the
+ failure points at the write that forgot to bind rather than at whatever
+ row-level-security error Postgres would otherwise raise first. Any code
+ that means to write across tenants uses `unscoped_session` and passes
+ `tenant_id` explicitly (system seeding, bootstrap); this exists for
+ everything else, which is supposed to have one bound by now.
+ """
+
+
def _tenant_id_default() -> str:
"""The tenant a new scoped row lands in when nothing tells it otherwise.
- Prefers the tenant bound to the current unit of work; falls back to tenant
- zero only when nothing is bound. The fallback is still load-bearing, and
- now for a sharper reason than before: the long-lived background tasks
- deliberately bind *nothing* for their lifetime
- (`switch_core.tenant_context.no_tenant`), so a write reached from one that
- did not bind the row's tenant lands here rather than on someone else's
- tenant. That is the right failure while there is one tenant and no policy
- to raise instead. It is the wrong one the day there are two — a write that
- should have been refused becomes a write into tenant zero — so this goes
- when row-level security lands, not before, and the raw-session inventory
- in `tests/switch_core/db/test_unscoped_session_allowlist.py` is what
- tracks how much is still relying on it.
+ Used to prefer the tenant bound to the current unit of work and fall back
+ to tenant zero when nothing was bound. That fallback is gone: with the
+ row-level-security policies in place (`db/rls_ddl.py`), a write into
+ tenant zero on behalf of a caller who forgot to bind is not a safe
+ default any more — it is a write into a real tenant that happens to be
+ wrong the day a second one exists, and `with check` cannot tell it apart
+ from a write tenant zero actually intended. Every writer is expected to
+ bind one by now: the long-lived background tasks unbind deliberately
+ (`switch_core.tenant_context.no_tenant`) and then bind the tenant of the
+ row they are about to act on before they act on it, and the raw-session
+ inventory in `tests/switch_core/db/test_unscoped_session_allowlist.py`
+ pins which modules may still open a session with nothing bound at all.
+ A write reached from one of those without an explicit `tenant_id` is
+ exactly the gap this now refuses to paper over.
"""
- return current_tenant_id() or TENANT_ZERO_ID
+ tenant_id = current_tenant_id()
+ if tenant_id is None:
+ raise TenantNotBoundError(
+ "no tenant is bound to this session; pass tenant_id explicitly "
+ "if this write is genuinely cross-tenant (system seeding), or "
+ "bind one before writing otherwise"
+ )
+ return tenant_id
class TenantScoped:
@@ -404,7 +426,7 @@ agent_skills = Table(
Text,
ForeignKey("tenants.id", name="fk_agent_skills_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("agent_id", Text, primary_key=True),
Column("skill_id", Text, primary_key=True),
@@ -459,7 +481,7 @@ room_agents = Table(
Text,
ForeignKey("tenants.id", name="fk_room_agents_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("room_id", Text, primary_key=True),
Column("agent_id", Text, primary_key=True),
@@ -493,7 +515,7 @@ room_skills = Table(
Text,
ForeignKey("tenants.id", name="fk_room_skills_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("room_id", Text, primary_key=True),
Column("skill_id", Text, primary_key=True),
@@ -713,7 +735,7 @@ room_references = Table(
Text,
ForeignKey("tenants.id", name="fk_room_references_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("room_id", Text, primary_key=True),
Column("reference_id", Text, primary_key=True),
@@ -737,7 +759,7 @@ room_documents = Table(
Text,
ForeignKey("tenants.id", name="fk_room_documents_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("room_id", Text, primary_key=True),
Column("document_id", Text, primary_key=True),
@@ -790,6 +812,11 @@ class ReferenceType(TenantScoped, Base):
Text,
ForeignKey("tenants.id", name="fk_reference_types_tenant"),
primary_key=True,
+ # Deliberately still the literal constant, not `_tenant_id_default`:
+ # every read in `ReferenceTypeStore` is hardcoded to `TENANT_ZERO_ID`
+ # too (each marked `TODO(next PR)`), so a context-aware write here
+ # would create rows a same-tenant read could no longer find. Fixing
+ # the pair is that follow-up's job, not this one's.
default=TENANT_ZERO_ID,
)
type: Mapped[str] = mapped_column(Text, primary_key=True)
@@ -857,7 +884,7 @@ room_packages = Table(
Text,
ForeignKey("tenants.id", name="fk_room_packages_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("room_id", Text, primary_key=True),
Column("package_id", Text, primary_key=True),
@@ -881,7 +908,7 @@ package_references = Table(
Text,
ForeignKey("tenants.id", name="fk_package_references_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("package_id", Text, primary_key=True),
Column("reference_id", Text, primary_key=True),
@@ -905,7 +932,7 @@ package_documents = Table(
Text,
ForeignKey("tenants.id", name="fk_package_documents_tenant"),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
),
Column("package_id", Text, primary_key=True),
Column("document_id", Text, primary_key=True),
@@ -1553,3 +1580,10 @@ event.listen(
"before_drop",
DDL(DROP_NOTIFY_TRIGGER).execute_if(dialect="postgresql"),
)
+
+# Same reasoning as the notify trigger above: `create_all` has to build the
+# row-level-security policies too, or the isolation test would pass against a
+# schema that has none. See `db/rls_ddl.py` for the DDL and why it takes this
+# shape; a migration carries its own frozen copy for the same reason the
+# notify trigger's migration does.
+attach_row_level_security(Base.metadata)
diff --git a/core/switch_core/db/rls_ddl.py b/core/switch_core/db/rls_ddl.py
new file mode 100644
index 000000000..9b58e3f29
--- /dev/null
+++ b/core/switch_core/db/rls_ddl.py
@@ -0,0 +1,184 @@
+"""Row-level security: the backstop for a query that forgets its tenant filter.
+
+Composite foreign keys (see `db/models.py`) stop a row from *referencing* a
+parent in another tenant. They do nothing for the read side: a store method
+that drops a `WHERE tenant_id = …` clause, by a typo or by never having one to
+begin with, still runs and still returns rows — just someone else's. Row-level
+security is what turns that into an empty result instead, at the database, so
+the guarantee does not depend on every one of roughly 250 store methods
+getting its filter right forever.
+
+**The function fails closed, and everything below rests on that.**
+`require_tenant_id()` reads `current_setting('app.tenant_id', true)` and
+raises unless it is a non-empty string. Both empty cases matter and are not
+the same bug: a session that never bound a tenant reads NULL (the `true`
+argument asks for that instead of an error); a session whose transaction
+already committed — releasing the `is_local` setting `db/tenant_session.py`
+issued — reads the empty string, not NULL. A function that only checked for
+NULL would pass the second case, which is exactly the pooled-connection leak
+this whole design exists to close: a session that finishes a tenant's
+transaction and is then handed unset-but-not-NULL to the next borrower. Empty
+string produced a real incident elsewhere in the company for that reason, so
+it gets the same treatment as NULL here rather than being assumed away.
+
+The policy text is one shape, applied identically to every scoped table:
+
+ alter table <t> enable row level security;
+ create policy tenant_isolation on <t>
+ for all
+ using (<col> = (select require_tenant_id()))
+ with check (<col> = (select require_tenant_id()));
+
+- **`with check` is not optional.** `using` only gates which existing rows a
+ statement can see; it says nothing about what a statement may write. An
+ `INSERT` has no existing row for `using` to filter, so without `with check`
+ it is free to address any tenant at all — writing a row into another
+ tenant that the writer can never read back. Prior art elsewhere, not a
+ hypothetical.
+- **`(select require_tenant_id())`**, not a bare call: wrapping it in a
+ `select` makes the planner evaluate it once per query, as an `InitPlan`,
+ instead of once per row. Marking the function `stable` is necessary but not
+ sufficient for that on its own.
+- **No `to <role>` clause.** Naming the eventual runtime role here would make
+ this DDL fail everywhere that role does not exist yet — including
+ `create_all` in every test that does not need it. Postgres already
+ exempts a table's owner from its own policies unless `force row level
+ security` is set (which this design deliberately does not set — see
+ `docs/old/multi-tenancy-phase1-db.md`'s "runtime role" section), so the
+ clause would buy nothing that ownership does not already give for free.
+- **`tenants` compares on `id`**, because a tenant *is* the boundary rather
+ than belonging to one. Every other scoped table compares on `tenant_id`.
+
+**The table list is derived, not copied.** A table is scoped if it carries a
+`tenant_id` column whose foreign key targets `tenants.id` — exactly
+`TenantScoped`'s column, and exactly what a plain `Table()` junction table
+gets by adding the equivalent column inline, since the mixin only works on a
+declarative class. Deriving it here means a table added later either follows
+the pattern and is picked up automatically, or does not and is exempt from
+these policies while still being visible as a gap to the catalogue test in
+`tests/switch_core/db/test_row_level_security.py` — never silently skipped by
+a list someone forgot to extend.
+
+**Where the SQL lives.** Same house pattern as `notify_ddl.py`: this module's
+DDL is attached to `Base.metadata` (`db/models.py`) so `create_all` builds it
+and every test exercises the same policies the server would run in
+production; the migration that installs this for real carries its own frozen
+verbatim copy of the SQL as it stood when written, because a migration is a
+record of a change that already happened and must not change meaning because
+this module later does.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy import DDL, MetaData, event
+
+REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"
+POLICY_NAME = "tenant_isolation"
+
+# SQLSTATE 42501, insufficient_privilege — the closest standard code for "you
+# may not see or touch this row", and the one an operator's tooling is likely
+# to already recognise as an authorization failure rather than a generic
+# error.
+_TENANT_NOT_SET_SQLSTATE = "42501"
+
+CREATE_REQUIRE_TENANT_FUNCTION = f"""
+CREATE OR REPLACE FUNCTION {REQUIRE_TENANT_FUNCTION_NAME}() RETURNS text
+LANGUAGE plpgsql STABLE AS $$
+DECLARE
+ v text := current_setting('app.tenant_id', true);
+BEGIN
+ IF v IS NULL OR v = '' THEN
+ RAISE EXCEPTION 'app.tenant_id is not set on this session'
+ USING ERRCODE = '{_TENANT_NOT_SET_SQLSTATE}';
+ END IF;
+ RETURN v;
+END;
+$$
+"""
+
+DROP_REQUIRE_TENANT_FUNCTION = (
+ f"DROP FUNCTION IF EXISTS {REQUIRE_TENANT_FUNCTION_NAME}()"
+)
+
+
+def enable_rls_ddl(table_name: str) -> str:
+ return f'ALTER TABLE "{table_name}" ENABLE ROW LEVEL SECURITY'
+
+
+def create_policy_ddl(table_name: str, tenant_column: str) -> str:
+ predicate = f'"{tenant_column}" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'
+ return (
+ f'CREATE POLICY {POLICY_NAME} ON "{table_name}"\n'
+ f" FOR ALL\n"
+ f" USING ({predicate})\n"
+ f" WITH CHECK ({predicate})"
+ )
+
+
+def drop_policy_ddl(table_name: str) -> str:
+ return f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{table_name}"'
+
+
+def scoped_tables(metadata: MetaData) -> dict[str, str]:
+ """Table name -> the column its policy compares, derived from the schema.
+
+ `tenants` is the one table scoped by `id`: every other table is scoped by
+ carrying a `tenant_id` column whose foreign key targets `tenants.id`. That
+ second test — the foreign key, not just the column name — is deliberate:
+ a table that merely happens to have a column called `tenant_id` without
+ the constraint is not actually tied to a tenant and must not silently pick
+ up a policy that would then reject every row it holds.
+ """
+ tables: dict[str, str] = {}
+ for table in metadata.tables.values():
+ if table.name == "tenants":
+ tables[table.name] = "id"
+ continue
+ tenant_id_col = table.columns.get("tenant_id")
+ if tenant_id_col is None:
+ continue
+ if any(
+ fk.column.table.name == "tenants" and fk.column.name == "id"
+ for fk in tenant_id_col.foreign_keys
+ ):
+ tables[table.name] = "tenant_id"
+ return tables
+
+
+def attach_row_level_security(metadata: MetaData) -> None:
+ """Register the function and every table's policy on `metadata`.
+
+ Mirrors how `notify_ddl.py`'s trigger is attached in `db/models.py`: the
+ function is bracketed around the whole `create_all`/`drop_all` (a
+ `MetaData`-level event, since no single table owns it), and each table's
+ `ENABLE ROW LEVEL SECURITY` plus its policy ride that table's own
+ `after_create` — after the function exists (metadata `before_create` runs
+ before any table's own events) and after the table itself does.
+ """
+ event.listen(
+ metadata,
+ "before_create",
+ DDL(CREATE_REQUIRE_TENANT_FUNCTION).execute_if(dialect="postgresql"),
+ )
+ for table_name, column in scoped_tables(metadata).items():
+ table = metadata.tables[table_name]
+ event.listen(
+ table,
+ "after_create",
+ DDL(enable_rls_ddl(table_name)).execute_if(dialect="postgresql"),
+ )
+ event.listen(
+ table,
+ "after_create",
+ DDL(create_policy_ddl(table_name, column)).execute_if(dialect="postgresql"),
+ )
+ event.listen(
+ table,
+ "before_drop",
+ DDL(drop_policy_ddl(table_name)).execute_if(dialect="postgresql"),
+ )
+ event.listen(
+ metadata,
+ "after_drop",
+ DDL(DROP_REQUIRE_TENANT_FUNCTION).execute_if(dialect="postgresql"),
+ )
diff --git a/core/switch_core/migrations/versions/265ed188ad6f_row_level_security.py b/core/switch_core/migrations/versions/265ed188ad6f_row_level_security.py
new file mode 100644
index 000000000..7f983be2b
--- /dev/null
+++ b/core/switch_core/migrations/versions/265ed188ad6f_row_level_security.py
@@ -0,0 +1,155 @@
+"""row-level security for every tenant-scoped table
+
+Implements the row-level-security half of Phase 1 multi-tenancy (see
+`docs/old/multi-tenancy-phase1-db.md`, "Row-level security"), which the
+schema migration (`8b276792ee30`) deliberately stopped short of: one
+function, one policy text, applied identically to all 38 tenant-scoped
+tables — the 36 the schema migration named plus `tenants` and
+`tenant_members`.
+
+`require_tenant_id()` reads `current_setting('app.tenant_id', true)` and
+raises unless it is a non-empty string. Both empty cases matter: a session
+that never bound a tenant reads NULL; a session whose transaction already
+committed — releasing the `is_local` setting `db/tenant_session.py` issued —
+reads the empty string, not NULL. A function that only checked for NULL would
+miss the second, which is exactly the pooled-connection leak this design
+exists to close.
+
+Every policy is `for all`, comparing `tenant_id` (or, for `tenants` itself,
+`id`) against `(select require_tenant_id())` in both `using` and `with
+check`. The `select` wrapper makes the planner evaluate the function once per
+query rather than once per row; `with check` is not optional — without it an
+`insert` or `update` can write any tenant at all, which is two of the four
+prior-art bugs this design cites. There is no `to <role>` clause: naming the
+future runtime role here would make this migration fail on every environment
+that role does not exist in yet, and Postgres already exempts a table's owner
+from its own policies (this migration does not set `force row level
+security`), which is the exemption the design relies on instead.
+
+The DDL below is a verbatim copy of `switch_core/db/rls_ddl.py` as it stood
+when this migration was written, copied rather than imported for the same
+reason `d4e17b90c3a5`'s notify trigger is: a migration is a record of a
+change that already happened, and importing the live module would let a
+later edit to it silently change what this migration means.
+
+This migration creates no roles and issues no grants — that is a separate,
+later change (CHOO-2685; see the design doc's "runtime role" section). Until
+that role exists and the application connects as it, every policy below is
+inert against a superuser or table-owner connection, which is what local
+Compose, the chart and the test containers use today. Nothing here changes
+that; it only makes the policies exist so that work has something to point
+the runtime at.
+
+Revision ID: 265ed188ad6f
+Revises: 8b276792ee30
+Create Date: 2026-09-10 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+from alembic import op
+
+revision: str = "265ed188ad6f"
+down_revision: str | None = "8b276792ee30"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"
+POLICY_NAME = "tenant_isolation"
+
+CREATE_REQUIRE_TENANT_FUNCTION = f"""
+CREATE OR REPLACE FUNCTION {REQUIRE_TENANT_FUNCTION_NAME}() RETURNS text
+LANGUAGE plpgsql STABLE AS $$
+DECLARE
+ v text := current_setting('app.tenant_id', true);
+BEGIN
+ IF v IS NULL OR v = '' THEN
+ RAISE EXCEPTION 'app.tenant_id is not set on this session'
+ USING ERRCODE = '42501';
+ END IF;
+ RETURN v;
+END;
+$$
+"""
+
+DROP_REQUIRE_TENANT_FUNCTION = (
+ f"DROP FUNCTION IF EXISTS {REQUIRE_TENANT_FUNCTION_NAME}()"
+)
+
+# Every scoped table and the column its policy compares. Matches
+# `8b276792ee30`'s `SCOPED_TABLES` (compared on `tenant_id`) plus
+# `tenant_members` (also `tenant_id`) and `tenants` itself (compared on `id`,
+# since a tenant *is* the boundary rather than belonging to one).
+SCOPED_TABLES: list[tuple[str, str]] = [
+ ("tenants", "id"),
+ ("tenant_members", "tenant_id"),
+ ("agent_runtime_states", "tenant_id"),
+ ("agent_sessions", "tenant_id"),
+ ("agent_skills", "tenant_id"),
+ ("agents", "tenant_id"),
+ ("api_keys", "tenant_id"),
+ ("bridge_message_map", "tenant_id"),
+ ("client_rooms", "tenant_id"),
+ ("clients", "tenant_id"),
+ ("collaboration_bridges", "tenant_id"),
+ ("delivery_cursors", "tenant_id"),
+ ("documents", "tenant_id"),
+ ("external_user_claims", "tenant_id"),
+ ("external_users", "tenant_id"),
+ ("media_blobs", "tenant_id"),
+ ("message_attachments", "tenant_id"),
+ ("messages", "tenant_id"),
+ ("models", "tenant_id"),
+ ("package_documents", "tenant_id"),
+ ("package_references", "tenant_id"),
+ ("packages", "tenant_id"),
+ ("reference_types", "tenant_id"),
+ ("references", "tenant_id"),
+ ("role_leases", "tenant_id"),
+ ("room_agents", "tenant_id"),
+ ("room_documents", "tenant_id"),
+ ("room_groups", "tenant_id"),
+ ("room_links", "tenant_id"),
+ ("room_packages", "tenant_id"),
+ ("room_references", "tenant_id"),
+ ("room_roles", "tenant_id"),
+ ("room_skills", "tenant_id"),
+ ("rooms", "tenant_id"),
+ ("server_connectors", "tenant_id"),
+ ("skills", "tenant_id"),
+ ("tasks", "tenant_id"),
+ ("tools", "tenant_id"),
+]
+
+
+def _enable_rls_ddl(table_name: str) -> str:
+ return f'ALTER TABLE "{table_name}" ENABLE ROW LEVEL SECURITY'
+
+
+def _create_policy_ddl(table_name: str, tenant_column: str) -> str:
+ predicate = f'"{tenant_column}" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'
+ return (
+ f'CREATE POLICY {POLICY_NAME} ON "{table_name}"\n'
+ f" FOR ALL\n"
+ f" USING ({predicate})\n"
+ f" WITH CHECK ({predicate})"
+ )
+
+
+def _drop_policy_ddl(table_name: str) -> str:
+ return f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{table_name}"'
+
+
+def upgrade() -> None:
+ op.execute(CREATE_REQUIRE_TENANT_FUNCTION)
+ for table_name, column in SCOPED_TABLES:
+ op.execute(_enable_rls_ddl(table_name))
+ op.execute(_create_policy_ddl(table_name, column))
+
+
+def downgrade() -> None:
+ for table_name, _column in reversed(SCOPED_TABLES):
+ op.execute(_drop_policy_ddl(table_name))
+ op.execute(f'ALTER TABLE "{table_name}" DISABLE ROW LEVEL SECURITY')
+ op.execute(DROP_REQUIRE_TENANT_FUNCTION)
diff --git a/core/tests/conftest.py b/core/tests/conftest.py
index 9f6f8b34b..49583fe13 100644
--- a/core/tests/conftest.py
+++ b/core/tests/conftest.py
@@ -1,10 +1,13 @@
from __future__ import annotations
+import uuid
from collections.abc import AsyncIterator, Iterator
+from dataclasses import dataclass
import pytest
import pytest_asyncio
-from sqlalchemy import insert
+from sqlalchemy import insert, text
+from sqlalchemy.engine import make_url
from sqlalchemy.ext.asyncio import (
AsyncConnection,
AsyncSession,
@@ -19,6 +22,7 @@ import switch_core.db.models # noqa: F401
from switch_core.db.base import Base
from switch_core.db.engine import create_session_factory
from switch_core.db.models import TENANT_ZERO_ID, Tenant
+from switch_core.tenant_context import bind_tenant_id, unbind_tenant_id
async def _seed_tenant_zero(conn: AsyncConnection) -> None:
@@ -52,19 +56,158 @@ def postgres_url() -> Iterator[str]:
@pytest_asyncio.fixture
async def session_factory(
- postgres_url: str,
+ postgres_url: str, request: pytest.FixtureRequest
) -> AsyncIterator[async_sessionmaker[AsyncSession]]:
- """Fresh schema per test: create all tables, yield a session factory, drop."""
+ """Fresh schema per test: create all tables, yield a session factory, drop.
+
+ Also binds tenant zero for the duration of the test, unless the test is
+ marked `no_ambient_tenant`. In production a tenant is always bound before
+ store code runs — an authenticated request, or one of the background call
+ sites `db/session_scope.py` covers — so a store method is never called
+ with nothing bound outside a deliberately unscoped path. Most of this
+ suite constructs scoped rows directly rather than through a request,
+ though, so without this default they would be calling those methods with
+ nothing bound — not a scenario the design means to exercise, and not what
+ any of these tests are about.
+
+ The marker exists for the tests that *are* about exactly that: a test
+ asserting what is or is not bound before, after or around a call — the
+ tenant-context machinery itself, not a store — needs `current_tenant_id()`
+ to start `None`, and this default would otherwise stand in its way. A test
+ doing ordinary multi-tenant work instead binds its own (`tenant_scope`,
+ `tenant_session`, `no_tenant`) over the part it cares about, which simply
+ overrides this default for that block — only the "nothing bound at all,
+ including before I do anything" assertions need the marker.
+ """
engine = create_async_engine(postgres_url)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
await _seed_tenant_zero(conn)
+ token = (
+ None
+ if request.node.get_closest_marker("no_ambient_tenant")
+ else bind_tenant_id(TENANT_ZERO_ID)
+ )
try:
# Goes through the same factory constructor production wiring uses,
# so this fixture — which backs most of the store test suite — differs
# from production in as little as possible.
yield create_session_factory(engine)
finally:
+ if token is not None:
+ unbind_tenant_id(token)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await engine.dispose()
+
+
+@dataclass(frozen=True)
+class RLSHarness:
+ """Two ways into the same database, for row-level-security tests that
+ need both (CHOO-2623).
+
+ `owner` connects the same way `session_factory` above does — as the
+ container's superuser, which bypasses every policy by ownership, the same
+ hatch a real system session relies on (see the design doc's "bootstrap
+ problem" section). Test setup uses it to create cross-tenant fixture data
+ no tenant-scoped session could ever legitimately write: a new `tenants`
+ row, for one, since its own policy compares on `id` — inserting tenant B
+ while bound to tenant A can never satisfy `with check`, and inserting it
+ unscoped can never satisfy `using` either, because creating a tenant is
+ necessarily a system operation.
+
+ `restricted` is the role the policies actually apply to: every assertion
+ about isolation is made through it, never through `owner` or the plain
+ `session_factory` fixture, both of which would pass regardless of whether
+ a single policy in `db/rls_ddl.py` exists.
+ """
+
+ owner: async_sessionmaker[AsyncSession]
+ restricted: async_sessionmaker[AsyncSession]
+
+
+@pytest_asyncio.fixture
+async def rls_harness(postgres_url: str) -> AsyncIterator[RLSHarness]:
+ """A session factory connected as a role row-level security applies to.
+
+ `session_factory` connects as the container's superuser — the same shape
+ local Compose, the chart and the test containers all use today — and **a
+ superuser ignores row-level security unconditionally**. A test built only
+ on that fixture cannot tell a working policy from a schema with none, so
+ `docs/old/multi-tenancy-phase1-db.md`'s "Done when" is unreachable without
+ something else.
+
+ This is that something else. Per test, it builds the schema (so
+ `create_all` attaches the same policies a migration would, exactly as
+ `session_factory` does), seeds tenant zero, and creates a throwaway login
+ role that is not the owner (so it doesn't inherit the owner's blanket
+ exemption from its own tables' policies), not a superuser, and carries no
+ `BYPASSRLS`. It is granted exactly what a restricted runtime role would
+ need — CRUD on the schema's tables and `EXECUTE` on `require_tenant_id()`
+ — and nothing else: deliberately the same shape `docs/old/multi-tenancy-
+ phase1-db.md`'s "runtime role" section describes for the real deployment
+ role this phase does not create. Creating it only here, inside a test
+ fixture, is what that section calls out as the one place Phase 1 does
+ keep a restricted role.
+
+ Only the tests that exist to prove the policies correct ask for this
+ fixture — the rest of the suite keeps using `session_factory` exactly as
+ it does today. What this proves, and what it does not: it proves the
+ *policies* are correct, that a session subject to them cannot cross a
+ tenant boundary through the ordinary store layer. It does not prove the
+ *deployment* is subject to them, since nothing here changes which role
+ local Compose, the chart or production connect as — that is the separate
+ role work (CHOO-2685); until it lands, a superuser or table-owner
+ connection bypasses every policy below regardless of what this fixture
+ demonstrates.
+ """
+ owner_engine = create_async_engine(postgres_url)
+ role = f"switch_rls_test_{uuid.uuid4().hex[:12]}"
+ password = uuid.uuid4().hex
+
+ async with owner_engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ await _seed_tenant_zero(conn)
+ # CREATE ROLE does not accept a bind parameter for PASSWORD (it is not
+ # a normal DML statement), so the password is interpolated directly.
+ # It is a fresh, random, throwaway value scoped to this one test.
+ await conn.execute(
+ text(
+ f"CREATE ROLE \"{role}\" LOGIN PASSWORD '{password}' "
+ "NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS"
+ )
+ )
+ await conn.execute(text(f'GRANT USAGE ON SCHEMA public TO "{role}"'))
+ await conn.execute(
+ text(
+ "GRANT SELECT, INSERT, UPDATE, DELETE "
+ f'ON ALL TABLES IN SCHEMA public TO "{role}"'
+ )
+ )
+ await conn.execute(
+ text(f'GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO "{role}"')
+ )
+ await conn.execute(
+ text(f'GRANT EXECUTE ON FUNCTION require_tenant_id() TO "{role}"')
+ )
+
+ restricted_url = make_url(postgres_url).set(username=role, password=password)
+ restricted_engine = create_async_engine(restricted_url)
+ try:
+ yield RLSHarness(
+ owner=create_session_factory(owner_engine),
+ restricted=create_session_factory(restricted_engine),
+ )
+ finally:
+ await restricted_engine.dispose()
+ async with owner_engine.begin() as conn:
+ await conn.run_sync(Base.metadata.drop_all)
+ async with owner_engine.begin() as conn:
+ # Dropping the tables removes their own grants with them, but the
+ # schema-level `GRANT USAGE` survives — `DROP OWNED BY` revokes
+ # every privilege still granted to the role (it owns no objects,
+ # so there is nothing for it to drop), which is what lets `DROP
+ # ROLE` succeed right after.
+ await conn.execute(text(f'DROP OWNED BY "{role}"'))
+ await conn.execute(text(f'DROP ROLE "{role}"'))
+ await owner_engine.dispose()
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py b/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py
index b004bcc73..09ecebb7a 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import hashlib
+import pytest
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
@@ -84,6 +85,7 @@ class TestRegistrationTokenDecidesTheTenant:
assert client is not None
assert client.tenant_id == TENANT_B
+ @pytest.mark.no_ambient_tenant
async def test_nothing_stays_bound_after_registration_returns(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py b/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py
index b45e231ba..8b69406de 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import uuid
+import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
@@ -121,6 +122,7 @@ async def _make_stale_runtime_state(
return agent.id, room.id
[email protected]_ambient_tenant
async def test_sweep_binds_each_row_s_own_tenant_and_does_not_leak(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
@@ -161,6 +163,7 @@ async def test_sweep_binds_each_row_s_own_tenant_and_does_not_leak(
assert row_b is not None and row_b.state == "idle"
[email protected]_ambient_tenant
async def test_the_tail_of_a_row_s_work_is_still_inside_its_binding(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
diff --git a/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py b/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py
index dcef7b913..6e2f6a932 100644
--- a/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py
+++ b/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import hashlib
from typing import Any
+import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.api_key_cache import ApiKeyCache
@@ -161,6 +162,7 @@ class TestBearerAuthBindsTheApiKeysTenant:
assert captured["agent_id"] is not None
assert captured["tenant_id"] == TENANT_A
+ @pytest.mark.no_ambient_tenant
async def test_the_tenant_is_not_bound_before_or_after_the_call(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -171,6 +173,7 @@ class TestBearerAuthBindsTheApiKeysTenant:
await _dispatch(mw, "tok")
assert current_tenant_id() is None
+ @pytest.mark.no_ambient_tenant
async def test_an_unknown_token_binds_nothing(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -211,6 +214,7 @@ class TestBearerAuthBindsARegistrationTokensTenant:
assert captured["tenant_id"] == TENANT_B
+ @pytest.mark.no_ambient_tenant
async def test_the_tenant_is_unbound_once_the_call_returns(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -221,6 +225,7 @@ class TestBearerAuthBindsARegistrationTokensTenant:
await _dispatch(mw, "reg-tok")
assert current_tenant_id() is None
+ @pytest.mark.no_ambient_tenant
async def test_mcp_still_refuses_a_registration_token_and_binds_nothing(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py
index 70e204091..d768ad57d 100644
--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py
+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py
@@ -30,10 +30,12 @@ from switch_core.bridges.collaboration.lifecycle_service import (
)
from switch_core.bridges.collaboration.models import BridgeConnectionConfig
from switch_core.db.models import Client, ClientRoom, CollaborationBridge, Room, Tenant
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.client_store import ClientStore
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.tenant_context import current_tenant_id, tenant_scope
+from tests.conftest import RLSHarness
def _service(
@@ -109,6 +111,7 @@ async def _make_bridge(session: AsyncSession, *, tenant_id: str) -> tuple[str, s
return bridge.id, client.id
[email protected]_ambient_tenant
async def test_start_all_binds_nothing_around_starting_a_bridge(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
@@ -139,6 +142,7 @@ async def test_start_all_binds_nothing_around_starting_a_bridge(
assert seen == {bridge_a: None, bridge_b: None}
[email protected]_ambient_tenant
async def test_a_failing_bridge_leaves_nothing_bound_for_the_next_one(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
@@ -291,10 +295,19 @@ async def test_a_host_resource_conflict_is_looked_for_across_every_tenant(
it miss precisely the case it exists for.
The conflict itself is asserted, and so is the tenant bound over the read
- that finds it. Both, because today nothing filters by tenant: no policy
- has landed, so a scoped read would still return every row and the
- conflict alone would pass either way. The binding is the part that will
- decide the answer once the policies bite.
+ that finds it: `_reject_resource_conflict` must reach `get_all` with
+ nothing bound, or a policy-bearing connection would silently narrow the
+ read to the caller's own tenant and this exact conflict — two tenants
+ claiming the same host resource — would go undetected.
+
+ That claim used to rest on the binding alone, because nothing yet made a
+ *scoped* read behave any differently. It does now:
+ `test_a_tenant_scoped_read_of_the_same_data_would_have_missed_the_conflict`
+ below runs the identical two-bridge fixture through the row-level-security
+ policies (`rls_harness`, a role they actually apply to) and shows a read
+ scoped to the newcomer's tenant does not see the incumbent's row — the
+ failure this test's unscoped read exists to avoid, made real rather than
+ inferred from where `current_tenant_id()` was `None`.
"""
incumbent_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
newcomer_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
@@ -348,3 +361,49 @@ async def test_a_host_resource_conflict_is_looked_for_across_every_tenant(
"tenant; under row-level security it would not have seen the "
"incumbent and would have let both claim the port"
)
+
+
+async def test_a_tenant_scoped_read_of_the_same_data_would_have_missed_the_conflict(
+ rls_harness: RLSHarness,
+) -> None:
+ """The row-visibility half of the test above, made real: the same
+ incumbent bridge, read through `CollaborationBridgeStore.get_all` — the
+ exact method `_reject_resource_conflict` calls — but scoped to the
+ newcomer's tenant instead of left unscoped. It comes back empty, which is
+ what would have let a second Teams listener claim the same port undetected
+ had the application code above been scoped instead of deliberately
+ unscoped.
+ """
+ incumbent_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+ newcomer_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+ async with rls_harness.owner() as session:
+ await _make_tenant(session, incumbent_tenant)
+ await _make_tenant(session, newcomer_tenant)
+ client = Client(
+ tenant_id=incumbent_tenant,
+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",
+ display_name="bridge client",
+ type="bridge",
+ )
+ session.add(client)
+ await session.flush()
+ session.add(
+ CollaborationBridge(
+ tenant_id=incumbent_tenant,
+ type="teams",
+ display_name="Their Teams",
+ client_id=client.id,
+ status="active",
+ connection_config={"listen_port": 3979},
+ )
+ )
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, newcomer_tenant) as session:
+ bridges = await CollaborationBridgeStore().get_all(session)
+
+ assert bridges == [], (
+ "a read scoped to the newcomer's tenant still saw the incumbent's "
+ "bridge — row-level security should have hidden it, which is what "
+ "the application code avoids by calling get_all unscoped"
+ )
diff --git a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py
index b5c1d6781..e473ca960 100644
--- a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py
+++ b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py
@@ -19,6 +19,7 @@ import asyncio
import uuid
from unittest.mock import MagicMock
+import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.clients.client_lifecycle_service import ClientLifecycleService
@@ -74,6 +75,7 @@ async def test_a_client_task_runs_with_no_tenant_bound(
)
[email protected]_ambient_tenant
async def test_start_all_binds_nothing_around_starting_each_client(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
diff --git a/core/tests/switch_core/db/test_row_level_security.py b/core/tests/switch_core/db/test_row_level_security.py
new file mode 100644
index 000000000..cc2c2d2cc
--- /dev/null
+++ b/core/tests/switch_core/db/test_row_level_security.py
@@ -0,0 +1,288 @@
+"""Row-level security (CHOO-2623): the "Done when" tests from
+`docs/old/multi-tenancy-phase1-db.md`.
+
+Every test here runs through `rls_harness` (`tests/conftest.py`, alongside
+`session_factory`), which connects as a throwaway role the policies actually
+apply to — never `session_factory` itself, the superuser-backed fixture the
+rest of the suite uses, which ignores every policy unconditionally and so
+cannot tell a working policy from a schema with none.
+
+What this file proves: a session subject to the policies cannot read, insert
+into, or update into another tenant through the ordinary store layer, and a
+session with no tenant bound gets an error rather than an empty (or worse,
+partial) result. What it does not prove: that any real deployment connects as
+such a role. Local Compose, the chart and the plain test containers all
+connect as the owner today, which bypasses every policy below by ownership —
+see `tests/conftest.py`'s `rls_harness` docstring and the design doc's
+"runtime role" section.
+
+**Verifying this file actually bites** (not automated; done once by hand when
+this suite was written and worth repeating after touching `db/rls_ddl.py`):
+weaken `create_policy_ddl`'s `WITH CHECK` clause to something permissive like
+`WITH CHECK (true)` and rerun `TestWriteSideNeedsWithCheck` — the insert test
+should fail. Omitting `WITH CHECK` entirely does *not* demonstrate this:
+Postgres reuses `USING` as `WITH CHECK` when none is given, which happens to
+still block that same insert and would falsely look like the test caught
+nothing.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from sqlalchemy import insert, select, text, update
+from sqlalchemy.exc import DBAPIError
+from sqlalchemy.ext.asyncio import async_sessionmaker
+
+from switch_core.db.base import Base
+from switch_core.db.models import RoomGroup, Tenant
+from switch_core.db.rls_ddl import POLICY_NAME, scoped_tables
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.room_group_store import RoomGroupStore
+from tests.conftest import RLSHarness
+
+
+async def _make_tenant(owner: async_sessionmaker, tenant_id: str) -> None:
+ async with owner() as session:
+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))
+ await session.commit()
+
+
+def _tenant_pair() -> tuple[str, str]:
+ return f"tenant-{uuid.uuid4().hex[:8]}", f"tenant-{uuid.uuid4().hex[:8]}"
+
+
+class TestIsolationThroughTheStoreLayer:
+ """The test the ticket closes on: two tenants, and tenant A cannot read
+ tenant B's rows through the ordinary store layer — connected as a
+ restricted role, through `RoomGroupStore`, not by hand-written SQL.
+ `RoomGroupStore.get` does no tenant filtering of its own (a plain
+ `session.get(RoomGroup, group_id)`), so row-level security is the only
+ thing standing between tenant A and tenant B's row.
+ """
+
+ async def test_tenant_a_cannot_read_tenant_bs_row_by_id(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ tenant_a, tenant_b = _tenant_pair()
+ await _make_tenant(rls_harness.owner, tenant_a)
+ await _make_tenant(rls_harness.owner, tenant_b)
+
+ store = RoomGroupStore()
+ async with tenant_session(rls_harness.restricted, tenant_b) as session:
+ group_b = await store.create(
+ session,
+ name="b-group",
+ description=None,
+ color=None,
+ parent_group_id=None,
+ )
+ await session.commit()
+ group_b_id = group_b.id
+
+ async with tenant_session(rls_harness.restricted, tenant_a) as session:
+ found = await store.get(session, group_b_id)
+
+ assert found is None, (
+ "tenant A's session read a row belonging to tenant B through "
+ "RoomGroupStore.get — the policy's USING clause should have "
+ "hidden it"
+ )
+
+ async def test_tenant_as_listing_never_includes_tenant_bs_rows(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ tenant_a, tenant_b = _tenant_pair()
+ await _make_tenant(rls_harness.owner, tenant_a)
+ await _make_tenant(rls_harness.owner, tenant_b)
+
+ store = RoomGroupStore()
+ async with tenant_session(rls_harness.restricted, tenant_a) as session:
+ await store.create(
+ session,
+ name="a-group",
+ description=None,
+ color=None,
+ parent_group_id=None,
+ )
+ await session.commit()
+ async with tenant_session(rls_harness.restricted, tenant_b) as session:
+ await store.create(
+ session,
+ name="b-group",
+ description=None,
+ color=None,
+ parent_group_id=None,
+ )
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, tenant_a) as session:
+ groups = await store.get_all(session)
+
+ assert [g.tenant_id for g in groups] == [tenant_a], (
+ "get_all issues no tenant filter of its own; a second tenant's "
+ "row reaching this list means the policy let it through"
+ )
+
+
+class TestWriteSideNeedsWithCheck:
+ """`USING` alone gates what a statement can *see*; it says nothing about
+ what a statement is allowed to *write*. The gap is starkest on `INSERT`:
+ there is no existing row for `USING` to filter, so a policy carrying only
+ `USING` — or a `WITH CHECK` weakened to something like `true` — leaves an
+ `INSERT` free to address any tenant at all. That is `with_check`'s job,
+ and this is what "reintroducing a defect" (see the module docstring's
+ verification note) actually bites: loosen `WITH CHECK` and this test is
+ the one that turns red.
+
+ The `UPDATE` case included below is *not* the same gap. Postgres re-checks
+ a row's new state against a table's visibility policy on `UPDATE`
+ regardless of what `WITH CHECK` says, so — because this design gives
+ `USING` and `WITH CHECK` the identical predicate — moving a row tenant A
+ can see into tenant B is already refused before `WITH CHECK` gets
+ involved. It is included anyway as the write-side counterpart the "Done
+ when" list asks for, and because a future edit that let the two
+ predicates diverge would only be caught by a test that actually exercises
+ `UPDATE`.
+ """
+
+ async def test_cannot_insert_a_row_explicitly_addressed_to_another_tenant(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """A plain Core `INSERT`, not `session.add()` + flush: the ORM path
+ fetches `RoomGroup.created_at` back via an implicit `RETURNING`, and
+ Postgres refuses to return a row `USING` would hide regardless of
+ `WITH CHECK` — which would make this pass for the wrong reason (via
+ `USING`-on-`RETURNING`, not `WITH CHECK`). A bare `INSERT` has no
+ `RETURNING` and so isolates the one thing this test is about.
+ """
+ tenant_a, tenant_b = _tenant_pair()
+ await _make_tenant(rls_harness.owner, tenant_a)
+ await _make_tenant(rls_harness.owner, tenant_b)
+
+ async with tenant_session(rls_harness.restricted, tenant_a) as session:
+ with pytest.raises(DBAPIError, match="row-level security"):
+ await session.execute(
+ insert(RoomGroup.__table__).values(
+ id=str(uuid.uuid4()), tenant_id=tenant_b, name="smuggled"
+ )
+ )
+
+ async def test_cannot_update_an_own_row_into_another_tenant(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Belt-and-suspenders, not a gap `WITH CHECK` alone closes here: see
+ the class docstring. `USING` and `WITH CHECK` share one predicate by
+ design, so this stays refused either way — pinned so a future change
+ that let them diverge would be caught by a test that exercises
+ `UPDATE`, not only the `INSERT` case above.
+ """
+ tenant_a, tenant_b = _tenant_pair()
+ await _make_tenant(rls_harness.owner, tenant_a)
+ await _make_tenant(rls_harness.owner, tenant_b)
+
+ store = RoomGroupStore()
+ async with tenant_session(rls_harness.restricted, tenant_a) as session:
+ own = await store.create(
+ session,
+ name="mine",
+ description=None,
+ color=None,
+ parent_group_id=None,
+ )
+ await session.commit()
+ own_id = own.id
+
+ async with tenant_session(rls_harness.restricted, tenant_a) as session:
+ with pytest.raises(DBAPIError, match="row-level security"):
+ await session.execute(
+ update(RoomGroup)
+ .where(RoomGroup.id == own_id)
+ .values(tenant_id=tenant_b)
+ )
+
+
+class TestNoTenantSetRaises:
+ async def test_a_query_with_no_tenant_bound_raises(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Not "returns nothing" — that would be indistinguishable from an
+ empty tenant. `require_tenant_id()` fails closed instead."""
+ async with rls_harness.restricted() as session:
+ with pytest.raises(DBAPIError, match="app.tenant_id is not set"):
+ await session.execute(select(RoomGroup))
+
+
+async def _rowsecurity_by_table(session) -> dict[str, bool]: # type: ignore[no-untyped-def]
+ result = await session.execute(
+ text("SELECT tablename, rowsecurity FROM pg_tables WHERE schemaname = 'public'")
+ )
+ return {row.tablename: row.rowsecurity for row in result}
+
+
+async def _tenant_isolation_policies(
+ session, # type: ignore[no-untyped-def]
+) -> dict[str, tuple[str | None, str | None]]:
+ result = await session.execute(
+ text(
+ "SELECT tablename, qual, with_check FROM pg_policies "
+ "WHERE schemaname = 'public' AND policyname = :name"
+ ),
+ {"name": POLICY_NAME},
+ )
+ return {row.tablename: (row.qual, row.with_check) for row in result}
+
+
+class TestCatalogueCoverage:
+ """Read the built schema back out of the database — `pg_tables` and
+ `pg_policies` — rather than the model source, so a scoped table added
+ later without a policy fails here even if nobody remembers to extend a
+ hand-kept list. The table list itself comes from `rls_ddl.scoped_tables`,
+ the same derivation `create_all` used to attach the policies in the first
+ place, not a copy of it.
+ """
+
+ async def test_scoped_table_list_is_not_trivially_small(
+ self, session_factory: async_sessionmaker
+ ) -> None:
+ scoped = scoped_tables(Base.metadata)
+ assert len(scoped) >= 30, scoped
+ assert "tenants" in scoped
+ assert scoped["tenants"] == "id"
+ assert "messages" in scoped
+ assert "agents" in scoped
+ for global_table in ("users", "oidc_identities", "feature_flags"):
+ assert global_table not in scoped
+
+ async def test_every_scoped_table_has_rls_enabled_and_a_well_formed_policy(
+ self, session_factory: async_sessionmaker
+ ) -> None:
+ scoped = scoped_tables(Base.metadata)
+ async with session_factory() as session:
+ rowsecurity = await _rowsecurity_by_table(session)
+ policies = await _tenant_isolation_policies(session)
+
+ missing_rls = sorted(t for t in scoped if not rowsecurity.get(t))
+ missing_policy = sorted(t for t in scoped if t not in policies)
+ missing_using_or_check = sorted(
+ t
+ for t, (qual, with_check) in policies.items()
+ if t in scoped and (qual is None or with_check is None)
+ )
+
+ assert missing_rls == [], f"row-level security not enabled: {missing_rls}"
+ assert missing_policy == [], f"no {POLICY_NAME!r} policy: {missing_policy}"
+ assert missing_using_or_check == [], (
+ f"policy missing USING or WITH CHECK: {missing_using_or_check}"
+ )
+
+ async def test_global_tables_carry_no_policy(
+ self, session_factory: async_sessionmaker
+ ) -> None:
+ scoped = scoped_tables(Base.metadata)
+ async with session_factory() as session:
+ policies = await _tenant_isolation_policies(session)
+ for global_table in ("users", "oidc_identities", "feature_flags"):
+ assert global_table not in scoped
+ assert global_table not in policies
diff --git a/core/tests/switch_core/db/test_session_scope.py b/core/tests/switch_core/db/test_session_scope.py
index dd710ae6f..a0218f3e8 100644
--- a/core/tests/switch_core/db/test_session_scope.py
+++ b/core/tests/switch_core/db/test_session_scope.py
@@ -44,6 +44,7 @@ class TestTenantSession:
assert await _current_setting(session) == TENANT_A
await session.commit()
+ @pytest.mark.no_ambient_tenant
async def test_the_tenant_is_unbound_once_the_block_exits(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -52,6 +53,7 @@ class TestTenantSession:
pass
assert current_tenant_id() is None
+ @pytest.mark.no_ambient_tenant
async def test_an_exception_still_unbinds(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -60,6 +62,7 @@ class TestTenantSession:
raise RuntimeError("boom")
assert current_tenant_id() is None
+ @pytest.mark.no_ambient_tenant
async def test_it_restores_an_outer_binding_rather_than_clearing_it(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -91,6 +94,7 @@ class TestUnscopedSession:
assert current_tenant_id() is None
assert await _current_setting(session) is None
+ @pytest.mark.no_ambient_tenant
async def test_it_unbinds_an_outer_tenant_for_the_duration(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -116,6 +120,7 @@ class TestUnscopedSession:
raise RuntimeError("boom")
assert current_tenant_id() == TENANT_A
+ @pytest.mark.no_ambient_tenant
async def test_current_tenant_id_is_unchanged_after_the_block(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/transport/test_postgres_transport.py b/core/tests/switch_core/transport/test_postgres_transport.py
index ea0b86e2e..2a16d8e66 100644
--- a/core/tests/switch_core/transport/test_postgres_transport.py
+++ b/core/tests/switch_core/transport/test_postgres_transport.py
@@ -21,6 +21,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.db.models import Client, ClientRoom, Message, Room, Tenant
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.media_store import MediaStore
from switch_core.db.stores.message_store import MessageStore
from switch_core.db.stores.room_store import RoomStore
@@ -37,6 +38,7 @@ from switch_core.transport import (
from switch_core.transport.ephemeral import EphemeralBus
from switch_core.transport.invites import InviteBus
from switch_core.transport.postgres import PostgresTransport
+from tests.conftest import RLSHarness
async def _make_room(session: AsyncSession) -> tuple[str, str, str, str]:
@@ -875,6 +877,7 @@ class TestDeliveryBindsTheRoomsTenant:
for task in self._tasks:
task.cancel()
+ @pytest.mark.no_ambient_tenant
async def test_a_delivery_binds_the_room_s_own_tenant(
self,
session_factory: async_sessionmaker[AsyncSession],
@@ -962,7 +965,13 @@ class TestATransportOwnsNoTenantOfItsOwn:
"""`joined_rooms` decides, once, what this client will ever hear. A
tenant bound over that read narrows it to a subset with no error to
say so — the client is simply deaf everywhere else, forever. So it
- must run unscoped even when reached from a bound context."""
+ must run unscoped even when reached from a bound context.
+
+ `test_a_tenant_scoped_read_would_have_returned_no_rooms_at_all` below
+ proves the "narrows it to a subset" half directly, through the row-
+ level-security policies rather than by inferring it from the tenant
+ this test's own spy observed.
+ """
tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"
async with session_factory() as session:
session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))
@@ -1012,6 +1021,53 @@ class TestATransportOwnsNoTenantOfItsOwn:
"silent in the rest"
)
+ async def test_a_tenant_scoped_read_would_have_returned_no_rooms_at_all(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The same client and its one room, read through
+ `RoomStore.get_for_client` — the exact method `joined_rooms` calls —
+ but scoped to a tenant the client does not belong to, instead of left
+ unscoped. It comes back empty: not a subset, since this client has
+ only the one room, but the same silent-and-wrong shape `joined_rooms`
+ avoids by never binding a tenant over this read at all.
+ """
+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"
+ other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+ async with rls_harness.owner() as session:
+ for t in (tenant_id, other_tenant):
+ session.add(Tenant(id=t, slug=t, name=t))
+ await session.flush()
+ suffix = uuid.uuid4().hex[:8]
+ client = Client(
+ tenant_id=tenant_id,
+ matrix_user_id=f"@sys-{suffix}:test",
+ display_name="admin",
+ type="admin",
+ )
+ session.add(client)
+ room = Room(
+ tenant_id=tenant_id,
+ matrix_room_id=f"!room-{suffix}:test",
+ name="a room",
+ description="",
+ )
+ session.add(room)
+ await session.flush()
+ session.add(
+ ClientRoom(tenant_id=tenant_id, client_id=client.id, room_id=room.id)
+ )
+ await session.commit()
+ client_id = client.id
+
+ async with tenant_session(rls_harness.restricted, other_tenant) as session:
+ rooms = await RoomStore().get_for_client(session, client_id)
+
+ assert rooms == [], (
+ "a read scoped to a tenant this client does not belong to still "
+ "returned its room — row-level security should have hidden it"
+ )
+
+ @pytest.mark.no_ambient_tenant
async def test_each_room_is_delivered_under_its_own_tenant(
self,
session_factory: async_sessionmaker[AsyncSession],
diff --git a/docs/old/multi-tenancy-phase1-db.md b/docs/old/multi-tenancy-phase1-db.md
index 8674d4fa3..5f7df515f 100644
--- a/docs/old/multi-tenancy-phase1-db.md
+++ b/docs/old/multi-tenancy-phase1-db.md
@@ -1,17 +1,14 @@
# Multi-tenancy Phase 1: the database design
-Status: partially built. Implements §2 of `multi-tenancy.md` (spike CHOO-2603)
-for CHOO-2623.
+Status: built. Implements §2 of `multi-tenancy.md` (spike CHOO-2603) for
+CHOO-2623.
This document was written as one design covering the whole schema half of
Phase 1 — new tables, per-tenant uniqueness, composite foreign keys, the
row-level-security policies, and the session plumbing that sets the tenant —
-and its reasoning below still describes that whole shape. What actually
-shipped is narrower: **the tenant model, per-tenant uniqueness and the
-composite foreign keys are built**, in the one migration this document
-describes. **Row-level security is not**: `require_tenant_id()`, the policy
-attached to each table, `db/rls_ddl.py` and the isolation test under "Done
-when" were all split out into a later change.
+and its reasoning below still describes that whole shape, in four changes
+rather than one. **The tenant model, per-tenant uniqueness and the composite
+foreign keys** landed first, in the migration `8b276792ee30`.
**"Setting the tenant" has since been built** and that section now describes
what was actually implemented, which differs from what it originally proposed —
an event hook rather than a dependency at every call site, for reasons given
@@ -21,11 +18,13 @@ work, described where "Setting the tenant" talks about background work below.
That section also records the model that was tried first, of binding once per
long-lived task, and the four ways it leaked; it is written up rather than
deleted because the reasoning that made it look right is easy to arrive at
-twice. Read the remaining
-sections as the design those later changes implement rather than as a
-description of what is running today; "What Phase 1 does not close" says which
-gaps are this migration's and which belong to the deferred work — row-level
-security is still the biggest of them.
+twice. **Row-level security has since been built too**: `require_tenant_id()`,
+the policy attached to each table, `db/rls_ddl.py` and the isolation test
+under "Done when" are all in place, in the migration `265ed188ad6f`. Read the
+remaining sections as a description of what is running today, except where a
+section says otherwise; "What Phase 1 does not close" says which gaps remain
+deliberately open — the runtime role that would make these policies bite in a
+deployed environment is the biggest of them, tracked separately as CHOO-2685.
Postgres 16 everywhere — local Compose, the chart, and the test containers —
and two things below need at least 15, so that is a floor, not an incidental
@@ -566,9 +565,19 @@ things remembered; with it, two, and both are checked by tests.
## The migration
-One revision:
+What shipped as one design landed as two revisions: the schema
+(`8b276792ee30`) below, and row-level security (`265ed188ad6f`, "Where the
+SQL lives" above) after it. Splitting them was not the original plan — it
+fell out of building this in stages — but it turned out to be the right
+shape anyway: the schema migration is safe to run and roll back on its own,
+with every policy still inert against the owner connection either way, and
+the second revision is a short, mechanical follow-on with nothing but
+`require_tenant_id()` and 38 near-identical `enable row level security` /
+`create policy` pairs to review.
-1. Create `tenants` and `tenant_members`; create `require_tenant_id()`.
+The schema revision:
+
+1. Create `tenants` and `tenant_members`.
2. Insert tenant zero, slug `default`, with a fixed id constant written into
the migration. Not read from the environment: `TENANT_ID` is config today
and a later edit to it must not silently desync from the row.
@@ -586,11 +595,11 @@ One revision:
7. Rewrite each scoped-to-scoped foreign key as composite, `not valid` first
and `validate constraint` after.
-No roles are created and no grants issued — see the role section above.
-Row-level security is not part of this migration either: `require_tenant_id()`,
-the policies and the isolation test described elsewhere in this document are
-deferred to a later change, tracked separately from the schema landed here
-(see "Status" at the top of this document).
+No roles are created and no grants issued, in either revision — see the role
+section above. Row-level security is not part of the schema revision: it is
+the second one, `265ed188ad6f`, which creates `require_tenant_id()` and every
+table's policy and nothing else — no roles or grants there either, for the
+same reason.
**On locking.** Alembic wraps a whole revision in one transaction
(`migrations/env.py`, `context.begin_transaction()`), and this migration does
@@ -624,37 +633,55 @@ note belongs in the migration's docstring.
## Done when
-An integration test proves tenant A cannot read tenant B's rows through the
-ordinary application paths — connected as a restricted role, through the store
-layer, not by hand-written SQL. That needs test infrastructure that does not
-exist yet: the fixtures create the role, grant to it, connect as it, and seed
-tenant zero, because the truncation between tests now empties `tenants` too.
+Built, in `tests/switch_core/db/test_row_level_security.py`. An integration
+test proves tenant A cannot read tenant B's rows through the ordinary
+application paths — connected as a restricted role, through the store layer
+(`RoomGroupStore`), not by hand-written SQL. That needed test infrastructure
+which did not exist before this change: `rls_harness`
+(`tests/conftest.py`, alongside `session_factory`) creates the role, grants to
+it, connects as it, and seeds tenant zero against a schema built the same way
+`session_factory` builds one — because the rest of the suite still runs
+against the owner connection, and always will until the role in the section
+above exists somewhere real.
Note what this does and does not prove. It proves the **policies** are correct,
which is the part Phase 1 owns. It does not prove the **deployment** is subject
to them — that is the role work, and until it lands the same test against a
real environment would pass for the wrong reason.
-Alongside it, three cheap tests that catch the regressions this design exists
-to prevent:
+Alongside it, the cheap tests that catch the regressions this design exists
+to prevent, also in that file:
- Every scoped table has row-level security enabled and a policy, asserted by
- querying `pg_policies` and `pg_tables` rather than by reading the code.
-- Every foreign key between two scoped tables includes `tenant_id`, asserted
- the same way from the catalogue. Without this a new table passes every other
- check while quietly falling back to a single-column key.
+ querying `pg_policies` and `pg_tables` rather than by reading the code, with
+ the table list itself derived from `rls_ddl.scoped_tables` rather than
+ copied.
+- A write-side pair — an `INSERT` addressed to another tenant, and an
+ `UPDATE` moving an own row into one — for what `with check` catches that
+ `using` alone would not. (The `UPDATE` case turns out to be defended either
+ way, because Postgres re-checks a row's new state against `using` on
+ `UPDATE` regardless of `with check`; it stays as the write-side test the
+ design calls for, and as a pin against the day the two predicates diverge.)
- A query issued with no tenant set raises rather than returning nothing.
+The foreign-key-carries-`tenant_id` catalogue check this section originally
+asked for shipped earlier, with the schema migration — see
+`tests/switch_core/db/test_tenant_schema_catalogue.py`, predating row-level
+security because it needed no policy to be meaningful.
+
## What Phase 1 does not close
Named so they are decisions rather than omissions.
-- **No row-level security yet.** The migration that landed adds the tenant
- model, per-tenant uniqueness and the composite foreign keys, and stops
- there — `require_tenant_id()`, the policy, and the runtime-role work that
- would make a policy bite are a later change, not merely inert code sitting
- next to this one. Deliberate, and safe while one tenant exists — and the
- hard prerequisite for the second.
+- **The policies exist and do not yet bite.** `require_tenant_id()` and every
+ table's policy are built and tested (`265ed188ad6f`,
+ `tests/switch_core/db/test_row_level_security.py`), but local Compose, the
+ chart and production all still connect as the table owner, which bypasses
+ row-level security by ownership regardless of what the policies say. The
+ runtime role that would make a policy bite in a deployed environment —
+ `switch_app`, described above — is CHOO-2685, not this phase. Deliberate,
+ and safe while one tenant exists — and the hard prerequisite for the
+ second.
- **Cross-tenant user enumeration.** `users` and `oidc_identities` have no
policy, so any tenant session can read every account. There is no exposure
while one tenant exists, and the correct fix needs invitations and a