: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(devex): verify slack requests through the ingress scheme (#103577)
Julian Bez9fe52943c12e
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex ac40bd216305..d4b3c9f39f98 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -8,7 +8,9 @@ rules:and register the handlers in `products/<product>/backend/webhook_consumers.py`.An endpoint that genuinely needs DRF team scoping (Customer.io) keeps its view andsubclasses `WebhookSignatureAuthentication`, which itself verifies through the ingress- schemes. `posthog/ingress/README.md` holds the transport contract.+ schemes. An endpoint that must answer its sender synchronously, such as a Slack slash+ command, keeps its view too and calls the provider's scheme builder directly, as+ `validate_slack_request` does. `posthog/ingress/README.md` holds the transport contract.Why: a hand-rolled verifier repeats the parts that are easy to get wrong, theconstant-time compare, the replay window and the exact signed input, and it lands@@ -116,5 +118,4 @@ rules:# so the rule holds whether or not the migrations land with it.- /ee/api/vercel/vercel_webhooks.py- /ee/partners/stripe/api/provisioning/signature.py- - /posthog/models/integration/slack.py- /products/workflows/backend/api/ses_events_webhook.pydiff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex dafe132be026..5192d818bfbe 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -265,6 +265,7 @@ Two shapes that already exist and are worth copying rather than re-deriving:- **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.It backs three endpoints rather than Customer.io alone, because the tasks cross-region usage lookup and the AI observability cross-region spend lookup subclass it too, each with its own header names, signed-input format, and secret.+- **The scheme-only caller.** An endpoint that must answer its sender synchronously cannot be a dispatched webhook, because dispatch answers a receipt. It keeps its view and calls the incarnation's scheme builder, so the window and the signed input still have one definition. `slack/` is the case: `build_slack_signature_scheme()` backs the `slack_app` product's endpoints through `posthog.models.integration.validate_slack_request`, while `build_slack_provider()` backs the dispatched conversations endpoints.## Dedupdiff --git a/posthog/ingress/slack/README.md b/posthog/ingress/slack/README.mdindex c7d0b5fccfa6..2e71ffe48b4c 100644--- a/posthog/ingress/slack/README.md+++ b/posthog/ingress/slack/README.md@@ -34,6 +34,10 @@ They are separate here because they are separate endpoints with separate payloadThe 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.+The `slack_app` product runs a second Slack app registration with its own signing secret, held as the `SLACK_APP_SIGNING_SECRET` instance setting.+Its endpoints answer Slack synchronously (a slash command, an interactivity ack, a cross-region workspace probe), so they keep their own views and verify through `build_slack_signature_scheme()` rather than through a provider.+`posthog.models.integration.validate_slack_request` is that call.+## QuirksSlack's `url_verification` handshake wants the challenge echoed in the response body, which no consumer can do.diff --git a/posthog/ingress/slack/provider.py b/posthog/ingress/slack/provider.pyindex 8f3f07ab07d2..5fb135681340 100644--- a/posthog/ingress/slack/provider.py+++ b/posthog/ingress/slack/provider.py@@ -49,6 +49,26 @@ SPECS = ()+def build_slack_signature_scheme(*, secret_getter: Callable[[], str | None]) -> HmacSha256:+ """Slack's request signature, as a scheme on its own.++ The dispatched endpoints reach it through `SlackProvider`. A view that must answer Slack+ synchronously, such as a slash command, keeps its view and calls this directly, so there is+ still one definition of the window and the signed input.+ """+ return HmacSha256(+ secret_getter=secret_getter,+ signature_header="X-Slack-Signature",+ prefix="v0=",+ signed_input="v0_timestamp_body",+ timestamp_header="X-Slack-Request-Timestamp",+ # Slack's own guidance: drop anything older than five minutes. The tighter future+ # bound is clock skew only, so a replayed future timestamp buys almost nothing.+ timestamp_max_age_seconds=300,+ timestamp_max_future_seconds=60,+ )++def _delivery_context(request: HttpRequest, *, slack_team_id: str) -> dict[str, str]:return {"slack_team_id": slack_team_id,@@ -69,17 +89,7 @@ class SlackProvider(WebhookProvider):def __init__(self, *, app: str = "supporthog", secret_getter: Callable[[], str | None]) -> None:require_known_app(self.provider, app, SPECS)self.app = app- self._scheme = HmacSha256(- secret_getter=secret_getter,- signature_header="X-Slack-Signature",- prefix="v0=",- signed_input="v0_timestamp_body",- timestamp_header="X-Slack-Request-Timestamp",- # Slack's own guidance: drop anything older than five minutes. The tighter future- # bound is clock skew only, so a replayed future timestamp buys almost nothing.- timestamp_max_age_seconds=300,- timestamp_max_future_seconds=60,- )+ self._scheme = build_slack_signature_scheme(secret_getter=secret_getter)def scheme(self) -> SignatureScheme:return self._schemediff --git a/posthog/models/integration/slack.py b/posthog/models/integration/slack.pyindex 02ea5c8e3439..d99562fa9420 100644--- a/posthog/models/integration/slack.py+++ b/posthog/models/integration/slack.py@@ -1,8 +1,6 @@"""Slack integration: connected-workspace API calls and request-signature verification."""-import hmacimport time-import hashlibfrom collections.abc import Iterablefrom datetime import timedeltafrom typing import TYPE_CHECKING, Literal, Optional@@ -23,6 +21,8 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.cache_utils import cache_forfrom posthog.egress.slack.client import SlackWebClient as WebClient+from posthog.ingress.slack.provider import build_slack_signature_scheme+from posthog.ingress.verify.schemes import VerificationOutcome, hmac_sha256_signaturefrom posthog.models.instance_setting import get_instance_settingsfrom . import model@@ -419,38 +419,23 @@ def sign_slack_request(body: bytes, signing_secret: str) -> SlackRequestSignaturand tests. The matching verifier is `validate_slack_request` below."""ts = str(int(time.time()))- sig_basestring = f"v0:{ts}:{body.decode('utf-8')}".encode()- signature = "v0=" + hmac.new(signing_secret.encode("utf-8"), sig_basestring, digestmod=hashlib.sha256).hexdigest()+ # Assembled as bytes, so a body that is not valid UTF-8 signs rather than raising.+ signed = b"v0:" + ts.encode("utf-8") + b":" + body+ signature = hmac_sha256_signature(signing_secret, signed, prefix="v0=")return SlackRequestSignature(signature=signature, timestamp=ts)def validate_slack_request(request: HttpRequest | Request, signing_secret: str) -> None:- """- Validate a Slack request using HMAC-SHA256 signature verification.- Based on https://api.slack.com/authentication/verifying-requests-from-slack- """- 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")+ """Verify a Slack-signed request through the ingress Slack signature scheme.- try:- if time.time() - float(slack_time) > 300:- raise SlackIntegrationError("Expired")- except ValueError:- raise SlackIntegrationError("Invalid")-- sig_basestring = f"v0:{slack_time}:{request.body.decode('utf-8')}"-- my_signature = (- "v0="- + hmac.new(- signing_secret.encode("utf-8"),- sig_basestring.encode("utf-8"),- digestmod=hashlib.sha256,- ).hexdigest()- )+ These endpoints keep their own views because they answer Slack or a sibling region+ synchronously, so only the verifying is delegated. Raises `SlackIntegrationError` on+ anything that is not a good signature inside the replay window.+ """+ scheme = build_slack_signature_scheme(secret_getter=lambda: signing_secret)+ verification = scheme.verify(body=request.body, headers=request.headers)- if not hmac.compare_digest(my_signature, slack_signature):+ if verification.outcome is VerificationOutcome.NOT_CONFIGURED:+ raise SlackIntegrationError("Not configured")+ if verification.outcome is not VerificationOutcome.VERIFIED:raise SlackIntegrationError("Invalid")diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex ca9032ed3744..88a6db367ab1 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -346,7 +346,6 @@ products/skills/backend/api/test/test_community_skills.py::TestSkillTemplateRendproducts/slack_app/backend/tests/test_followup_forwarding.py::TestEventLevelDedupeproducts/slack_app/backend/tests/test_fork_thread.py::TestForkMenuBlockproducts/slack_app/backend/tests/test_posthog_code_interactivity.py::TestExtractAlertSnoozeHints-products/slack_app/backend/tests/test_validate_slack_request.py::TestValidateSlackRequestproducts/slack_app/backend/tests/test_workspace_claims.py::TestDoesOtherRegionClaimWorkspaceproducts/streamlit_apps/backend/tests/test_app_runtime.py::TestGetOtelLogsConfigproducts/streamlit_apps/backend/tests/test_app_runtime.py::TestSandboxCallbackUrldiff --git a/products/slack_app/backend/tests/test_validate_slack_request.py b/products/slack_app/backend/tests/test_validate_slack_request.pyindex c7325e76b6ac..89e6b1006195 100644--- a/products/slack_app/backend/tests/test_validate_slack_request.py+++ b/products/slack_app/backend/tests/test_validate_slack_request.py@@ -5,7 +5,7 @@ import hashlibimport pytestfrom django.core.handlers.wsgi import WSGIRequest-from django.test import RequestFactory, TestCase+from django.test import RequestFactory, SimpleTestCasefrom parameterized import parameterized@@ -28,13 +28,14 @@ def _make_signed_request(body: str, secret: str, timestamp: str | None = None) -return request-class TestValidateSlackRequest(TestCase):+class TestValidateSlackRequest(SimpleTestCase):@parameterized.expand([("valid_signature", "test-secret", "test-secret", None, None),("wrong_secret", "test-secret", "wrong-secret", None, "Invalid"),- ("expired_timestamp", "test-secret", "test-secret", "1000000000", "Expired"),- ("empty_secret", "", "test-secret", None, "Invalid"),+ ("expired_timestamp", "test-secret", "test-secret", "1000000000", "Invalid"),+ ("future_timestamp", "test-secret", "test-secret", str(int(time.time()) + 3600), "Invalid"),+ ("empty_secret", "", "test-secret", None, "Not configured"),("invalid_timestamp", "test-secret", "test-secret", "not-a-number", "Invalid"),])@@ -59,6 +60,34 @@ class TestValidateSlackRequest(TestCase):else:validate_slack_request(request, signing_secret)+ def test_a_non_ascii_signature_header_is_rejected(self):+ # The header arrives decoded as latin-1, and comparing it as a str raises TypeError on a+ # non-ASCII code point, which an unauthenticated caller could turn into a 500.+ factory = RequestFactory()+ request = factory.post(+ "/slack/event-callback",+ data='{"type": "test"}',+ content_type="application/json",+ HTTP_X_SLACK_SIGNATURE="v0=é",+ HTTP_X_SLACK_REQUEST_TIMESTAMP=str(int(time.time())),+ )+ with pytest.raises(SlackIntegrationError, match="Invalid"):+ validate_slack_request(request, "test-secret")++ def test_a_body_that_is_not_utf_8_is_rejected(self):+ # The signed input is assembled as bytes, so a body Slack never sent fails the compare+ # instead of raising a decode error.+ factory = RequestFactory()+ request = factory.post(+ "/slack/event-callback",+ data=b"\xff\xfe",+ content_type="application/json",+ HTTP_X_SLACK_SIGNATURE="v0=" + "0" * 64,+ HTTP_X_SLACK_REQUEST_TIMESTAMP=str(int(time.time())),+ )+ with pytest.raises(SlackIntegrationError, match="Invalid"):+ validate_slack_request(request, "test-secret")+def test_missing_headers(self):factory = RequestFactory()request = factory.post(