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(collaboration): route inbound platform events to the installing tenant

Petr Bauch5128e71fd13b
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index e4df7bea6..36e16f7d4 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -5,7 +5,7 @@ import logging
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, replace
-from typing import ClassVar
+from typing import Any, ClassVar
from switch_core.agent_display_name import defuse_label_markup
from switch_core.agent_icon import default_icon_url
@@ -20,6 +20,7 @@ from switch_core.bridges.collaboration.models import (
InboundMessage,
InboundUserJoin,
OutboundAttachment,
+ WebhookDeliveryUnsupported,
)
logger = logging.getLogger(__name__)
@@ -248,6 +249,29 @@ class CollaborationAdapter(ABC):
@abstractmethod
async def stop(self) -> None: ...
+ async def dispatch_event(
+ self, *, envelope_type: str, payload: dict[str, Any]
+ ) -> None:
+ """Handle one event that arrived over the public webhook.
+
+ Concrete on the base and raising, rather than abstract, because
+ receiving events over HTTP is a property of a platform and of which app
+ a bridge's token came from — most adapters dial out and are handed
+ their events on a connection they opened, and have nothing to override
+ here.
+
+ Raising rather than returning quietly matters: the caller is a route
+ that has already proved the request genuine and resolved which bridge
+ it belongs to, so reaching an adapter that cannot take it means a
+ workspace's traffic is being delivered nowhere. Silence there is the
+ failure that reads as "the platform has gone quiet".
+ """
+ raise WebhookDeliveryUnsupported(
+ f"{type(self).__name__} does not receive events over HTTP, so the "
+ "event posted for this bridge cannot be delivered. A bridge reached "
+ "this way was installed as a distributed app; this one was not."
+ )
+
@abstractmethod
async def send_message(
self,
diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.py
index bd80a4bda..62b7012a8 100644
--- a/core/switch_core/bridges/collaboration/install.py
+++ b/core/switch_core/bridges/collaboration/install.py
@@ -35,7 +35,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Mapping
from dataclasses import dataclass
-from typing import ClassVar
+from typing import Any, ClassVar, Literal
#: The public prefix every install endpoint hangs off.
#:
@@ -101,6 +101,51 @@ class WebhookAuthenticityError(RuntimeError):
"""
+class WebhookPayloadError(RuntimeError):
+ """A webhook proved genuine and then could not be read.
+
+ Distinct from :class:`WebhookAuthenticityError` because it says something
+ entirely different: the signature checked out, so this really is the
+ platform, and what it sent is a shape this build does not know. That is a
+ fault worth seeing in a log — an unrecognised body is how a platform's
+ change first shows up — where a bad signature is just the internet.
+ """
+
+
+#: Which of a platform's inbound endpoints a request arrived on.
+#:
+#: Three, because that is what the platforms ask for and what the app manifests
+#: declare: events, interactivity, and slash commands. They are separate URLs
+#: rather than one, because a platform decides that, not us — and they carry
+#: genuinely different bodies (Slack posts JSON to the first and a form to the
+#: other two), which is why the endpoint is an argument to parsing rather than
+#: something a handler could infer.
+WebhookEndpoint = Literal["events", "interactive", "commands"]
+
+
+@dataclass(frozen=True)
+class InboundWebhook:
+ """One authenticated inbound event, in the shape a running adapter takes.
+
+ `envelope_type` and `payload` are deliberately the two arguments Socket
+ Mode's own listener is handed, so an event that arrived over HTTP and the
+ same event over a socket reach `dispatch_event` indistinguishable from one
+ another. Anything that made them differ would be two code paths for one
+ behaviour, drifting apart at the speed of whichever gets used more.
+
+ `handshake` is the exception, and it is not an event at all: a platform
+ proving the URL it was given is really ours (Slack's `url_verification`)
+ expects a specific string echoed straight back and nothing dispatched. It
+ is `None` for every real event, and it arrives before any workspace has
+ installed anything — so it must be answerable with no tenant, no install
+ row, and nothing running.
+ """
+
+ envelope_type: str
+ payload: dict[str, Any]
+ handshake: str | None
+
+
@dataclass(frozen=True)
class InstallGrant:
"""What the platform handed back when a workspace installed us.
@@ -173,14 +218,31 @@ class MessagingAppInstaller(ABC):
:class:`WebhookAuthenticityError`.
"""
+ @abstractmethod
+ def parse_webhook(
+ self, *, endpoint: WebhookEndpoint, body: bytes
+ ) -> InboundWebhook:
+ """Read a verified request body into an event a running adapter takes.
+
+ Called only after :meth:`verify_webhook` has passed, and separate from
+ it for exactly that reason: parsing before verifying is how an
+ unauthenticated body gets to choose which code runs.
+
+ Takes the raw bytes rather than a parsed payload because only this
+ method knows the encoding, which is per platform and per endpoint —
+ Slack posts JSON to one of its three and form data to the other two.
+
+ Raise :class:`WebhookPayloadError` for a body that cannot be read.
+ """
+
@abstractmethod
def workspace_of_event(self, payload: Mapping[str, object]) -> str:
"""Which workspace an authenticated event came from.
The answer is what resolves a tenant, so this runs on a request with
nothing bound and must not touch the database. Raise
- :class:`WebhookAuthenticityError` for a payload that names no
- workspace: an event we cannot route is not an event we may guess at.
+ :class:`WebhookPayloadError` for a payload that names no workspace: an
+ event we cannot route is not an event we may guess at.
"""
@abstractmethod
diff --git a/core/switch_core/bridges/collaboration/install_routes.py b/core/switch_core/bridges/collaboration/install_routes.py
index 38a6dd855..5c7029a7d 100644
--- a/core/switch_core/bridges/collaboration/install_routes.py
+++ b/core/switch_core/bridges/collaboration/install_routes.py
@@ -1,4 +1,10 @@
-"""The public half of an install: the callback the platform redirects back to.
+"""The public half of an install: the OAuth callback, and the events after it.
+
+Everything here is unauthenticated in the sense that matters — no caller holds
+a credential of ours. A browser mid-redirect proves itself with a state we
+signed; a platform posting an event proves itself with a signature over the
+raw body. Neither is a session, and nothing here may assume a tenant before it
+has established one.
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
@@ -12,6 +18,9 @@ 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.
+
+The event routes answer nobody who reads English, so they answer in status
+codes and say the rest in the log.
"""
from __future__ import annotations
@@ -19,16 +28,23 @@ from __future__ import annotations
import html
import logging
-from fastapi import APIRouter, Query
-from starlette.responses import HTMLResponse
+from fastapi import APIRouter, BackgroundTasks, Query, Request, Response
+from starlette.responses import HTMLResponse, PlainTextResponse
from switch_core.bridges.collaboration.install import (
PUBLIC_PATH_PREFIX,
+ InboundWebhook,
MessagingInstallError,
+ WebhookAuthenticityError,
+ WebhookEndpoint,
+ WebhookPayloadError,
)
from switch_core.bridges.collaboration.install_service import (
InstallPlatformMismatch,
MessagingInstallService,
+ WebhookBridgeUnavailable,
+ WebhookTarget,
+ WebhookWorkspaceUnknown,
)
from switch_core.bridges.collaboration.install_state import InstallStateError
from switch_core.db.stores.messaging_install_store import (
@@ -142,4 +158,113 @@ def create_messaging_install_router(
status=200,
)
+ async def _deliver(target: WebhookTarget, event: InboundWebhook) -> None:
+ """Handle one event after the platform has been answered.
+
+ Its own wrapper so a failure is logged here rather than raised into the
+ server's background-task machinery, where it would surface — if at all
+ — as an unattributed traceback with nothing in it naming the bridge.
+ """
+ try:
+ await service.deliver(target, event)
+ except Exception:
+ logger.exception(
+ "Failed to handle a %s event for bridge %s (tenant %s)",
+ event.envelope_type,
+ target.bridge_id,
+ target.tenant_id,
+ )
+
+ async def _inbound(
+ platform: str,
+ endpoint: WebhookEndpoint,
+ request: Request,
+ background: BackgroundTasks,
+ ) -> Response:
+ """One verified event, from any of a platform's three inbound URLs.
+
+ The status codes are read by the platform, not by a person, and they
+ are chosen for what it does with them. Slack retries a 5xx and gives up
+ on a 4xx, and counts failures against the app as a whole — so a
+ permanent condition must not look transient, and a transient one must
+ not look permanent.
+ """
+ body = await request.body()
+ try:
+ event = service.authenticate(
+ platform=platform,
+ endpoint=endpoint,
+ headers=dict(request.headers),
+ body=body,
+ )
+ except MessagingInstallError:
+ # No app registered for this platform, so nothing here could have
+ # signed anything. Not found rather than an explanation: the caller
+ # is unauthenticated and learns only that there is nothing here.
+ return Response(status_code=404)
+ except WebhookAuthenticityError as failure:
+ logger.warning("Refused an unverified %s webhook: %s", platform, failure)
+ return Response(status_code=401)
+ except WebhookPayloadError as failure:
+ # Verified, so this really is the platform sending something this
+ # build cannot read. Worth an error rather than a shrug — it is how
+ # a platform's change to its own payloads first becomes visible.
+ logger.error("Could not read a verified %s webhook: %s", platform, failure)
+ return Response(status_code=400)
+
+ if event.handshake is not None:
+ logger.info("Answered a %s URL verification", platform)
+ return PlainTextResponse(event.handshake)
+
+ try:
+ target = await service.resolve(platform=platform, event=event)
+ except WebhookPayloadError as failure:
+ logger.error(
+ "A verified %s event named no workspace: %s", platform, failure
+ )
+ return Response(status_code=400)
+ except WebhookWorkspaceUnknown as failure:
+ logger.warning("Dropped a %s event: %s", platform, failure)
+ return Response(status_code=404)
+ 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 message
+ # on the floor and report that it had been handled.
+ logger.error("Could not deliver a %s event: %s", platform, failure)
+ return Response(status_code=503)
+
+ # Answered first, handled after. The platform's deadline is short and
+ # what happens next is not bounded by it — a turn can take minutes —
+ # so acknowledging on the way out is what keeps a slow room from
+ # becoming a retried, duplicated one.
+ background.add_task(_deliver, target, event)
+ return Response(status_code=200)
+
+ @router.post("/{platform}/events")
+ async def events(
+ platform: str, request: Request, background: BackgroundTasks
+ ) -> Response:
+ return await _inbound(platform, "events", request, background)
+
+ @router.post("/{platform}/interactive")
+ async def interactive(
+ platform: str, request: Request, background: BackgroundTasks
+ ) -> Response:
+ """Interactions with a message this app posted.
+
+ Routed like any other event and, on Slack today, handled by nothing:
+ the app declares an interactivity URL because features it does use
+ require one, and its stop button arrives as an ordinary event instead.
+ The route exists because the URL is declared — a declared URL that 404s
+ counts against the app — and because the alternative is deciding here,
+ rather than in the adapter, what a platform's interactions mean.
+ """
+ return await _inbound(platform, "interactive", request, background)
+
+ @router.post("/{platform}/commands")
+ async def commands(
+ platform: str, request: Request, background: BackgroundTasks
+ ) -> Response:
+ return await _inbound(platform, "commands", request, background)
+
return router
diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.py
index 74601a8c8..55c37b5bc 100644
--- a/core/switch_core/bridges/collaboration/install_service.py
+++ b/core/switch_core/bridges/collaboration/install_service.py
@@ -31,12 +31,17 @@ allows for.
from __future__ import annotations
import logging
+from collections.abc import Mapping
+from dataclasses import dataclass
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.bridges.collaboration.adapter import CollaborationAdapter
from switch_core.bridges.collaboration.install import (
+ InboundWebhook,
MessagingAppInstaller,
MessagingInstallerRegistry,
+ WebhookEndpoint,
oauth_callback_path,
public_url,
)
@@ -52,11 +57,40 @@ 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
+from switch_core.db.tenant_lookup import tenant_of_messaging_install
+from switch_core.tenant_context import no_tenant, tenant_scope
logger = logging.getLogger(__name__)
+class WebhookWorkspaceUnknown(RuntimeError):
+ """An authentic event named a workspace no tenant here has installed.
+
+ Ordinary rather than alarming: an app left in a workspace whose install was
+ removed 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.
+ """
+
+
+class WebhookBridgeUnavailable(RuntimeError):
+ """The workspace resolves to a tenant, and nothing is running to take it.
+
+ Transient by nature — a bridge mid-restart, or one that has not been built
+ for a recorded install yet — so it is worth telling the platform to try
+ again rather than swallowing the event.
+ """
+
+
+@dataclass(frozen=True)
+class WebhookTarget:
+ """Where one verified event goes: a tenant, a bridge, and its live adapter."""
+
+ tenant_id: str
+ bridge_id: str
+ adapter: CollaborationAdapter
+
+
class InstallPlatformMismatch(RuntimeError):
"""A state minted for one platform arrived at another's callback.
@@ -194,3 +228,100 @@ class MessagingInstallService:
bridge.id,
)
return attached
+
+ # ── Inbound events ───────────────────────────────────────────────────────
+ #
+ # The other direction, and the one that runs constantly. Three steps, kept
+ # separate because each answers to something different:
+ #
+ # `authenticate` is pure and does no I/O, so a request that cannot prove
+ # itself is refused without this deployment doing any work on its behalf.
+ # `resolve` is two indexed reads and decides *whose* event this is.
+ # `deliver` is the handling, which can take as long as the work takes.
+ #
+ # The split is what lets the route acknowledge in time. Slack gives three
+ # seconds and retries what it does not get an answer to, so a handler that
+ # posts to Matrix before replying turns one slow room into duplicate
+ # messages. Everything up to and including `resolve` is fast enough to
+ # answer inside, and `deliver` runs after the response has gone.
+
+ def authenticate(
+ self,
+ *,
+ platform: str,
+ endpoint: WebhookEndpoint,
+ headers: Mapping[str, str],
+ body: bytes,
+ ) -> InboundWebhook:
+ """Prove an inbound request came from the platform, and read it.
+
+ Verification is first and unconditional. Nothing above it inspects the
+ body, so an unsigned request cannot pick which parser runs, and nothing
+ is logged from it either — it is a stranger's bytes until this passes.
+ """
+ installer = self._installers.get(platform)
+ installer.verify_webhook(headers=headers, body=body)
+ return installer.parse_webhook(endpoint=endpoint, body=body)
+
+ async def resolve(self, *, platform: str, event: InboundWebhook) -> WebhookTarget:
+ """Turn a workspace id into the one bridge entitled to the event.
+
+ The tenant comes from the exempt lookup (`db/tenant_lookup.py`), which
+ is the only way to answer it: the caller authenticated to nothing, and
+ every table that could say is scoped. The install row is then read
+ *again* under that tenant rather than returned by the lookup — a
+ deliberate second check, so a wrong answer above is a miss here instead
+ of a cross-tenant read.
+ """
+ installer = self._installers.get(platform)
+ workspace_id = installer.workspace_of_event(event.payload)
+
+ tenant_id = await tenant_of_messaging_install(
+ self._session_factory, platform, workspace_id
+ )
+ if tenant_id is None:
+ raise WebhookWorkspaceUnknown(
+ f"no tenant has installed Switch into {platform} workspace "
+ f"{workspace_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:
+ raise WebhookWorkspaceUnknown(
+ f"the install of {platform} workspace {workspace_id} resolved to "
+ f"tenant {tenant_id} and could not then be read as that tenant"
+ )
+ if install.bridge_id is None:
+ raise WebhookBridgeUnavailable(
+ f"the install of {platform} workspace {workspace_id} has no "
+ "bridge yet, so there is nothing to deliver its events to"
+ )
+
+ adapter = self._lifecycle.get_adapter(install.bridge_id)
+ if adapter is None:
+ raise WebhookBridgeUnavailable(
+ f"bridge {install.bridge_id}, which serves {platform} workspace "
+ f"{workspace_id}, is not running"
+ )
+ return WebhookTarget(
+ tenant_id=tenant_id, bridge_id=install.bridge_id, adapter=adapter
+ )
+
+ async def deliver(self, target: WebhookTarget, event: InboundWebhook) -> None:
+ """Hand a resolved event to the bridge, as its own transport would.
+
+ With **nothing bound**, which is not an oversight. A bridge that
+ receives over a socket dispatches from a task that binds no tenant, and
+ every handler below it binds the tenant of the room it is acting on.
+ Binding here would make the two delivery paths differ in the one
+ respect that decides who a message reaches, and would hide a handler
+ that had forgotten to bind for itself — for exactly as long as it took
+ someone to receive the same event over a socket instead.
+ """
+ with no_tenant():
+ await target.adapter.dispatch_event(
+ envelope_type=event.envelope_type, payload=event.payload
+ )
diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.py
index 054369cde..94eb44f6a 100644
--- a/core/switch_core/bridges/collaboration/models.py
+++ b/core/switch_core/bridges/collaboration/models.py
@@ -17,6 +17,17 @@ class ChannelCreationUnsupported(ValueError):
"""
+class WebhookDeliveryUnsupported(RuntimeError):
+ """A verified inbound event was routed to a bridge that cannot take one.
+
+ Only reachable when a bridge is recorded as serving an installed workspace
+ and its adapter receives events some other way — so it is a deployment
+ inconsistency rather than anything the sender did, and it is raised rather
+ than logged-and-dropped so the route answers with a failure the platform's
+ own delivery log records.
+ """
+
+
class Attachment(BaseModel):
"""An inbound file attachment of any type, with its raw bytes.
diff --git a/core/switch_core/bridges/collaboration/slack/install.py b/core/switch_core/bridges/collaboration/slack/install.py
index 2a3922994..492e8891b 100644
--- a/core/switch_core/bridges/collaboration/slack/install.py
+++ b/core/switch_core/bridges/collaboration/slack/install.py
@@ -15,26 +15,59 @@ the boundary and has no equivalent on the adapter.
from __future__ import annotations
+import json
import logging
from collections.abc import Mapping
-from typing import ClassVar
-from urllib.parse import urlencode
+from typing import Any, ClassVar
+from urllib.parse import parse_qsl, urlencode
from slack_sdk.errors import SlackApiError
from slack_sdk.signature import SignatureVerifier
from slack_sdk.web.async_client import AsyncWebClient
from switch_core.bridges.collaboration.install import (
+ InboundWebhook,
InstallGrant,
MessagingAppInstaller,
MessagingInstallError,
WebhookAuthenticityError,
+ WebhookEndpoint,
+ WebhookPayloadError,
)
logger = logging.getLogger(__name__)
AUTHORIZE_URL = "https://slack.com/oauth/v2/authorize"
+
+def _json_object(raw: bytes) -> dict[str, Any]:
+ try:
+ parsed = json.loads(raw)
+ except ValueError as error:
+ raise WebhookPayloadError("Slack posted a body that is not JSON") from error
+ if not isinstance(parsed, dict):
+ raise WebhookPayloadError("Slack posted JSON that is not an object")
+ return parsed
+
+
+def _form_fields(raw: bytes) -> dict[str, Any]:
+ """Slack's form encoding as a flat dict, matching Socket Mode's payload.
+
+ `parse_qsl` and not `parse_qs`: the latter makes every value a list, and
+ the adapter reads these fields as the strings Socket Mode hands it. A
+ repeated field would be a Slack change worth noticing rather than a list to
+ accommodate, and the last value wins the way a form is usually read.
+ """
+ try:
+ return dict(
+ parse_qsl(raw.decode(), keep_blank_values=True, strict_parsing=True)
+ )
+ except (UnicodeDecodeError, ValueError) as error:
+ raise WebhookPayloadError(
+ "Slack posted a body that is not form data"
+ ) from error
+
+
#: The bot scopes the distributed app requests, in the manifest's order.
#:
#: Identical to the self-registered app's: the two apps differ in how they are
@@ -141,10 +174,66 @@ class SlackAppInstaller(MessagingAppInstaller):
if not valid:
raise WebhookAuthenticityError("bad Slack signature")
+ def parse_webhook(
+ self, *, endpoint: WebhookEndpoint, body: bytes
+ ) -> InboundWebhook:
+ if endpoint == "commands":
+ # A slash command posts its fields as a form, and Socket Mode
+ # delivers that same flat dict — so the parsed form *is* the
+ # payload, with no unwrapping.
+ return InboundWebhook(
+ envelope_type="slash_commands",
+ payload=_form_fields(body),
+ handshake=None,
+ )
+
+ if endpoint == "interactive":
+ # Nested once: the form carries a single `payload` field whose
+ # value is JSON.
+ raw = _form_fields(body).get("payload")
+ if not raw:
+ raise WebhookPayloadError(
+ "Slack posted an interaction with no payload field"
+ )
+ return InboundWebhook(
+ envelope_type="interactive",
+ payload=_json_object(raw.encode()),
+ handshake=None,
+ )
+
+ envelope = _json_object(body)
+ if envelope.get("type") == "url_verification":
+ # Slack proving the URL is ours, at the moment the Request URL is
+ # saved. It is signed like any other post, so it reaches here
+ # having been verified — and it names no workspace, because none
+ # has installed anything yet.
+ challenge = envelope.get("challenge")
+ if not isinstance(challenge, str) or not challenge:
+ raise WebhookPayloadError(
+ "Slack sent a URL verification with no challenge to echo"
+ )
+ return InboundWebhook(
+ envelope_type="url_verification", payload=envelope, handshake=challenge
+ )
+
+ return InboundWebhook(
+ envelope_type="events_api", payload=envelope, handshake=None
+ )
+
def workspace_of_event(self, payload: Mapping[str, object]) -> str:
+ """Which workspace an event came from, over Slack's two spellings.
+
+ An event callback and a slash command name it flat, as `team_id`; an
+ interaction nests it under `team`. Both are read here rather than
+ normalised at parse time, because the payload handed to the adapter has
+ to stay byte-identical to the one Socket Mode delivers.
+ """
workspace_id = payload.get("team_id")
if not isinstance(workspace_id, str) or not workspace_id:
- raise WebhookAuthenticityError("Slack event names no workspace")
+ team = payload.get("team")
+ workspace_id = team.get("id") if isinstance(team, dict) else None
+ if not isinstance(workspace_id, str) or not workspace_id:
+ raise WebhookPayloadError("Slack event names no workspace")
return workspace_id
def connection_config(self, grant: InstallGrant) -> dict[str, object]:
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 aec860c6b..9f8897369 100644
--- a/core/tests/switch_core/bridges/collaboration/test_install_service.py
+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py
@@ -22,9 +22,11 @@ import pytest
from sqlalchemy.ext.asyncio import async_sessionmaker
from switch_core.bridges.collaboration.install import (
+ InboundWebhook,
InstallGrant,
MessagingAppInstaller,
MessagingInstallerRegistry,
+ WebhookEndpoint,
)
from switch_core.bridges.collaboration.install_service import (
InstallPlatformMismatch,
@@ -81,6 +83,11 @@ class _FakeInstaller(MessagingAppInstaller):
def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:
return None
+ def parse_webhook(
+ self, *, endpoint: WebhookEndpoint, body: bytes
+ ) -> InboundWebhook:
+ return InboundWebhook(envelope_type=endpoint, payload={}, handshake=None)
+
def workspace_of_event(self, payload: Mapping[str, object]) -> str:
return self.workspace_id
diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py
new file mode 100644
index 000000000..f7d346af0
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py
@@ -0,0 +1,537 @@
+"""An event from an installed workspace, from the wire to the right bridge.
+
+This is the half of multi-tenancy that has no session to lean on. A Slack post
+arrives at one public URL shared by every tenant on the deployment, carrying no
+credential of ours, and something has to decide whose it is. Everything that
+decides it is here: the signature, the workspace id in the payload, and the
+lookup from that workspace to a tenant.
+
+Two tenants exist in every fixture below, each with the app installed into its
+own workspace, and the assertion that matters is the same one each time: an
+event for one of them reaches that one's bridge and **no part of it reaches the
+other's**. A test with a single tenant would pass against a router that ignored
+the payload entirely.
+
+Real Postgres, the restricted role, and the real Slack installer — including
+the real signature check. What is faked is only what would otherwise open a
+socket: the bridge lifecycle and the adapter at the end of it.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+import time
+import uuid
+from dataclasses import dataclass
+from typing import Any
+from urllib.parse import urlencode
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from sqlalchemy.ext.asyncio import async_sessionmaker
+
+from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.install import (
+ MessagingInstallerRegistry,
+ commands_path,
+ events_path,
+ interactive_path,
+)
+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.slack.install import SlackAppInstaller
+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 MessagingInstallStore
+from switch_core.tenant_context import current_tenant_id
+from tests.conftest import RLSHarness
+
+pytestmark = pytest.mark.no_ambient_tenant
+
+_SIGNING_SECRET = "test-signing-secret"
+_SECRET = "test-secret"
+_ORIGIN = "https://switch.example"
+
+
+def _signed(body: bytes) -> dict[str, str]:
+ timestamp = str(int(time.time()))
+ digest = hmac.new(
+ _SIGNING_SECRET.encode(),
+ b"v0:" + timestamp.encode() + b":" + body,
+ hashlib.sha256,
+ ).hexdigest()
+ return {
+ "X-Slack-Request-Timestamp": timestamp,
+ "X-Slack-Signature": f"v0={digest}",
+ "Content-Type": "application/json",
+ }
+
+
+class _SocketOnlyAdapter(CollaborationAdapter):
+ """A bridge that takes its events some other way.
+
+ Concrete only so one can be built; every platform call is a stub, because
+ nothing on the webhook path may reach one. It inherits `dispatch_event`
+ from the base — the refusal — which is the behaviour one test below is
+ about.
+ """
+
+ def __init__(self) -> None: ...
+
+ async def start(self, *a: Any, **k: Any) -> Any: ...
+ async def stop(self, *a: Any, **k: Any) -> Any: ...
+ async def send_message(self, *a: Any, **k: Any) -> Any: ...
+ async def send_typing(self, *a: Any, **k: Any) -> Any: ...
+ async def update_message(self, *a: Any, **k: Any) -> Any: ...
+ async def delete_message(self, *a: Any, **k: Any) -> Any: ...
+ async def create_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def get_channel_type(self, *a: Any, **k: Any) -> Any: ...
+ async def get_channel_agent_names(self, *a: Any, **k: Any) -> Any: ...
+ async def add_agents_to_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def add_users_to_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...
+ async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...
+ def translate_inbound(self, *a: Any, **k: Any) -> Any: ...
+ def translate_outbound(self, *a: Any, **k: Any) -> Any: ...
+
+
+class _RecordingAdapter(_SocketOnlyAdapter):
+ """An adapter that only remembers what it was handed.
+
+ It also records the tenant bound at the moment of dispatch, which is the
+ subject of one of the tests below: the answer has to be "none", the same as
+ it is under Socket Mode.
+ """
+
+ def __init__(self) -> None:
+ self.dispatched: list[tuple[str, dict[str, Any]]] = []
+ self.tenants_bound: list[str | None] = []
+
+ async def dispatch_event(
+ self, *, envelope_type: str, payload: dict[str, Any]
+ ) -> None:
+ self.dispatched.append((envelope_type, payload))
+ self.tenants_bound.append(current_tenant_id())
+
+
+class _FakeLifecycle:
+ def __init__(self) -> None:
+ self.adapters: dict[str, CollaborationAdapter] = {}
+
+ def get_adapter(self, bridge_id: str) -> CollaborationAdapter | None:
+ return self.adapters.get(bridge_id)
+
+
+@dataclass
+class _Workspace:
+ tenant_id: str
+ workspace_id: str
+ bridge_id: str
+ adapter: _RecordingAdapter
+
+
+class _Fixture:
+ def __init__(self, harness: RLSHarness) -> None:
+ self.harness = harness
+ self.lifecycle = _FakeLifecycle()
+ self.a: _Workspace
+ self.b: _Workspace
+ self.client: httpx.AsyncClient
+ self.service: MessagingInstallService
+
+
+async def _make_bridge(factory: async_sessionmaker, tenant_id: str, suffix: str) -> str:
+ async with tenant_session(factory, tenant_id) as session:
+ client = Client(
+ matrix_user_id=f"@bridge-{tenant_id}:{suffix}",
+ display_name="bridge",
+ type="collaboration_bridge",
+ )
+ session.add(client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name="Acme",
+ connection_config={},
+ client_id=client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ bridge_id = bridge.id
+ await session.commit()
+ return bridge_id
+
+
+async def _fixture(harness: RLSHarness) -> _Fixture:
+ fixture = _Fixture(harness)
+ suffix = uuid.uuid4().hex[:8]
+
+ async with harness.owner() as session:
+ for label in ("a", "b"):
+ tenant_id = f"tenant-{label}-{suffix}"
+ 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()
+ user_id = user.id
+ await session.commit()
+
+ workspaces = []
+ for label in ("a", "b"):
+ tenant_id = f"tenant-{label}-{suffix}"
+ workspace_id = f"T-{label}-{suffix}"
+ bridge_id = await _make_bridge(harness.restricted, tenant_id, suffix)
+ async with tenant_session(harness.restricted, tenant_id) as session:
+ session.add(
+ MessagingInstall(
+ tenant_id=tenant_id,
+ platform="slack",
+ external_workspace_id=workspace_id,
+ encrypted_bot_token="ciphertext",
+ scopes="chat:write",
+ status="active",
+ installed_by_user_id=user_id,
+ bridge_id=bridge_id,
+ )
+ )
+ await session.commit()
+ adapter = _RecordingAdapter()
+ fixture.lifecycle.adapters[bridge_id] = adapter
+ workspaces.append(
+ _Workspace(
+ tenant_id=tenant_id,
+ workspace_id=workspace_id,
+ bridge_id=bridge_id,
+ adapter=adapter,
+ )
+ )
+ fixture.a, fixture.b = workspaces
+
+ installers = MessagingInstallerRegistry()
+ installers.register(
+ SlackAppInstaller(
+ client_id="1234.5678",
+ client_secret="test-client-secret",
+ signing_secret=_SIGNING_SECRET,
+ )
+ )
+ fixture.service = MessagingInstallService(
+ session_factory=harness.restricted,
+ store=MessagingInstallStore(),
+ installers=installers,
+ lifecycle=fixture.lifecycle, # type: ignore[arg-type]
+ public_origin=_ORIGIN,
+ secret=_SECRET,
+ )
+
+ app = FastAPI()
+ app.include_router(create_messaging_install_router(fixture.service))
+ fixture.client = httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN
+ )
+ return fixture
+
+
+def _event(workspace_id: str, text: str) -> bytes:
+ return json.dumps(
+ {
+ "type": "event_callback",
+ "team_id": workspace_id,
+ "event": {"type": "message", "text": text, "channel": "C1"},
+ }
+ ).encode()
+
+
+def _texts(adapter: _RecordingAdapter) -> list[str]:
+ return [payload["event"]["text"] for _, payload in adapter.dispatched]
+
+
+async def _post(fixture: _Fixture, path: str, body: bytes) -> httpx.Response:
+ return await fixture.client.post(path, content=body, headers=_signed(body))
+
+
+class TestAnEventReachesOneTenant:
+ async def test_it_reaches_the_tenant_that_installed_the_workspace(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ body = _event(fixture.a.workspace_id, "hello")
+
+ response = await _post(fixture, events_path("slack"), body)
+
+ assert response.status_code == 200
+ assert len(fixture.a.adapter.dispatched) == 1
+ envelope_type, payload = fixture.a.adapter.dispatched[0]
+ assert envelope_type == "events_api"
+ assert payload["event"]["text"] == "hello"
+
+ async def test_it_reaches_no_other_tenant(self, rls_harness: RLSHarness) -> None:
+ """The whole point. One URL, two customers, and the payload decides.
+
+ Asserted from both directions in one test, because the failure this
+ guards against is a router that resolves the tenant once and then
+ fans out to every bridge it knows: that passes any test that only
+ looks at the intended recipient.
+ """
+ fixture = await _fixture(rls_harness)
+
+ await _post(fixture, events_path("slack"), _event(fixture.a.workspace_id, "a"))
+ await _post(fixture, events_path("slack"), _event(fixture.b.workspace_id, "b"))
+
+ assert _texts(fixture.a.adapter) == ["a"]
+ assert _texts(fixture.b.adapter) == ["b"]
+
+ async def test_nothing_is_bound_when_the_adapter_runs(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Same as Socket Mode, deliberately.
+
+ A bridge that dials out dispatches from a task with no tenant bound,
+ and every handler underneath binds the tenant of the room it is acting
+ on. Binding one here would make the two delivery paths differ in the
+ one respect that decides who a message reaches, and would hide a
+ handler that had forgotten to bind for itself.
+ """
+ fixture = await _fixture(rls_harness)
+
+ await _post(fixture, events_path("slack"), _event(fixture.a.workspace_id, "x"))
+
+ assert fixture.a.adapter.tenants_bound == [None]
+
+ async def test_a_slash_command_arrives_as_its_form_fields(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ body = urlencode(
+ {
+ "command": "/agents-status",
+ "text": "",
+ "team_id": fixture.a.workspace_id,
+ "channel_id": "C1",
+ }
+ ).encode()
+
+ response = await _post(fixture, commands_path("slack"), body)
+
+ assert response.status_code == 200
+ envelope_type, payload = fixture.a.adapter.dispatched[0]
+ assert envelope_type == "slash_commands"
+ assert payload["command"] == "/agents-status"
+
+ async def test_an_interaction_is_routed_by_its_nested_team(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Slack names the workspace differently here, and it still routes."""
+ fixture = await _fixture(rls_harness)
+ body = urlencode(
+ {
+ "payload": json.dumps(
+ {"type": "block_actions", "team": {"id": fixture.b.workspace_id}}
+ )
+ }
+ ).encode()
+
+ response = await _post(fixture, interactive_path("slack"), body)
+
+ assert response.status_code == 200
+ assert fixture.b.adapter.dispatched[0][0] == "interactive"
+ assert fixture.a.adapter.dispatched == []
+
+
+class TestWhatTheEndpointRefuses:
+ async def test_an_unsigned_post_is_refused_and_delivers_nothing(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """The first line, and the only one that runs before anything is read.
+
+ A workspace id in an unsigned body is just a string somebody typed;
+ acting on it would let anyone who knows a customer's Slack team id post
+ into their rooms.
+ """
+ fixture = await _fixture(rls_harness)
+ body = _event(fixture.a.workspace_id, "forged")
+
+ response = await fixture.client.post(
+ events_path("slack"),
+ content=body,
+ headers={"Content-Type": "application/json"},
+ )
+
+ assert response.status_code == 401
+ assert fixture.a.adapter.dispatched == []
+
+ async def test_a_signature_over_a_different_body_is_refused(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """A captured signature re-used over a payload naming another tenant."""
+ fixture = await _fixture(rls_harness)
+ captured = _signed(_event(fixture.b.workspace_id, "theirs"))
+
+ response = await fixture.client.post(
+ events_path("slack"),
+ content=_event(fixture.a.workspace_id, "mine"),
+ headers=captured,
+ )
+
+ assert response.status_code == 401
+ assert fixture.a.adapter.dispatched == []
+ assert fixture.b.adapter.dispatched == []
+
+ async def test_an_unknown_workspace_is_not_reported_as_handled(
+ 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.
+ """
+ fixture = await _fixture(rls_harness)
+
+ response = await _post(fixture, events_path("slack"), _event("T-nobody", "x"))
+
+ assert response.status_code == 404
+ assert fixture.a.adapter.dispatched == []
+ assert fixture.b.adapter.dispatched == []
+
+ async def test_an_event_naming_no_workspace_is_refused(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+ body = json.dumps({"type": "event_callback", "event": {}}).encode()
+
+ response = await _post(fixture, events_path("slack"), body)
+
+ assert response.status_code == 400
+
+ async def test_a_body_that_cannot_be_read_is_refused(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+
+ response = await _post(fixture, events_path("slack"), b"not json")
+
+ assert response.status_code == 400
+
+ async def test_a_platform_with_no_app_registered_is_not_found(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+
+ response = await _post(fixture, events_path("teams"), _event("T1", "x"))
+
+ assert response.status_code == 404
+
+
+class TestWhenTheBridgeIsNotThere:
+ async def test_a_stopped_bridge_asks_the_platform_to_retry(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """503, so Slack retries while a bridge restarts.
+
+ The alternative is a 200 that discards a real message and reports it
+ handled — the exact shape of failure that reads as "Slack lost a
+ message" and is never found.
+ """
+ fixture = await _fixture(rls_harness)
+ del fixture.lifecycle.adapters[fixture.a.bridge_id]
+
+ response = await _post(
+ fixture, events_path("slack"), _event(fixture.a.workspace_id, "x")
+ )
+
+ assert response.status_code == 503
+
+ async def test_an_install_with_no_bridge_yet_says_the_same(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """A recorded credential nothing has been built on. The schema allows
+ it, so the router has to answer for it."""
+ fixture = await _fixture(rls_harness)
+ async with tenant_session(
+ rls_harness.restricted, fixture.a.tenant_id
+ ) as session:
+ install = await MessagingInstallStore().get_for_workspace(
+ session,
+ platform="slack",
+ external_workspace_id=fixture.a.workspace_id,
+ )
+ assert install is not None
+ install.bridge_id = None
+ await session.commit()
+
+ response = await _post(
+ fixture, events_path("slack"), _event(fixture.a.workspace_id, "x")
+ )
+
+ assert response.status_code == 503
+
+
+class TestTheHandshake:
+ async def test_it_is_answered_before_anyone_has_installed_anything(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Slack saves a Request URL only if this is echoed back.
+
+ It carries no workspace, so a handshake that had to resolve a tenant
+ could never be answered — and the app could never be configured at all.
+ """
+ fixture = await _fixture(rls_harness)
+ body = json.dumps(
+ {"type": "url_verification", "challenge": "let-me-in"}
+ ).encode()
+
+ response = await _post(fixture, events_path("slack"), body)
+
+ assert response.status_code == 200
+ assert response.text == "let-me-in"
+ assert fixture.a.adapter.dispatched == []
+
+ async def test_an_unsigned_handshake_is_still_refused(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _fixture(rls_harness)
+
+ response = await fixture.client.post(
+ events_path("slack"),
+ content=b'{"type":"url_verification","challenge":"let-me-in"}',
+ )
+
+ assert response.status_code == 401
+
+
+class TestABridgeThatCannotTakeEvents:
+ async def test_the_refusal_is_not_swallowed(self, rls_harness: RLSHarness) -> None:
+ """A webhook install pointed at a socket-mode adapter is a fault.
+
+ It cannot happen through the install flow — the rendered config says
+ `event_delivery: webhook` — but it is exactly the state a hand-edited
+ connection config could reach, and delivering nowhere while answering
+ 200 is how it would stay hidden.
+ """
+ fixture = await _fixture(rls_harness)
+ adapter = _SocketOnlyAdapter()
+ fixture.lifecycle.adapters[fixture.a.bridge_id] = adapter
+
+ event = fixture.service.authenticate(
+ platform="slack",
+ endpoint="events",
+ headers=_signed(_event(fixture.a.workspace_id, "x")),
+ body=_event(fixture.a.workspace_id, "x"),
+ )
+ 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)
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 dc2f5159f..5c7cb4c47 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_installer.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_installer.py
@@ -9,7 +9,9 @@ from __future__ import annotations
import hashlib
import hmac
+import json
import time
+from urllib.parse import urlencode
import pytest
from slack_sdk.web.async_client import AsyncWebClient
@@ -19,6 +21,7 @@ from switch_core.bridges.collaboration.install import (
MessagingInstallerRegistry,
MessagingInstallError,
WebhookAuthenticityError,
+ WebhookPayloadError,
events_path,
oauth_callback_path,
public_url,
@@ -130,23 +133,6 @@ class TestWebhookVerification:
installer.verify_webhook(headers=headers, body=body)
-class TestWorkspaceOfEvent:
- def test_it_reads_the_team_id(self, installer: SlackAppInstaller) -> None:
- assert installer.workspace_of_event({"team_id": "T123"}) == "T123"
-
- @pytest.mark.parametrize("payload", [{}, {"team_id": ""}, {"team_id": 7}])
- def test_an_event_naming_no_workspace_is_refused(
- self, installer: SlackAppInstaller, payload: dict
- ) -> None:
- """An event we cannot route is not an event to guess at.
-
- There is no sensible default here: picking any tenant would deliver a
- stranger's message into somebody's rooms.
- """
- with pytest.raises(WebhookAuthenticityError):
- installer.workspace_of_event(payload)
-
-
class TestRedeem:
async def _redeem_returning(
self, monkeypatch: pytest.MonkeyPatch, installer: SlackAppInstaller, response
@@ -228,6 +214,137 @@ class TestRedeem:
)
+class TestParsingAWebhook:
+ """Turning three differently-shaped bodies into what Socket Mode delivers.
+
+ The comparison that matters is not with Slack's documentation but with the
+ socket transport: `dispatch_event` is shared, so anything parsed into a
+ different shape here is a bridge that behaves differently depending on
+ which Slack app its token came from.
+ """
+
+ def test_an_event_callback_becomes_the_socket_mode_envelope(
+ self, installer: SlackAppInstaller
+ ) -> None:
+ body = json.dumps(
+ {
+ "type": "event_callback",
+ "team_id": "T1",
+ "event": {"type": "message", "text": "hello"},
+ }
+ ).encode()
+
+ parsed = installer.parse_webhook(endpoint="events", body=body)
+
+ assert parsed.envelope_type == "events_api"
+ assert parsed.handshake is None
+ # The whole envelope, not the inner event: `dispatch_event` reads
+ # `payload["event"]` out of it, exactly as Socket Mode hands it over.
+ assert parsed.payload["event"] == {"type": "message", "text": "hello"}
+ assert parsed.payload["team_id"] == "T1"
+
+ def test_a_url_verification_is_answered_and_not_dispatched(
+ self, installer: SlackAppInstaller
+ ) -> None:
+ """Slack proving the URL at the moment it is saved.
+
+ It arrives before any workspace has installed anything, so a handshake
+ that had to resolve a tenant could never be answered — which would mean
+ the Request URL could not be saved at all.
+ """
+ body = json.dumps({"type": "url_verification", "challenge": "abc123"}).encode()
+
+ parsed = installer.parse_webhook(endpoint="events", body=body)
+
+ assert parsed.handshake == "abc123"
+
+ def test_a_url_verification_with_nothing_to_echo_is_refused(
+ self, installer: SlackAppInstaller
+ ) -> None:
+ with pytest.raises(WebhookPayloadError, match="challenge"):
+ installer.parse_webhook(
+ endpoint="events", body=b'{"type":"url_verification"}'
+ )
+
+ def test_a_slash_command_is_its_form_fields(
+ self, installer: SlackAppInstaller
+ ) -> None:
+ body = urlencode(
+ {"command": "/agents-status", "text": "", "team_id": "T1", "user_id": "U1"}
+ ).encode()
+
+ parsed = installer.parse_webhook(endpoint="commands", body=body)
+
+ assert parsed.envelope_type == "slash_commands"
+ assert parsed.payload["command"] == "/agents-status"
+ # A string, not a one-element list: the adapter reads these the way
+ # Socket Mode delivers them.
+ assert parsed.payload["text"] == ""
+
+ def test_an_interaction_is_unwrapped_from_its_payload_field(
+ self, installer: SlackAppInstaller
+ ) -> None:
+ inner = {"type": "block_actions", "team": {"id": "T1"}}
+ body = urlencode({"payload": json.dumps(inner)}).encode()
+
+ parsed = installer.parse_webhook(endpoint="interactive", body=body)
+
+ assert parsed.envelope_type == "interactive"
+ assert parsed.payload == inner
+
+ def test_an_interaction_with_no_payload_field_is_refused(
+ self, installer: SlackAppInstaller
+ ) -> None:
+ with pytest.raises(WebhookPayloadError, match="payload"):
+ installer.parse_webhook(endpoint="interactive", body=b"other=1")
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param(b"not json at all", id="not-json"),
+ pytest.param(b"[1, 2, 3]", id="json-but-not-an-object"),
+ pytest.param(b"", id="empty"),
+ ],
+ )
+ def test_a_body_that_cannot_be_read_is_a_payload_error(
+ self, installer: SlackAppInstaller, body: bytes
+ ) -> None:
+ """Verified, so it really is Slack. That makes it worth a loud error.
+
+ A bad signature is the internet; a signed body this build cannot parse
+ is either a Slack change or a bug of ours, and both want a log line
+ rather than a shrug.
+ """
+ with pytest.raises(WebhookPayloadError):
+ installer.parse_webhook(endpoint="events", body=body)
+
+
+class TestWhichWorkspaceSentIt:
+ """The one question that decides who the event belongs to."""
+
+ def test_an_event_names_it_flat(self, installer: SlackAppInstaller) -> None:
+ assert installer.workspace_of_event({"team_id": "T1"}) == "T1"
+
+ def test_an_interaction_names_it_nested(self, installer: SlackAppInstaller) -> None:
+ assert installer.workspace_of_event({"team": {"id": "T1"}}) == "T1"
+
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ pytest.param({}, id="absent"),
+ pytest.param({"team_id": ""}, id="empty"),
+ pytest.param({"team_id": 7}, id="not-a-string"),
+ pytest.param({"team": "T1"}, id="team-not-an-object"),
+ ],
+ )
+ def test_an_event_naming_none_is_refused_rather_than_guessed_at(
+ self, installer: SlackAppInstaller, payload: dict[str, object]
+ ) -> None:
+ """There is no safe default. Any guess picks somebody's tenant."""
+ with pytest.raises(WebhookPayloadError):
+ installer.workspace_of_event(payload)
+
+
class TestConnectionConfig:
def test_a_grant_renders_a_config_the_adapter_accepts(
self, installer: SlackAppInstaller
diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
index 64c129911..3d57a604d 100644
--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
@@ -77,6 +77,13 @@ _ALLOWED_MODULES = {
# `_room_tenant`'s fallback: which tenant is this room in, asked when the
# answer is not already cached alongside the channel mapping.
"switch_core.bridges.collaboration.bridge_core",
+ # An inbound webhook from an installed workspace: the platform's signature
+ # proves the sender and the payload names a workspace, and nothing in
+ # either names a tenant. It is the one read that must happen before a
+ # tenant can be bound at all, and the install row is then re-read scoped to
+ # the tenant it produced, so a wrong answer here is a miss rather than a
+ # cross-tenant read.
+ "switch_core.bridges.collaboration.install_service",
# `switch_core.transport.postgres` and `switch_core.clients.agent_client`
# came off this list with `tenant_of_client`: both were built from a
# `clients` row that already named the tenant, so they carry it instead of