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(messaging): let an install end (CHOO-2626)

Petr Bauch0919a002506f
diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.py
index 8abdcffee..aa1b2d6fa 100644
--- a/core/switch_core/bridges/collaboration/install.py
+++ b/core/switch_core/bridges/collaboration/install.py
@@ -205,6 +205,31 @@ class MessagingAppInstaller(ABC):
grant, including a well-formed response the platform marked as failed.
"""
+ @abstractmethod
+ async def revoke(self, *, bot_token: str) -> None:
+ """Tell the platform the credential it granted us is finished with.
+
+ Called when an operator disconnects an install. Deleting our copy is
+ not the same act: the token stays valid at the platform, so a dump
+ taken before the disconnect would still hold a working key into a
+ customer's workspace. This is the half only the platform can do.
+
+ **A token the platform already considers dead is a success, not a
+ failure.** The common reason to be disconnecting at all is that the
+ customer removed the app on their side, and an implementation that
+ raised on "this token is already invalid" would make exactly that
+ install impossible to disconnect, forever.
+
+ Raise :class:`MessagingInstallError` for anything else — a refusal we
+ do not understand leaves a live credential behind and the operator
+ should hear about it rather than see a disconnect that reports
+ success.
+
+ Not the same thing as the platform's own uninstall. Revoking a token
+ does not remove the app from the workspace; it ends this deployment's
+ access with it.
+ """
+
@abstractmethod
def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:
"""Prove an inbound event came from the platform, or raise.
@@ -245,6 +270,24 @@ class MessagingAppInstaller(ABC):
event we cannot route is not an event we may guess at.
"""
+ @abstractmethod
+ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:
+ """Why this event says the install is over, or `None` if it does not.
+
+ Platforms report the end of an install as an ordinary event on the
+ ordinary endpoint, which makes it easy to treat as one: the app is
+ removed from a workspace, an event arrives saying so, nothing reads
+ it, and the deployment goes on holding a dead token, a running bridge
+ and a claim on a workspace whose owner believes they have left.
+
+ A reason rather than a flag because it is the thing worth logging — an
+ operator asking why their bridge stopped needs the platform's own
+ answer, and there is more than one way an install can end.
+
+ Runs on a payload that has been authenticated and not yet routed, so
+ like :meth:`workspace_of_event` it must not touch the database.
+ """
+
@abstractmethod
def connection_config(self, grant: InstallGrant) -> dict[str, object]:
"""Render a grant as the connection config this platform's adapter takes.
diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.py
index 55c37b5bc..ba83e198e 100644
--- a/core/switch_core/bridges/collaboration/install_service.py
+++ b/core/switch_core/bridges/collaboration/install_service.py
@@ -26,6 +26,27 @@ 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.
+
+**Ending one runs the same steps backwards, and there are two ways in.** An
+operator disconnects here, or the platform tells us the app is gone. They
+differ in exactly one step — whether there is a live token to revoke — and in
+nothing else, because both have to leave the same state behind: no bridge, no
+stored credential, a released workspace and a row saying what happened. A
+deployment that handled only the first would go on holding a dead token and a
+claim on a workspace whose owner believes they have left.
+
+The revoking order is: tell the platform first, then destroy things. A
+revocation we do not understand then leaves the install exactly as it was and
+the operator can try again, where the other order would have removed the
+bridge and left a working key into a customer's workspace in whatever dump was
+taken next.
+
+Then the row, and the bridge last — the reverse of the building order and for
+the same reason read backwards. The install's pointer at the bridge is a real
+foreign key, so the row has to let go before the bridge can be deleted at all;
+and if the deletion then fails, what is left is a bridge with no credential
+that an operator can see and remove, rather than an install still claiming a
+workspace it has already been thrown out of.
"""
from __future__ import annotations
@@ -53,10 +74,15 @@ from switch_core.bridges.collaboration.install_state import (
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
-from switch_core.crypto import encrypt_token
+from switch_core.crypto import decrypt_token, 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.db.stores.messaging_install_store import (
+ INSTALL_ACTIVE,
+ INSTALL_DISCONNECTED,
+ INSTALL_REVOKED,
+ MessagingInstallStore,
+)
from switch_core.db.tenant_lookup import tenant_of_messaging_install
from switch_core.tenant_context import no_tenant, tenant_scope
@@ -229,6 +255,127 @@ class MessagingInstallService:
)
return attached
+ # ── Ending an install ────────────────────────────────────────────────────
+
+ async def disconnect(self, *, tenant_id: str, install_id: str) -> MessagingInstall:
+ """End an install because somebody here said to.
+
+ Idempotent: disconnecting an install that has already ended returns it
+ unchanged. An operator can reach this for a row the platform's own
+ `app_uninstalled` ended a second earlier, and that is not an error to
+ show them.
+
+ **Removing the bridge detaches every room that used it**, which become
+ internal-only. That is the honest consequence of disconnecting a
+ messaging app and it is not softened here — but it is the reason this
+ is an explicit action with a confirmation in front of it rather than
+ something inferred.
+ """
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ install = await self._store.get(session, install_id=install_id)
+ platform = install.platform
+ workspace_id = install.external_workspace_id
+ bridge_id = install.bridge_id
+ token = install.encrypted_bot_token
+ already_ended = install.status != INSTALL_ACTIVE
+
+ if already_ended:
+ logger.info(
+ "Install %s of %s workspace %s had already ended; nothing to do",
+ install_id,
+ platform,
+ workspace_id,
+ )
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ return await self._store.get(session, install_id=install_id)
+
+ with tenant_scope(tenant_id):
+ if token is not None:
+ await self._installers.get(platform).revoke(
+ bot_token=decrypt_token(token, self._secret)
+ )
+
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ ended = await self._store.end(
+ session, install_id=install_id, status=INSTALL_DISCONNECTED
+ )
+ await session.commit()
+
+ if bridge_id is not None:
+ await self._lifecycle.remove(bridge_id)
+
+ logger.info(
+ "Disconnected %s workspace %s for tenant %s",
+ platform,
+ workspace_id,
+ tenant_id,
+ )
+ return ended
+
+ async def revoked(self, *, platform: str, workspace_id: str, reason: str) -> None:
+ """End an install because the platform said it is over.
+
+ Resolves the workspace itself rather than going through `resolve`,
+ which is built for delivering an event and insists on a running bridge.
+ Here a missing bridge is beside the point: the news is that the install
+ is finished, and a deployment that could only record that while the
+ bridge happened to be up would keep the dead ones it most needs to
+ clear.
+
+ A workspace that resolves to nobody is the ordinary case, not a fault.
+ The platform retries these events, so the second delivery arrives after
+ the first has already ended the install.
+
+ No revocation call: the token this would revoke is the one the platform
+ has just told us it killed.
+ """
+ tenant_id = await tenant_of_messaging_install(
+ self._session_factory, platform, workspace_id
+ )
+ if tenant_id is None:
+ logger.info(
+ "Ignoring end-of-install for %s workspace %s (%s): no tenant "
+ "holds it, so it has already ended",
+ platform,
+ workspace_id,
+ reason,
+ )
+ return
+
+ with tenant_scope(tenant_id):
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ install = await self._store.get_for_workspace(
+ session, platform=platform, external_workspace_id=workspace_id
+ )
+ if install is None:
+ logger.warning(
+ "End-of-install for %s workspace %s resolved to tenant "
+ "%s and could not then be read as that tenant",
+ platform,
+ workspace_id,
+ tenant_id,
+ )
+ return
+ install_id = install.id
+ bridge_id = install.bridge_id
+
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ await self._store.end(
+ session, install_id=install_id, status=INSTALL_REVOKED
+ )
+ await session.commit()
+
+ if bridge_id is not None:
+ await self._lifecycle.remove(bridge_id)
+
+ logger.warning(
+ "Ended the install of %s workspace %s for tenant %s: %s",
+ platform,
+ workspace_id,
+ tenant_id,
+ reason,
+ )
+
# ── Inbound events ───────────────────────────────────────────────────────
#
# The other direction, and the one that runs constantly. Three steps, kept
diff --git a/core/switch_core/bridges/collaboration/slack/install.py b/core/switch_core/bridges/collaboration/slack/install.py
index 492e8891b..848aada72 100644
--- a/core/switch_core/bridges/collaboration/slack/install.py
+++ b/core/switch_core/bridges/collaboration/slack/install.py
@@ -39,6 +39,21 @@ logger = logging.getLogger(__name__)
AUTHORIZE_URL = "https://slack.com/oauth/v2/authorize"
+#: Slack's ways of saying the token is finished already. Revoking one of these
+#: is the outcome the caller wanted, so it is a success — and it is the usual
+#: case, because the reason to be disconnecting is often that the customer
+#: removed the app first.
+_ALREADY_DEAD = frozenset({"invalid_auth", "token_revoked", "account_inactive"})
+
+#: The two events by which Slack says an install is over, and what each means
+#: in words an operator can read. `app_uninstalled` is the customer removing
+#: the app; `tokens_revoked` is the narrower case of the tokens being killed
+#: while the app stays. Both leave us unable to act in the workspace.
+_REVOCATION_EVENTS: dict[str, str] = {
+ "app_uninstalled": "the app was removed from the Slack workspace",
+ "tokens_revoked": "Slack revoked this workspace's tokens",
+}
+
def _json_object(raw: bytes) -> dict[str, Any]:
try:
@@ -163,6 +178,31 @@ class SlackAppInstaller(MessagingAppInstaller):
scopes=response.get("scope") or "",
)
+ async def revoke(self, *, bot_token: str) -> None:
+ try:
+ response = await AsyncWebClient(token=bot_token).auth_revoke()
+ except SlackApiError as error:
+ reason = error.response.get("error", "")
+ if reason in _ALREADY_DEAD:
+ logger.info(
+ "Slack reports the bot token was already invalid (%s); "
+ "treating the revocation as done",
+ reason,
+ )
+ return
+ raise MessagingInstallError(
+ f"Slack refused to revoke the bot token: {reason or error}"
+ ) from error
+
+ # `revoked: false` with `ok: true` is Slack accepting the call and
+ # telling you it did nothing — which for a disconnect is the whole of
+ # what was asked for, so it cannot be read off `ok` alone.
+ if not response.get("revoked"):
+ raise MessagingInstallError(
+ "Slack accepted the revocation request and reported the token "
+ "was not revoked, so it is still valid."
+ )
+
def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:
try:
valid = self._verifier.is_valid_request(body, dict(headers))
@@ -236,6 +276,21 @@ class SlackAppInstaller(MessagingAppInstaller):
raise WebhookPayloadError("Slack event names no workspace")
return workspace_id
+ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:
+ """Read the two end-of-install events out of an Events API envelope.
+
+ Only `event_callback` envelopes carry one. A slash command or an
+ interaction cannot say the app was uninstalled — there would be nobody
+ left to press the button — so the inner `event.type` is the only place
+ worth looking, and reading a `type` from anywhere else would let an
+ interaction payload with the right-looking field disconnect a
+ customer's workspace.
+ """
+ event = payload.get("event")
+ if not isinstance(event, dict):
+ return None
+ return _REVOCATION_EVENTS.get(event.get("type", ""))
+
def connection_config(self, grant: InstallGrant) -> dict[str, object]:
return {
"bot_token": grant.bot_token,
diff --git a/core/switch_core/db/stores/messaging_install_store.py b/core/switch_core/db/stores/messaging_install_store.py
index b91a6d2a5..714e9c0c2 100644
--- a/core/switch_core/db/stores/messaging_install_store.py
+++ b/core/switch_core/db/stores/messaging_install_store.py
@@ -46,6 +46,16 @@ class MessagingInstallStateError(RuntimeError):
"""A state could not be redeemed: already used, expired, or not ours."""
+class MessagingInstallNotFound(RuntimeError):
+ """No install of that id is visible to the tenant bound on this session.
+
+ "Not visible" rather than "does not exist", and the two are deliberately
+ not distinguished: the reads here are scoped, so an id belonging to
+ another tenant misses exactly as an invented one does. Telling them apart
+ would be a way to ask whether an id exists elsewhere.
+ """
+
+
class MessagingInstallStore:
async def start_install(
self, session: AsyncSession, *, platform: str, user_id: str
@@ -171,13 +181,78 @@ class MessagingInstallStore:
)
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)
+ if install is None:
+ raise MessagingInstallNotFound(
+ f"no install {install_id} belongs to this organisation"
+ )
+ return install
+
+ async def list_for_tenant(self, session: AsyncSession) -> list[MessagingInstall]:
+ """Every install this tenant has ever made, newest first.
+
+ Ended ones included, and that is the point of the method rather than a
+ side effect. An operator looking at this list is usually looking at it
+ because something stopped working, and a list of only the live installs
+ answers "there is nothing here" to the question "what happened to the
+ one that was here yesterday".
+ """
+ result = await session.execute(
+ select(MessagingInstall).order_by(
+ MessagingInstall.installed_at.desc(), MessagingInstall.id
+ )
+ )
+ return list(result.scalars())
+
+ async def end(
+ self, session: AsyncSession, *, install_id: str, status: str
+ ) -> MessagingInstall:
+ """Mark an install finished, and discard the credential and bridge with it.
+
+ `status` says which of the two ways it ended — see
+ `INSTALL_DISCONNECTED` and `INSTALL_REVOKED`. Anything else is a
+ programming error rather than a state the column may hold: the
+ uniqueness index reads `status = 'active'`, so a typo here would leave
+ a row that is neither serving nor releasing its workspace.
+
+ **Ending an install twice is success.** The platform retries the event
+ that says an app was uninstalled, and an operator can click disconnect
+ on a row a retry has already ended; both must reach the same place.
+ That is also why this is an ordinary read-then-write rather than the
+ single conditional statement `redeem_state` uses — there is no race to
+ lose here, because two writers racing to end the same install both want
+ what the other is doing.
+ """
+ if status not in (INSTALL_DISCONNECTED, INSTALL_REVOKED):
+ raise ValueError(
+ f"{status!r} is not a way an install can end; expected "
+ f"{INSTALL_DISCONNECTED!r} or {INSTALL_REVOKED!r}"
+ )
+ install = await self.get(session, install_id=install_id)
+ if install.status != INSTALL_ACTIVE:
+ return install
+
+ install.status = status
+ install.ended_at = datetime.now(UTC)
+ # The token is worthless the moment the platform is told so, and a
+ # worthless credential still reads like a live one to whoever finds
+ # the dump. Keeping the row is the record; keeping the secret is not
+ # part of it.
+ install.encrypted_bot_token = None
+ # And the pointer goes with it, because the bridge is about to. The
+ # foreign key has no `ON DELETE`, so a row still naming the bridge is
+ # what would refuse its deletion.
+ install.bridge_id = None
+ await session.flush()
+ return install
+
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 = await self.get(session, install_id=install_id)
install.bridge_id = bridge_id
await session.flush()
return install
diff --git a/core/tests/switch_core/bridges/collaboration/test_install_service.py b/core/tests/switch_core/bridges/collaboration/test_install_service.py
index 9f8897369..c7f0252f6 100644
--- a/core/tests/switch_core/bridges/collaboration/test_install_service.py
+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py
@@ -26,6 +26,7 @@ from switch_core.bridges.collaboration.install import (
InstallGrant,
MessagingAppInstaller,
MessagingInstallerRegistry,
+ MessagingInstallError,
WebhookEndpoint,
)
from switch_core.bridges.collaboration.install_service import (
@@ -47,7 +48,11 @@ from switch_core.db.models import (
)
from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.messaging_install_store import (
+ INSTALL_ACTIVE,
+ INSTALL_DISCONNECTED,
+ INSTALL_REVOKED,
MessagingInstallClaimedError,
+ MessagingInstallNotFound,
MessagingInstallStateError,
MessagingInstallStore,
)
@@ -67,6 +72,8 @@ class _FakeInstaller(MessagingAppInstaller):
def __init__(self, workspace_id: str) -> None:
self.workspace_id = workspace_id
self.redeem_calls: list[str] = []
+ self.revoked_tokens: list[str] = []
+ self.revoke_error: Exception | None = None
def authorize_url(self, *, state: str, redirect_uri: str) -> str:
return f"https://platform.example/authorize?state={state}"
@@ -80,6 +87,19 @@ class _FakeInstaller(MessagingAppInstaller):
scopes="chat:write",
)
+ async def revoke(self, *, bot_token: str) -> None:
+ if self.revoke_error is not None:
+ raise self.revoke_error
+ self.revoked_tokens.append(bot_token)
+
+ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:
+ event = payload.get("event")
+ if not isinstance(event, dict):
+ return None
+ if event.get("type") == "app_uninstalled":
+ return "the app was removed"
+ return None
+
def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:
return None
@@ -110,6 +130,7 @@ class _FakeLifecycle:
self._tenant_id = tenant_id
self._suffix = suffix
self.registered: list[dict[str, object]] = []
+ self.removed: list[str] = []
async def register(self, **kwargs: object) -> CollaborationBridge:
self.registered.append(kwargs)
@@ -134,6 +155,20 @@ class _FakeLifecycle:
await session.commit()
return CollaborationBridge(id=bridge_id)
+ async def remove(self, bridge_id: str) -> None:
+ """Delete the row, not just record the call.
+
+ The install points at the bridge through a foreign key with no
+ `ON DELETE`, so a stub that only counted removals would let a caller
+ that forgot to release the pointer pass here and fail in production.
+ """
+ self.removed.append(bridge_id)
+ async with tenant_session(self._factory, self._tenant_id) as session:
+ bridge = await session.get(CollaborationBridge, bridge_id)
+ if bridge is not None:
+ await session.delete(bridge)
+ await session.commit()
+
class _Fixture:
def __init__(self) -> None:
@@ -187,6 +222,23 @@ async def _begin(factory: async_sessionmaker, fixture: _Fixture, tenant_id: str)
return parse_qs(urlparse(url).query)["state"][0]
+async def _installed(
+ factory: async_sessionmaker, fixture: _Fixture, tenant_id: str
+) -> MessagingInstall:
+ """Run both legs and return the install they produced."""
+ state = await _begin(factory, fixture, tenant_id)
+ return await fixture.service.complete(
+ platform="slack", code="the-code", state_token=state
+ )
+
+
+async def _reread(
+ factory: async_sessionmaker, tenant_id: str, install_id: str
+) -> MessagingInstall:
+ async with tenant_session(factory, tenant_id) as session:
+ return await MessagingInstallStore().get(session, install_id=install_id)
+
+
class TestTheRoundTrip:
async def test_an_install_lands_in_the_tenant_that_started_it(
self, rls_harness: RLSHarness
@@ -359,3 +411,213 @@ class TestWhatTheCallbackWillNotDo:
platform="slack", code="the-code", state_token=state
)
assert fixture.lifecycle.registered == []
+
+
+class TestDisconnecting:
+ """An install an operator ended, and what has to be true afterwards."""
+
+ async def test_the_platform_is_told_before_anything_is_destroyed(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Deleting our copy of a token does not stop it working.
+
+ Revoking is the half only the platform can do, so a disconnect that
+ skipped it would leave a live key into a customer's workspace in every
+ backup taken before it.
+ """
+ fixture = await _fixture(rls_harness)
+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ await fixture.service.disconnect(
+ tenant_id=fixture.tenant_a, install_id=install.id
+ )
+
+ assert fixture.installer.revoked_tokens == ["xoxb-granted"]
+
+ async def test_it_leaves_no_credential_and_no_bridge(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+ bridge_id = install.bridge_id
+
+ ended = await fixture.service.disconnect(
+ tenant_id=fixture.tenant_a, install_id=install.id
+ )
+
+ assert ended.status == INSTALL_DISCONNECTED
+ assert ended.ended_at is not None
+ assert ended.encrypted_bot_token is None
+ assert ended.bridge_id is None
+ assert fixture.lifecycle.removed == [bridge_id]
+
+ async def test_the_workspace_can_be_installed_again(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The reason the uniqueness index is partial.
+
+ A customer who disconnects and changes their mind must be able to
+ click Add to Slack again, and a row that went on occupying the
+ workspace would mean nobody ever could.
+ """
+ fixture = await _fixture(rls_harness)
+ first = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+ await fixture.service.disconnect(
+ tenant_id=fixture.tenant_a, install_id=first.id
+ )
+
+ second = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ assert second.id != first.id
+ assert second.status == INSTALL_ACTIVE
+ assert second.bridge_id is not None
+
+ async def test_disconnecting_twice_is_success(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """An operator can click it on a row the platform ended a second ago."""
+ fixture = await _fixture(rls_harness)
+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+ await fixture.service.disconnect(
+ tenant_id=fixture.tenant_a, install_id=install.id
+ )
+
+ again = await fixture.service.disconnect(
+ tenant_id=fixture.tenant_a, install_id=install.id
+ )
+
+ assert again.status == INSTALL_DISCONNECTED
+ assert fixture.installer.revoked_tokens == ["xoxb-granted"]
+ assert len(fixture.lifecycle.removed) == 1
+
+ async def test_a_refusal_nobody_understands_leaves_the_install_intact(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Which is the whole reason the platform is told first.
+
+ The operator sees the failure and can try again; the alternative is a
+ bridge already gone and a token still valid.
+ """
+ fixture = await _fixture(rls_harness)
+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+ fixture.installer.revoke_error = MessagingInstallError("Slack said no")
+
+ with pytest.raises(MessagingInstallError):
+ await fixture.service.disconnect(
+ tenant_id=fixture.tenant_a, install_id=install.id
+ )
+
+ still = await _reread(rls_harness.restricted, fixture.tenant_a, install.id)
+ assert still.status == INSTALL_ACTIVE
+ assert still.encrypted_bot_token is not None
+ assert still.bridge_id is not None
+ assert fixture.lifecycle.removed == []
+
+ async def test_another_tenants_install_is_not_disconnectable(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """And misses the way an invented id would, telling the caller nothing."""
+ fixture = await _fixture(rls_harness)
+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ with pytest.raises(MessagingInstallNotFound):
+ await fixture.service.disconnect(
+ tenant_id=fixture.tenant_b, install_id=install.id
+ )
+
+ assert fixture.installer.revoked_tokens == []
+
+
+class TestThePlatformEndingIt:
+ async def test_an_uninstall_event_ends_the_install(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ await fixture.service.revoked(
+ platform="slack",
+ workspace_id=fixture.workspace,
+ reason="the app was removed",
+ )
+
+ ended = await _reread(rls_harness.restricted, fixture.tenant_a, install.id)
+ assert ended.status == INSTALL_REVOKED
+ assert ended.encrypted_bot_token is None
+ assert ended.bridge_id is None
+ assert fixture.lifecycle.removed == [install.bridge_id]
+
+ async def test_nothing_is_revoked_at_a_platform_that_already_did_it(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ await fixture.service.revoked(
+ platform="slack",
+ workspace_id=fixture.workspace,
+ reason="the app was removed",
+ )
+
+ assert fixture.installer.revoked_tokens == []
+
+ async def test_a_retried_event_is_not_an_error(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Slack redelivers, so the second one arrives after the workspace is free."""
+ fixture = await _fixture(rls_harness)
+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+ await fixture.service.revoked(
+ platform="slack", workspace_id=fixture.workspace, reason="removed"
+ )
+
+ await fixture.service.revoked(
+ platform="slack", workspace_id=fixture.workspace, reason="removed"
+ )
+
+ assert len(fixture.lifecycle.removed) == 1
+
+ async def test_a_workspace_nobody_installed_is_ignored(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+
+ await fixture.service.revoked(
+ platform="slack", workspace_id="T-nobody", reason="removed"
+ )
+
+ assert fixture.lifecycle.removed == []
+
+
+class TestWhatTheOperatorSees:
+ async def test_the_list_keeps_installs_that_ended(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """A list of only the live ones answers "nothing here" to "what happened
+ to the one that was here yesterday"."""
+ fixture = await _fixture(rls_harness)
+ first = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+ await fixture.service.disconnect(
+ tenant_id=fixture.tenant_a, install_id=first.id
+ )
+ second = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:
+ listed = await MessagingInstallStore().list_for_tenant(session)
+
+ assert {install.id for install in listed} == {first.id, second.id}
+ assert {install.status for install in listed} == {
+ INSTALL_ACTIVE,
+ INSTALL_DISCONNECTED,
+ }
+
+ async def test_the_list_is_the_bound_tenants_own(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)
+
+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:
+ listed = await MessagingInstallStore().list_for_tenant(session)
+
+ assert listed == []