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(bridges): an install that completes, from the button to a running bridge (CHOO-2626)

Petr Bauchcb94f48bc778
diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.py
index ff9e4039e..bd80a4bda 100644
--- a/core/switch_core/bridges/collaboration/install.py
+++ b/core/switch_core/bridges/collaboration/install.py
@@ -105,11 +105,16 @@ class WebhookAuthenticityError(RuntimeError):
class InstallGrant:
"""What the platform handed back when a workspace installed us.
- Deliberately three fields and not the platform's whole response. What a
+ Deliberately four fields and not the platform's whole response. What a
grant *is*, across platforms, is a workspace, a credential, and the
permissions that credential was actually given — everything else in the
response is Slack's shape and belongs behind `connection_config`.
+ `workspace_name` is the exception, and it earns its place by being the only
+ thing here a person recognises. It names the bridge in the operator's list,
+ where the alternative is a row of opaque platform ids. It is the customer's
+ own text and is never matched on.
+
`scopes` is the platform's own spelling, kept verbatim. A scope string that
means nothing to us is still the thing to show an operator asking why a
call was refused, and parsing it into a list here would be a parser to keep
@@ -117,6 +122,7 @@ class InstallGrant:
"""
external_workspace_id: str
+ workspace_name: str
bot_token: str
scopes: str
diff --git a/core/switch_core/bridges/collaboration/install_routes.py b/core/switch_core/bridges/collaboration/install_routes.py
new file mode 100644
index 000000000..38a6dd855
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/install_routes.py
@@ -0,0 +1,145 @@
+"""The public half of an install: the callback the platform redirects back to.
+
+Mounted on the agent-bridge app rather than inside `/gateway`, because this is
+the leg the outside world reaches. `/gateway` is not routed here from the
+public load balancer at all, and it would not help if it were — it is
+cookie-authenticated and this caller has no cookie of ours.
+
+**The reply is a page, not a redirect.** Sending the browser on to the gateway
+would work today, when the person installing is an operator who can reach it,
+and would break the moment the same flow is offered to a customer who cannot:
+the gateway is on a private hostname and the callback is not. So the outcome is
+rendered here, in one self-contained page, on the origin the browser already
+reached. It is deliberately plain; when there is a place to send people, this
+becomes a redirect and the page becomes its fallback.
+"""
+
+from __future__ import annotations
+
+import html
+import logging
+
+from fastapi import APIRouter, Query
+from starlette.responses import HTMLResponse
+
+from switch_core.bridges.collaboration.install import (
+ PUBLIC_PATH_PREFIX,
+ MessagingInstallError,
+)
+from switch_core.bridges.collaboration.install_service import (
+ InstallPlatformMismatch,
+ MessagingInstallService,
+)
+from switch_core.bridges.collaboration.install_state import InstallStateError
+from switch_core.db.stores.messaging_install_store import (
+ MessagingInstallClaimedError,
+ MessagingInstallStateError,
+)
+
+logger = logging.getLogger(__name__)
+
+_PAGE = """<!doctype html>
+<html lang="en"><head><meta charset="utf-8">
+<title>{title}</title>
+<style>
+ body {{ font: 16px/1.5 system-ui, sans-serif; margin: 4rem auto; max-width: 34rem;
+ padding: 0 1rem; color: #1a1a1a; }}
+ h1 {{ font-size: 1.25rem; }}
+ p {{ color: #444; }}
+</style></head>
+<body><h1>{title}</h1><p>{detail}</p></body></html>
+"""
+
+
+def _page(*, title: str, detail: str, status: int) -> HTMLResponse:
+ return HTMLResponse(
+ _PAGE.format(title=html.escape(title), detail=html.escape(detail)),
+ status_code=status,
+ )
+
+
+def create_messaging_install_router(
+ service: MessagingInstallService,
+) -> APIRouter:
+ """Build the public install routes over one already-configured service.
+
+ A factory closing over the service rather than a module-level router with
+ dependencies, because this app has no dependency-injection module of its
+ own and adding one for a single object would be the larger change.
+ """
+ router = APIRouter(prefix=PUBLIC_PATH_PREFIX)
+
+ @router.get("/{platform}/oauth/callback")
+ async def oauth_callback(
+ platform: str,
+ code: str | None = Query(default=None),
+ state: str | None = Query(default=None),
+ error: str | None = Query(default=None),
+ ) -> HTMLResponse:
+ # The platform's own refusal, which is usually the customer deciding
+ # not to install after all. Nothing went wrong here and nothing was
+ # written; saying so is the whole handling.
+ if error:
+ return _page(
+ title="Install cancelled",
+ detail=f"{platform} reported: {error}. Nothing was connected.",
+ status=200,
+ )
+
+ if not code or not state:
+ return _page(
+ title="Install could not be completed",
+ detail=(
+ f"{platform} did not send back everything this needs. Start "
+ "the install again from Switch."
+ ),
+ status=400,
+ )
+
+ try:
+ install = await service.complete(
+ platform=platform, code=code, state_token=state
+ )
+ except (InstallStateError, InstallPlatformMismatch) as failure:
+ # Unauthenticated input, so the reply says nothing the caller did
+ # not already know. The reason goes to the log, at warning: a
+ # forged state is worth noticing and is not worth an alert.
+ logger.warning("Refused a %s install callback: %s", platform, failure)
+ return _page(
+ title="Install could not be completed",
+ detail=(
+ "This install link is not one Switch recognises. Start the "
+ "install again from Switch."
+ ),
+ status=400,
+ )
+ except MessagingInstallStateError as failure:
+ return _page(
+ title="Install link already used",
+ detail=str(failure),
+ status=400,
+ )
+ except MessagingInstallClaimedError as failure:
+ return _page(
+ title="Workspace already connected",
+ detail=str(failure),
+ status=409,
+ )
+ except MessagingInstallError as failure:
+ return _page(
+ title="Install could not be completed",
+ detail=str(failure),
+ status=400,
+ )
+
+ return _page(
+ title="Switch is connected",
+ detail=(
+ f"The {platform} workspace {install.external_workspace_id} is "
+ "connected to Switch. You can close this page and finish setting "
+ "it up there."
+ ),
+ status=200,
+ )
+
+ return router
diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.py
new file mode 100644
index 000000000..74601a8c8
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/install_service.py
@@ -0,0 +1,196 @@
+"""The two legs of an install, and the order they have to happen in.
+
+An install is one operation split across two requests that share no session,
+no origin and no credential — only the state token. The first leg is
+authenticated and decides the tenant; the second is a stranger arriving from
+the platform. Everything here is about that asymmetry.
+
+The finishing order is load-bearing and not the obvious one:
+
+1. **Verify the signature, then bind the tenant.** Nothing before this touches
+ the database, because until the signature verifies there is no tenant to
+ bind and RLS would refuse every statement anyway.
+2. **Burn the state, and commit.** Before talking to the platform, not after.
+ Redeeming first would leave a window in which a replayed callback is still
+ redeemable, and burning inside the same transaction as the rest would hold
+ a row lock across a call to someone else's API. The cost is that a platform
+ outage burns the link — the customer starts a ten-second flow again, and
+ the property we keep in exchange is that a captured state is worth nothing.
+3. **Exchange the code**, which is the only network call.
+4. **Claim the workspace**, which is where a workspace already held by another
+ tenant fails, in the database rather than in a check above it.
+5. **Register the bridge** from the rendered connection config, exactly as if
+ an operator had typed the token in, and point the install row at it.
+
+Step 5 last is deliberate too: a bridge that exists with no install row behind
+it is an orphan nothing can revoke, whereas an install row with no bridge is a
+recorded credential waiting to be used, which is a state the schema already
+allows for.
+"""
+
+from __future__ import annotations
+
+import logging
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.collaboration.install import (
+ MessagingAppInstaller,
+ MessagingInstallerRegistry,
+ oauth_callback_path,
+ public_url,
+)
+from switch_core.bridges.collaboration.install_state import (
+ InstallState,
+ mint,
+ verify,
+)
+from switch_core.bridges.collaboration.lifecycle_service import (
+ CollaborationBridgeLifecycleService,
+)
+from switch_core.crypto import encrypt_token
+from switch_core.db.models import MessagingInstall
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.messaging_install_store import MessagingInstallStore
+from switch_core.tenant_context import tenant_scope
+
+logger = logging.getLogger(__name__)
+
+
+class InstallPlatformMismatch(RuntimeError):
+ """A state minted for one platform arrived at another's callback.
+
+ Only reachable with a valid signature, so this is not an attack so much as
+ a deployment that has crossed its own wires — but it would otherwise redeem
+ a real state against the wrong installer, and the store's own platform
+ predicate would then refuse it with a message about expiry that is not
+ true.
+ """
+
+
+class MessagingInstallService:
+ def __init__(
+ self,
+ *,
+ session_factory: async_sessionmaker[AsyncSession],
+ store: MessagingInstallStore,
+ installers: MessagingInstallerRegistry,
+ lifecycle: CollaborationBridgeLifecycleService,
+ public_origin: str,
+ secret: str,
+ ) -> None:
+ self._session_factory = session_factory
+ self._store = store
+ self._installers = installers
+ self._lifecycle = lifecycle
+ self._public_origin = public_origin
+ self._secret = secret
+
+ def _redirect_uri(self, platform: str) -> str:
+ """Where the platform sends the browser back to.
+
+ Built from the public origin rather than from the incoming request,
+ because the two legs arrive on different hostnames and the platform
+ compares this string byte for byte against the one registered with the
+ app. Deriving it from `request.url` would produce the gateway's
+ hostname on the first leg and a redirect the platform refuses.
+ """
+ return public_url(self._public_origin, oauth_callback_path(platform))
+
+ def installer(self, platform: str) -> MessagingAppInstaller:
+ return self._installers.get(platform)
+
+ def platforms(self) -> list[str]:
+ return self._installers.platforms()
+
+ async def begin(self, session: AsyncSession, *, platform: str, user_id: str) -> str:
+ """Start an install and return where to send the browser.
+
+ Runs on the caller's own scoped session, so the tenant recorded is the
+ tenant they are authenticated for and there is no parameter through
+ which they could name another.
+ """
+ installer = self._installers.get(platform)
+ state = await self._store.start_install(
+ session, platform=platform, user_id=user_id
+ )
+ token = mint(
+ InstallState(
+ tenant_id=state.tenant_id, state_id=state.id, platform=platform
+ ),
+ secret=self._secret,
+ )
+ return installer.authorize_url(
+ state=token, redirect_uri=self._redirect_uri(platform)
+ )
+
+ async def complete(
+ self, *, platform: str, code: str, state_token: str
+ ) -> MessagingInstall:
+ """Finish an install begun elsewhere, on behalf of nobody in particular.
+
+ The caller is unauthenticated: everything trusted here comes out of the
+ signature on `state_token` or out of the platform's own response.
+ """
+ installer = self._installers.get(platform)
+ state = verify(state_token, secret=self._secret)
+ if state.platform != platform:
+ raise InstallPlatformMismatch(
+ f"an install state for {state.platform} was presented to the "
+ f"{platform} callback"
+ )
+
+ with tenant_scope(state.tenant_id):
+ async with tenant_session(
+ self._session_factory, state.tenant_id
+ ) as session:
+ burnt = await self._store.redeem_state(
+ session, state_id=state.state_id, platform=platform
+ )
+ await session.commit()
+
+ grant = await installer.redeem(
+ code=code, redirect_uri=self._redirect_uri(platform)
+ )
+
+ async with tenant_session(
+ self._session_factory, state.tenant_id
+ ) as session:
+ install = await self._store.record_install(
+ session,
+ platform=platform,
+ external_workspace_id=grant.external_workspace_id,
+ encrypted_bot_token=encrypt_token(grant.bot_token, self._secret),
+ scopes=grant.scopes,
+ user_id=burnt.created_by_user_id,
+ )
+ install_id = install.id
+ await session.commit()
+
+ bridge = await self._lifecycle.register(
+ bridge_type=platform,
+ display_name=grant.workspace_name,
+ connection_config=installer.connection_config(grant),
+ # Off, though the granted scopes would allow it. Nobody was
+ # asked: an install has no registration form, and letting an
+ # app create channels in a customer's workspace is a decision
+ # someone should make rather than inherit.
+ channel_creation_enabled=False,
+ )
+
+ async with tenant_session(
+ self._session_factory, state.tenant_id
+ ) as session:
+ attached = await self._store.attach_bridge(
+ session, install_id=install_id, bridge_id=bridge.id
+ )
+ await session.commit()
+
+ logger.info(
+ "Installed %s workspace %s for tenant %s as bridge %s",
+ platform,
+ grant.external_workspace_id,
+ state.tenant_id,
+ bridge.id,
+ )
+ return attached
diff --git a/core/switch_core/bridges/collaboration/install_state.py b/core/switch_core/bridges/collaboration/install_state.py
new file mode 100644
index 000000000..fda5928be
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/install_state.py
@@ -0,0 +1,133 @@
+"""The `state` parameter that carries a tenant across the install round trip.
+
+An install starts on the gateway, where the caller is authenticated and their
+tenant is known, and finishes on a public callback the platform redirects the
+browser to. Something has to get the tenant from one to the other, and the two
+obvious candidates do not work here:
+
+- **A cookie** is what the gateway's own OIDC flow uses, and it cannot be used
+ for this. The gateway is reached on one hostname and the public callback on
+ another — they are different origins by deployment, not by accident — so a
+ cookie set at the start leg is simply not sent to the callback.
+- **A database lookup** keyed by the state would work, but the callback runs
+ with no tenant bound and RLS refuses every read until one is. Making it
+ possible would mean a ninth `SECURITY DEFINER` function, and the shortness of
+ that list is the property that makes it reviewable.
+
+So the state is a token *we* sign, naming the tenant. The callback verifies the
+signature, binds the tenant it names, and from that point runs as an ordinary
+scoped request — every subsequent read and write is checked by RLS in the
+normal way. A forged or edited state fails the signature and never reaches the
+database at all.
+
+**A signature is not enough on its own**, which is why the token names a row as
+well as a tenant. A signed token stays valid as long as the key does, so a
+captured state could be replayed to install an attacker's workspace against the
+victim's tenant — message injection into someone else's rooms. Single use is
+the missing half and only the database can provide it: the row named here is
+burnt with a conditional update, and a second attempt finds nothing to burn.
+
+The signing key is derived from `JWT_SECRET_KEY` rather than being another
+value to deploy, but it is *derived* rather than reused: a token minted here
+must never be mistakable for an agent's JWT, or for whatever the next thing to
+want a signature turns out to be.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+from dataclasses import dataclass
+
+#: Distinguishes this key from every other use of `JWT_SECRET_KEY`, and this
+#: token format from whatever replaces it. Changing either string invalidates
+#: every state in flight, which for a flow measured in seconds is free.
+_KEY_INFO = b"switch/messaging-install-state/v1"
+
+_PREFIX = "v1."
+
+
+class InstallStateError(RuntimeError):
+ """A state parameter was absent, malformed, or not signed by us.
+
+ All three are the same answer to the caller — the install is refused —
+ and deliberately the same answer to an observer: nothing distinguishes a
+ truncated token from a forged one, because the difference is only ever
+ interesting to someone probing.
+ """
+
+
+@dataclass(frozen=True)
+class InstallState:
+ """What a verified state names.
+
+ `tenant_id` is trusted *because* the signature verified, and is bound to
+ the session before anything else happens. `state_id` names the row to burn.
+ `platform` is carried so the callback route's own path cannot be used to
+ redeem a state minted for a different platform.
+ """
+
+ tenant_id: str
+ state_id: str
+ platform: str
+
+
+def _signing_key(secret: str) -> bytes:
+ return hmac.new(secret.encode(), _KEY_INFO, hashlib.sha256).digest()
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).decode().rstrip("=")
+
+
+def _unb64(encoded: str) -> bytes:
+ return base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))
+
+
+def mint(state: InstallState, *, secret: str) -> str:
+ """Sign a state for the platform to hand back to us unchanged."""
+ payload = _b64(
+ json.dumps(
+ {"tid": state.tenant_id, "sid": state.state_id, "plat": state.platform},
+ separators=(",", ":"),
+ sort_keys=True,
+ ).encode()
+ )
+ signature = hmac.new(_signing_key(secret), payload.encode(), hashlib.sha256)
+ return f"{_PREFIX}{payload}.{_b64(signature.digest())}"
+
+
+def verify(token: str, *, secret: str) -> InstallState:
+ """Recover the state from a token, or raise.
+
+ Nothing here touches the database, and nothing here is trusted before the
+ comparison: the payload is not decoded until its signature has matched, so
+ a hostile token is bytes we compared and discarded.
+ """
+ if not token.startswith(_PREFIX):
+ raise InstallStateError("install state is not a state this deployment minted")
+
+ try:
+ payload, signature = token[len(_PREFIX) :].split(".")
+ except ValueError:
+ raise InstallStateError("install state is malformed") from None
+
+ expected = hmac.new(_signing_key(secret), payload.encode(), hashlib.sha256).digest()
+ try:
+ matches = hmac.compare_digest(_unb64(signature), expected)
+ except ValueError:
+ raise InstallStateError("install state is malformed") from None
+ if not matches:
+ raise InstallStateError("install state was not signed by this deployment")
+
+ try:
+ decoded = json.loads(_unb64(payload))
+ return InstallState(
+ tenant_id=decoded["tid"],
+ state_id=decoded["sid"],
+ platform=decoded["plat"],
+ )
+ except (ValueError, KeyError, TypeError):
+ raise InstallStateError("install state is malformed") from None
diff --git a/core/switch_core/bridges/collaboration/slack/install.py b/core/switch_core/bridges/collaboration/slack/install.py
index cf63742ff..2a3922994 100644
--- a/core/switch_core/bridges/collaboration/slack/install.py
+++ b/core/switch_core/bridges/collaboration/slack/install.py
@@ -125,6 +125,7 @@ class SlackAppInstaller(MessagingAppInstaller):
return InstallGrant(
external_workspace_id=workspace_id,
+ workspace_name=team.get("name") or workspace_id,
bot_token=access_token,
scopes=response.get("scope") or "",
)
@@ -150,4 +151,9 @@ class SlackAppInstaller(MessagingAppInstaller):
return {
"bot_token": grant.bot_token,
"workspace_id": grant.external_workspace_id,
+ # Not a detail of this rendering: it is the difference between the
+ # two apps. Left out, the config validates as a Socket Mode bridge
+ # missing its app token, and the install fails at registration
+ # rather than at anything a reader would look at.
+ "event_delivery": "webhook",
}
diff --git a/core/switch_core/db/stores/__init__.py b/core/switch_core/db/stores/__init__.py
index dbee2199f..114b00a82 100644
--- a/core/switch_core/db/stores/__init__.py
+++ b/core/switch_core/db/stores/__init__.py
@@ -7,6 +7,7 @@ from switch_core.db.stores.document_store import DocumentStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.invitation_store import InvitationStore
from switch_core.db.stores.message_store import MessageStore
+from switch_core.db.stores.messaging_install_store import MessagingInstallStore
from switch_core.db.stores.reference_store import ReferenceStore
from switch_core.db.stores.reference_type_store import ReferenceTypeStore
from switch_core.db.stores.room_group_store import RoomGroupStore
@@ -28,6 +29,7 @@ __all__ = [
"ExternalUserStore",
"InvitationStore",
"MessageStore",
+ "MessagingInstallStore",
"ReferenceStore",
"ReferenceTypeStore",
"RoomGroupStore",
diff --git a/core/switch_core/db/stores/messaging_install_store.py b/core/switch_core/db/stores/messaging_install_store.py
new file mode 100644
index 000000000..269560850
--- /dev/null
+++ b/core/switch_core/db/stores/messaging_install_store.py
@@ -0,0 +1,160 @@
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+from sqlalchemy import select, update
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import (
+ MessagingInstall,
+ MessagingInstallState,
+ require_tenant_id,
+)
+
+#: How long a customer has to finish the platform's half of the flow. Long
+#: enough for a real person to read a consent screen and pick a workspace,
+#: short enough that a state captured from a browser's history or a proxy log
+#: is worthless by the time anyone reads it.
+STATE_TTL = timedelta(minutes=10)
+
+
+class MessagingInstallClaimedError(RuntimeError):
+ """Another tenant has already installed the app into this workspace.
+
+ Worth its own type because it is the one install failure that is not a
+ mistake by the caller and cannot be retried into working. What it discloses
+ — that *somebody* holds this workspace — is deliberate: the alternative is
+ accepting a second claim and delivering that workspace's messages to
+ whichever tenant the router happened to pick.
+ """
+
+
+class MessagingInstallStateError(RuntimeError):
+ """A state could not be redeemed: already used, expired, or not ours."""
+
+
+class MessagingInstallStore:
+ async def start_install(
+ self, session: AsyncSession, *, platform: str, user_id: str
+ ) -> MessagingInstallState:
+ """Record an install about to be attempted, and return the row to sign.
+
+ `tenant_id` is left to the model's default, which reads the tenant
+ bound to this session — the caller does not get to name one. That is
+ the whole reason the start leg is authenticated and the callback is
+ not: this is where the tenant is decided.
+ """
+ state = MessagingInstallState(
+ platform=platform,
+ created_by_user_id=user_id,
+ expires_at=datetime.now(UTC) + STATE_TTL,
+ )
+ session.add(state)
+ await session.flush()
+ return state
+
+ async def redeem_state(
+ self, session: AsyncSession, *, state_id: str, platform: str
+ ) -> MessagingInstallState:
+ """Burn a state, or raise. Exactly one caller can succeed.
+
+ The check and the write are one statement on purpose. Reading the row,
+ deciding it is unused and then updating it leaves a window in which two
+ callbacks both read `consumed_at IS NULL` — and the whole reason this
+ row exists is to make a replayed state fail. `expires_at` is in the
+ same predicate for the same reason.
+
+ Scoped to the bound tenant as well, which the signature has already
+ established: a state signed for one tenant and naming a row belonging
+ to another matches nothing, so RLS is a second, independent check on
+ the first.
+ """
+ result = await session.execute(
+ update(MessagingInstallState)
+ .where(
+ MessagingInstallState.id == state_id,
+ MessagingInstallState.tenant_id == require_tenant_id(),
+ MessagingInstallState.platform == platform,
+ MessagingInstallState.consumed_at.is_(None),
+ MessagingInstallState.expires_at > datetime.now(UTC),
+ )
+ .values(consumed_at=datetime.now(UTC))
+ .returning(MessagingInstallState)
+ )
+ state = result.scalars().one_or_none()
+ if state is None:
+ raise MessagingInstallStateError(
+ "this install link has already been used or has expired. Start "
+ "the install again from Switch."
+ )
+ return state
+
+ async def record_install(
+ self,
+ session: AsyncSession,
+ *,
+ platform: str,
+ external_workspace_id: str,
+ encrypted_bot_token: str,
+ scopes: str,
+ user_id: str,
+ ) -> MessagingInstall:
+ """Claim a workspace for the bound tenant.
+
+ The claim is the insert: `(platform, external_workspace_id)` is unique
+ across the deployment, so the database decides who holds a workspace
+ rather than a read followed by a write that cannot be made atomic with
+ it. A second tenant's install therefore fails here, loudly, instead of
+ producing an event with two possible destinations.
+ """
+ install = MessagingInstall(
+ platform=platform,
+ external_workspace_id=external_workspace_id,
+ encrypted_bot_token=encrypted_bot_token,
+ scopes=scopes,
+ status="active",
+ installed_by_user_id=user_id,
+ )
+ session.add(install)
+ try:
+ await session.flush()
+ except IntegrityError as exc:
+ if "uq_messaging_installs_workspace" not in str(exc.orig):
+ raise
+ raise MessagingInstallClaimedError(
+ f"the {platform} workspace {external_workspace_id} is already "
+ "connected to Switch. Remove the existing install before "
+ "connecting it again."
+ ) from exc
+ return install
+
+ async def get_for_workspace(
+ self, session: AsyncSession, *, platform: str, external_workspace_id: str
+ ) -> MessagingInstall | None:
+ """The bound tenant's install of one workspace, if it is theirs.
+
+ Deliberately still scoped, even though the unique constraint means at
+ most one row exists deployment-wide: the caller is an inbound webhook
+ that resolved a tenant from the workspace a moment ago, and this
+ re-reading it under RLS is what makes a mistake there a miss rather
+ than a cross-tenant read.
+ """
+ result = await session.execute(
+ select(MessagingInstall).where(
+ MessagingInstall.platform == platform,
+ MessagingInstall.external_workspace_id == external_workspace_id,
+ )
+ )
+ return result.scalars().one_or_none()
+
+ async def attach_bridge(
+ self, session: AsyncSession, *, install_id: str, bridge_id: str
+ ) -> MessagingInstall:
+ """Point an install at the bridge now serving it."""
+ install = await session.get(MessagingInstall, install_id)
+ if install is None:
+ raise MessagingInstallStateError(f"install not found: {install_id}")
+ install.bridge_id = bridge_id
+ await session.flush()
+ return install
diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.py
index 6f1b46d2f..a97deaf73 100644
--- a/core/switch_core/gateway/app.py
+++ b/core/switch_core/gateway/app.py
@@ -8,6 +8,9 @@ from switch_core.bridges.agent.protocol.service import ProtocolService
from switch_core.bridges.agent.server_connectors.lifecycle import (
ServerSideConnectorLifecycleService,
)
+from switch_core.bridges.collaboration.install_service import (
+ MessagingInstallService,
+)
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
@@ -32,6 +35,9 @@ from switch_core.gateway.connectors import router as connectors_router
from switch_core.gateway.dependencies import init_dependencies
from switch_core.gateway.documents import router as documents_router
from switch_core.gateway.ecosystem import router as ecosystem_router
+from switch_core.gateway.messaging_installs import (
+ router as messaging_installs_router,
+)
from switch_core.gateway.oidc_routes import register_oidc_client
from switch_core.gateway.oidc_routes import router as oidc_router
from switch_core.gateway.packages import router as packages_router
@@ -64,6 +70,7 @@ def create_gateway_app(
template_store: TemplateStore,
resource_service: ResourceService,
protocol: ProtocolService,
+ install_service: MessagingInstallService | None,
config: SwitchConfig,
) -> FastAPI:
init_dependencies(
@@ -85,6 +92,7 @@ def create_gateway_app(
template_store=template_store,
resource_service=resource_service,
protocol=protocol,
+ install_service=install_service,
config=config,
)
@@ -120,5 +128,10 @@ def create_gateway_app(
app.include_router(packages_router, tags=["packages"])
app.include_router(templates_router, tags=["templates"])
app.include_router(ecosystem_router, prefix="/ecosystem", tags=["ecosystem"])
+ app.include_router(
+ messaging_installs_router,
+ prefix="/messaging-apps",
+ tags=["messaging-apps"],
+ )
return app
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index 962561960..8f85508d1 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -10,6 +10,9 @@ from switch_core.bridges.agent.protocol.service import ProtocolService
from switch_core.bridges.agent.server_connectors.lifecycle import (
ServerSideConnectorLifecycleService,
)
+from switch_core.bridges.collaboration.install_service import (
+ MessagingInstallService,
+)
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
@@ -52,6 +55,7 @@ def init_dependencies(
template_store: TemplateStore,
resource_service: ResourceService,
protocol: ProtocolService,
+ install_service: MessagingInstallService | None,
config: SwitchConfig,
) -> None:
_state["agent_store"] = agent_store
@@ -72,6 +76,7 @@ def init_dependencies(
_state["template_store"] = template_store
_state["resource_service"] = resource_service
_state["protocol"] = protocol
+ _state["install_service"] = install_service
_state["config"] = config
@@ -215,5 +220,15 @@ def get_protocol() -> ProtocolService:
return _state["protocol"] # type: ignore[no-any-return]
+def get_install_service() -> MessagingInstallService | None:
+ """None when this deployment registered no messaging app of its own.
+
+ Nullable rather than absent because that is the ordinary case, and the
+ endpoints have to answer it with a refusal that says so rather than with a
+ KeyError.
+ """
+ return _state["install_service"] # type: ignore[no-any-return]
+
+
def get_resource_service() -> ResourceService:
return _state["resource_service"] # type: ignore[no-any-return]
diff --git a/core/switch_core/gateway/messaging_installs.py b/core/switch_core/gateway/messaging_installs.py
new file mode 100644
index 000000000..16ee7ffab
--- /dev/null
+++ b/core/switch_core/gateway/messaging_installs.py
@@ -0,0 +1,86 @@
+"""Starting an install: the authenticated leg, and the only one that picks a tenant.
+
+The endpoint answers with a URL rather than a redirect. The install has to
+begin in a top-level browser window on the platform's own domain, and a
+redirect from an XHR the operator's dashboard made would be followed by the
+XHR, not by the window. Handing the URL back and letting the page navigate is
+the shape that works.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, HTTPException
+from pydantic import BaseModel
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.bridges.collaboration.install import MessagingInstallError
+from switch_core.bridges.collaboration.install_service import MessagingInstallService
+from switch_core.db.models import User
+from switch_core.gateway.auth import require_admin
+from switch_core.gateway.dependencies import get_install_service, get_session
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter()
+
+
+class InstallStart(BaseModel):
+ authorize_url: str
+
+
+class InstallablePlatforms(BaseModel):
+ platforms: list[str]
+
+
+def _require_installs(
+ service: MessagingInstallService | None,
+) -> MessagingInstallService:
+ """Refuse rather than pretend when this deployment registered no app.
+
+ Most deployments will register none — the self-hosted path is an operator
+ registering their own app and pasting the token in — so this is an ordinary
+ answer and not an error condition. It is still a refusal: a deployment that
+ offered the button and then failed at the platform would be worse.
+ """
+ if service is None:
+ raise HTTPException(
+ status_code=501,
+ detail=(
+ "This Switch deployment has no messaging app of its own to "
+ "install. Register a bridge with your own app's credentials "
+ "instead."
+ ),
+ )
+ return service
+
+
+async def installable_platforms(
+ service: Annotated[MessagingInstallService | None, Depends(get_install_service)],
+ _user: Annotated[User, Depends(require_admin)],
+) -> InstallablePlatforms:
+ return InstallablePlatforms(
+ platforms=[] if service is None else service.platforms()
+ )
+
+
[email protected]("/{platform}/install")
+async def begin_install(
+ platform: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ service: Annotated[MessagingInstallService | None, Depends(get_install_service)],
+ user: Annotated[User, Depends(require_admin)],
+) -> InstallStart:
+ try:
+ authorize_url = await _require_installs(service).begin(
+ session, platform=platform, user_id=user.id
+ )
+ except MessagingInstallError as failure:
+ raise HTTPException(status_code=404, detail=str(failure)) from failure
+
+ await session.commit()
+ logger.info("Started a %s install for user %s", platform, user.id)
+ return InstallStart(authorize_url=authorize_url)
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 1c0423e2f..f36744ffc 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -49,6 +49,11 @@ from switch_core.bridges.collaboration.discord.adapter import (
DiscordAdapter,
DiscordConnectionConfig,
)
+from switch_core.bridges.collaboration.install import MessagingInstallerRegistry
+from switch_core.bridges.collaboration.install_routes import (
+ create_messaging_install_router,
+)
+from switch_core.bridges.collaboration.install_service import MessagingInstallService
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
@@ -60,6 +65,7 @@ from switch_core.bridges.collaboration.slack.adapter import (
SlackAdapter,
SlackConnectionConfig,
)
+from switch_core.bridges.collaboration.slack.install import SlackAppInstaller
from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
TeamsConnectionConfig,
@@ -100,6 +106,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.invitation_store import InvitationStore
from switch_core.db.stores.media_store import MediaStore
from switch_core.db.stores.message_store import MessageStore
+from switch_core.db.stores.messaging_install_store import MessagingInstallStore
from switch_core.db.stores.package_store import PackageStore
from switch_core.db.stores.reference_store import ReferenceStore
from switch_core.db.stores.reference_type_store import ReferenceTypeStore
@@ -475,6 +482,36 @@ async def run(config: SwitchConfig) -> None:
"opencode", OpenCodeConnector, OpenCodeConnectionConfig
)
+ # ── Messaging app installs ──────────────────────────────────────────────
+ # Registration is the feature flag. An installer exists for a platform when
+ # this deployment holds that platform's app credentials, and the whole
+ # install surface refuses when none does — a deployment that registered no
+ # app cannot half-offer the button. Config validation has already required
+ # the three Slack values all together and a public origin with them.
+ installers = MessagingInstallerRegistry()
+ if config.slack_app_client_id:
+ assert config.slack_app_client_secret is not None
+ assert config.slack_app_signing_secret is not None
+ installers.register(
+ SlackAppInstaller(
+ client_id=config.slack_app_client_id,
+ client_secret=config.slack_app_client_secret,
+ signing_secret=config.slack_app_signing_secret,
+ )
+ )
+
+ install_service: MessagingInstallService | None = None
+ if installers.platforms():
+ assert config.gateway_public_url is not None
+ install_service = MessagingInstallService(
+ session_factory=session_factory,
+ store=MessagingInstallStore(),
+ installers=installers,
+ lifecycle=collab_lifecycle,
+ public_origin=config.gateway_public_url,
+ secret=config.jwt_secret_key,
+ )
+
# ── Gateway app ───────────────────────────────────────────────────────────
gateway_app = create_gateway_app(
agent_store=agent_store,
@@ -495,6 +532,7 @@ async def run(config: SwitchConfig) -> None:
template_store=template_store,
resource_service=resource_service,
protocol=protocol,
+ install_service=install_service,
config=config,
)
@@ -516,6 +554,15 @@ async def run(config: SwitchConfig) -> None:
async def health_check() -> JSONResponse:
return JSONResponse({"status": "ok"})
+ # Mounted on the agent-bridge app, not inside /gateway: this is the leg a
+ # platform and a customer's browser reach, and /gateway is neither routed
+ # here from outside nor reachable without a cookie they do not have.
+ if install_service is not None:
+ agent_bridge_app.include_router(
+ create_messaging_install_router(install_service),
+ tags=["messaging-installs"],
+ )
+
agent_bridge_app.mount("/gateway", gateway_app)
# ── Ensure system clients exist ─────────────────────────────────────────
diff --git a/core/tests/switch_core/bridges/collaboration/test_install_service.py b/core/tests/switch_core/bridges/collaboration/test_install_service.py
new file mode 100644
index 000000000..aec860c6b
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py
@@ -0,0 +1,354 @@
+"""The install as one operation, across the two requests it is actually made of.
+
+The individual pieces are covered elsewhere — the signature in
+`test_install_state.py`, single use in the store's own tests, Slack's responses
+in `test_slack_installer.py`. What is only visible here is the join: that the
+tenant the first leg was authenticated for is the tenant the second leg writes
+to, that a replay gets no further than the burn, and that a bridge appears at
+the end configured the way an operator's own would be.
+
+Postgres is real because row-level security is the second half of the argument
+and a mock has no policies.
+"""
+
+from __future__ import annotations
+
+import uuid
+from collections.abc import Mapping
+from typing import ClassVar
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from sqlalchemy.ext.asyncio import async_sessionmaker
+
+from switch_core.bridges.collaboration.install import (
+ InstallGrant,
+ MessagingAppInstaller,
+ MessagingInstallerRegistry,
+)
+from switch_core.bridges.collaboration.install_service import (
+ InstallPlatformMismatch,
+ MessagingInstallService,
+)
+from switch_core.bridges.collaboration.install_state import (
+ InstallState,
+ InstallStateError,
+ mint,
+)
+from switch_core.crypto import decrypt_token
+from switch_core.db.models import (
+ Client,
+ CollaborationBridge,
+ MessagingInstall,
+ Tenant,
+ User,
+)
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.messaging_install_store import (
+ MessagingInstallClaimedError,
+ MessagingInstallStateError,
+ MessagingInstallStore,
+)
+from tests.conftest import RLSHarness
+
+pytestmark = pytest.mark.no_ambient_tenant
+
+_SECRET = "test-secret"
+_ORIGIN = "https://switch.example"
+
+
+class _FakeInstaller(MessagingAppInstaller):
+ """A platform that always says yes, and counts how often it was asked."""
+
+ platform: ClassVar[str] = "slack"
+
+ def __init__(self, workspace_id: str) -> None:
+ self.workspace_id = workspace_id
+ self.redeem_calls: list[str] = []
+
+ def authorize_url(self, *, state: str, redirect_uri: str) -> str:
+ return f"https://platform.example/authorize?state={state}"
+
+ async def redeem(self, *, code: str, redirect_uri: str) -> InstallGrant:
+ self.redeem_calls.append(redirect_uri)
+ return InstallGrant(
+ external_workspace_id=self.workspace_id,
+ workspace_name="Acme",
+ bot_token="xoxb-granted",
+ scopes="chat:write",
+ )
+
+ def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:
+ return None
+
+ def workspace_of_event(self, payload: Mapping[str, object]) -> str:
+ return self.workspace_id
+
+ def connection_config(self, grant: InstallGrant) -> dict[str, object]:
+ return {"bot_token": grant.bot_token, "workspace_id": grant.workspace_name}
+
+
+class _FakeLifecycle:
+ """Stands in for the bridge lifecycle, which starts real network clients.
+
+ It still writes the rows, because the install points at the bridge through
+ a composite foreign key and a stub returning an id that is not in the table
+ would prove the last step works when it does not.
+ """
+
+ def __init__(
+ self, factory: async_sessionmaker, tenant_id: str, suffix: str
+ ) -> None:
+ self._factory = factory
+ self._tenant_id = tenant_id
+ self._suffix = suffix
+ self.registered: list[dict[str, object]] = []
+
+ async def register(self, **kwargs: object) -> CollaborationBridge:
+ self.registered.append(kwargs)
+ async with tenant_session(self._factory, self._tenant_id) as session:
+ client = Client(
+ matrix_user_id=f"@bridge-{len(self.registered)}:{self._suffix}",
+ display_name=str(kwargs["display_name"]),
+ type="collaboration_bridge",
+ )
+ session.add(client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type=str(kwargs["bridge_type"]),
+ display_name=str(kwargs["display_name"]),
+ connection_config={},
+ client_id=client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ bridge_id = bridge.id
+ await session.commit()
+ return CollaborationBridge(id=bridge_id)
+
+
+class _Fixture:
+ def __init__(self) -> None:
+ self.tenant_a: str = ""
+ self.tenant_b: str = ""
+ self.user_id: str = ""
+ self.workspace: str = ""
+ self.installer: _FakeInstaller
+ self.lifecycle: _FakeLifecycle
+ self.service: MessagingInstallService
+
+
+async def _fixture(harness: RLSHarness) -> _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 harness.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()
+
+ fixture.installer = _FakeInstaller(fixture.workspace)
+ fixture.lifecycle = _FakeLifecycle(harness.restricted, fixture.tenant_a, suffix)
+ installers = MessagingInstallerRegistry()
+ installers.register(fixture.installer)
+ fixture.service = MessagingInstallService(
+ session_factory=harness.restricted,
+ store=MessagingInstallStore(),
+ installers=installers,
+ lifecycle=fixture.lifecycle, # type: ignore[arg-type]
+ public_origin=_ORIGIN,
+ secret=_SECRET,
+ )
+ return fixture
+
+
+async def _begin(factory: async_sessionmaker, fixture: _Fixture, tenant_id: str) -> str:
+ """Start an install as `tenant_id` and return the state it minted."""
+ async with tenant_session(factory, tenant_id) as session:
+ url = await fixture.service.begin(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ await session.commit()
+ return parse_qs(urlparse(url).query)["state"][0]
+
+
+class TestTheRoundTrip:
+ async def test_an_install_lands_in_the_tenant_that_started_it(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ install = await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+
+ assert install.tenant_id == fixture.tenant_a
+ assert install.external_workspace_id == fixture.workspace
+ assert install.installed_by_user_id == fixture.user_id
+
+ async def test_the_bot_token_is_encrypted_at_rest(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ install = await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+
+ assert "xoxb-granted" not in install.encrypted_bot_token
+ assert decrypt_token(install.encrypted_bot_token, _SECRET) == "xoxb-granted"
+
+ async def test_it_ends_with_a_bridge_the_install_points_at(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The seam. An install that records a credential and builds nothing is
+ a customer who clicked Add to Slack and got nothing."""
+ fixture = await _fixture(rls_harness)
+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ install = await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+
+ assert len(fixture.lifecycle.registered) == 1
+ registered = fixture.lifecycle.registered[0]
+ assert registered["bridge_type"] == "slack"
+ assert registered["display_name"] == "Acme"
+ assert install.bridge_id is not None
+
+ async def test_the_redirect_is_the_public_one_on_both_legs(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The platform compares them, so a mismatch is a refused install.
+
+ Built from the configured origin rather than from either request,
+ which is the only way the two legs — on different hostnames — agree.
+ """
+ fixture = await _fixture(rls_harness)
+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)
+ await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+
+ assert fixture.installer.redeem_calls == [
+ f"{_ORIGIN}/messaging/slack/oauth/callback"
+ ]
+
+
+class TestWhatTheCallbackWillNotDo:
+ async def test_a_replayed_state_never_reaches_the_platform(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Burnt before the code is exchanged, not after.
+
+ The count is the assertion: a replay that got as far as redeeming would
+ have obtained a second credential before anything refused it.
+ """
+ fixture = await _fixture(rls_harness)
+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)
+ await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+
+ with pytest.raises(MessagingInstallStateError):
+ await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+ assert len(fixture.installer.redeem_calls) == 1
+
+ async def test_a_state_naming_a_tenant_it_does_not_own_is_refused(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """What is left if the signing key ever leaks.
+
+ Forging a state for tenant B against tenant A's row gets past the
+ signature by construction, and row-level security still finds no row
+ to burn.
+ """
+ fixture = await _fixture(rls_harness)
+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state_id = (
+ await MessagingInstallStore().start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ ).id
+ await session.commit()
+
+ forged = mint(
+ InstallState(
+ tenant_id=fixture.tenant_b, state_id=state_id, platform="slack"
+ ),
+ secret=_SECRET,
+ )
+ with pytest.raises(MessagingInstallStateError):
+ await fixture.service.complete(
+ platform="slack", code="the-code", state_token=forged
+ )
+ assert fixture.installer.redeem_calls == []
+ assert state # the untouched state is still redeemable; nothing was burnt
+
+ async def test_an_unsigned_state_never_touches_the_database(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ with pytest.raises(InstallStateError):
+ await fixture.service.complete(
+ platform="slack", code="the-code", state_token="v1.aaa.bbb"
+ )
+
+ async def test_a_state_for_another_platform_is_refused(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ forged = mint(
+ InstallState(
+ tenant_id=fixture.tenant_a, state_id="whatever", platform="teams"
+ ),
+ secret=_SECRET,
+ )
+ with pytest.raises(InstallPlatformMismatch):
+ await fixture.service.complete(
+ platform="slack", code="the-code", state_token=forged
+ )
+
+ async def test_a_workspace_another_tenant_holds_is_refused(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """And no bridge is built for it.
+
+ The whole point of the deployment-wide unique constraint: one
+ workspace's events have exactly one destination.
+ """
+ fixture = await _fixture(rls_harness)
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ session.add(
+ MessagingInstall(
+ tenant_id=fixture.tenant_b,
+ platform="slack",
+ external_workspace_id=fixture.workspace,
+ encrypted_bot_token="ciphertext",
+ scopes="chat:write",
+ status="active",
+ installed_by_user_id=fixture.user_id,
+ )
+ )
+ await session.commit()
+
+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)
+ with pytest.raises(MessagingInstallClaimedError):
+ await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+ assert fixture.lifecycle.registered == []
diff --git a/core/tests/switch_core/bridges/collaboration/test_install_state.py b/core/tests/switch_core/bridges/collaboration/test_install_state.py
new file mode 100644
index 000000000..6ba915df0
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_install_state.py
@@ -0,0 +1,117 @@
+"""The state token is the only thing binding a tenant across the install.
+
+It is minted on a page a customer's admin loaded and comes back from the
+public internet, so every test here is about what happens when what comes back
+is not what went out. The consequence of getting it wrong is not a failed
+install: it is an attacker's Slack workspace attached to somebody else's
+tenant, delivering messages into their rooms.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+
+import pytest
+
+from switch_core.bridges.collaboration.install_state import (
+ InstallState,
+ InstallStateError,
+ mint,
+ verify,
+)
+
+_SECRET = "test-jwt-secret"
+
+_STATE = InstallState(tenant_id="tenant-a", state_id="state-1", platform="slack")
+
+
+def test_a_minted_state_verifies_back_to_what_went_in() -> None:
+ assert verify(mint(_STATE, secret=_SECRET), secret=_SECRET) == _STATE
+
+
+def test_the_token_is_safe_in_a_url() -> None:
+ """It travels as a query parameter through a redirect the platform builds."""
+ token = mint(_STATE, secret=_SECRET)
+ assert all(c.isalnum() or c in "-_." for c in token)
+
+
+class TestForgery:
+ def test_an_edited_tenant_is_refused(self) -> None:
+ """The attack the signature exists to stop.
+
+ Swapping the tenant in a captured state is how you would attach your
+ own workspace to someone else's rooms.
+ """
+ token = mint(_STATE, secret=_SECRET)
+ payload, signature = token.removeprefix("v1.").split(".")
+ decoded = json.loads(base64.urlsafe_b64decode(payload + "=="))
+ decoded["tid"] = "tenant-b"
+ forged = (
+ base64.urlsafe_b64encode(json.dumps(decoded).encode()).decode().rstrip("=")
+ )
+
+ with pytest.raises(InstallStateError):
+ verify(f"v1.{forged}.{signature}", secret=_SECRET)
+
+ def test_a_state_from_another_deployment_is_refused(self) -> None:
+ token = mint(_STATE, secret="a-different-secret")
+ with pytest.raises(InstallStateError, match="not signed by this deployment"):
+ verify(token, secret=_SECRET)
+
+ def test_the_key_is_not_the_jwt_key_itself(self) -> None:
+ """Domain separation, so one signature can never be read as the other.
+
+ Asserted by construction rather than by outcome: the token is signed
+ under a derived key, so signing the same payload with the raw secret
+ produces something this refuses.
+ """
+ token = mint(_STATE, secret=_SECRET)
+ payload = token.removeprefix("v1.").split(".")[0]
+ raw = hmac.new(_SECRET.encode(), payload.encode(), hashlib.sha256).digest()
+ naive = base64.urlsafe_b64encode(raw).decode().rstrip("=")
+
+ with pytest.raises(InstallStateError):
+ verify(f"v1.{payload}.{naive}", secret=_SECRET)
+
+
+class TestMalformed:
+ @pytest.mark.parametrize(
+ "token",
+ [
+ "",
+ "not-a-token",
+ "v1.",
+ "v1.only-one-part",
+ "v1.a.b.c",
+ "v1.!!!.!!!",
+ "v2." + mint(_STATE, secret=_SECRET).removeprefix("v1."),
+ ],
+ )
+ def test_garbage_is_an_error_and_not_a_crash(self, token: str) -> None:
+ """Reachable by anyone who finds the callback URL.
+
+ Every one of these has to be a refused install rather than a traceback,
+ because the caller is unauthenticated by nature.
+ """
+ with pytest.raises(InstallStateError):
+ verify(token, secret=_SECRET)
+
+ def test_a_well_signed_payload_that_is_not_a_state_is_refused(self) -> None:
+ """Signed by us, but not this. A key used for two things is a bug."""
+ payload = base64.urlsafe_b64encode(b'{"sub":"agent-1"}').decode().rstrip("=")
+ key = hmac.new(
+ _SECRET.encode(), b"switch/messaging-install-state/v1", hashlib.sha256
+ ).digest()
+ signature = (
+ base64.urlsafe_b64encode(
+ hmac.new(key, payload.encode(), hashlib.sha256).digest()
+ )
+ .decode()
+ .rstrip("=")
+ )
+
+ with pytest.raises(InstallStateError, match="malformed"):
+ verify(f"v1.{payload}.{signature}", secret=_SECRET)
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_installer.py b/core/tests/switch_core/bridges/collaboration/test_slack_installer.py
index aa7e6499a..dc2f5159f 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_installer.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_installer.py
@@ -157,7 +157,7 @@ class TestRedeem:
monkeypatch.setattr(AsyncWebClient, "oauth_v2_access", fake)
return await installer.redeem(code="c", redirect_uri="https://x.example/cb")
- async def test_a_good_grant_becomes_the_three_things_we_keep(
+ async def test_a_good_grant_becomes_the_few_things_we_keep(
self, installer: SlackAppInstaller, monkeypatch: pytest.MonkeyPatch
) -> None:
grant = await self._redeem_returning(
@@ -172,10 +172,27 @@ class TestRedeem:
)
assert grant == InstallGrant(
external_workspace_id="T123",
+ workspace_name="Acme",
bot_token="xoxb-granted",
scopes="chat:write,commands",
)
+ async def test_a_workspace_with_no_name_falls_back_to_its_id(
+ self, installer: SlackAppInstaller, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """The name is only ever a label, so its absence is not a failure."""
+ grant = await self._redeem_returning(
+ monkeypatch,
+ installer,
+ {
+ "ok": True,
+ "access_token": "xoxb-granted",
+ "scope": "chat:write",
+ "team": {"id": "T123"},
+ },
+ )
+ assert grant.workspace_name == "T123"
+
async def test_a_two_hundred_saying_not_ok_is_still_a_failure(
self, installer: SlackAppInstaller, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -215,19 +232,24 @@ class TestConnectionConfig:
def test_a_grant_renders_a_config_the_adapter_accepts(
self, installer: SlackAppInstaller
) -> None:
- """The seam: after this an installed bridge is an ordinary bridge."""
+ """The seam: after this an installed bridge is an ordinary bridge.
+
+ Validated as-is, with nothing added. What the installer renders is what
+ `register` is handed, so a rendering that only validates once the test
+ has helped it along is a registration that fails in production.
+ """
rendered = installer.connection_config(
InstallGrant(
external_workspace_id="T123",
+ workspace_name="Acme",
bot_token="xoxb-granted",
scopes="chat:write",
)
)
- config = SlackConnectionConfig.model_validate(
- {**rendered, "event_delivery": "webhook"}
- )
+ config = SlackConnectionConfig.model_validate(rendered)
assert config.bot_token == "xoxb-granted"
assert config.workspace_id == "T123"
+ assert config.event_delivery == "webhook"
assert config.app_token is None
diff --git a/core/tests/switch_core/db/stores/test_messaging_install_store.py b/core/tests/switch_core/db/stores/test_messaging_install_store.py
new file mode 100644
index 000000000..5b1304417
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_messaging_install_store.py
@@ -0,0 +1,271 @@
+"""Redeeming an install state is a race, and only one caller may win it.
+
+The state is the only thing tying an authenticated "install this" to an
+unauthenticated callback from the platform, and a signature alone cannot make
+it single-use. This is where that property lives, so these run against a real
+Postgres through the restricted role — a test that redeemed a state in Python
+would prove nothing about the statement that actually runs.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from sqlalchemy.ext.asyncio import async_sessionmaker
+
+from switch_core.db.models import Tenant, User
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.messaging_install_store import (
+ MessagingInstallClaimedError,
+ MessagingInstallStateError,
+ MessagingInstallStore,
+)
+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(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
+
+
+class TestStartingAnInstall:
+ async def test_the_state_takes_its_tenant_from_the_session(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The caller never names a tenant; the bound session decides.
+
+ This is the whole reason the start leg is the authenticated one.
+ """
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state = await store.start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ await session.commit()
+ assert state.tenant_id == fixture.tenant_a
+
+
+class TestRedeemingAState:
+ async def test_a_state_redeems_once(self, rls_harness: RLSHarness) -> None:
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state_id = (
+ await store.start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ ).id
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ redeemed = await store.redeem_state(
+ session, state_id=state_id, platform="slack"
+ )
+ await session.commit()
+ assert redeemed.consumed_at is not None
+
+ async def test_replaying_it_is_refused(self, rls_harness: RLSHarness) -> None:
+ """The attack. A captured state must not install a second workspace."""
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state_id = (
+ await store.start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ ).id
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ await store.redeem_state(session, state_id=state_id, platform="slack")
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ with pytest.raises(MessagingInstallStateError, match="already been used"):
+ await store.redeem_state(session, state_id=state_id, platform="slack")
+
+ async def test_two_simultaneous_redemptions_produce_one_winner(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Sequential replay is the easy half; this is the one that needs the
+ check and the write to be a single statement.
+
+ Two callbacks arriving together would both read `consumed_at IS NULL`
+ under a read-then-update, and both would proceed.
+ """
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state_id = (
+ await store.start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ ).id
+ await session.commit()
+
+ async def attempt() -> bool:
+ async with tenant_session(
+ rls_harness.restricted, fixture.tenant_a
+ ) as session:
+ try:
+ await store.redeem_state(
+ session, state_id=state_id, platform="slack"
+ )
+ except MessagingInstallStateError:
+ return False
+ await session.commit()
+ return True
+
+ outcomes = await asyncio.gather(attempt(), attempt())
+ assert sum(outcomes) == 1
+
+ async def test_an_expired_state_is_refused(self, rls_harness: RLSHarness) -> None:
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state = await store.start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ state.expires_at = datetime.now(UTC) - timedelta(seconds=1)
+ await session.commit()
+ state_id = state.id
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ with pytest.raises(MessagingInstallStateError, match="expired"):
+ await store.redeem_state(session, state_id=state_id, platform="slack")
+
+ async def test_another_tenant_cannot_redeem_it(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The second check on the signature.
+
+ A state's tenant is established by the signature before this runs, so
+ reaching here with the wrong one means the signature was forged or the
+ key leaked. Row-level security still refuses, independently.
+ """
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state_id = (
+ await store.start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ ).id
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ with pytest.raises(MessagingInstallStateError):
+ await store.redeem_state(session, state_id=state_id, platform="slack")
+
+ async def test_a_state_cannot_be_redeemed_on_another_platform(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The path a callback is served on does not get to pick the state."""
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ state_id = (
+ await store.start_install(
+ session, platform="slack", user_id=fixture.user_id
+ )
+ ).id
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ with pytest.raises(MessagingInstallStateError):
+ await store.redeem_state(session, state_id=state_id, platform="teams")
+
+
+class TestRecordingAnInstall:
+ async def test_a_claimed_workspace_raises_something_showable(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """An IntegrityError reaching a request handler is a 500 and a
+ traceback; this failure is ordinary and has to read as one."""
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ await store.record_install(
+ session,
+ platform="slack",
+ external_workspace_id=fixture.workspace,
+ encrypted_bot_token="ciphertext",
+ scopes="chat:write",
+ user_id=fixture.user_id,
+ )
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ with pytest.raises(MessagingInstallClaimedError, match="already connected"):
+ await store.record_install(
+ session,
+ platform="slack",
+ external_workspace_id=fixture.workspace,
+ encrypted_bot_token="ciphertext",
+ scopes="chat:write",
+ user_id=fixture.user_id,
+ )
+
+ async def test_only_the_owning_tenant_reads_it_back(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _two_tenants(rls_harness.owner)
+ store = MessagingInstallStore()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ await store.record_install(
+ session,
+ platform="slack",
+ external_workspace_id=fixture.workspace,
+ encrypted_bot_token="ciphertext",
+ scopes="chat:write",
+ user_id=fixture.user_id,
+ )
+ await session.commit()
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ mine = await store.get_for_workspace(
+ session, platform="slack", external_workspace_id=fixture.workspace
+ )
+ assert mine is not None
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ theirs = await store.get_for_workspace(
+ session, platform="slack", external_workspace_id=fixture.workspace
+ )
+ assert theirs is None