Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(messaging): routes for ending an install (CHOO-2626)
Petr Bauched5ca180267a
diff --git a/core/switch_core/bridges/collaboration/install_routes.py b/core/switch_core/bridges/collaboration/install_routes.pyindex 5c7029a7d..899ec55fe 100644--- a/core/switch_core/bridges/collaboration/install_routes.py+++ b/core/switch_core/bridges/collaboration/install_routes.py@@ -42,6 +42,7 @@ from switch_core.bridges.collaboration.install import (from switch_core.bridges.collaboration.install_service import (InstallPlatformMismatch,MessagingInstallService,+ Revocation,WebhookBridgeUnavailable,WebhookTarget,WebhookWorkspaceUnknown,@@ -175,6 +176,29 @@ def create_messaging_install_router(target.tenant_id,)+ async def _end_install(platform: str, revocation: Revocation) -> None:+ """Act on the platform's news after it has been acknowledged.++ Logged and not raised for the same reason as `_deliver`, and with more+ at stake: the platform redelivers what it gets no answer to, and a+ traceback out of a background task would leave a dead install claiming+ a workspace with nothing in the log naming it.+ """+ try:+ await service.revoked(+ platform=platform,+ workspace_id=revocation.workspace_id,+ reason=revocation.reason,+ )+ except Exception:+ logger.exception(+ "Failed to end the install of %s workspace %s after the platform "+ "reported it was over (%s)",+ platform,+ revocation.workspace_id,+ revocation.reason,+ )+async def _inbound(platform: str,endpoint: WebhookEndpoint,@@ -217,6 +241,13 @@ def create_messaging_install_router(return PlainTextResponse(event.handshake)try:+ # Before resolving, because this is the one event that arrives as+ # the bridge it would be resolved to is going away.+ revocation = service.revocation(platform=platform, event=event)+ if revocation is not None:+ background.add_task(_end_install, platform, revocation)+ return Response(status_code=200)+target = await service.resolve(platform=platform, event=event)except WebhookPayloadError as failure:logger.error(@@ -224,8 +255,14 @@ def create_messaging_install_router()return Response(status_code=400)except WebhookWorkspaceUnknown as failure:+ # A 200 for an event that reached nobody, which is the one place+ # this file answers something other than what happened. The app+ # left behind in a workspace whose install ended goes on posting,+ # the platform cannot act on a 404, and it counts the refusals+ # against the app as a whole — so the honest answer costs every+ # other customer's delivery. The log is where it is visible.logger.warning("Dropped a %s event: %s", platform, failure)- return Response(status_code=404)+ return Response(status_code=200)except WebhookBridgeUnavailable as failure:# Deliberately a 503: the platform retrying is the right behaviour# while a bridge restarts, and a 200 here would drop a real messagediff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.pyindex ba83e198e..bacbb1fbe 100644--- a/core/switch_core/bridges/collaboration/install_service.py+++ b/core/switch_core/bridges/collaboration/install_service.py@@ -94,8 +94,10 @@ class WebhookWorkspaceUnknown(RuntimeError):Ordinary rather than alarming: an app left in a workspace whose install wasremoved goes on posting for as long as someone leaves it there. It is still- an error, because the alternative is answering "fine" to traffic that- reaches nobody.+ an error here, because a resolver that returned nothing would make "nobody+ holds this" and "here is where it goes" the same shape — but it is one the+ route absorbs rather than reports, since the platform cannot fix it and+ telling it repeatedly that its posts fail is held against the app itself."""@@ -108,6 +110,14 @@ class WebhookBridgeUnavailable(RuntimeError):"""+@dataclass(frozen=True)+class Revocation:+ """A platform saying, in an ordinary event, that an install is over."""++ workspace_id: str+ reason: str++@dataclass(frozen=True)class WebhookTarget:"""Where one verified event goes: a tenant, a bridge, and its live adapter."""@@ -255,6 +265,14 @@ class MessagingInstallService:)return attached+ async def list_installs(self, session: AsyncSession) -> list[MessagingInstall]:+ """The bound tenant's installs, for the operator's own list.++ On the caller's session like `begin`, and scoped by it: there is no+ tenant argument because there is no tenant to choose.+ """+ return await self._store.list_for_tenant(session)+# ── Ending an install ────────────────────────────────────────────────────async def disconnect(self, *, tenant_id: str, install_id: str) -> MessagingInstall:@@ -410,6 +428,26 @@ class MessagingInstallService:installer.verify_webhook(headers=headers, body=body)return installer.parse_webhook(endpoint=endpoint, body=body)+ def revocation(self, *, platform: str, event: InboundWebhook) -> Revocation | None:+ """Whether this event is the platform ending the install, and for whom.++ Asked before `resolve` and not after, because the two disagree about+ what a missing bridge means. `resolve` insists on one, and the event+ most worth reading here is precisely the one that arrives when the+ bridge is on its way out — so an uninstall routed through the ordinary+ path would be dropped exactly when it mattered.++ Pure, like `authenticate`: it reads the payload and nothing else, so+ the route can answer the platform before any of the work begins.+ """+ installer = self._installers.get(platform)+ reason = installer.revocation_of_event(event.payload)+ if reason is None:+ return None+ return Revocation(+ workspace_id=installer.workspace_of_event(event.payload), reason=reason+ )+async def resolve(self, *, platform: str, event: InboundWebhook) -> WebhookTarget:"""Turn a workspace id into the one bridge entitled to the event.diff --git a/core/switch_core/gateway/messaging_installs.py b/core/switch_core/gateway/messaging_installs.pyindex 16ee7ffab..ac730188d 100644--- a/core/switch_core/gateway/messaging_installs.py+++ b/core/switch_core/gateway/messaging_installs.py@@ -10,6 +10,7 @@ the shape that works.from __future__ import annotationsimport logging+from datetime import datetimefrom typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPException@@ -18,7 +19,8 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.bridges.collaboration.install import MessagingInstallErrorfrom switch_core.bridges.collaboration.install_service import MessagingInstallService-from switch_core.db.models import User+from switch_core.db.models import User, require_tenant_id+from switch_core.db.stores.messaging_install_store import MessagingInstallNotFoundfrom switch_core.gateway.auth import require_adminfrom switch_core.gateway.dependencies import get_install_service, get_session@@ -35,6 +37,30 @@ class InstallablePlatforms(BaseModel):platforms: list[str]+class InstalledApp(BaseModel):+ """One install as an operator needs to see it.++ No token and nothing derived from one. `status` and `ended_at` are the+ point of the shape rather than decoration: an operator looks at this list+ because a bridge stopped working, and "disconnected" and "revoked" are the+ difference between a decision someone here made and news from the+ platform.+ """++ id: str+ platform: str+ external_workspace_id: str+ status: str+ scopes: str+ bridge_id: str | None+ installed_at: datetime+ ended_at: datetime | None+++class InstalledApps(BaseModel):+ installs: list[InstalledApp]++def _require_installs(service: MessagingInstallService | None,) -> MessagingInstallService:@@ -84,3 +110,59 @@ async def begin_install(await session.commit()logger.info("Started a %s install for user %s", platform, user.id)return InstallStart(authorize_url=authorize_url)++[email protected]("/installs")+async def list_installs(+ session: Annotated[AsyncSession, Depends(get_session)],+ service: Annotated[MessagingInstallService | None, Depends(get_install_service)],+ _user: Annotated[User, Depends(require_admin)],+) -> InstalledApps:+ """This organisation's installs, ended ones included.++ An empty list when the deployment registered no app of its own, rather+ than the 501 the install endpoints answer with: a deployment can have+ installs recorded from before its credentials were removed, and a page+ that cannot even show them is worse than one with nothing on it.+ """+ if service is None:+ return InstalledApps(installs=[])+ return InstalledApps(+ installs=[+ InstalledApp.model_validate(install, from_attributes=True)+ for install in await service.list_installs(session)+ ]+ )++[email protected]("/installs/{install_id}")+async def disconnect_install(+ install_id: str,+ service: Annotated[MessagingInstallService | None, Depends(get_install_service)],+ user: Annotated[User, Depends(require_admin)],+) -> InstalledApp:+ """End an install: revoke the credential, remove the bridge, free the workspace.++ Not on the request's session, deliberately. Disconnecting revokes a token+ at the platform and tears a bridge down, and holding this request's+ transaction open across both would keep a row locked while somebody else's+ API is slow. The service opens what it needs, in the order failure can be+ recovered from.++ **Rooms that used the bridge become internal-only**, which is why this is a+ delete an operator has to ask for rather than anything inferred.+ """+ try:+ ended = await _require_installs(service).disconnect(+ tenant_id=require_tenant_id(), install_id=install_id+ )+ except MessagingInstallNotFound as missing:+ raise HTTPException(status_code=404, detail=str(missing)) from missing+ except MessagingInstallError as failure:+ # The platform refused to revoke and nothing was destroyed, so this is+ # upstream's answer rather than a fault here — and it is retryable,+ # which the operator needs to be told rather than left to guess.+ raise HTTPException(status_code=502, detail=str(failure)) from failure++ logger.info("User %s disconnected messaging install %s", user.id, install_id)+ return InstalledApp.model_validate(ended, from_attributes=True)diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.pyindex f7d346af0..fd4244e92 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py@@ -126,12 +126,29 @@ class _RecordingAdapter(_SocketOnlyAdapter):class _FakeLifecycle:- def __init__(self) -> None:+ def __init__(self, factory: async_sessionmaker) -> None:+ self._factory = factoryself.adapters: dict[str, CollaborationAdapter] = {}+ self.removed: list[str] = []def get_adapter(self, bridge_id: str) -> CollaborationAdapter | None:return self.adapters.get(bridge_id)+ async def remove(self, bridge_id: str) -> None:+ """Delete the row, on an unscoped session like the real one.++ The real lifecycle opens a plain session and lets the tenant bound+ around the call decide what it can see, so a fake that took a tenant+ argument would not be exercising the same thing.+ """+ self.removed.append(bridge_id)+ self.adapters.pop(bridge_id, None)+ async with self._factory() as session:+ bridge = await session.get(CollaborationBridge, bridge_id)+ if bridge is not None:+ await session.delete(bridge)+ await session.commit()+@dataclassclass _Workspace:@@ -144,7 +161,7 @@ class _Workspace:class _Fixture:def __init__(self, harness: RLSHarness) -> None:self.harness = harness- self.lifecycle = _FakeLifecycle()+ self.lifecycle = _FakeLifecycle(harness.restricted)self.a: _Workspaceself.b: _Workspaceself.client: httpx.AsyncClient@@ -254,6 +271,16 @@ def _event(workspace_id: str, text: str) -> bytes:).encode()+def _uninstalled(workspace_id: str) -> bytes:+ return json.dumps(+ {+ "type": "event_callback",+ "team_id": workspace_id,+ "event": {"type": "app_uninstalled"},+ }+ ).encode()++def _texts(adapter: _RecordingAdapter) -> list[str]:return [payload["event"]["text"] for _, payload in adapter.dispatched]@@ -389,21 +416,24 @@ class TestWhatTheEndpointRefuses:assert fixture.a.adapter.dispatched == []assert fixture.b.adapter.dispatched == []- async def test_an_unknown_workspace_is_not_reported_as_handled(+ async def test_an_unknown_workspace_is_dropped_without_telling_the_platform(self, rls_harness: RLSHarness) -> None:- """404 rather than a polite 200.-- The app is still installed somewhere we no longer serve, and the- honest answer is that this event reached nobody. A 200 would make it- invisible on both sides — a platform's own delivery log is often the- only place anyone would see it.+ """200, and the one place this endpoint answers something other than+ what happened.++ The app is still installed in a workspace we no longer serve, so it+ posts for as long as someone leaves it there. The platform cannot act+ on a refusal — there is nothing for it to fix — and it counts the+ refusals against the app as a whole, so the honest 404 would be paid+ for by every other customer's delivery. It is dropped, and it is in the+ log."""fixture = await _fixture(rls_harness)response = await _post(fixture, events_path("slack"), _event("T-nobody", "x"))- assert response.status_code == 404+ assert response.status_code == 200assert fixture.a.adapter.dispatched == []assert fixture.b.adapter.dispatched == []@@ -535,3 +565,71 @@ class TestABridgeThatCannotTakeEvents:target = await fixture.service.resolve(platform="slack", event=event)with pytest.raises(Exception, match="does not receive events over HTTP"):await fixture.service.deliver(target, event)+++class TestThePlatformSayingTheInstallIsOver:+ """`app_uninstalled` arrives on the same URL as everything else."""++ async def test_it_ends_the_install_instead_of_dispatching(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)++ response = await _post(+ fixture, events_path("slack"), _uninstalled(fixture.a.workspace_id)+ )++ assert response.status_code == 200+ assert fixture.a.adapter.dispatched == []+ assert fixture.lifecycle.removed == [fixture.a.bridge_id]++ async with tenant_session(+ rls_harness.restricted, fixture.a.tenant_id+ ) as session:+ installs = await MessagingInstallStore().list_for_tenant(session)+ assert [install.status for install in installs] == ["revoked"]++ async def test_it_ends_nobody_elses(self, rls_harness: RLSHarness) -> None:+ """The payload decides here as well, and the blast radius is larger.++ A revocation routed by anything but the workspace in the event would+ disconnect a customer who did nothing.+ """+ fixture = await _fixture(rls_harness)++ await _post(fixture, events_path("slack"), _uninstalled(fixture.a.workspace_id))+ await _post(fixture, events_path("slack"), _event(fixture.b.workspace_id, "b"))++ assert _texts(fixture.b.adapter) == ["b"]+ assert fixture.lifecycle.removed == [fixture.a.bridge_id]++ async def test_the_workspace_stops_resolving_to_anyone(+ self, rls_harness: RLSHarness+ ) -> None:+ """Which is what frees it to be installed again.++ An app removed from a workspace can still post on its way out, and an+ ended install that went on answering for the workspace would route+ those to a bridge that no longer exists.+ """+ fixture = await _fixture(rls_harness)+ await _post(fixture, events_path("slack"), _uninstalled(fixture.a.workspace_id))++ trailing = await _post(+ fixture, events_path("slack"), _event(fixture.a.workspace_id, "late")+ )++ assert trailing.status_code == 200+ assert fixture.a.adapter.dispatched == []++ async def test_a_redelivery_is_not_an_error(self, rls_harness: RLSHarness) -> None:+ """Slack retries what it is slow to hear back from, and it hears 200+ from the first delivery only after the install has already gone."""+ fixture = await _fixture(rls_harness)+ body = _uninstalled(fixture.a.workspace_id)++ first = await _post(fixture, events_path("slack"), body)+ second = await _post(fixture, events_path("slack"), body)++ assert (first.status_code, second.status_code) == (200, 200)+ assert fixture.lifecycle.removed == [fixture.a.bridge_id]