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): messaging_installs and the lookup that routes a workspace to a tenant

Petr Bauchc08707dc824f
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index f61bfb12f..2ecd40132 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -1131,6 +1131,80 @@ class CollaborationBridge(TenantScoped, Base):
)
+# ── Messaging Installs ─────────────────────────────────────────────────────────
+
+
+class MessagingInstall(TenantScoped, Base):
+ """A tenant's installation of the Switch app into one external workspace.
+
+ The difference from `collaboration_bridges` is who supplied the
+ credential. A bridge holds a token an operator pasted in, from an app that
+ operator registered; an install holds a token *we* were granted, for our
+ app, by whoever clicked Add to Slack. Both end up driving the same adapter,
+ so this table records only what the install added: which workspace, whose
+ token, and what it may do.
+
+ **`(platform, external_workspace_id)` is unique across the whole
+ deployment, not per tenant**, and that is the single most important line
+ here. Inbound events arrive over one public endpoint carrying a workspace
+ id and no tenant, so a workspace claimed by two tenants is a message with
+ two possible destinations and no way to choose — which is the failure this
+ whole phase exists to make unrepresentable. The database decides it rather
+ than a read-then-insert in application code, because the check and the
+ write cannot be made atomic from outside.
+
+ That constraint is also the one place a tenant learns something about
+ another: claiming a workspace somebody else already claimed fails, and the
+ failure says so. It is the right answer — the alternative is a silent
+ second claim — and what it discloses is that *some* tenant holds a
+ workspace the caller was already able to name.
+
+ `bridge_id` is nullable because the install row is written before anything
+ is built on it, and because removing a bridge should not force the
+ credential to be thrown away and re-granted. A null there means the
+ install is recorded and not yet serving.
+
+ `encrypted_bot_token` uses the same key as every other credential this
+ schema stores (`crypto.encrypt_token` over the configured secret), so it
+ is protected against a stolen dump and not against a compromised process.
+ A per-tenant key is a stronger boundary and a later decision.
+
+ `scopes` is the platform's own spelling of what was granted, stored
+ verbatim rather than parsed into a list — a scope string that means
+ nothing to us is still the thing to show an operator asking why a call was
+ refused.
+ """
+
+ __tablename__ = "messaging_installs"
+ __table_args__ = (
+ UniqueConstraint(
+ "platform",
+ "external_workspace_id",
+ name="uq_messaging_installs_workspace",
+ ),
+ UniqueConstraint("id", "tenant_id", name="uq_messaging_installs_id_tenant"),
+ ForeignKeyConstraint(
+ ["tenant_id", "bridge_id"],
+ ["collaboration_bridges.tenant_id", "collaboration_bridges.id"],
+ name="fk_messaging_installs_bridge",
+ ),
+ )
+
+ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)
+ platform: Mapped[str] = mapped_column(Text, nullable=False)
+ external_workspace_id: Mapped[str] = mapped_column(Text, nullable=False)
+ encrypted_bot_token: Mapped[str] = mapped_column(Text, nullable=False)
+ scopes: Mapped[str] = mapped_column(Text, nullable=False)
+ status: Mapped[str] = mapped_column(Text, nullable=False)
+ installed_by_user_id: Mapped[str] = mapped_column(
+ Text, ForeignKey("users.id"), nullable=False
+ )
+ bridge_id: Mapped[str | None] = mapped_column(Text, nullable=True)
+ installed_at: Mapped[str] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), nullable=False
+ )
+
+
# ── Server-Side Connectors ────────────────────────────────────────────────────
diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.py
index dcb3fbcfe..adcd78dfd 100644
--- a/core/switch_core/db/tenant_lookup.py
+++ b/core/switch_core/db/tenant_lookup.py
@@ -1,4 +1,4 @@
-"""The whole exemption from row-level security, written out as eight functions.
+"""The whole exemption from row-level security, written out as nine functions.
Row-level security is enforced by `require_tenant_id()` (`db/rls_ddl.py`),
which raises when no tenant is bound. That is the property everything else
@@ -64,8 +64,9 @@ them about *metadata* rather than rows:
So the property this design actually holds is: **the exemption discloses the
shape of the deployment — which tenants exist, and which tenant a given user,
-credential, room, bridge, connector or invitation belongs to — and no row of
-any tenant-scoped table.** It is a boundary on data, not on metadata. Narrowing
+credential, room, bridge, connector, invitation or installed workspace belongs
+to — and no row of any tenant-scoped table.** It is a boundary on data, not on
+metadata. Narrowing
the second is a question about who may hold the runtime role's credentials at
all, since everything above is reachable by anyone who has them.
@@ -108,6 +109,19 @@ gates are actually enforced. Nothing about *that* row crosses the exemption;
only the tenant id does, which is the property every lookup in this module
rests on.
+**`tenant_of_messaging_install` is the ninth, and the only one whose caller is
+not a person.** An event from the Switch app installed in a customer's Slack
+arrives over a public endpoint that no one has authenticated to: what it
+carries is a workspace id, and the tenant is precisely what has to be worked out before
+anything else may happen. There is no row in hand to read the answer off, so
+this is shape 1 with the credential replaced by a workspace — resolve the
+tenant, bind it, and read everything after that through the ordinary scoped
+store. It takes both the platform and the workspace id because that pair,
+not the workspace id alone, is what `messaging_installs` makes unique; a
+lookup on the id alone would answer twice the first time two platforms
+happened to mint the same string, and refuse a customer's traffic for a
+reason in someone else's account.
+
Why not the obvious alternatives is argued in
`docs/old/multi-tenancy-phase1-db.md`, "The bootstrap problem"; the short
version is that returning rows instead of tenant ids would put a second copy
@@ -160,9 +174,9 @@ class TenantLookupError(RuntimeError):
@dataclass(frozen=True)
class TenantLookup:
- """One exempt function: its name, its single argument, and what it reads.
+ """One exempt function: its name, its arguments, and what it reads.
- `argument` is the parameter name *without* the `p_` prefix the SQL carries.
+ `arguments` are the parameter names *without* the `p_` prefix the SQL carries.
The prefix is not decoration: a `LANGUAGE sql` function whose parameter is
spelled like a column of a table in its own query resolves the name to the
column, silently, rather than to the parameter. Verified on Postgres 16,
@@ -183,25 +197,29 @@ class TenantLookup:
"""
name: str
- argument: str | None
+ arguments: tuple[str, ...]
query: str
purpose: str
@property
- def parameter(self) -> str | None:
- return None if self.argument is None else f"p_{self.argument}"
+ def parameters(self) -> tuple[str, ...]:
+ return tuple(f"p_{argument}" for argument in self.arguments)
+
+ @property
+ def parameter_declaration(self) -> str:
+ return ", ".join(f"{parameter} text" for parameter in self.parameters)
@property
def signature(self) -> str:
- return f"{self.name}({'' if self.argument is None else 'text'})"
+ return f"{self.name}({', '.join('text' for _ in self.arguments)})"
-# The seven of them. Ordered as the three shapes above: enumeration, then
+# The nine of them. Ordered as the three shapes above: enumeration, then
# credential resolution, then deriving a tenant from an identifier in hand.
TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
TenantLookup(
name="all_tenant_ids",
- argument=None,
+ arguments=(),
query="SELECT id FROM tenants ORDER BY created_at, id",
purpose=(
"Every tenant in the deployment, oldest first. The one question a "
@@ -211,7 +229,7 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
),
TenantLookup(
name="tenants_of_user",
- argument="user_id",
+ arguments=("user_id",),
query=(
"SELECT tenant_id FROM tenant_members "
"WHERE user_id = p_user_id ORDER BY tenant_id"
@@ -224,7 +242,7 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
),
TenantLookup(
name="tenant_of_api_key",
- argument="key_hash",
+ arguments=("key_hash",),
query="SELECT tenant_id FROM api_keys WHERE key_hash = p_key_hash",
purpose=(
"Which tenant a bearer credential belongs to. `api_keys.key_hash` "
@@ -234,7 +252,7 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
),
TenantLookup(
name="tenant_of_agent_oauth_client",
- argument="oauth_client_id",
+ arguments=("oauth_client_id",),
query=(
"SELECT tenant_id FROM agents WHERE oauth_client_id = p_oauth_client_id"
),
@@ -247,7 +265,7 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
),
TenantLookup(
name="tenant_of_room",
- argument="room_id",
+ arguments=("room_id",),
query="SELECT tenant_id FROM rooms WHERE id = p_room_id",
purpose=(
"Which tenant a room belongs to, for work reaching a room by its "
@@ -256,7 +274,7 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
),
TenantLookup(
name="tenant_of_collaboration_bridge",
- argument="bridge_id",
+ arguments=("bridge_id",),
query="SELECT tenant_id FROM collaboration_bridges WHERE id = p_bridge_id",
purpose=(
"Which tenant a bridge belongs to. Asked from boot, with nothing "
@@ -266,13 +284,13 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
),
TenantLookup(
name="tenant_of_server_connector",
- argument="connector_id",
+ arguments=("connector_id",),
query="SELECT tenant_id FROM server_connectors WHERE id = p_connector_id",
purpose="Same as the bridge, for a server-side connector.",
),
TenantLookup(
name="tenant_of_invitation",
- argument="token_hash",
+ arguments=("token_hash",),
query="SELECT tenant_id FROM invitations WHERE token_hash = p_token_hash",
purpose=(
"Which tenant an invitation belongs to, resolved from the hash of "
@@ -282,6 +300,22 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
"refuses to a session with nothing bound yet."
),
),
+ TenantLookup(
+ name="tenant_of_messaging_install",
+ arguments=("platform", "external_workspace_id"),
+ query=(
+ "SELECT tenant_id FROM messaging_installs "
+ "WHERE platform = p_platform "
+ "AND external_workspace_id = p_external_workspace_id"
+ ),
+ purpose=(
+ "Which tenant an inbound event from an installed workspace belongs "
+ "to. The public webhook is unauthenticated by nature and knows only "
+ "the platform it was posted to and the workspace the payload names, "
+ "so this runs before anything else the request does. Unique by "
+ "constraint on exactly this pair, so it answers at most once."
+ ),
+ ),
)
TENANT_LOOKUPS_BY_NAME: dict[str, TenantLookup] = {
@@ -297,9 +331,8 @@ SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"
def create_lookup_ddl(lookup: TenantLookup) -> str:
- parameters = "" if lookup.parameter is None else f"{lookup.parameter} text"
return (
- f"CREATE OR REPLACE FUNCTION {lookup.name}({parameters})\n"
+ f"CREATE OR REPLACE FUNCTION {lookup.name}({lookup.parameter_declaration})\n"
f" RETURNS SETOF text\n"
f" LANGUAGE sql STABLE SECURITY DEFINER\n"
f" SET search_path = {SECURE_SEARCH_PATH}\n"
@@ -337,33 +370,40 @@ def attach_tenant_lookups(metadata: MetaData) -> None:
# ── Calling them ──────────────────────────────────────────────────────────────
# One `text()` per lookup, written out rather than assembled from `lookup.name`
-# at call time: the eight names are fixed and known here, so there is nothing
-# for a call site to build. The assertion below is what keeps this dict from
-# quietly falling behind `TENANT_LOOKUPS` — a ninth lookup with no entry
-# here fails at import, not with a `KeyError` on whatever request reaches it
-# first.
+# at call time: the nine names are fixed and known here, so there is nothing
+# for a call site to build. Each bind is named after the lookup's own argument,
+# which is what lets `_call` zip them positionally against the dataclass and
+# fail loudly on a mismatch rather than binding the workspace to the platform.
+# The assertion below is what keeps this dict from quietly falling behind
+# `TENANT_LOOKUPS` — a tenth lookup with no entry here fails at import, not
+# with a `KeyError` on whatever request reaches it first.
_LOOKUP_STATEMENTS: dict[str, TextClause] = {
"all_tenant_ids": text("SELECT tenant_id FROM all_tenant_ids() AS tenant_id"),
"tenants_of_user": text(
- "SELECT tenant_id FROM tenants_of_user(:argument) AS tenant_id"
+ "SELECT tenant_id FROM tenants_of_user(:user_id) AS tenant_id"
),
"tenant_of_api_key": text(
- "SELECT tenant_id FROM tenant_of_api_key(:argument) AS tenant_id"
+ "SELECT tenant_id FROM tenant_of_api_key(:key_hash) AS tenant_id"
),
"tenant_of_agent_oauth_client": text(
- "SELECT tenant_id FROM tenant_of_agent_oauth_client(:argument) AS tenant_id"
+ "SELECT tenant_id FROM tenant_of_agent_oauth_client(:oauth_client_id) "
+ "AS tenant_id"
),
"tenant_of_room": text(
- "SELECT tenant_id FROM tenant_of_room(:argument) AS tenant_id"
+ "SELECT tenant_id FROM tenant_of_room(:room_id) AS tenant_id"
),
"tenant_of_collaboration_bridge": text(
- "SELECT tenant_id FROM tenant_of_collaboration_bridge(:argument) AS tenant_id"
+ "SELECT tenant_id FROM tenant_of_collaboration_bridge(:bridge_id) AS tenant_id"
),
"tenant_of_server_connector": text(
- "SELECT tenant_id FROM tenant_of_server_connector(:argument) AS tenant_id"
+ "SELECT tenant_id FROM tenant_of_server_connector(:connector_id) AS tenant_id"
),
"tenant_of_invitation": text(
- "SELECT tenant_id FROM tenant_of_invitation(:argument) AS tenant_id"
+ "SELECT tenant_id FROM tenant_of_invitation(:token_hash) AS tenant_id"
+ ),
+ "tenant_of_messaging_install": text(
+ "SELECT tenant_id FROM "
+ "tenant_of_messaging_install(:platform, :external_workspace_id) AS tenant_id"
),
}
@@ -375,7 +415,7 @@ assert _LOOKUP_STATEMENTS.keys() == TENANT_LOOKUPS_BY_NAME.keys(), (
async def _call(
session_factory: async_sessionmaker[AsyncSession],
lookup: TenantLookup,
- argument: str | None = None,
+ *arguments: str,
) -> list[str]:
"""Run one lookup on a session of its own, with nothing bound.
@@ -384,10 +424,14 @@ async def _call(
— and the answer must not be narrowed to it. Nothing bound is also the
honest state: this session may not touch a scoped table, and the database
is what enforces that now rather than an allowlist.
+
+ `strict=True` on the zip is the arity check. A lookup called with one
+ argument too few would otherwise leave a bind unfilled, and a lookup whose
+ two arguments were passed the wrong way round is a webhook resolving the
+ wrong tenant — both are worth a `ValueError` here rather than a surprise
+ further down.
"""
- parameters: dict[str, object] = {}
- if lookup.parameter is not None:
- parameters["argument"] = argument
+ parameters: dict[str, object] = dict(zip(lookup.arguments, arguments, strict=True))
with no_tenant():
async with session_factory() as session:
result = await session.execute(_LOOKUP_STATEMENTS[lookup.name], parameters)
@@ -460,3 +504,14 @@ async def tenant_of_invitation(
) -> str | None:
lookup = TENANT_LOOKUPS_BY_NAME["tenant_of_invitation"]
return _at_most_one(lookup, await _call(session_factory, lookup, token_hash))
+
+
+async def tenant_of_messaging_install(
+ session_factory: async_sessionmaker[AsyncSession],
+ platform: str,
+ external_workspace_id: str,
+) -> str | None:
+ lookup = TENANT_LOOKUPS_BY_NAME["tenant_of_messaging_install"]
+ return _at_most_one(
+ lookup, await _call(session_factory, lookup, platform, external_workspace_id)
+ )
diff --git a/core/switch_core/migrations/versions/c8a4e21f6d30_messaging_installs.py b/core/switch_core/migrations/versions/c8a4e21f6d30_messaging_installs.py
new file mode 100644
index 000000000..160a15d79
--- /dev/null
+++ b/core/switch_core/migrations/versions/c8a4e21f6d30_messaging_installs.py
@@ -0,0 +1,126 @@
+"""messaging_installs, and the lookup that resolves one to a tenant
+
+The table behind the official Slack app: one row per external workspace a
+tenant has installed us into, holding the token that install granted. It is
+tenant-scoped like everything else, so it gets the same `tenant_isolation`
+policy as the other tables — written out below rather than inherited, because
+`265ed188ad6f` installed the policies as they stood then and a table added
+afterwards has to bring its own.
+
+`(platform, external_workspace_id)` is unique across the deployment rather
+than per tenant. Inbound events arrive over one public endpoint carrying a
+workspace id and no tenant, so a workspace claimed twice is an event with two
+possible destinations; the constraint makes that unrepresentable, and it has
+to be the database that decides because a read-then-insert in application code
+cannot be made atomic. It is also globally unique for the same reason
+`api_keys.key_hash` is: the value is resolved before a tenant is known, so a
+per-tenant index could not answer the question being asked.
+
+`tenant_of_messaging_install(platform, workspace)` is the lookup that asks it,
+and it is an addition to the closed set of `SECURITY DEFINER` functions
+`9c41a7b0e5d8` installed as the whole exemption from row-level security. That
+set is deliberately short and every entry in it is callable by anyone holding
+the runtime role's credentials, so adding one is meant to be argued with. The
+argument for this one: the webhook is unauthenticated by nature and holds
+nothing but a workspace id, the answer it returns is a tenant id and never a
+row, and without it there is no way to bind a tenant before touching the
+payload — which is the only order in which the payload may be touched at all.
+
+It takes two arguments where every other lookup takes one, because the pair is
+what the table makes unique. A lookup on the workspace id alone would answer
+twice the first time two platforms minted the same string, and the caller
+refuses an ambiguous answer rather than picking — so one customer's traffic
+would start failing for a reason in another platform's namespace.
+
+The DDL below is a verbatim copy of `switch_core/db/rls_ddl.py` and
+`switch_core/db/tenant_lookup.py` as they stood when this migration was
+written, copied rather than imported for the same reason every other revision
+in this chain copies rather than imports: a migration is a record of a change
+that already happened, and importing the live module would let a later edit
+silently change what this one means.
+`tests/switch_core/db/test_frozen_ddl_matches_create_all.py` is what keeps the
+copy from drifting.
+
+Revision ID: c8a4e21f6d30
+Revises: b1d7c4f0a92e
+Create Date: 2026-09-11 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "c8a4e21f6d30"
+down_revision: str | None = "5daaea6b674d"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+TABLE = "messaging_installs"
+POLICY_NAME = "tenant_isolation"
+
+ENABLE_RLS = f'ALTER TABLE "{TABLE}" ENABLE ROW LEVEL SECURITY'
+
+CREATE_POLICY = f"""CREATE POLICY {POLICY_NAME} ON "{TABLE}"
+ FOR ALL
+ USING ("tenant_id" = (SELECT require_tenant_id()))
+ WITH CHECK ("tenant_id" = (SELECT require_tenant_id()))"""
+
+DROP_POLICY = f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{TABLE}"'
+
+SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"
+
+CREATE_TENANT_OF_MESSAGING_INSTALL = f"""CREATE OR REPLACE FUNCTION tenant_of_messaging_install(p_platform text, p_external_workspace_id text)
+ RETURNS SETOF text
+ LANGUAGE sql STABLE SECURITY DEFINER
+ SET search_path = {SECURE_SEARCH_PATH}
+AS $$SELECT tenant_id FROM messaging_installs WHERE platform = p_platform AND external_workspace_id = p_external_workspace_id$$"""
+
+DROP_TENANT_OF_MESSAGING_INSTALL = (
+ "DROP FUNCTION IF EXISTS tenant_of_messaging_install(text, text)"
+)
+
+
+def upgrade() -> None:
+ op.create_table(
+ TABLE,
+ sa.Column("id", sa.Text(), nullable=False),
+ sa.Column("tenant_id", sa.Text(), nullable=False),
+ sa.Column("platform", sa.Text(), nullable=False),
+ sa.Column("external_workspace_id", sa.Text(), nullable=False),
+ sa.Column("encrypted_bot_token", sa.Text(), nullable=False),
+ sa.Column("scopes", sa.Text(), nullable=False),
+ sa.Column("status", sa.Text(), nullable=False),
+ sa.Column("installed_by_user_id", sa.Text(), nullable=False),
+ sa.Column("bridge_id", sa.Text(), nullable=True),
+ sa.Column(
+ "installed_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ sa.ForeignKeyConstraint(
+ ["tenant_id"], ["tenants.id"], name="fk_messaging_installs_tenant"
+ ),
+ sa.ForeignKeyConstraint(["installed_by_user_id"], ["users.id"]),
+ sa.ForeignKeyConstraint(
+ ["tenant_id", "bridge_id"],
+ ["collaboration_bridges.tenant_id", "collaboration_bridges.id"],
+ name="fk_messaging_installs_bridge",
+ ),
+ sa.UniqueConstraint(
+ "platform", "external_workspace_id", name="uq_messaging_installs_workspace"
+ ),
+ sa.UniqueConstraint("id", "tenant_id", name="uq_messaging_installs_id_tenant"),
+ )
+ op.execute(ENABLE_RLS)
+ op.execute(CREATE_POLICY)
+ op.execute(CREATE_TENANT_OF_MESSAGING_INSTALL)
+
+
+def downgrade() -> None:
+ op.execute(DROP_TENANT_OF_MESSAGING_INSTALL)
+ op.execute(DROP_POLICY)
+ op.drop_table(TABLE)
diff --git a/core/tests/switch_core/db/test_messaging_install_claim.py b/core/tests/switch_core/db/test_messaging_install_claim.py
new file mode 100644
index 000000000..1319744ae
--- /dev/null
+++ b/core/tests/switch_core/db/test_messaging_install_claim.py
@@ -0,0 +1,151 @@
+"""One external workspace belongs to one tenant, and the database is what says so.
+
+Inbound events from the Switch messaging app arrive over a public endpoint
+carrying a workspace id and nothing else — no tenant, no credential of ours.
+`tenant_of_messaging_install` turns that workspace into a tenant, and the whole
+of why it can is that `messaging_installs` makes `(platform,
+external_workspace_id)` unique across the deployment. Two tenants holding the
+same workspace would be an event with two possible destinations and a lookup
+that refuses rather than picking; every message from that workspace would stop.
+
+So the constraint is the routing guarantee, and it is asserted here through the
+restricted role rather than through the owner, because the interesting part is
+what row-level security does *not* do to it. A unique index is enforced against
+rows the policy hides, which is the behaviour this needs and is easy to assume
+the other way round: the second tenant cannot read the first tenant's row and
+is still refused the insert.
+
+That refusal discloses one bit — some tenant holds this workspace — to a caller
+who could already name it. That is deliberate, and the alternative is worse: a
+silent second claim, discovered when a customer's messages start arriving in
+somebody else's rooms.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import async_sessionmaker
+
+from switch_core.db.models import MessagingInstall, Tenant, User
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.tenant_lookup import tenant_of_messaging_install
+from tests.conftest import RLSHarness
+
+pytestmark = pytest.mark.no_ambient_tenant
+
+
+class _Fixture:
+ def __init__(self) -> None:
+ self.tenant_a: str = ""
+ self.tenant_b: str = ""
+ self.user_id: str = ""
+ self.workspace: str = ""
+
+
+async def _two_tenants_and_a_workspace(owner: async_sessionmaker) -> _Fixture:
+ fixture = _Fixture()
+ suffix = uuid.uuid4().hex[:8]
+ fixture.tenant_a = f"tenant-a-{suffix}"
+ fixture.tenant_b = f"tenant-b-{suffix}"
+ fixture.workspace = f"T-{suffix}"
+
+ async with owner() as session:
+ for tenant_id in (fixture.tenant_a, fixture.tenant_b):
+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))
+ user = User(name="installer", email=f"{suffix}@example.test", role="user")
+ session.add(user)
+ await session.flush()
+ fixture.user_id = user.id
+ await session.commit()
+ return fixture
+
+
+def _install(fixture: _Fixture, tenant_id: str) -> MessagingInstall:
+ return MessagingInstall(
+ tenant_id=tenant_id,
+ platform="slack",
+ external_workspace_id=fixture.workspace,
+ encrypted_bot_token="ciphertext",
+ scopes="chat:write",
+ status="active",
+ installed_by_user_id=fixture.user_id,
+ )
+
+
+async def test_a_second_tenant_cannot_claim_a_claimed_workspace(
+ rls_harness: RLSHarness,
+) -> None:
+ fixture = await _two_tenants_and_a_workspace(rls_harness.owner)
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ session.add(_install(fixture, fixture.tenant_a))
+ await session.commit()
+
+ with pytest.raises(IntegrityError) as raised:
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ session.add(_install(fixture, fixture.tenant_b))
+ await session.commit()
+ assert "uq_messaging_installs_workspace" in str(raised.value)
+
+
+async def test_the_claiming_tenant_still_cannot_see_the_row_it_collided_with(
+ rls_harness: RLSHarness,
+) -> None:
+ """The measurement that makes the test above mean something.
+
+ If tenant B could read tenant A's install, the constraint would be
+ redundant with an ordinary application-level check. It cannot, so the
+ constraint is the only thing standing between two claims on one workspace.
+ """
+ fixture = await _two_tenants_and_a_workspace(rls_harness.owner)
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ session.add(_install(fixture, fixture.tenant_a))
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ visible = (
+ await session.execute(
+ select(MessagingInstall.id).where(
+ MessagingInstall.external_workspace_id == fixture.workspace
+ )
+ )
+ ).scalars()
+ assert list(visible) == []
+
+
+async def test_the_same_workspace_on_another_platform_is_a_separate_claim(
+ rls_harness: RLSHarness,
+) -> None:
+ """Uniqueness is on the pair. Two platforms minting the same string is a
+ coincidence, not a conflict, and refusing the second install would take a
+ customer's Teams workspace away because somebody's Slack workspace shares
+ an id."""
+ fixture = await _two_tenants_and_a_workspace(rls_harness.owner)
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ session.add(_install(fixture, fixture.tenant_a))
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ install = _install(fixture, fixture.tenant_b)
+ install.platform = "teams"
+ session.add(install)
+ await session.commit()
+
+ assert (
+ await tenant_of_messaging_install(
+ rls_harness.restricted, "slack", fixture.workspace
+ )
+ == fixture.tenant_a
+ )
+ assert (
+ await tenant_of_messaging_install(
+ rls_harness.restricted, "teams", fixture.workspace
+ )
+ == fixture.tenant_b
+ )
diff --git a/core/tests/switch_core/db/test_row_level_security.py b/core/tests/switch_core/db/test_row_level_security.py
index b1446b51c..c6a1a6ca8 100644
--- a/core/tests/switch_core/db/test_row_level_security.py
+++ b/core/tests/switch_core/db/test_row_level_security.py
@@ -46,6 +46,8 @@ from switch_core.db.rls_ddl import (
GLOBAL_TABLES,
POLICY_NAME,
REQUIRE_TENANT_FUNCTION_NAME,
+ create_policy_ddl,
+ enable_rls_ddl,
scoped_tables,
unscoped_tables,
)
@@ -328,8 +330,8 @@ def _expected_predicate(tenant_column: str) -> str:
)
-def _migration_module() -> ModuleType:
- """The `265ed188ad6f` revision module, loaded through Alembic.
+def _revision_module(revision: str) -> ModuleType:
+ """One revision module, loaded through Alembic.
Alembic's own loader, rather than an `importlib` call on a path, so this
finds the file the same way a deployment would and fails the same way if
@@ -338,8 +340,12 @@ def _migration_module() -> ModuleType:
core = Path(switch_core.__file__).resolve().parents[1]
config = Config(str(core / "alembic.ini"))
config.set_main_option("script_location", str(core / "switch_core" / "migrations"))
- revision = ScriptDirectory.from_config(config).get_revision(_RLS_REVISION)
- return revision.module
+ return ScriptDirectory.from_config(config).get_revision(revision).module
+
+
+def _migration_module() -> ModuleType:
+ """The revision that installed the policies."""
+ return _revision_module(_RLS_REVISION)
class TestCatalogueCoverage:
diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.py
index 70cb344bc..5e39f0bf9 100644
--- a/core/tests/switch_core/db/test_tenant_lookup.py
+++ b/core/tests/switch_core/db/test_tenant_lookup.py
@@ -52,6 +52,7 @@ from switch_core.db.models import (
Client,
CollaborationBridge,
Invitation,
+ MessagingInstall,
Room,
ServerConnector,
Tenant,
@@ -69,6 +70,7 @@ from switch_core.db.tenant_lookup import (
tenant_of_api_key,
tenant_of_collaboration_bridge,
tenant_of_invitation,
+ tenant_of_messaging_install,
tenant_of_room,
tenant_of_server_connector,
tenants_of_user,
@@ -92,11 +94,14 @@ _DROPPED_SINCE = {"tenant_of_client": "b1d7c4f0a92e"}
# The same bookkeeping in the other direction: a lookup the live module names
# that `9c41a7b0e5d8` never created, and the revision that did create it. The
# frozen-copy comparison below has to know about both to stay exact — without
-# this entry the only way to keep it green would be to loosen it to a subset
+# these entries the only way to keep it green would be to loosen it to a subset
# check, and a subset check passes for a lookup that exists in the module and
-# in no migration at all, which is a deployment whose invitation acceptance
-# cannot resolve a tenant with the whole suite green.
-_ADDED_SINCE = {"tenant_of_invitation": "5daaea6b674d"}
+# in no migration at all, which is a deployment whose invitation acceptance —
+# or whose inbound webhook — cannot resolve a tenant with the whole suite green.
+_ADDED_SINCE = {
+ "tenant_of_invitation": "5daaea6b674d",
+ "tenant_of_messaging_install": "c8a4e21f6d30",
+}
def _revision_module(revision: str) -> ModuleType:
@@ -128,6 +133,8 @@ class _Fixture:
self.bridge_a: str = ""
self.connector_a: str = ""
self.key_hash_a: str = ""
+ self.workspace_a: str = ""
+ self.workspace_b: str = ""
self.oauth_client_a: str = ""
self.user_a: str = ""
self.user_in_both: str = ""
@@ -151,6 +158,8 @@ async def _two_populated_tenants(harness: RLSHarness) -> _Fixture:
fixture.tenant_b = f"tenant-b-{suffix}"
fixture.oauth_client_a = f"oauth-{suffix}"
fixture.key_hash_a = f"hash-a-{suffix}"
+ fixture.workspace_a = f"T-a-{suffix}"
+ fixture.workspace_b = f"T-b-{suffix}"
async with harness.owner() as session:
for tenant_id in (fixture.tenant_a, fixture.tenant_b):
@@ -226,6 +235,17 @@ async def _two_populated_tenants(harness: RLSHarness) -> _Fixture:
created_by=user_both.id,
)
session.add(invitation)
+ session.add(
+ MessagingInstall(
+ tenant_id=tenant_id,
+ platform="slack",
+ external_workspace_id=f"T-{tag}-{suffix}",
+ encrypted_bot_token="x",
+ scopes="chat:write",
+ status="active",
+ installed_by_user_id=user_both.id,
+ )
+ )
session.add(
Agent(
tenant_id=tenant_id,
@@ -453,6 +473,57 @@ class TestWhatTheyAnswer:
await tenant_of_invitation(rls_harness.restricted, "no-such-hash") is None
)
+ async def test_an_installed_workspace_resolves_to_the_tenant_that_installed_it(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The whole of what routes an inbound webhook.
+
+ Both tenants have installed the same platform, so a lookup that
+ ignored its arguments, or matched on the platform alone, answers twice
+ and is refused rather than passing.
+ """
+ fixture = await _two_populated_tenants(rls_harness)
+ restricted = rls_harness.restricted
+ assert (
+ await tenant_of_messaging_install(restricted, "slack", fixture.workspace_a)
+ == fixture.tenant_a
+ )
+ assert (
+ await tenant_of_messaging_install(restricted, "slack", fixture.workspace_b)
+ == fixture.tenant_b
+ )
+
+ async def test_a_workspace_on_another_platform_resolves_to_nothing(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The pair is the key, not either half of it.
+
+ A workspace id that exists under `slack` must not answer for `teams`;
+ the two arguments being applied to the columns they name is the
+ difference between routing an event and delivering it to whoever
+ happened to mint the same string first.
+ """
+ fixture = await _two_populated_tenants(rls_harness)
+ assert (
+ await tenant_of_messaging_install(
+ rls_harness.restricted, "teams", fixture.workspace_a
+ )
+ is None
+ )
+
+ async def test_an_uninstalled_workspace_resolves_to_nothing_rather_than_raising(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """A webhook for a workspace we are not installed in is a request to
+ reject, not a fault. Same shape as an unknown bearer token."""
+ await _two_populated_tenants(rls_harness)
+ assert (
+ await tenant_of_messaging_install(
+ rls_harness.restricted, "slack", "T-never-installed"
+ )
+ is None
+ )
+
async def test_an_ambiguous_answer_is_refused_rather_than_picked(
self, rls_harness: RLSHarness
) -> None:
@@ -614,7 +685,7 @@ class TestTheMigrationInstallsTheSameThing:
live = {
(
lookup.name,
- "" if lookup.parameter is None else f"{lookup.parameter} text",
+ lookup.parameter_declaration,
lookup.signature,
lookup.query,
)
@@ -640,24 +711,30 @@ class TestTheMigrationInstallsTheSameThing:
A lookup added to `db/tenant_lookup.py` is built by `create_all`, so
every test in this file exercises it and passes. A deployment's schema
is built by Alembic, which knows nothing about it: the function is
- absent, and the first call — an invitation acceptance trying to
- resolve a tenant — fails at runtime in production and nowhere else.
+ absent, and the first call — an invitation acceptance or an inbound
+ webhook trying to resolve a tenant — fails at runtime in production and
+ nowhere else.
Comparing the rendered statement rather than the pieces, for the same
reason the test below does: a revision that created the function
`SECURITY INVOKER`, or without the `search_path`, would install
something that cannot read across tenants at all.
+
+ Driven by `_ADDED_SINCE` rather than naming one lookup, so the next
+ entry is covered by adding it there and nowhere else.
"""
- revision = _ADDED_SINCE["tenant_of_invitation"]
- lookup = TENANT_LOOKUPS_BY_NAME["tenant_of_invitation"]
- module = _revision_module(revision)
- assert module.CREATE_TENANT_OF_INVITATION == create_lookup_ddl(lookup), (
- f"revision {revision} would install tenant_of_invitation with "
- "different DDL from the one db/tenant_lookup.py builds."
- )
- assert module.DROP_TENANT_OF_INVITATION == (
- f"DROP FUNCTION IF EXISTS {lookup.signature}"
- )
+ for name, revision in _ADDED_SINCE.items():
+ lookup = TENANT_LOOKUPS_BY_NAME[name]
+ module = _revision_module(revision)
+ assert getattr(module, f"CREATE_{name.upper()}") == create_lookup_ddl(
+ lookup
+ ), (
+ f"revision {revision} would install {name} with different DDL "
+ "from the one db/tenant_lookup.py builds."
+ )
+ assert getattr(module, f"DROP_{name.upper()}") == (
+ f"DROP FUNCTION IF EXISTS {lookup.signature}"
+ )
def test_the_dropped_lookup_is_dropped_by_a_revision_and_not_only_here(
self,
@@ -713,9 +790,8 @@ class TestTheMigrationInstallsTheSameThing:
for lookup in TENANT_LOOKUPS:
if lookup.name in _ADDED_SINCE:
continue
- parameters = "" if lookup.parameter is None else f"{lookup.parameter} text"
assert module.create_lookup_ddl(
- lookup.name, parameters, lookup.query
+ lookup.name, lookup.parameter_declaration, lookup.query
) == create_lookup_ddl(lookup), (
f"migration 9c41a7b0e5d8 would install {lookup.name} with "
"different DDL from the one db/tenant_lookup.py builds."