:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(conversations): verify Slack events through ingress (#101487)
Julian Bez5e9be18f1143
diff --git a/.agents/skills/setting-up-support-slack-locally/SKILL.md b/.agents/skills/setting-up-support-slack-locally/SKILL.mdindex 6d0fa01a7c1e..f4508350cf2f 100644--- a/.agents/skills/setting-up-support-slack-locally/SKILL.md+++ b/.agents/skills/setting-up-support-slack-locally/SKILL.md@@ -38,7 +38,7 @@ All under `products/conversations/backend/api/urls.py`, prefixed `/api/conversat| ------------------------ | ------------------------------------------------------------- | ------------------------ || `v1/slack/authorize` | returns the Slack OAuth URL (auth-gated) | browser (localhost) || `v1/slack/callback` | OAuth redirect target; built from `SITE_URL`, no forced https | browser (localhost) |-| `v1/slack/events` | inbound event webhook | Slack's servers (tunnel) |+| `v1/slack/events` | inbound event webhook, built on `posthog/ingress/` | Slack's servers (tunnel) || `v1/slack/interactivity` | interactive component callbacks | Slack's servers (tunnel) |The callback requires an authenticated session on whatever origin `SITE_URL` resolves to, because the@@ -101,8 +101,8 @@ Slack sends a synchronous `url_verification` challenge on save, so the backend mechoes it back automatically.The Request URL alone only passes verification; it delivers nothing until you subscribe to events. Under-**Event Subscriptions → Subscribe to bot events**, add the events the backend handles (`SUPPORT_EVENT_TYPES`-in `products/conversations/backend/api/slack_events.py`):+**Event Subscriptions → Subscribe to bot events**, add the events the backend handles (`SLACK_EVENT_TYPES`+in `posthog/ingress/slack/provider.py`, which is also what the consumer registers for):- `app_mention`- `message.channels` (and `message.groups` for private channels), both arriving as the inner `message` event@@ -111,6 +111,37 @@ in `products/conversations/backend/api/slack_events.py`):Reinstall the app after changing scopes/events so the new grants take effect.+## Region routing, locally++The events endpoint is an ingress view: `products/conversations/backend/api/slack_events.py` wires the Slack+provider into `build_webhook_view()`, and ingress verifies the signature, parses the envelope and hands each+delivery to the `conversations_slack` consumer.++Which region handles a delivery is two separate answers:++1. The consumer's ownership lookup, `slack_delivery_ownership` in+ `products/conversations/backend/services/slack_events.py`. A workspace this database is connected to is+ `LOCAL`; a workspace it does not know is `ELSEWHERE`.+2. The ingress forward, which replays the signed request to `SECONDARY_REGION_DOMAIN` when any consumer+ answered `ELSEWHERE` **and** the request arrived on the primary region. See+ [Regional forwarding](../../../posthog/ingress/README.md#regional-forwarding).++`posthog/regions.py` holds both domains, and under `DEBUG` it rewrites them: the primary becomes+`urlparse(SITE_URL).netloc` (`localhost:8010` with the default dev `SITE_URL`) and the secondary becomes+`localhost:8000`.++The old handler also had a `DEBUG`-only shortcut that forwarded from the primary region even when the local+database held the workspace. That is gone. Ownership answers from the data alone in every environment, so a+workspace your local stack is connected to is always handled locally.++To exercise the forward on your laptop you need all three of: a request whose `Host` is the primary domain, a+`team_id` no local team is connected to, and something listening on `localhost:8000`. The tunnel cannot give+you the first, because the host rewrite makes the request arrive as bare `localhost`, which is not+`localhost:8010`. So sign a body yourself and POST it straight at `http://localhost:8010/...` (the snippet in+[references/troubleshooting.md](references/troubleshooting.md) signs one for you) with an unknown `team_id`.+Without a second stack on `localhost:8000` the forward fails and the endpoint answers `502`, which is still+proof that the forward was attempted; with one, the delivery lands there.+## Step 4 — connect and testBrowse the app at `http://localhost:8010`, log in, go to Support settings, and connect Slack. The OAuthdiff --git a/.agents/skills/setting-up-support-slack-locally/references/troubleshooting.md b/.agents/skills/setting-up-support-slack-locally/references/troubleshooting.mdindex 9b51bfb36091..7ea7701a3158 100644--- a/.agents/skills/setting-up-support-slack-locally/references/troubleshooting.md+++ b/.agents/skills/setting-up-support-slack-locally/references/troubleshooting.md@@ -13,19 +13,20 @@ touching Slack.| OAuth returns to the callback URL as a **white page** (URL bar still on `/slack/callback`) | The callback ran without a session. The callback needs an authenticated session on the origin `SITE_URL` resolves to. Log in on that same origin before connecting. The blank look is the `401` JSON being hidden by its `Content-Security-Policy: default-src 'none'`. || Any page over the tunnel is a **white page**, and `curl https://<tunnel>/_preflight` returns `200` with an **empty body** and `server: Caddy` | The tunnel isn't rewriting the upstream `Host` to `localhost`, so the dev Caddy (which only answers for the `localhost` host) drops through to nothing. Add the host rewrite: ngrok `--host-header=localhost` (or `host_header: localhost` in the config), cloudflared `--http-host-header localhost`. A correct hit shows `server: granian`. || Lots of **"Network error — There was an issue loading the requested resource"** across the SPA when browsing over the tunnel | Free-tier tunnel rate limiting. The ngrok request inspector shows many `/api/...` calls with status `0` (dropped). The SPA fires dozens of requests per scene, past `ngrok-free.app`'s per-minute cap. Fix: don't browse the SPA over the tunnel — keep the app and OAuth on `localhost`, and use the tunnel only for inbound events (low volume). Or switch to Cloudflare Tunnel (no such limit), or a paid ngrok plan. |-| Events reach the tunnel but no ticket appears | Check the celery worker log for `process_supporthog_event`, and confirm `team_exists_for_slack_workspace` matches the `slack_team_id` saved by your OAuth connect. Also confirm the bot is in the channel. |+| Events reach the tunnel but no ticket appears | The 202 only means the `ConversationInboundEvent` receipt committed. Check the celery worker log for `process_supporthog_event_receipt`, and confirm `team_for_slack_workspace` (`products/conversations/backend/support_slack.py`) matches the `slack_team_id` saved by your OAuth connect. Also confirm the bot is in the channel. |## Two things that look like problems but aren't- **`http://localhost:8234` assets from an https tunnel page.** Browsers treat `localhost` as a securecontext, so those dev-server scripts and the `ws://localhost:8234` HMR socket are not blocked as mixedcontent. The white page over a tunnel is the Host-header issue above, not mixed content.-- **Region routing proxying your events away.** In `DEBUG`, `PRIMARY_REGION_DOMAIN` is `urlparse(SITE_URL).netloc`- (`products/conversations/backend/services/region_routing.py`). With `SITE_URL=http://localhost:8010` the- primary is `localhost:8010`, but the tunnel rewrites Host to `localhost`, so `is_primary_region` is false- and `slack_events.py` processes the event locally instead of proxying. If you ever set the tunnel to- forward the port too, the host would match and events would proxy to `localhost:8000` — keep the rewrite- at bare `localhost`.+- **Region routing forwarding your events away.** Ingress only forwards when the consumer's ownership lookup+ answers `ELSEWHERE`, which means no local team is connected to that Slack workspace. A workspace your local+ stack owns is handled locally, in `DEBUG` as anywhere else. On top of that, only the primary region+ forwards, and in `DEBUG` `PRIMARY_REGION_DOMAIN` is `urlparse(SITE_URL).netloc` (`posthog/regions.py`), so+ `localhost:8010` by default. The tunnel rewrites Host to bare `localhost`, which does not match, so a+ tunnelled delivery is never forwarded either way. See "Region routing, locally" in the skill for how to+ exercise the forward on purpose.## Verify the event path without Slack@@ -60,6 +61,8 @@ curl -sS -i -X POST "https://<tunnel-host>/api/conversations/v1/slack/events" \## Watching real eventsThe tunnel's request inspector (`http://localhost:4040` for ngrok) shows each Slack POST and its response.-A real `event_callback` returns `202` (accepted and enqueued, `slack_events.py:98`); `url_verification`-returns `200`. `X-Slack-Retry-Num` on a request means Slack is retrying because a previous delivery didn't-`200`/`202` in time.+A real `event_callback` returns `202`, the ingress receipt status (`success_status` in+`posthog/ingress/providers.py`), which means the durable receipt committed; `url_verification` returns `200`,+answered before any consumer runs. A `502` is the Slack provider's `retry_status`: ingress could not vouch+that the delivery was taken, so it asks Slack to send it again. `X-Slack-Retry-Num` on a request means Slack+is retrying because a previous delivery didn't `200`/`202` in time.diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex 53def9cfce2a..a7c79535f4a5 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -117,7 +117,6 @@ rules:- /ee/api/vercel/vercel_webhooks.py- /ee/partners/stripe/api/provisioning/signature.py- /posthog/models/integration/slack.py- - /products/conversations/backend/api/slack_events.py- /products/conversations/backend/mailgun.py- /products/conversations/backend/support_slack.py- /products/user_interviews/backend/presentation/webhooks.pydiff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 1ecc0538164e..0189644ac0d7 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -197,8 +197,8 @@ Local dispatch alone would otherwise receipt the delivery: the consumer's own loNothing has claimed a dedup mark at that point, so the redelivery is processed in full, and the lookups it asks again decide the forward then.A provider that does not redeliver keeps the delivery instead: the failure counts as `UNDECIDED`, local dispatch runs, and the request is receipted, because a non-2xx there would only lose the local run as well.-An ownership lookup should therefore let a transient error out rather than answering `LOCAL` or `UNDECIDED` through it.-A guess is what turns a dropped connection into a lost delivery.+An ownership lookup should therefore let a transient error out rather than answering `LOCAL`, `UNDECIDED` or `ELSEWHERE` through it.+A guess is what turns a dropped connection into a lost delivery, and an `ELSEWHERE` guess also sends the delivery's contents to a region that may not own them.What crosses is the raw signed body, except for a provider that signs the form rather than the body.Reading that form consumes the request stream and leaves no raw bytes, so the forward rebuilds the fields and the files and drops the original `Content-Type`, which names the boundary of a body that is gone.diff --git a/posthog/ingress/contracts.py b/posthog/ingress/contracts.pyindex 414439e1d8f9..442c88399138 100644--- a/posthog/ingress/contracts.py+++ b/posthog/ingress/contracts.py@@ -56,8 +56,9 @@ class WebhookConsumer:# A consumer whose resources are split by region answers where this delivery's resource lives,# and ingress forwards the signed request when the answer is elsewhere. A lookup inside must be# bounded (`bounded_statement_timeout`): it runs in the request, before dispatch. Let a- # transient error out rather than answering local or undecided through it: a raised lookup asks- # a provider that redelivers for the delivery again, and a guess loses it.+ # transient error out rather than answering local, undecided or elsewhere through it: a raised+ # lookup asks a provider that redelivers for the delivery again, a guess loses the delivery,+ # and an elsewhere guess also sends its contents to a region that may not own them.ownership: Callable[[WebhookDelivery], DeliveryOwnership] | None = Nonediff --git a/posthog/ingress/slack/README.md b/posthog/ingress/slack/README.mdindex b8e33d6eaac8..0e5799536a4b 100644--- a/posthog/ingress/slack/README.md+++ b/posthog/ingress/slack/README.md@@ -31,10 +31,16 @@ Nothing under `posthog/ingress/` reads it.Slack's `url_verification` handshake wants the challenge echoed in the response body, which no consumer can do.The incarnation answers it in `pre_dispatch_response()`, before dispatch.-The status codes are the defaults.++Slack redelivers a delivery it got a non-2xx for, so `retry_status` is 502: a workspace ownership lookup that raised or hit its timeout, a forward to the region that owns the workspace that did not land, and a receipt write that raised must not be receipted, or the event is lost.+The other status codes are the defaults.## Consumers-No product registers a Slack consumer yet.-The conversations Slack endpoint moves to ingress in its own PR.+`conversations_slack`, on the `supporthog` app, for every event type the app is subscribed to.+It declares `ownership`, so a delivery about a workspace the other region holds is forwarded there.+A lookup that does not answer, the bounded statement timeout included, forwards nothing and takes `retry_status`:+a lookup that never finished is no evidence that the other region owns the workspace, and the delivery carries the workspace's support messages.+It also sets `dedup=False`, because its receipt row is unique per Slack event id and already absorbs a redelivery.+A dedup mark would only add a way to lose one: a run that exits between the claim and the receipt commit leaves the mark behind with nothing durable written, and every redelivery then takes `retry_status` until Slack gives up.See the [Endpoints table](../README.md#endpoints).diff --git a/posthog/ingress/slack/provider.py b/posthog/ingress/slack/provider.pyindex 9f0bb0b20c3b..53d332597237 100644--- a/posthog/ingress/slack/provider.py+++ b/posthog/ingress/slack/provider.py@@ -18,6 +18,7 @@ from posthog.ingress.verify.schemes import HmacSha256, SignatureSchemeSLACK_EVENT_TYPES = frozenset({"app_mention",+ "link_shared","message","reaction_added","member_joined_channel",@@ -30,6 +31,10 @@ SPECS = (ProviderSpec(provider="slack", app="supporthog", event_types=SLACK_EVENclass SlackProvider(WebhookProvider):provider = "slack"+ # Slack redelivers on a non-2xx, so a delivery ingress cannot vouch for must not be receipted:+ # a workspace ownership lookup that raised or hit its timeout, a forward to the owning region+ # that never landed, and a receipt write that raised all lose the 202.+ retry_status = 502def __init__(self, *, app: str = "supporthog", secret_getter: Callable[[], str | None]) -> None:self.app = appdiff --git a/products/conversations/backend/api/slack_events.py b/products/conversations/backend/api/slack_events.pyindex ac153d11aa3b..9e1fb08a77f0 100644--- a/products/conversations/backend/api/slack_events.py+++ b/products/conversations/backend/api/slack_events.py@@ -1,123 +1,8 @@"""Slack events endpoint for SupportHog app."""-import json-from typing import Any+from posthog.ingress.slack.provider import build_slack_provider+from posthog.ingress.views import build_webhook_view-from django.conf import settings-from django.http import HttpRequest, HttpResponse, JsonResponse-from django.views.decorators.csrf import csrf_exempt+from products.conversations.backend.support_slack import get_support_slack_signing_secret-import structlog--from posthog.models.integration import SlackIntegrationError-from posthog.regions import is_primary_region--from products.conversations.backend.models import ConversationInboundEventSource-from products.conversations.backend.services.inbound_events import (- accept_inbound_event,- slack_events_source_id,- slack_retry_metadata,-)-from products.conversations.backend.services.region_routing import proxy_to_secondary_region-from products.conversations.backend.support_slack import team_for_slack_workspace, validate_support_request-from products.conversations.backend.tasks.slack import wake_inbound_event--logger = structlog.get_logger(__name__)--# Event types we handle for support tickets-SUPPORT_EVENT_TYPES = [- "app_mention",- "link_shared",- "message",- "reaction_added",- "member_joined_channel",- "member_left_channel",-]---def _accept_event_callback(request: HttpRequest, data: dict[str, Any]) -> HttpResponse:- raw_event = data.get("event")- event: dict[str, Any] = raw_event if isinstance(raw_event, dict) else {}- slack_team_id = data.get("team_id", "") if isinstance(data.get("team_id"), str) else ""- inner_event_type = event.get("type")- retry_num, retry_reason = slack_retry_metadata(request)-- logger.info(- "supporthog_event_callback",- inner_event_type=inner_event_type,- slack_team_id=slack_team_id,- channel=event.get("channel"),- retry_num=retry_num,- )-- if inner_event_type not in SUPPORT_EVENT_TYPES:- return HttpResponse(status=202)-- team = team_for_slack_workspace(slack_team_id) if slack_team_id else None-- if team is not None and not (settings.DEBUG and is_primary_region(request)):- event_id = data.get("event_id") if isinstance(data.get("event_id"), str) else None- accept_inbound_event(- team=team,- source=ConversationInboundEventSource.SLACK_EVENTS,- source_id=slack_events_source_id(event_id=event_id, signed_body=request.body),- provider_account_id=slack_team_id,- payload=data,- provider_retry_num=retry_num,- provider_retry_reason=retry_reason,- wake=wake_inbound_event,- )- return HttpResponse(status=202)-- if is_primary_region(request):- if not proxy_to_secondary_region(request, log_prefix="supporthog"):- return HttpResponse("Failed to reach owning region", status=502)- return HttpResponse(status=202)-- logger.warning("supporthog_no_team_any_region", slack_team_id=slack_team_id)- return HttpResponse(status=202)---@csrf_exempt-def supporthog_event_handler(request: HttpRequest) -> HttpResponse:- """- Handle incoming Slack events for SupportHog app.-- This endpoint handles:- - URL verification challenges from Slack- - Event callbacks (message, app_mention, reaction_added)-- Regional routing: EU is the primary region. If the workspace isn't found- locally, the request is proxied to the secondary region (US).- A 2xx means the owning region's Postgres receipt committed, not that a- worker has processed the callback.- """- if request.method != "POST":- return HttpResponse(status=405)-- try:- validate_support_request(request)- except SlackIntegrationError as e:- logger.warning("supporthog_event_invalid_request", error=str(e))- return HttpResponse("Invalid request", status=403)-- try:- data = json.loads(request.body)- except json.JSONDecodeError:- return HttpResponse("Invalid JSON", status=400)- if not isinstance(data, dict):- return HttpResponse("Invalid JSON", status=400)-- logger.info("supporthog_event_received", event_type=data.get("type"))-- event_type = data.get("type")-- if event_type == "url_verification":- challenge = data.get("challenge", "")- logger.info("supporthog_url_verification", challenge=challenge[:20] + "...")- return JsonResponse({"challenge": challenge})-- if event_type == "event_callback":- return _accept_event_callback(request, data)-- return HttpResponse(status=200)+supporthog_event_handler = build_webhook_view(build_slack_provider(secret_getter=get_support_slack_signing_secret))diff --git a/products/conversations/backend/api/tests/test_slack_endpoints.py b/products/conversations/backend/api/tests/test_slack_endpoints.pyindex b8a2669e0acc..6fd10b7d211a 100644--- a/products/conversations/backend/api/tests/test_slack_endpoints.py+++ b/products/conversations/backend/api/tests/test_slack_endpoints.py@@ -1,5 +1,8 @@+import hmacimport json+import timeimport hashlib+from collections.abc import Callablefrom typing import Anyfrom urllib.parse import parse_qs, urlencode, urlparse@@ -7,15 +10,20 @@ from posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import MagicMock, patchfrom django.core.cache import cache+from django.db import DatabaseError, OperationalErrorfrom django.http import HttpResponse+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework.test import APIClientfrom slack_sdk.errors import SlackApiError+from posthog.ingress.contracts import DeliveryOwnership, WebhookDelivery+from posthog.ingress.dispatch.dedup import DeliveryDedupfrom posthog.models.integration import SlackIntegrationErrorfrom posthog.models.organization import OrganizationMembership+from products.conversations.backend.facade.api import accept_slack_event, slack_delivery_ownershipfrom products.conversations.backend.models import (ConversationInboundEvent,ConversationInboundEventSource,@@ -23,6 +31,10 @@ from products.conversations.backend.models import ()from products.conversations.backend.models.inbound_event import INBOUND_PAYLOAD_MAX_BYTES+SUPPORT_SLACK_SIGNING_SECRET = "slack-signing-secret"+SLACK_EVENTS_MODULE = "products.conversations.backend.services.slack_events"+WAKE_INBOUND_EVENT = f"{SLACK_EVENTS_MODULE}.wake_inbound_event"+class TestSupportSlackEventsAPI(BaseTest):client: APIClient@@ -38,15 +50,35 @@ class TestSupportSlackEventsAPI(BaseTest):)self.client = APIClient()cache.clear()-- def _post(self, payload: dict[str, Any], **kwargs):+ signing_secret = patch(+ "products.conversations.backend.support_slack.get_support_slack_settings",+ return_value={"SUPPORT_SLACK_SIGNING_SECRET": SUPPORT_SLACK_SIGNING_SECRET},+ )+ signing_secret.start()+ self.addCleanup(signing_secret.stop)++ def _signed_headers(self, body: bytes) -> dict[str, str]:+ timestamp = str(int(time.time()))+ signature = hmac.new(+ SUPPORT_SLACK_SIGNING_SECRET.encode("utf-8"),+ b"v0:" + timestamp.encode("utf-8") + b":" + body,+ hashlib.sha256,+ ).hexdigest()+ return {"x-slack-request-timestamp": timestamp, "x-slack-signature": f"v0={signature}"}++ def _post_raw(self, body: bytes, **kwargs: Any):+ headers = {**self._signed_headers(body), **kwargs.pop("headers", {})}return self.client.post("/api/conversations/v1/slack/events",- data=json.dumps(payload),+ data=body,content_type="application/json",+ headers=headers,**kwargs,)+ def _post(self, payload: dict[str, Any], **kwargs: Any):+ return self._post_raw(json.dumps(payload).encode("utf-8"), **kwargs)+def _post_committed(self, payload: dict[str, Any], **kwargs: Any) -> HttpResponse:with self.captureOnCommitCallbacks(execute=True):return self._post(payload, **kwargs)@@ -54,18 +86,17 @@ class TestSupportSlackEventsAPI(BaseTest):def _event_row(self) -> ConversationInboundEvent:return ConversationInboundEvent.objects.for_team(self.team.id).get()- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_invalid_signature_returns_403(self, mock_validate: MagicMock):- mock_validate.side_effect = SlackIntegrationError("Invalid")-- response = self._post({"type": "event_callback"})+ def test_invalid_signature_returns_403(self):+ response = self.client.post(+ "/api/conversations/v1/slack/events",+ data=json.dumps({"type": "event_callback"}),+ content_type="application/json",+ )assert response.status_code == 403- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_slack_retry_is_recorded_and_processed(self, mock_validate: MagicMock, mock_wake: MagicMock):- mock_validate.return_value = None+ @patch(WAKE_INBOUND_EVENT)+ def test_slack_retry_is_recorded_and_processed(self, mock_wake: MagicMock):payload = {"type": "event_callback","event_id": "Ev_retry",@@ -85,31 +116,19 @@ class TestSupportSlackEventsAPI(BaseTest):assert row.provider_retry_reason == "http_timeout"assert row.status == ConversationInboundEvent.Status.PENDING- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_invalid_json_returns_400(self, mock_validate: MagicMock):- mock_validate.return_value = None-- response = self.client.post(- "/api/conversations/v1/slack/events",- data="{",- content_type="application/json",- )+ def test_invalid_json_returns_400(self):+ response = self._post_raw(b"{")assert response.status_code == 400- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_url_verification_returns_challenge(self, mock_validate: MagicMock):- mock_validate.return_value = None-+ def test_url_verification_returns_challenge(self):response = self._post({"type": "url_verification", "challenge": "challenge123"})assert response.status_code == 200assert response.json() == {"challenge": "challenge123"}- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_event_callback_enqueues_processing(self, mock_validate: MagicMock, mock_wake: MagicMock):- mock_validate.return_value = None+ @patch(WAKE_INBOUND_EVENT)+ def test_event_callback_enqueues_processing(self, mock_wake: MagicMock):payload = {"type": "event_callback","event_id": "Ev_123",@@ -122,30 +141,54 @@ class TestSupportSlackEventsAPI(BaseTest):assert first.status_code == 202assert second.status_code == 202+ # The redelivery reaches the consumer now, and the unique receipt absorbs it into one row.assert ConversationInboundEvent.objects.for_team(self.team.id).count() == 1assert mock_wake.call_count == 2- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_event_callback_routes_to_handler(self, mock_validate: MagicMock, mock_wake: MagicMock):- mock_validate.return_value = None+ @patch(WAKE_INBOUND_EVENT)+ def test_a_redelivery_reaches_the_handler_past_a_dedup_mark_a_dead_run_left(self, mock_wake: MagicMock):+ # A run that exits between the dedup claim and the receipt commit leaves the mark behind.+ payload = {+ "type": "event_callback",+ "event_id": "Ev_abandoned",+ "team_id": "T123",+ "event": {"type": "message", "channel": "C1"},+ }+ DeliveryDedup().claim(provider="slack", consumer="conversations_slack", delivery_id="Ev_abandoned")++ response = self._post_committed(payload)++ assert response.status_code == 202+ mock_wake.assert_called_once()+ assert self._event_row().source_id == "Ev_abandoned"+ # Spelled out rather than read from the provider, so dropping a type there fails here.+ @parameterized.expand(+ [+ ("app_mention",),+ ("link_shared",),+ ("message",),+ ("reaction_added",),+ ("member_joined_channel",),+ ("member_left_channel",),+ ]+ )+ @patch(WAKE_INBOUND_EVENT)+ def test_every_subscribed_event_type_reaches_the_consumer(self, event_type: str, mock_wake: MagicMock):response = self._post_committed({"type": "event_callback",- "event_id": "Ev_456",+ "event_id": f"Ev_{event_type}","team_id": "T123",- "event": {"type": "reaction_added"},+ "event": {"type": event_type},})assert response.status_code == 202mock_wake.assert_called_once()- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_broker_failure_after_commit_still_acknowledges(self, mock_validate: MagicMock, mock_wake: MagicMock):- mock_validate.return_value = None+ @patch(WAKE_INBOUND_EVENT)+ def test_broker_failure_after_commit_still_acknowledges(self, mock_wake: MagicMock):mock_wake.side_effect = ConnectionError("broker down")payload = {"type": "event_callback",@@ -161,10 +204,27 @@ class TestSupportSlackEventsAPI(BaseTest):assert row.status == ConversationInboundEvent.Status.PENDINGassert row.source_id == "Ev_broker"- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_oversized_payload_is_tombstoned_and_acknowledged(self, mock_validate: MagicMock, mock_wake: MagicMock):- mock_validate.return_value = None+ @patch(WAKE_INBOUND_EVENT)+ @patch(f"{SLACK_EVENTS_MODULE}.accept_inbound_event")+ def test_a_receipt_write_that_raises_is_not_acknowledged(self, mock_accept: MagicMock, mock_wake: MagicMock):+ # The receipt is the product's only durable record of the event, and no sweeper can+ # recover one that was never written, so the request must not earn Slack's 202.+ mock_accept.side_effect = DatabaseError("receipt write failed")+ payload = {+ "type": "event_callback",+ "event_id": "Ev_unwritten",+ "team_id": "T123",+ "event": {"type": "message", "channel": "C1"},+ }++ response = self._post_committed(payload)++ assert response.status_code == 502+ mock_wake.assert_not_called()+ assert not ConversationInboundEvent.objects.unscoped().filter(source_id="Ev_unwritten").exists()++ @patch(WAKE_INBOUND_EVENT)+ def test_oversized_payload_is_tombstoned_and_acknowledged(self, mock_wake: MagicMock):payload = {"type": "event_callback","event_id": "Ev_poison",@@ -181,73 +241,125 @@ class TestSupportSlackEventsAPI(BaseTest):assert row.status == ConversationInboundEvent.Status.FAILEDassert row.last_error_code == "payload_too_large"- @patch("products.conversations.backend.api.slack_events.proxy_to_secondary_region")- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_proxies_to_secondary_when_team_not_found_on_primary(- self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock+ @parameterized.expand(+ [+ ("the owning region accepts it", 202, 202),+ # Slack redelivers on a non-2xx, so a forward that never landed must not be receipted.+ ("the owning region is unreachable", 500, 502),+ ]+ )+ def test_a_workspace_another_region_owns_is_forwarded_once_from_the_primary(+ self, _name: str, secondary_status: int, expected_status: int):- mock_validate.return_value = None- mock_proxy.return_value = True+ payload = {+ "type": "event_callback",+ "event_id": "Ev_forward",+ "team_id": "T_UNKNOWN",+ "event": {"type": "message", "channel": "C1"},+ }- with patch("products.conversations.backend.api.slack_events.is_primary_region", return_value=True):- response = self._post(- {- "type": "event_callback",- "event_id": "Ev_proxy",- "team_id": "T_UNKNOWN",- "event": {"type": "message", "channel": "C1"},- },- )+ with (+ patch(WAKE_INBOUND_EVENT) as mock_wake,+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ ):+ mock_forward.return_value = MagicMock(ok=200 <= secondary_status < 300, status_code=secondary_status)+ response = self._post(payload)- assert response.status_code == 202+ assert response.status_code == expected_status+ mock_forward.assert_called_once()mock_wake.assert_not_called()- mock_proxy.assert_called_once()- assert not ConversationInboundEvent.objects.unscoped().filter(source_id="Ev_proxy").exists()+ assert not ConversationInboundEvent.objects.unscoped().filter(source_id="Ev_forward").exists()- @patch("products.conversations.backend.api.slack_events.proxy_to_secondary_region")- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_returns_502_when_event_proxy_to_secondary_fails(- self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock- ):- mock_validate.return_value = None- mock_proxy.return_value = False+ @patch(f"{SLACK_EVENTS_MODULE}.team_for_slack_workspace")+ def test_a_workspace_lookup_that_hits_its_timeout_asks_slack_to_redeliver(self, mock_lookup: MagicMock):+ # The delivery carries the workspace's support messages, so a lookup that never finished+ # must not send them to the other region: it has not shown that region owns the workspace.+ mock_lookup.side_effect = OperationalError("canceling statement due to statement timeout")+ payload = {+ "type": "event_callback",+ "event_id": "Ev_timeout",+ "team_id": "T123",+ "event": {"type": "message", "channel": "C1"},+ }- with patch("products.conversations.backend.api.slack_events.is_primary_region", return_value=True):- response = self._post(- {- "type": "event_callback",- "event_id": "Ev_proxy_fail",- "team_id": "T_UNKNOWN",- "event": {"type": "message", "channel": "C1"},- },- )+ with (+ patch(WAKE_INBOUND_EVENT) as mock_wake,+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ ):+ refused = self._post(payload)- assert response.status_code == 502+ assert refused.status_code == 502+ mock_forward.assert_not_called()mock_wake.assert_not_called()+ assert not ConversationInboundEvent.objects.unscoped().filter(source_id="Ev_timeout").exists()- @patch("products.conversations.backend.api.slack_events.proxy_to_secondary_region")- @patch("products.conversations.backend.api.slack_events.wake_inbound_event")- @patch("products.conversations.backend.api.slack_events.validate_support_request")- def test_drops_event_when_team_not_found_on_secondary(- self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock+ # Nothing claimed a dedup mark, so Slack's redelivery is the recovery rather than a drop.+ mock_lookup.side_effect = None+ mock_lookup.return_value = self.team+ with patch(WAKE_INBOUND_EVENT) as mock_wake:+ redelivered = self._post_committed(payload)++ assert redelivered.status_code == 202+ mock_wake.assert_called_once()+ assert self._event_row().source_id == "Ev_timeout"+++class TestSupportSlackDeliveries(BaseTest):+ def setUp(self):+ super().setUp()+ TeamConversationsSlackConfig.objects.update_or_create(+ team=self.team,+ defaults={"slack_team_id": "T123", "slack_bot_token": "xoxb-test"},+ )++ def _delivery(self, context: dict[str, str]) -> WebhookDelivery:+ return WebhookDelivery(+ provider="slack",+ app="supporthog",+ delivery_id="Ev_own",+ event_type="message",+ payload={+ "type": "event_callback",+ "team_id": context.get("slack_team_id", ""),+ "event": {"type": "message"},+ },+ received_at=timezone.now(),+ context=context,+ )++ @parameterized.expand(+ [+ ("a workspace this region holds", {"slack_team_id": "T123"}, DeliveryOwnership.LOCAL),+ ("a workspace it does not", {"slack_team_id": "T_UNKNOWN"}, DeliveryOwnership.ELSEWHERE),+ ("a delivery naming no workspace", {}, DeliveryOwnership.UNDECIDED),+ ]+ )+ def test_ownership(self, _name: str, context: dict[str, str], expected: DeliveryOwnership):+ assert slack_delivery_ownership(self._delivery(context)) == expected++ @parameterized.expand(+ [+ ("the ownership lookup", slack_delivery_ownership),+ ("the consumer", accept_slack_event),+ ]+ )+ @patch(WAKE_INBOUND_EVENT)+ @patch(f"{SLACK_EVENTS_MODULE}.team_for_slack_workspace")+ def test_a_workspace_lookup_that_hits_its_timeout_raises_out_of(+ self, _name: str, entry_point: Callable[[WebhookDelivery], Any], mock_lookup: MagicMock, mock_wake: MagicMock):- mock_validate.return_value = None+ # Answering through a timeout is what ingress cannot recover from: an `ELSEWHERE` guess+ # forwards a workspace this region owns to the other one, and a quiet return receipts a+ # delivery that was never written. Raising asks Slack to redeliver.+ mock_lookup.side_effect = OperationalError("canceling statement due to statement timeout")- with patch("products.conversations.backend.api.slack_events.is_primary_region", return_value=False):- response = self._post(- {- "type": "event_callback",- "event_id": "Ev_drop",- "team_id": "T_UNKNOWN",- "event": {"type": "message", "channel": "C1"},- },- )+ with self.assertRaises(OperationalError):+ entry_point(self._delivery({"slack_team_id": "T123"}))- assert response.status_code == 202mock_wake.assert_not_called()- mock_proxy.assert_not_called()+ assert not ConversationInboundEvent.objects.unscoped().filter(source_id="Ev_own").exists()class TestSupportSlackInteractivityAPI(BaseTest):diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 5d86bd2a510d..cbbf1adbf280 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -23,7 +23,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom temporalio.service import RPCErrorfrom posthog.dataclasses import frozen-from posthog.ingress.contracts import WebhookDelivery+from posthog.ingress.contracts import DeliveryOwnership, WebhookDeliveryfrom posthog.models.comment import Commentfrom posthog.models.integration import Integrationfrom posthog.models.team import Team@@ -114,6 +114,26 @@ def accept_github_event(delivery: WebhookDelivery) -> None:github_events.accept_github_event(delivery)+def accept_slack_event(delivery: WebhookDelivery) -> None:+ """The inbound SupportHog Slack webhook enters conversations here, so its consumer needs no internal import."""+ # Deferred to keep the Celery task module off the facade import path.+ from products.conversations.backend.services import slack_events # noqa: PLC0415++ slack_events.accept_slack_event(delivery)+++def slack_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Whether this region holds the team the delivery's Slack workspace is connected to.++ Ingress asks before it dispatches, and forwards the signed request to the other region when+ the answer is elsewhere.+ """+ # Deferred to keep the Celery task module off the facade import path.+ from products.conversations.backend.services import slack_events # noqa: PLC0415++ return slack_events.slack_delivery_ownership(delivery)++def sync_google_account_email(integration_id: int, team_id: int) -> None:from products.conversations.backend.services.gmail_sync import ( # noqa: PLC0415 -- avoids the Conversations and Customer Analytics facade cycleGmailSyncError,diff --git a/products/conversations/backend/services/inbound_events.py b/products/conversations/backend/services/inbound_events.pyindex a6dda4a57f22..53d16910c8cc 100644--- a/products/conversations/backend/services/inbound_events.py+++ b/products/conversations/backend/services/inbound_events.py@@ -85,13 +85,13 @@ class InboundQueueMetrics:oldest_ready_age_seconds: float-def slack_retry_metadata(request: HttpRequest) -> tuple[int | None, str]:- raw_num = request.headers.get("X-Slack-Retry-Num")- reason = (request.headers.get("X-Slack-Retry-Reason") or "")[:64]- if not raw_num:+def slack_retry_metadata_from_values(*, raw_retry_num: str, retry_reason: str) -> tuple[int | None, str]:+ """Parse Slack's retry headers from values, for callers that hold no request."""+ reason = retry_reason[:64]+ if not raw_retry_num:return None, reasontry:- retry_num = int(raw_num)+ retry_num = int(raw_retry_num)except ValueError:return None, reasonif retry_num < 0:@@ -99,6 +99,13 @@ def slack_retry_metadata(request: HttpRequest) -> tuple[int | None, str]:return retry_num, reason+def slack_retry_metadata(request: HttpRequest) -> tuple[int | None, str]:+ return slack_retry_metadata_from_values(+ raw_retry_num=request.headers.get("X-Slack-Retry-Num") or "",+ retry_reason=request.headers.get("X-Slack-Retry-Reason") or "",+ )++def slack_events_source_id(*, event_id: str | None, signed_body: bytes) -> str:if event_id:return event_id[:512]diff --git a/products/conversations/backend/services/slack_events.py b/products/conversations/backend/services/slack_events.pynew file mode 100644index 000000000000..d93d05dc94b0--- /dev/null+++ b/products/conversations/backend/services/slack_events.py@@ -0,0 +1,88 @@+"""Slack Events API deliveries for the SupportHog app.++Two entry points, both reached from the facade after ingress verified the signature and parsed+the envelope: ``slack_delivery_ownership`` answers which region holds the workspace the delivery+is about, and ``accept_slack_event`` writes the inbound receipt and wakes its worker. No HTTP in+here -- ingress owns the request, the receipt and the forward to the region that owns the+workspace.+"""++import json+from typing import Any++from posthog.ingress.contracts import DeliveryOwnership, WebhookDelivery+from posthog.ingress.dispatch.database import bounded_statement_timeout+from posthog.models.team import Team++from products.conversations.backend.models import ConversationInboundEventSource, TeamConversationsSlackConfig+from products.conversations.backend.services.inbound_events import (+ accept_inbound_event,+ slack_events_source_id,+ slack_retry_metadata_from_values,+)+from products.conversations.backend.support_slack import team_for_slack_workspace+from products.conversations.backend.tasks.slack import wake_inbound_event++# The lookup runs inside the request, before dispatch, so it draws on the delivery's wall clock.+_WORKSPACE_LOOKUP_TIMEOUT_MS = 800+++def _team_for_workspace(slack_team_id: str) -> Team | None:+ """The team SupportHog is connected to for this workspace, or None when no team here is.++ A cancelled statement raises, because a lookup that never finished is not an answer. Both+ callers let it out rather than guessing past it.+ """+ with bounded_statement_timeout(_WORKSPACE_LOOKUP_TIMEOUT_MS, models=[TeamConversationsSlackConfig]):+ return team_for_slack_workspace(slack_team_id)+++def slack_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Which region holds the team the delivery's Slack workspace is connected to.++ A workspace this region does not know is `ELSEWHERE` rather than undecided, so the delivery+ reaches the other region: it is the only one that can tell a workspace it holds from one+ nobody holds. A lookup that raised, the statement timeout included, has shown no such thing,+ so it propagates rather than answering `ELSEWHERE`: the delivery carries the workspace's+ support messages, and a workspace this region owns must not have them forwarded across the+ region boundary on a guess. A raised lookup asks Slack to redeliver instead.+ """+ slack_team_id = delivery.context.get("slack_team_id", "")+ if not slack_team_id:+ return DeliveryOwnership.UNDECIDED++ team = _team_for_workspace(slack_team_id)+ return DeliveryOwnership.LOCAL if team is not None else DeliveryOwnership.ELSEWHERE+++def accept_slack_event(delivery: WebhookDelivery) -> None:+ """Record a verified Slack event against the workspace's team and wake its worker."""+ payload: dict[str, Any] = dict(delivery.payload)+ slack_team_id = delivery.context.get("slack_team_id", "")+ # Unguarded on purpose: a timed-out lookup fails the delivery, so the dispatcher releases the+ # dedup mark and Slack's redelivery reaches this consumer instead of the event being lost.+ team = _team_for_workspace(slack_team_id) if slack_team_id else None+ if team is None:+ # Quiet on purpose: ingress reports a delivery no region here owns, off the ownership+ # answer this module gave it before dispatch.+ return++ retry_num, retry_reason = slack_retry_metadata_from_values(+ raw_retry_num=delivery.context.get("retry_num", ""),+ retry_reason=delivery.context.get("retry_reason", ""),+ )+ accept_inbound_event(+ team=team,+ source=ConversationInboundEventSource.SLACK_EVENTS,+ # A delivery carries no raw body, so an event without an id falls back to a hash of the+ # parsed payload rather than of the signed bytes.+ source_id=slack_events_source_id(+ event_id=delivery.delivery_id,+ signed_body=json.dumps(payload, sort_keys=True).encode("utf-8"),+ ),+ provider_account_id=slack_team_id,+ payload=payload,+ provider_retry_num=retry_num,+ provider_retry_reason=retry_reason,+ wake=wake_inbound_event,+ )diff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.pyindex 017255bb28f2..2b6d0546906e 100644--- a/products/conversations/backend/support_slack.py+++ b/products/conversations/backend/support_slack.py@@ -37,6 +37,12 @@ def get_support_slack_settings() -> dict:)+def get_support_slack_signing_secret() -> str | None:+ """The secret ingress verifies SupportHog deliveries with."""+ secret = get_support_slack_settings().get("SUPPORT_SLACK_SIGNING_SECRET")+ return str(secret) if secret else None++def supporthog_missing_file_scopes(team: "Team") -> list[str]:"""File scopes this install hasn't granted, for logging why attachments failed.diff --git a/products/conversations/backend/webhook_consumers.py b/products/conversations/backend/webhook_consumers.pyindex 7df977766bbf..ddebec9da7b7 100644--- a/products/conversations/backend/webhook_consumers.py+++ b/products/conversations/backend/webhook_consumers.py@@ -1,10 +1,11 @@-"""Conversations' consumer on the customer-facing GitHub App endpoint.+"""Conversations' consumers on the customer-facing GitHub App and the SupportHog Slack app.-The registry imports this module on the first delivery, so it stays cheap: the callable defers+The registry imports this module on the first delivery, so it stays cheap: every callable defersits own product import."""-from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery+from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDelivery+from posthog.ingress.slack.provider import SLACK_EVENT_TYPESdef _run_conversations(delivery: WebhookDelivery) -> None:@@ -13,6 +14,18 @@ def _run_conversations(delivery: WebhookDelivery) -> None:accept_github_event(delivery)+def _run_slack_events(delivery: WebhookDelivery) -> None:+ from products.conversations.backend.facade.api import accept_slack_event # noqa: PLC0415++ accept_slack_event(delivery)+++def _slack_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ from products.conversations.backend.facade.api import slack_delivery_ownership # noqa: PLC0415++ return slack_delivery_ownership(delivery)++WEBHOOK_CONSUMERS = (WebhookConsumer(name="conversations",@@ -21,4 +34,14 @@ WEBHOOK_CONSUMERS = (event_types=frozenset({"issues", "issue_comment"}),handler=_run_conversations,),+ WebhookConsumer(+ name="conversations_slack",+ provider="slack",+ app="supporthog",+ event_types=SLACK_EVENT_TYPES,+ handler=_run_slack_events,+ # The unique inbound receipt row is the idempotency here, so a redelivery must reach it.+ dedup=False,+ ownership=_slack_ownership,+ ),)