Skip to content

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

fix(gateway): refuse to delete a bridge an install built (CHOO-2626)

Petr Bauchb8dc18542f53
diff --git a/core/switch_core/db/stores/messaging_install_store.py b/core/switch_core/db/stores/messaging_install_store.py
index 714e9c0c2..5e6ae18e8 100644
--- a/core/switch_core/db/stores/messaging_install_store.py
+++ b/core/switch_core/db/stores/messaging_install_store.py
@@ -181,6 +181,27 @@ class MessagingInstallStore:
)
return result.scalars().one_or_none()
+ async def get_for_bridge(
+ self, session: AsyncSession, *, bridge_id: str
+ ) -> MessagingInstall | None:
+ """The live install a bridge was built for, if it was built for one.
+
+ Asked from the other direction than the rest of this store, and by
+ something that does not otherwise know installs exist: the bridge
+ delete endpoint, which has to refuse rather than tear down a bridge
+ whose credential is a token nobody here has revoked.
+
+ Live installs only. An ended one has already released its pointer, so a
+ row matching here is always a bridge that is still somebody's install.
+ """
+ result = await session.execute(
+ select(MessagingInstall).where(
+ MessagingInstall.bridge_id == bridge_id,
+ MessagingInstall.status == INSTALL_ACTIVE,
+ )
+ )
+ return result.scalars().one_or_none()
+
async def get(self, session: AsyncSession, *, install_id: str) -> MessagingInstall:
"""One of the bound tenant's installs, by id, or raise."""
install = await session.get(MessagingInstall, install_id)
diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py
index 902a5c974..3490b6216 100644
--- a/core/switch_core/gateway/collaborations.py
+++ b/core/switch_core/gateway/collaborations.py
@@ -19,6 +19,7 @@ from switch_core.bridges.collaboration.models import (
from switch_core.db.models import CollaborationBridge, ExternalUser, User
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.external_user_store import ExternalUserStore
+from switch_core.db.stores.messaging_install_store import MessagingInstallStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.auth import (
@@ -30,6 +31,7 @@ from switch_core.gateway.dependencies import (
get_bridge_store,
get_collab_lifecycle,
get_external_user_store,
+ get_install_store,
get_room_service,
get_room_store,
get_session,
@@ -677,6 +679,7 @@ async def delete_bridge(
bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
room_store: Annotated[RoomStore, Depends(get_room_store)],
room_service: Annotated[RoomService, Depends(get_room_service)],
+ install_store: Annotated[MessagingInstallStore, Depends(get_install_store)],
collab_lifecycle: Annotated[
CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
],
@@ -688,6 +691,25 @@ async def delete_bridge(
if bridge is None:
raise HTTPException(status_code=404, detail="Bridge not found")
+ # Before a single room is deleted, because the rooms do not come back. A
+ # bridge built by an install holds a token this deployment did not issue
+ # and the platform still honours, and the install row's pointer at it is a
+ # real foreign key — so this delete would destroy every room on the bridge
+ # and *then* be refused by Postgres, leaving the bridge running, the rooms
+ # gone and a live credential nobody has revoked.
+ install = await install_store.get_for_bridge(session, bridge_id=bridge_id)
+ if install is not None:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"This connection was created by installing the Switch app into "
+ f"{install.platform} workspace {install.external_workspace_id}, so "
+ "it cannot be deleted here — the app would stay installed and its "
+ "token would stay valid. Disconnect the app instead, which revokes "
+ "the token at the platform and then removes this connection."
+ ),
+ )
+
rooms = await room_store.get_by_bridge(session, bridge_id)
for room in rooms:
await room_service.delete_room(room.id)
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index 8f85508d1..5358de849 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -24,6 +24,7 @@ from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.invitation_store import InvitationStore
+from switch_core.db.stores.messaging_install_store import MessagingInstallStore
from switch_core.db.stores.room_group_store import RoomGroupStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.server_connector_store import ServerConnectorStore
@@ -220,6 +221,21 @@ def get_protocol() -> ProtocolService:
return _state["protocol"] # type: ignore[no-any-return]
+def get_install_store() -> MessagingInstallStore:
+ """Built here rather than threaded through `init_dependencies`.
+
+ It is stateless — no connection, no configuration, nothing for a shared
+ instance to own — and `get_room_yaml_service` above already constructs
+ rather than reads.
+
+ Deliberately not reached through `get_install_service`, which is `None` on
+ a deployment that registered no app of its own. Install rows outlive those
+ credentials: a bridge built by an install has to stay protected after the
+ credentials are taken away, which is exactly when the service is gone.
+ """
+ return MessagingInstallStore()
+
+
def get_install_service() -> MessagingInstallService | None:
"""None when this deployment registered no messaging app of its own.
diff --git a/core/tests/switch_core/gateway/test_bridge_delete_guard.py b/core/tests/switch_core/gateway/test_bridge_delete_guard.py
new file mode 100644
index 000000000..c0c39ea18
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_bridge_delete_guard.py
@@ -0,0 +1,252 @@
+"""Deleting a bridge an install built must be refused, not half-done.
+
+`messaging_installs.bridge_id` is a real foreign key with no `ON DELETE`, and
+the delete endpoint tears down every room on the bridge *before* it removes the
+bridge itself. Without a guard the ordering plays out as: rooms irreversibly
+deleted, Postgres then refuses the bridge deletion, operator gets a 500 — and
+the app is still installed with a token nobody revoked.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import (
+ Client,
+ CollaborationBridge,
+ MessagingInstall,
+ Room,
+ User,
+)
+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
+from switch_core.db.stores.messaging_install_store import (
+ INSTALL_ACTIVE,
+ INSTALL_DISCONNECTED,
+ MessagingInstallStore,
+)
+from switch_core.db.stores.room_store import RoomStore
+from switch_core.gateway.collaborations import delete_bridge
+
+_BRIDGE_STORE = CollaborationBridgeStore()
+_ROOM_STORE = RoomStore()
+_INSTALL_STORE = MessagingInstallStore()
+
+
+class _RecordingRoomService:
+ """Remembers the rooms it was told to delete and deletes nothing.
+
+ A spy rather than the real service because the property under test is that
+ it is never called at all: an assertion on the list is the assertion that
+ the refusal came first.
+ """
+
+ def __init__(self) -> None:
+ self.deleted: list[str] = []
+
+ async def delete_room(self, room_id: str) -> None:
+ self.deleted.append(room_id)
+
+
+class _RecordingLifecycle:
+ def __init__(self) -> None:
+ self.removed: list[str] = []
+
+ async def remove(self, bridge_id: str) -> None:
+ self.removed.append(bridge_id)
+
+
+async def _make_admin(session: AsyncSession) -> User:
+ user = User(
+ id=f"admin-{uuid.uuid4().hex[:8]}",
+ name=f"admin-{uuid.uuid4().hex[:8]}",
+ email=f"admin-{uuid.uuid4().hex[:8]}@example.test",
+ role="admin",
+ )
+ session.add(user)
+ await session.flush()
+ return user
+
+
+async def _make_bridge(session: AsyncSession) -> str:
+ client = Client(
+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",
+ display_name="bridge client",
+ type="bridge",
+ )
+ session.add(client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name="Slack",
+ client_id=client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ return bridge.id
+
+
+async def _make_room(session: AsyncSession, *, bridge_id: str) -> str:
+ room = Room(
+ matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",
+ name="bridged room",
+ description="mirror of an external channel",
+ bridge_id=bridge_id,
+ channel_type="channel_public",
+ external_channel_id="C123",
+ )
+ session.add(room)
+ await session.flush()
+ return room.id
+
+
+async def _make_install(
+ session: AsyncSession, *, bridge_id: str | None, status: str, user_id: str
+) -> str:
+ install = MessagingInstall(
+ platform="slack",
+ external_workspace_id=f"T{uuid.uuid4().hex[:8]}",
+ encrypted_bot_token="encrypted-placeholder",
+ scopes="app_mentions:read,chat:write",
+ status=status,
+ installed_by_user_id=user_id,
+ bridge_id=bridge_id,
+ )
+ session.add(install)
+ await session.flush()
+ return install.id
+
+
+async def test_a_bridge_an_install_built_cannot_be_deleted_here(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ admin = await _make_admin(session)
+ bridge_id = await _make_bridge(session)
+ room_id = await _make_room(session, bridge_id=bridge_id)
+ await _make_install(
+ session, bridge_id=bridge_id, status=INSTALL_ACTIVE, user_id=admin.id
+ )
+ await session.commit()
+
+ room_service = _RecordingRoomService()
+ lifecycle = _RecordingLifecycle()
+ async with session_factory() as session:
+ admin = await _make_admin(session)
+ with pytest.raises(HTTPException) as excinfo:
+ await delete_bridge(
+ bridge_id,
+ session,
+ _BRIDGE_STORE,
+ _ROOM_STORE,
+ room_service, # type: ignore[arg-type]
+ _INSTALL_STORE,
+ lifecycle, # type: ignore[arg-type]
+ admin,
+ )
+
+ assert excinfo.value.status_code == 409
+ # The whole point of the ordering: nothing was destroyed on the way to the
+ # refusal, so retrying after disconnecting is a clean retry.
+ assert room_service.deleted == []
+ assert lifecycle.removed == []
+
+ async with session_factory() as session:
+ assert await _BRIDGE_STORE.get(session, bridge_id) is not None
+ assert await _ROOM_STORE.get(session, room_id) is not None
+
+
+async def test_the_refusal_names_the_workspace_to_disconnect(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """An operator who cannot delete here has to be told where to go instead."""
+ async with session_factory() as session:
+ admin = await _make_admin(session)
+ bridge_id = await _make_bridge(session)
+ install_id = await _make_install(
+ session, bridge_id=bridge_id, status=INSTALL_ACTIVE, user_id=admin.id
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ install = await _INSTALL_STORE.get(session, install_id=install_id)
+ workspace = install.external_workspace_id
+ with pytest.raises(HTTPException) as excinfo:
+ await delete_bridge(
+ bridge_id,
+ session,
+ _BRIDGE_STORE,
+ _ROOM_STORE,
+ _RecordingRoomService(), # type: ignore[arg-type]
+ _INSTALL_STORE,
+ _RecordingLifecycle(), # type: ignore[arg-type]
+ await _make_admin(session),
+ )
+
+ detail = str(excinfo.value.detail)
+ assert workspace in detail
+ assert "slack" in detail
+ assert "Disconnect" in detail
+
+
+async def test_a_bridge_registered_by_hand_still_deletes(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ room_id = await _make_room(session, bridge_id=bridge_id)
+ await session.commit()
+
+ room_service = _RecordingRoomService()
+ lifecycle = _RecordingLifecycle()
+ async with session_factory() as session:
+ result = await delete_bridge(
+ bridge_id,
+ session,
+ _BRIDGE_STORE,
+ _ROOM_STORE,
+ room_service, # type: ignore[arg-type]
+ _INSTALL_STORE,
+ lifecycle, # type: ignore[arg-type]
+ await _make_admin(session),
+ )
+
+ assert result == {"ok": True}
+ assert room_service.deleted == [room_id]
+ assert lifecycle.removed == [bridge_id]
+
+
+async def test_a_bridge_whose_install_already_ended_still_deletes(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """Disconnecting releases the pointer, so an ended install guards nothing.
+
+ The row it leaves behind is a record, not a claim — and a bridge that
+ outlived its install is an ordinary bridge again.
+ """
+ async with session_factory() as session:
+ admin = await _make_admin(session)
+ bridge_id = await _make_bridge(session)
+ await _make_install(
+ session, bridge_id=None, status=INSTALL_DISCONNECTED, user_id=admin.id
+ )
+ await session.commit()
+
+ lifecycle = _RecordingLifecycle()
+ async with session_factory() as session:
+ await delete_bridge(
+ bridge_id,
+ session,
+ _BRIDGE_STORE,
+ _ROOM_STORE,
+ _RecordingRoomService(), # type: ignore[arg-type]
+ _INSTALL_STORE,
+ lifecycle, # type: ignore[arg-type]
+ await _make_admin(session),
+ )
+
+ assert lifecycle.removed == [bridge_id]