Skip to content

: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.

chore(conversations): verify Slack interactivity through ingress (#101519)

Julian Bez02cf425dc63a
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
index a7c79535f4a5..984399394b95 100644
--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
@@ -118,6 +118,5 @@ rules:
- /ee/partners/stripe/api/provisioning/signature.py
- /posthog/models/integration/slack.py
- /products/conversations/backend/mailgun.py
- - /products/conversations/backend/support_slack.py
- /products/user_interviews/backend/presentation/webhooks.py
- /products/workflows/backend/api/ses_events_webhook.py
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 0189644ac0d7..276d272039b3 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -54,17 +54,18 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf
## Endpoints
-| Provider | Path | App | Consumers | Product code |
-| ------------ | ------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
-| `github` | `/webhooks/github`, `/webhooks/github/pr` | `posthog` | `installation_lifecycle`, `installation_repositories` (core), `conversations`, `loops`, `tasks_pr_backstop`, `tasks_pr_review`, `workflows` | `products/{tasks,conversations,workflows}/backend/webhook_consumers.py` |
-| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
-| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
-| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
-| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
-| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/api/email_events.py` |
-| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/api/email_events.py` |
-| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
-| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
+| Provider | Path | App | Consumers | Product code |
+| ------------ | ------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
+| `github` | `/webhooks/github`, `/webhooks/github/pr` | `posthog` | `installation_lifecycle`, `installation_repositories` (core), `conversations`, `loops`, `tasks_pr_backstop`, `tasks_pr_review`, `workflows` | `products/{tasks,conversations,workflows}/backend/webhook_consumers.py` |
+| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
+| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
+| `slack` | `/api/conversations/v1/slack/interactivity` | `supporthog_interactivity` | `conversations_slack_interactivity` | `products/conversations/backend/webhook_consumers.py` |
+| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
+| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
+| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/api/email_events.py` |
+| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/api/email_events.py` |
+| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
+| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
The owner of the third-party App registration owns the route.
The customer-facing GitHub App is shared across products, so its two endpoints are declared in `posthog/urls.py`.
@@ -242,7 +243,7 @@ Last, write `<provider>/README.md` with the fixed sections every provider README
Two shapes that already exist and are worth copying rather than re-deriving:
-- **Several apps on one provider.** One incarnation can serve several apps, each with its own secret getter, its own subscribed event types, and its own consumer set. Consumers register against the app name. `github/` is the case.
+- **Several apps on one provider.** One incarnation can serve several apps, each with its own secret getter, its own subscribed event types, and its own consumer set. Consumers register against the app name. `github/` is the case. An app is one endpoint's consumer surface rather than one registration with the third party: Slack's events and interactivity endpoints are two apps on one Slack app registration, sharing a secret, so each endpoint validates its consumers against only the types it receives.
- **A provider that signs the form rather than the body.** The incarnation overrides both `verify()` and `parse()` to read `request.POST`, assembles the signed input from the form fields, and hands it to `HmacSha256` as if it came from headers. `mailgun/` is the case.
- **The DRF adapter path.** An endpoint that genuinely needs DRF's team scoping keeps its view, and the incarnation contributes a scheme only, declaring no spec, because nothing dispatches there. `customerio/` is the case. The view verifies through `posthog.auth.WebhookSignatureAuthentication`.
That base class computes its digest with `hmac_sha256_signature()` and compares with `signatures_match()` from `verify/schemes.py`, so the adapter path and the dispatched path share one implementation of HMAC-SHA256.
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index 78985ce6cd42..5d2a243265fb 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -39,6 +39,19 @@ class InvalidPayload(Exception):
"""
+def decode_json(raw: str | bytes) -> Any:
+ """Decode a body this package accepts, or raise `InvalidPayload` for one it cannot read.
+
+ One decoder for every provider, so which failures mean 400 is decided once. A provider that
+ reads a form decodes the field it holds the JSON in through here.
+ """
+ try:
+ # RecursionError: deeply nested JSON must answer 400, not 500.
+ return json.loads(raw)
+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError) as error:
+ raise InvalidPayload(str(error)) from error
+
+
class WebhookProvider(ABC):
"""One provider app: how a delivery is verified, and how it is read.
@@ -94,11 +107,7 @@ class WebhookProvider(ABC):
form instead (Slack interactivity, Mailgun) overrides this and reads `request.POST`.
Raise `InvalidPayload` for a body this provider cannot read, and the view answers 400.
"""
- try:
- # RecursionError: deeply nested JSON must answer 400, not 500.
- return json.loads(request.body)
- except (json.JSONDecodeError, UnicodeDecodeError, RecursionError) as error:
- raise InvalidPayload(str(error)) from error
+ return decode_json(request.body)
def pre_dispatch_response(self, request: HttpRequest, payload: Any) -> HttpResponse | None:
"""A handshake the protocol demands, answered before any consumer runs.
diff --git a/posthog/ingress/slack/README.md b/posthog/ingress/slack/README.md
index 0e5799536a4b..c7d0b5fccfa6 100644
--- a/posthog/ingress/slack/README.md
+++ b/posthog/ingress/slack/README.md
@@ -1,6 +1,6 @@
# Slack
-Deliveries from the Slack Events API.
+Deliveries from the Slack Events API and from Slack's interactive components.
## Headers
@@ -11,20 +11,27 @@ Deliveries from the Slack Events API.
## Signature scheme
HMAC-SHA256, hex encoded, with the prefix `v0=`.
-The signed input is `v0:{timestamp}:{body}`.
+The signed input is `v0:{timestamp}:{body}`, over the raw body of either endpoint.
The replay window accepts a timestamp up to 300 seconds old, which is Slack's own guidance, and up to 60 seconds in the future for clock skew.
## Delivery id and event type
-The delivery id is the envelope's `event_id`.
+For an event, the delivery id is the envelope's `event_id`.
The event type is the inner `event.type`, not the envelope's `type`, so a consumer registers for `message` rather than for `event_callback`.
An envelope that is not an `event_callback` becomes no delivery at all.
-The context also carries `slack_team_id`.
+
+An interactive payload carries no id of its own, so its delivery id is `None` and dedup does not apply to it.
+Its event type is the payload's own `type`, such as `block_actions`.
+A consumer that needs idempotency there brings its own key.
+
+Both contexts carry `slack_team_id`, which is `team_id` on an event envelope and `team.id` on an interactive payload.
+An interactive delivery's context also carries `raw_payload`, the signed form field (see [Quirks](#quirks)).
## Apps and secrets
-One app, `supporthog`.
-The signing secret belongs to the product that owns the Slack app, so `build_slack_provider()` takes it as a getter.
+Two apps on one Slack app registration: `supporthog` for the Events API, and `supporthog_interactivity` for interactive components.
+They are separate here because they are separate endpoints with separate payload types, so each one's consumers are validated against only the types its own endpoint receives.
+The signing secret is the same for both, and it belongs to the product that owns the Slack app, so `build_slack_provider()` and `build_slack_interactivity_provider()` take it as a getter.
Nothing under `posthog/ingress/` reads it.
## Quirks
@@ -33,12 +40,19 @@ Slack's `url_verification` handshake wants the challenge echoed in the response
The incarnation answers it in `pre_dispatch_response()`, before dispatch.
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.
+On the interactivity endpoint that also keeps a click visible: Slack shows the person who clicked a delivery error rather than nothing.
The other status codes are the defaults.
+Interactive components are posted as a form with one `payload` field holding the JSON, so `SlackInteractivityProvider` overrides `parse()` and reads `request.POST`.
+That read consumes the request stream under ASGI, which is safe only because the view verifies the raw body first.
+Slack signs the form body rather than the field, and a parsed mapping cannot be serialized back into the signed bytes, so the field itself travels verbatim in the delivery context under `raw_payload`.
+A consumer that keys idempotency on the signed bytes reads it there, and the payload stays exactly what Slack sent.
+
## Consumers
`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.
+`conversations_slack_interactivity`, on the `supporthog_interactivity` app, for the interactive payload types the app can receive.
+Both declare `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.
diff --git a/posthog/ingress/slack/provider.py b/posthog/ingress/slack/provider.py
index 53d332597237..2ce8544708b6 100644
--- a/posthog/ingress/slack/provider.py
+++ b/posthog/ingress/slack/provider.py
@@ -1,8 +1,12 @@
-"""Slack Events API deliveries.
+"""Slack Events API and interactivity deliveries.
Slack wraps the interesting event in an envelope, so the event type a consumer registers for
is the inner `event.type`, not the envelope's. The `url_verification` handshake is answered
before any consumer runs, because Slack wants the challenge echoed in the body.
+
+Interactive components arrive at a second URL, as a form, with a payload shape of their own.
+They are a second app here rather than more event types on `supporthog`, so each endpoint's
+consumers are validated against the type list of the endpoint they actually run on.
"""
from collections.abc import Callable, Mapping, Sequence
@@ -12,7 +16,7 @@ from django.http import HttpRequest, HttpResponse, JsonResponse
from django.utils import timezone
from posthog.ingress.contracts import ProviderSpec, WebhookDelivery
-from posthog.ingress.providers import WebhookProvider
+from posthog.ingress.providers import InvalidPayload, WebhookProvider, decode_json
from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme
SLACK_EVENT_TYPES = frozenset(
@@ -26,7 +30,33 @@ SLACK_EVENT_TYPES = frozenset(
}
)
-SPECS = (ProviderSpec(provider="slack", app="supporthog", event_types=SLACK_EVENT_TYPES),)
+SLACK_INTERACTIVITY_APP = "supporthog_interactivity"
+
+SLACK_INTERACTIVITY_TYPES = frozenset(
+ {
+ "block_actions",
+ "block_suggestion",
+ "message_action",
+ "shortcut",
+ "view_closed",
+ "view_submission",
+ }
+)
+
+SPECS = (
+ ProviderSpec(provider="slack", app="supporthog", event_types=SLACK_EVENT_TYPES),
+ ProviderSpec(provider="slack", app=SLACK_INTERACTIVITY_APP, event_types=SLACK_INTERACTIVITY_TYPES),
+)
+
+
+def _delivery_context(request: HttpRequest, *, slack_team_id: str) -> dict[str, str]:
+ return {
+ "slack_team_id": slack_team_id,
+ # Slack retries a delivery it thinks failed and says so in these headers, which
+ # consumers record on their receipt.
+ "retry_num": request.headers.get("X-Slack-Retry-Num", ""),
+ "retry_reason": request.headers.get("X-Slack-Retry-Reason", ""),
+ }
class SlackProvider(WebhookProvider):
@@ -64,13 +94,6 @@ class SlackProvider(WebhookProvider):
event = payload.get("event")
event = event if isinstance(event, Mapping) else {}
event_id = payload.get("event_id")
- context = {
- "slack_team_id": str(payload.get("team_id") or ""),
- # Slack retries a delivery it thinks failed and says so in these headers, which
- # consumers record on their receipt.
- "retry_num": request.headers.get("X-Slack-Retry-Num", ""),
- "retry_reason": request.headers.get("X-Slack-Retry-Reason", ""),
- }
return (
WebhookDelivery(
provider=self.provider,
@@ -79,6 +102,53 @@ class SlackProvider(WebhookProvider):
event_type=str(event.get("type", "")),
payload=payload,
received_at=timezone.now(),
+ context=_delivery_context(request, slack_team_id=str(payload.get("team_id") or "")),
+ ),
+ )
+
+
+class SlackInteractivityProvider(SlackProvider):
+ """Interactive components: the same app registration and signing secret, a form body.
+
+ The payload shape is its own: no envelope, so the event type is the payload's own `type`,
+ and the workspace is `team.id` rather than `team_id`.
+ """
+
+ def pre_dispatch_response(self, request: HttpRequest, payload: Any) -> HttpResponse | None:
+ """No handshake here. Slack verifies the Events API URL only, never this one."""
+ return None
+
+ def parse(self, request: HttpRequest) -> Any:
+ """The JSON Slack put in the form's `payload` field."""
+ raw_payload = request.POST.get("payload")
+ if raw_payload is None:
+ raise InvalidPayload("no payload field in the form body")
+ payload = decode_json(raw_payload)
+ if not isinstance(payload, dict):
+ raise InvalidPayload("payload field is not a JSON object")
+ return payload
+
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping):
+ return ()
+ team = payload.get("team")
+ slack_team_id = str(team.get("id") or "") if isinstance(team, Mapping) else ""
+ context = _delivery_context(request, slack_team_id=slack_team_id)
+ # Slack signs the form body rather than the `payload` field, and the parsed mapping cannot
+ # be serialized back into the signed bytes: key order and separators are already lost. A
+ # consumer that keys idempotency on those bytes reads the field verbatim here. Django
+ # caches the parsed form, so this reads the request stream no second time.
+ context["raw_payload"] = request.POST.get("payload", "")
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ # Slack sends no id with an interactive payload, so dedup has nothing to key on.
+ # Idempotency is the consumer's own source id.
+ delivery_id=None,
+ event_type=str(payload.get("type", "")),
+ payload=payload,
+ received_at=timezone.now(),
context=context,
),
)
@@ -87,3 +157,8 @@ class SlackProvider(WebhookProvider):
def build_slack_provider(*, secret_getter: Callable[[], str | None], app: str = "supporthog") -> SlackProvider:
"""The signing secret lives with the product that owns the Slack app, so it is passed in."""
return SlackProvider(app=app, secret_getter=secret_getter)
+
+
+def build_slack_interactivity_provider(*, secret_getter: Callable[[], str | None]) -> SlackInteractivityProvider:
+ """The interactivity endpoint runs on the same signing secret as the events endpoint."""
+ return SlackInteractivityProvider(app=SLACK_INTERACTIVITY_APP, secret_getter=secret_getter)
diff --git a/posthog/ingress/test/test_slack.py b/posthog/ingress/test/test_slack.py
new file mode 100644
index 000000000000..f80e28cda5e6
--- /dev/null
+++ b/posthog/ingress/test/test_slack.py
@@ -0,0 +1,67 @@
+import json
+from typing import Any
+from urllib.parse import urlencode
+
+from django.test import RequestFactory, SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.ingress.providers import InvalidPayload
+from posthog.ingress.slack.provider import build_slack_interactivity_provider
+
+URL = "/webhooks/slack/interactivity"
+FORM_CONTENT_TYPE = "application/x-www-form-urlencoded"
+
+
+def _form_request(payload_field: str, headers: dict[str, str] | None = None) -> Any:
+ return RequestFactory().post(
+ URL,
+ data=urlencode({"payload": payload_field}),
+ content_type=FORM_CONTENT_TYPE,
+ headers=headers or {},
+ )
+
+
+class TestSlackInteractivityProvider(SimpleTestCase):
+ def setUp(self) -> None:
+ self.provider = build_slack_interactivity_provider(secret_getter=lambda: "slack-signing-secret")
+
+ def test_the_signed_payload_field_reaches_the_consumer_unaltered(self) -> None:
+ # A consumer hashes these exact bytes for its idempotency key, and the parsed mapping
+ # cannot be serialized back into them: this spacing does not survive the round trip.
+ raw_payload = '{"type":"block_actions", "team":{"id":"T123"}}'
+ request = _form_request(raw_payload)
+
+ delivery = self.provider.deliveries(request, self.provider.parse(request), {})[0]
+
+ self.assertEqual(delivery.context["raw_payload"], raw_payload)
+ # The payload stays what Slack sent inside the field. Carrying the raw string in it
+ # instead would put a key of ours in the receipt the consumer stores.
+ self.assertEqual(delivery.payload, {"type": "block_actions", "team": {"id": "T123"}})
+
+ @parameterized.expand(
+ [
+ ("a field that is not JSON", _form_request("{")),
+ ("a field that is not an object", _form_request("null")),
+ ("a form with no payload field", RequestFactory().post(URL, data="", content_type=FORM_CONTENT_TYPE)),
+ ]
+ )
+ def test_a_body_this_provider_cannot_read_is_an_invalid_payload(self, _name: str, request: Any) -> None:
+ with self.assertRaises(InvalidPayload):
+ self.provider.parse(request)
+
+ def test_a_delivery_reads_the_interactive_payload_shape(self) -> None:
+ raw_payload = json.dumps({"type": "block_actions", "team": {"id": "T123"}, "actions": [{"action_id": "open"}]})
+ request = _form_request(raw_payload, headers={"X-Slack-Retry-Num": "2", "X-Slack-Retry-Reason": "http_timeout"})
+
+ deliveries = self.provider.deliveries(request, self.provider.parse(request), {})
+
+ self.assertEqual(len(deliveries), 1)
+ delivery = deliveries[0]
+ self.assertEqual(delivery.app, "supporthog_interactivity")
+ self.assertEqual(delivery.event_type, "block_actions")
+ # Slack sends no id with a click, so dedup has nothing to key on.
+ self.assertIsNone(delivery.delivery_id)
+ self.assertEqual(delivery.context["slack_team_id"], "T123")
+ self.assertEqual(delivery.context["retry_num"], "2")
+ self.assertEqual(delivery.context["retry_reason"], "http_timeout")
diff --git a/products/conversations/backend/api/slack_interactivity.py b/products/conversations/backend/api/slack_interactivity.py
index caefc3095b05..38c98a6347cc 100644
--- a/products/conversations/backend/api/slack_interactivity.py
+++ b/products/conversations/backend/api/slack_interactivity.py
@@ -6,95 +6,11 @@ The events endpoint posts the prompt; this endpoint handles the click and create
— or skips — the ticket.
"""
-import json
+from posthog.ingress.slack.provider import build_slack_interactivity_provider
+from posthog.ingress.views import build_webhook_view
-from django.conf import settings
-from django.http import HttpRequest, HttpResponse
-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_interactivity_source_id,
- slack_retry_metadata,
+supporthog_interactivity_handler = build_webhook_view(
+ build_slack_interactivity_provider(secret_getter=get_support_slack_signing_secret)
)
-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__)
-
-
-@csrf_exempt
-def supporthog_interactivity_handler(request: HttpRequest) -> HttpResponse:
- """Handle Slack interactive button clicks for SupportHog.
-
- Regional routing matches the events endpoint: 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 click.
- """
- if request.method != "POST":
- return HttpResponse(status=405)
-
- try:
- validate_support_request(request)
- except SlackIntegrationError as e:
- logger.warning("supporthog_interactivity_invalid_request", error=str(e))
- return HttpResponse("Invalid request", status=403)
-
- # Hash the form `payload` field. request.body is already consumed after request.POST
- # on ASGI, and Slack retries send the same payload JSON.
- raw_payload = request.POST.get("payload", "{}")
- try:
- payload = json.loads(raw_payload)
- except (json.JSONDecodeError, TypeError):
- return HttpResponse("Invalid JSON", status=400)
- if not isinstance(payload, dict):
- return HttpResponse("Invalid payload", status=400)
-
- slack_team = payload.get("team")
- slack_team_id = slack_team.get("id", "") if isinstance(slack_team, dict) else ""
- if not slack_team_id:
- return HttpResponse(status=200)
-
- retry_num, retry_reason = slack_retry_metadata(request)
- logger.info(
- "supporthog_interactivity_received",
- payload_type=payload.get("type"),
- slack_team_id=slack_team_id,
- retry_num=retry_num,
- )
-
- team = team_for_slack_workspace(slack_team_id)
- if team is not None and not (settings.DEBUG and is_primary_region(request)):
- accept_inbound_event(
- team=team,
- source=ConversationInboundEventSource.SLACK_INTERACTIVITY,
- source_id=slack_interactivity_source_id(
- payload=payload,
- signed_body=(raw_payload or "").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,
- )
- return HttpResponse(status=200)
-
- if is_primary_region(request):
- # Acking a failed proxy with 200 makes the click silently vanish — Slack shows the
- # clicker nothing and never resends. Surface the failure so Slack displays a
- # delivery error and the user knows to click again.
- if not proxy_to_secondary_region(request, log_prefix="supporthog_interactivity"):
- return HttpResponse("Failed to reach owning region", status=502)
- return HttpResponse(status=200)
-
- logger.warning("supporthog_interactivity_no_team_any_region", slack_team_id=slack_team_id)
- return HttpResponse(status=200)
diff --git a/products/conversations/backend/api/tests/test_slack_endpoints.py b/products/conversations/backend/api/tests/test_slack_endpoints.py
index 6fd10b7d211a..8b94742e8762 100644
--- a/products/conversations/backend/api/tests/test_slack_endpoints.py
+++ b/products/conversations/backend/api/tests/test_slack_endpoints.py
@@ -20,7 +20,6 @@ from slack_sdk.errors import SlackApiError
from posthog.ingress.contracts import DeliveryOwnership, WebhookDelivery
from posthog.ingress.dispatch.dedup import DeliveryDedup
-from posthog.models.integration import SlackIntegrationError
from posthog.models.organization import OrganizationMembership
from products.conversations.backend.facade.api import accept_slack_event, slack_delivery_ownership
@@ -36,6 +35,22 @@ SLACK_EVENTS_MODULE = "products.conversations.backend.services.slack_events"
WAKE_INBOUND_EVENT = f"{SLACK_EVENTS_MODULE}.wake_inbound_event"
+def _signed_headers(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 _forged_headers(signed_body: bytes | None) -> dict[str, str]:
+ if signed_body is None:
+ return {"x-slack-request-timestamp": "", "x-slack-signature": ""}
+ return _signed_headers(signed_body)
+
+
class TestSupportSlackEventsAPI(BaseTest):
client: APIClient
@@ -57,17 +72,8 @@ class TestSupportSlackEventsAPI(BaseTest):
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", {})}
+ headers = {**_signed_headers(body), **kwargs.pop("headers", {})}
return self.client.post(
"/api/conversations/v1/slack/events",
data=body,
@@ -86,14 +92,18 @@ class TestSupportSlackEventsAPI(BaseTest):
def _event_row(self) -> ConversationInboundEvent:
return ConversationInboundEvent.objects.for_team(self.team.id).get()
- 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",
- )
+ @parameterized.expand(
+ [
+ ("missing_headers", None),
+ ("signature_of_another_body", b"another body"),
+ ]
+ )
+ @patch(WAKE_INBOUND_EVENT)
+ def test_invalid_signature_returns_403(self, _name: str, signed_body: bytes | None, mock_wake: MagicMock):
+ response = self._post({"type": "event_callback", "event_id": "Ev_forged"}, headers=_forged_headers(signed_body))
assert response.status_code == 403
+ mock_wake.assert_not_called()
@patch(WAKE_INBOUND_EVENT)
def test_slack_retry_is_recorded_and_processed(self, mock_wake: MagicMock):
@@ -376,13 +386,23 @@ class TestSupportSlackInteractivityAPI(BaseTest):
)
self.client = APIClient()
cache.clear()
+ 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 _post_raw(self, payload_field: str, **kwargs):
- # Slack sends interactivity payloads form-encoded, as a `payload` field.
+ # Slack sends interactivity payloads form-encoded, as a `payload` field, and signs the
+ # form body rather than the field.
+ body = urlencode({"payload": payload_field}).encode("utf-8")
+ headers = {**_signed_headers(body), **kwargs.pop("headers", {})}
return self.client.post(
"/api/conversations/v1/slack/interactivity",
- data=urlencode({"payload": payload_field}),
+ data=body,
content_type="application/x-www-form-urlencoded",
+ headers=headers,
**kwargs,
)
@@ -393,44 +413,36 @@ class TestSupportSlackInteractivityAPI(BaseTest):
with self.captureOnCommitCallbacks(execute=True):
return self._post(payload, **kwargs)
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_invalid_signature_returns_403(self, mock_validate: MagicMock):
- mock_validate.side_effect = SlackIntegrationError("Invalid")
-
- response = self._post({"type": "block_actions"})
+ @parameterized.expand(
+ [
+ ("missing_headers", None),
+ ("signature_of_another_body", b"another body"),
+ ]
+ )
+ def test_invalid_signature_returns_403(self, _name: str, signed_body: bytes | None):
+ response = self._post({"type": "block_actions"}, headers=_forged_headers(signed_body))
assert response.status_code == 403
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_invalid_json_returns_400(self, mock_validate: MagicMock):
- mock_validate.return_value = None
-
+ def test_invalid_json_returns_400(self):
response = self._post_raw("{")
assert response.status_code == 400
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_non_object_payload_returns_400(self, mock_validate: MagicMock):
- mock_validate.return_value = None
-
+ def test_non_object_payload_returns_400(self):
response = self._post(None)
assert response.status_code == 400
- @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_missing_team_id_returns_200_without_processing(self, mock_validate: MagicMock, mock_wake: MagicMock):
- mock_validate.return_value = None
-
+ @patch(WAKE_INBOUND_EVENT)
+ def test_missing_team_id_is_receipted_without_processing(self, mock_wake: MagicMock):
response = self._post({"type": "block_actions"})
- assert response.status_code == 200
+ assert response.status_code == 202
mock_wake.assert_not_called()
- @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_block_actions_enqueues_processing(self, mock_validate: MagicMock, mock_wake: MagicMock):
- mock_validate.return_value = None
+ @patch(WAKE_INBOUND_EVENT)
+ def test_block_actions_enqueues_processing(self, mock_wake: MagicMock):
payload = {
"type": "block_actions",
"team": {"id": "T123"},
@@ -442,20 +454,18 @@ class TestSupportSlackInteractivityAPI(BaseTest):
first = self._post_committed(payload)
second = self._post_committed(payload)
- assert first.status_code == 200
- assert second.status_code == 200
+ assert first.status_code == 202
+ assert second.status_code == 202
assert ConversationInboundEvent.objects.for_team(self.team.id).count() == 1
row = ConversationInboundEvent.objects.for_team(self.team.id).get()
assert row.source == ConversationInboundEventSource.SLACK_INTERACTIVITY
assert row.source_id.startswith("trig.1:")
+ # Slack sends no delivery id with a click, so ingress dedup has nothing to key on and the
+ # consumer runs on both posts. The source id is what keeps the second one to one row.
assert mock_wake.call_count == 2
- @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_block_actions_without_trigger_id_hashes_payload_field(
- self, mock_validate: MagicMock, mock_wake: MagicMock
- ):
- mock_validate.return_value = None
+ @patch(WAKE_INBOUND_EVENT)
+ def test_block_actions_without_trigger_id_hashes_payload_field(self, mock_wake: MagicMock):
payload = {
"type": "block_actions",
"team": {"id": "T123"},
@@ -465,58 +475,43 @@ class TestSupportSlackInteractivityAPI(BaseTest):
response = self._post_committed(payload)
- assert response.status_code == 200
+ assert response.status_code == 202
row = ConversationInboundEvent.objects.for_team(self.team.id).get()
assert row.source_id == hashlib.sha256(raw_payload.encode("utf-8")).hexdigest()
+ assert row.payload == payload
mock_wake.assert_called_once()
- @patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_proxies_to_secondary_when_team_not_found_on_primary(
- self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
- ):
- mock_validate.return_value = None
- mock_proxy.return_value = True
-
- with patch("products.conversations.backend.api.slack_interactivity.is_primary_region", return_value=True):
- response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})
-
- assert response.status_code == 200
- mock_wake.assert_not_called()
- mock_proxy.assert_called_once()
-
- @patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_returns_502_when_proxy_to_secondary_fails(
- self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
+ @parameterized.expand(
+ [
+ ("the owning region accepts it", 202, 202),
+ # Acking a failed forward with a 2xx silently drops the click. Slack shows the clicker
+ # nothing and never resends. A non-2xx surfaces the failure in Slack.
+ ("the owning region is unreachable", 500, 502),
+ ]
+ )
+ def test_a_workspace_another_region_owns_is_forwarded_from_the_primary(
+ self, _name: str, secondary_status: int, expected_status: int
):
- # Acking a failed proxy with 200 silently drops the click. Slack shows the
- # clicker nothing and never resends. A non-2xx surfaces the failure in Slack.
- mock_validate.return_value = None
- mock_proxy.return_value = False
-
- with patch("products.conversations.backend.api.slack_interactivity.is_primary_region", return_value=True):
+ 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({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})
- assert response.status_code == 502
+ assert response.status_code == expected_status
+ mock_forward.assert_called_once()
mock_wake.assert_not_called()
- @patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
- @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_drops_click_when_team_not_found_on_secondary(
- self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
- ):
- mock_validate.return_value = None
-
- with patch("products.conversations.backend.api.slack_interactivity.is_primary_region", return_value=False):
- response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})
+ @patch("posthog.ingress.dispatch.forward.requests.request")
+ @patch(WAKE_INBOUND_EVENT)
+ def test_drops_click_when_team_not_found_on_secondary(self, mock_wake: MagicMock, mock_forward: MagicMock):
+ response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})
- assert response.status_code == 200
+ assert response.status_code == 202
mock_wake.assert_not_called()
- mock_proxy.assert_not_called()
+ mock_forward.assert_not_called()
class TestSlackChannelsAPI(APIBaseTest):
diff --git a/products/conversations/backend/api/tests/test_support_slack.py b/products/conversations/backend/api/tests/test_support_slack.py
deleted file mode 100644
index 7ea84c05c60c..000000000000
--- a/products/conversations/backend/api/tests/test_support_slack.py
+++ /dev/null
@@ -1,136 +0,0 @@
-import hmac
-import time
-import hashlib
-
-from unittest.mock import MagicMock, patch
-
-from django.test import SimpleTestCase
-
-from parameterized import parameterized
-
-from posthog.models.integration import SlackIntegrationError
-
-from products.conversations.backend.support_slack import validate_support_request
-
-
-class TestValidateSupportRequest(SimpleTestCase):
- def _make_request(self, timestamp: str, body: str, signature: str | None = None) -> MagicMock:
- request = MagicMock()
- request.body = body.encode("utf-8")
- request.headers = {
- "X-SLACK-REQUEST-TIMESTAMP": timestamp,
- "X-SLACK-SIGNATURE": signature or "",
- }
- return request
-
- def _compute_signature(self, secret: str, timestamp: str, body: str) -> str:
- sig_basestring = f"v0:{timestamp}:{body}"
- return (
- "v0="
- + hmac.new(
- secret.encode("utf-8"),
- sig_basestring.encode("utf-8"),
- digestmod=hashlib.sha256,
- ).hexdigest()
- )
-
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_valid_signature_passes(self, mock_settings: MagicMock) -> None:
- secret = "test-secret"
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": secret}
-
- timestamp = str(int(time.time()))
- body = '{"type": "event_callback"}'
- signature = self._compute_signature(secret, timestamp, body)
-
- request = self._make_request(timestamp, body, signature)
-
- validate_support_request(request)
-
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_invalid_signature_raises(self, mock_settings: MagicMock) -> None:
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": "test-secret"}
-
- request = self._make_request(str(int(time.time())), "{}", "v0=invalid")
-
- with self.assertRaises(SlackIntegrationError):
- validate_support_request(request)
-
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_missing_signature_raises(self, mock_settings: MagicMock) -> None:
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": "test-secret"}
-
- request = MagicMock()
- request.body = b"{}"
- request.headers = {"X-SLACK-REQUEST-TIMESTAMP": str(int(time.time()))}
-
- with self.assertRaises(SlackIntegrationError):
- validate_support_request(request)
-
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_missing_timestamp_raises(self, mock_settings: MagicMock) -> None:
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": "test-secret"}
-
- request = MagicMock()
- request.body = b"{}"
- request.headers = {"X-SLACK-SIGNATURE": "v0=something"}
-
- with self.assertRaises(SlackIntegrationError):
- validate_support_request(request)
-
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_expired_timestamp_raises(self, mock_settings: MagicMock) -> None:
- secret = "test-secret"
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": secret}
-
- old_timestamp = str(int(time.time()) - 400)
- body = "{}"
- signature = self._compute_signature(secret, old_timestamp, body)
-
- request = self._make_request(old_timestamp, body, signature)
-
- with self.assertRaises(SlackIntegrationError):
- validate_support_request(request)
-
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_future_timestamp_beyond_tolerance_raises(self, mock_settings: MagicMock) -> None:
- secret = "test-secret"
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": secret}
-
- future_timestamp = str(int(time.time()) + 120)
- body = "{}"
- signature = self._compute_signature(secret, future_timestamp, body)
-
- request = self._make_request(future_timestamp, body, signature)
-
- with self.assertRaises(SlackIntegrationError):
- validate_support_request(request)
-
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_future_timestamp_within_tolerance_passes(self, mock_settings: MagicMock) -> None:
- secret = "test-secret"
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": secret}
-
- future_timestamp = str(int(time.time()) + 30)
- body = "{}"
- signature = self._compute_signature(secret, future_timestamp, body)
-
- request = self._make_request(future_timestamp, body, signature)
-
- validate_support_request(request)
-
- @parameterized.expand(
- [
- ("empty", ""),
- ("text", "not-a-number"),
- ("float_invalid", "12.34.56"),
- ]
- )
- @patch("products.conversations.backend.support_slack.get_support_slack_settings")
- def test_invalid_timestamp_format_raises(self, _name: str, timestamp: str, mock_settings: MagicMock) -> None:
- mock_settings.return_value = {"SUPPORT_SLACK_SIGNING_SECRET": "test-secret"}
-
- request = self._make_request(timestamp, "{}", "v0=something")
-
- with self.assertRaises(SlackIntegrationError):
- validate_support_request(request)
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.py
index cbbf1adbf280..7c97abcfb853 100644
--- a/products/conversations/backend/facade/api.py
+++ b/products/conversations/backend/facade/api.py
@@ -122,11 +122,19 @@ def accept_slack_event(delivery: WebhookDelivery) -> None:
slack_events.accept_slack_event(delivery)
+def accept_slack_interactivity(delivery: WebhookDelivery) -> None:
+ """The inbound SupportHog Slack click 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_interactivity(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.
+ Both Slack endpoints ask through here. 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
diff --git a/products/conversations/backend/services/inbound_events.py b/products/conversations/backend/services/inbound_events.py
index 53d16910c8cc..eb901eed85cc 100644
--- a/products/conversations/backend/services/inbound_events.py
+++ b/products/conversations/backend/services/inbound_events.py
@@ -11,7 +11,6 @@ from uuid import UUID
from django.db import IntegrityError, transaction
from django.db.models import Q, QuerySet
-from django.http import HttpRequest
from django.utils import timezone
import structlog
@@ -99,13 +98,6 @@ def slack_retry_metadata_from_values(*, raw_retry_num: str, retry_reason: 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.py
index d93d05dc94b0..a2a82885b9f1 100644
--- a/products/conversations/backend/services/slack_events.py
+++ b/products/conversations/backend/services/slack_events.py
@@ -1,10 +1,13 @@
-"""Slack Events API deliveries for the SupportHog app.
+"""Slack deliveries for the SupportHog app, from the Events API and from interactive components.
-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.
+Three entry points, all reached from the facade after ingress verified the signature and parsed
+the body: ``slack_delivery_ownership`` answers which region holds the workspace the delivery is
+about, and ``accept_slack_event`` and ``accept_slack_interactivity`` write the inbound receipt and
+wake its worker. No HTTP in here -- ingress owns the request, the receipt and the forward to the
+region that owns the workspace.
+
+Both Slack endpoints live here because they answer ownership the same way: each carries the
+workspace id in the delivery context, and one bounded lookup resolves it for both.
"""
import json
@@ -18,6 +21,7 @@ from products.conversations.backend.models import ConversationInboundEventSource
from products.conversations.backend.services.inbound_events import (
accept_inbound_event,
slack_events_source_id,
+ slack_interactivity_source_id,
slack_retry_metadata_from_values,
)
from products.conversations.backend.support_slack import team_for_slack_workspace
@@ -55,12 +59,17 @@ def slack_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
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)
+def _accept_delivery(
+ delivery: WebhookDelivery,
+ *,
+ source: ConversationInboundEventSource,
+ payload: dict[str, Any],
+ source_id: str,
+) -> None:
+ """Write the inbound receipt for a verified Slack delivery and wake its worker."""
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.
+ # dedup mark and Slack's redelivery reaches this consumer instead of the delivery 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
@@ -73,16 +82,41 @@ def accept_slack_event(delivery: WebhookDelivery) -> None:
)
accept_inbound_event(
team=team,
+ source=source,
+ source_id=source_id,
+ provider_account_id=slack_team_id,
+ payload=payload,
+ provider_retry_num=retry_num,
+ provider_retry_reason=retry_reason,
+ wake=wake_inbound_event,
+ )
+
+
+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)
+ _accept_delivery(
+ delivery,
source=ConversationInboundEventSource.SLACK_EVENTS,
+ payload=payload,
# 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,
+ )
+
+
+def accept_slack_interactivity(delivery: WebhookDelivery) -> None:
+ """Record a verified Slack interactive payload against the workspace's team and wake its worker."""
+ payload: dict[str, Any] = dict(delivery.payload)
+ # The signed `payload` field, which the incarnation carries on the context so the source id
+ # hashes the bytes Slack signed rather than a re-serialization of the parsed mapping.
+ raw_payload = delivery.context.get("raw_payload", "")
+ _accept_delivery(
+ delivery,
+ source=ConversationInboundEventSource.SLACK_INTERACTIVITY,
payload=payload,
- provider_retry_num=retry_num,
- provider_retry_reason=retry_reason,
- wake=wake_inbound_event,
+ source_id=slack_interactivity_source_id(payload=payload, signed_body=raw_payload.encode("utf-8")),
)
diff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.py
index 2b6d0546906e..19aea3130b98 100644
--- a/products/conversations/backend/support_slack.py
+++ b/products/conversations/backend/support_slack.py
@@ -1,16 +1,9 @@
-import hmac
-import time
-import hashlib
from typing import TYPE_CHECKING, cast
from django.db import transaction
-from django.http import HttpRequest
-
-from rest_framework.request import Request
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.instance_setting import get_instance_settings
-from posthog.models.integration import SlackIntegrationError
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import mask_key_value
@@ -81,41 +74,6 @@ def team_exists_for_slack_workspace(slack_team_id: str) -> bool:
).exists()
-def validate_support_request(request: HttpRequest | Request) -> None:
- """
- Validate Support Slack bot requests.
- Based on https://api.slack.com/authentication/verifying-requests-from-slack
- """
- support_settings = get_support_slack_settings()
- signing_secret = str(support_settings.get("SUPPORT_SLACK_SIGNING_SECRET") or "")
- slack_signature = request.headers.get("X-SLACK-SIGNATURE")
- slack_time = request.headers.get("X-SLACK-REQUEST-TIMESTAMP")
-
- if not signing_secret or not slack_signature or not slack_time:
- raise SlackIntegrationError("Invalid")
-
- try:
- timestamp_diff = time.time() - float(slack_time)
- # Reject requests older than 5 minutes OR from the future (with 60s tolerance for clock skew)
- if timestamp_diff > 300 or timestamp_diff < -60:
- raise SlackIntegrationError("Expired")
- except ValueError:
- raise SlackIntegrationError("Invalid")
-
- sig_basestring = f"v0:{slack_time}:{request.body.decode('utf-8')}"
- expected_signature = (
- "v0="
- + hmac.new(
- signing_secret.encode("utf-8"),
- sig_basestring.encode("utf-8"),
- digestmod=hashlib.sha256,
- ).hexdigest()
- )
-
- if not hmac.compare_digest(expected_signature, slack_signature):
- raise SlackIntegrationError("Invalid")
-
-
def save_supporthog_slack_token(
*,
team: "Team",
diff --git a/products/conversations/backend/tests/test_inbound_event_processing.py b/products/conversations/backend/tests/test_inbound_event_processing.py
index 1222a6e62978..0ce103d866bb 100644
--- a/products/conversations/backend/tests/test_inbound_event_processing.py
+++ b/products/conversations/backend/tests/test_inbound_event_processing.py
@@ -9,7 +9,7 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.db import IntegrityError
-from django.test import RequestFactory, SimpleTestCase
+from django.test import SimpleTestCase
from django.utils import timezone
from prometheus_client import REGISTRY, CollectorRegistry
@@ -38,7 +38,7 @@ from products.conversations.backend.services.inbound_events import (
schedule_inbound_retry,
slack_events_source_id,
slack_interactivity_source_id,
- slack_retry_metadata,
+ slack_retry_metadata_from_values,
)
from products.conversations.backend.slack import TICKET_CONFIRM_ACTION_OPEN
from products.conversations.backend.tasks.slack import (
@@ -91,17 +91,17 @@ class TestInboundEventSourceId(SimpleTestCase):
class TestSlackRetryMetadata(SimpleTestCase):
- def test_parses_retry_headers(self) -> None:
- request = RequestFactory().post("/", HTTP_X_SLACK_RETRY_NUM="2", HTTP_X_SLACK_RETRY_REASON="http_timeout")
- assert slack_retry_metadata(request) == (2, "http_timeout")
+ def test_parses_retry_values(self) -> None:
+ assert slack_retry_metadata_from_values(raw_retry_num="2", retry_reason="http_timeout") == (2, "http_timeout")
def test_invalid_retry_num_is_ignored(self) -> None:
- request = RequestFactory().post("/", HTTP_X_SLACK_RETRY_NUM="nope", HTTP_X_SLACK_RETRY_REASON="http_timeout")
- assert slack_retry_metadata(request) == (None, "http_timeout")
+ assert slack_retry_metadata_from_values(raw_retry_num="nope", retry_reason="http_timeout") == (
+ None,
+ "http_timeout",
+ )
def test_negative_retry_num_is_ignored(self) -> None:
- request = RequestFactory().post("/", HTTP_X_SLACK_RETRY_NUM="-1")
- assert slack_retry_metadata(request) == (None, "")
+ assert slack_retry_metadata_from_values(raw_retry_num="-1", retry_reason="") == (None, "")
class TestWakeInboundEvent(SimpleTestCase):
diff --git a/products/conversations/backend/webhook_consumers.py b/products/conversations/backend/webhook_consumers.py
index ddebec9da7b7..74f59c468573 100644
--- a/products/conversations/backend/webhook_consumers.py
+++ b/products/conversations/backend/webhook_consumers.py
@@ -5,7 +5,7 @@ its own product import.
"""
from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDelivery
-from posthog.ingress.slack.provider import SLACK_EVENT_TYPES
+from posthog.ingress.slack.provider import SLACK_EVENT_TYPES, SLACK_INTERACTIVITY_APP, SLACK_INTERACTIVITY_TYPES
def _run_conversations(delivery: WebhookDelivery) -> None:
@@ -20,6 +20,12 @@ def _run_slack_events(delivery: WebhookDelivery) -> None:
accept_slack_event(delivery)
+def _run_slack_interactivity(delivery: WebhookDelivery) -> None:
+ from products.conversations.backend.facade.api import accept_slack_interactivity # noqa: PLC0415
+
+ accept_slack_interactivity(delivery)
+
+
def _slack_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
from products.conversations.backend.facade.api import slack_delivery_ownership # noqa: PLC0415
@@ -44,4 +50,14 @@ WEBHOOK_CONSUMERS = (
dedup=False,
ownership=_slack_ownership,
),
+ WebhookConsumer(
+ name="conversations_slack_interactivity",
+ provider="slack",
+ app=SLACK_INTERACTIVITY_APP,
+ event_types=SLACK_INTERACTIVITY_TYPES,
+ handler=_run_slack_interactivity,
+ # The same workspace lookup as the events consumer: an interactive payload names the
+ # workspace too, so a click on a workspace the other region holds is forwarded there.
+ ownership=_slack_ownership,
+ ),
)