: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
feat(slack-app): region-aware routing for slack event-callback (#60350)
Vojta Bartoš1fac86f365a8
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex ed7fdc9a1973..36492034f4b1 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -1258,6 +1258,18 @@ class SlackIntegration:}+def sign_slack_request(body: bytes, signing_secret: str) -> tuple[str, str]:+ """Sign a body with the Slack HMAC-SHA256 scheme; returns (signature, timestamp).++ Used by both prod (PostHog→PostHog cross-region calls that reuse the Slack signing scheme)+ and 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()+ return signature, ts++def validate_slack_request(request: HttpRequest | Request, signing_secret: str) -> None:"""Validate a Slack request using HMAC-SHA256 signature verification.diff --git a/posthog/urls.py b/posthog/urls.pyindex de297e2b46fd..7f30c1c3e8c3 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -56,7 +56,11 @@ from products.messaging.backend.api.customerio_webhook import CustomerIOWebhookVfrom products.product_tours.backend.api import product_toursfrom products.signals.backend import views as signals_viewsfrom products.signals.backend.views import SignalUserAutonomyConfigView as signals_user_autonomy_view-from products.slack_app.backend.api import posthog_code_event_handler, posthog_code_interactivity_handler+from products.slack_app.backend.api import (+ posthog_code_event_handler,+ posthog_code_interactivity_handler,+ slack_workspace_claims_view,+)from products.surveys.backend.api.survey import public_survey_pagefrom products.user_interviews.backend.presentation.webhooks import (start_call as user_interviews_start_call,@@ -404,6 +408,7 @@ urlpatterns = [path("uploaded_media/<str:image_uuid>", uploaded_media.download),opt_slash_path("slack/interactivity-callback", posthog_code_interactivity_handler),opt_slash_path("slack/event-callback", posthog_code_event_handler),+ opt_slash_path("slack/workspace/claims", slack_workspace_claims_view),# GitHub App webhook — fans out to tasks (PRs) and conversations (issues)opt_slash_path("webhooks/github/pr", github_webhook),opt_slash_path("webhooks/github", github_webhook),diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 3a03ee62e443..5750525767c5 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -23,10 +23,12 @@ from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.llm.gateway_client import get_llm_clientfrom posthog.models.integration import (+ SLACK_INTEGRATION_KINDS,GitHubIntegration,Integration,SlackIntegration,SlackIntegrationError,+ sign_slack_request,validate_slack_request,)from posthog.models.organization import OrganizationMembership@@ -500,29 +502,71 @@ def resolve_slack_user(return None-# To support Slack in both Cloud regions, one region acts as the primary, or "master".-# The primary receives all the events from Slack, and decides what to do about each event:-# 1. If the workspace is connected to any project in the primary region (via Integration), primary handles the event itself;-# 2. If the workspace is NOT connected to any project in the primary region, primary proxies the event to the secondary.-# The secondary region does the same Integration lookup, but if it doesn't find a match either, it stops processing.-# We use EU as the primary region, as it's more important to EU customers that their requests don't leave the EU,-# than to US users that their requests don't leave the US.-SLACK_PRIMARY_REGION_DOMAIN = "eu.posthog.com"-SLACK_SECONDARY_REGION_DOMAIN = "us.posthog.com"+# Slack delivers a single webhook URL per app, but the workspace's PostHog Integration may live+# in either Cloud region. Whichever region Slack hits, we route the event to the region that+# owns the workspace. US is the primary; when both regions hold a row for the same workspace+# (only possible during cutover or migration), US wins. This means:+#+# - hit US, local match -> handle locally+# - hit US, no local match -> proxy to EU (loop header set)+# - hit EU, US says "I have it" -> proxy to US (loop header set)+# - hit EU, US says "no" / errs -> handle locally if found, else drop+# - hit either with loop header -> never proxy again; handle locally or drop+#+# This keeps the slack manifest endpoint swappable between us.posthog.com and eu.posthog.com+# without any other coordination.+REGION_PROXY_HEADER = "X-PostHog-Region-Proxied"+REGION_PROXY_TIMEOUT_SECONDS = 3+# Tight budget: the workspace_claims endpoint is just a DB .exists(), and EU calls it inline+# before deciding whether to proxy. Slack's webhook ack deadline is 3s total, so we want this+# call to fail fast (and fall back to local handling) rather than eat into the proxy budget.+WORKSPACE_CLAIMS_TIMEOUT_SECONDS = (1, 1)-if settings.DEBUG:- # In local dev, we implicitly test the regional routing by ALWAYS proxying once. When the request first arrives via- # SITE_URL (e.g. slackhog.ngrok.dev) we treat that as the primary region with no relevant integration, and proxy- # to localhost:8000, where the actual event handler runs. This way we ensure routing works, and works well.- SLACK_PRIMARY_REGION_DOMAIN = urlparse(settings.SITE_URL).netloc- SLACK_SECONDARY_REGION_DOMAIN = "localhost:8000"+def _us_region_domain() -> str:+ # Resolved at call time so override_settings(DEBUG=...) flips the topology cleanly in tests.+ # In dev we run a single instance pretending to be both regions: the incoming SITE_URL host+ # plays the part of US, and the other region is mapped to localhost so the proxy round-trips+ # through the same process and exercises the at-most-one-hop guarantee end-to-end.+ if settings.DEBUG:+ return urlparse(settings.SITE_URL).netloc+ return "us.posthog.com"-def _proxy_to_secondary(request: HttpRequest) -> requests.Response | None:- """Proxy a request to the secondary region, returning the upstream response or None on failure."""++def _eu_region_domain() -> str:+ if settings.DEBUG:+ return "localhost:8000"+ return "eu.posthog.com"+++def _is_us_host(host: str) -> bool:+ return host == _us_region_domain()+++def _other_region_domain(incoming_host: str) -> str:+ return _eu_region_domain() if _is_us_host(incoming_host) else _us_region_domain()+++def _was_proxied(request: HttpRequest) -> bool:+ # Match the literal value the sender sets (`"1"`) rather than coercing the header value to+ # bool — semgrep flags the latter as nan-injection and we control the sender anyway.+ return request.headers.get(REGION_PROXY_HEADER) == "1"+++def _proxy_event_to_region(request: HttpRequest, target_domain: str) -> requests.Response | None:+ """Forward the original Slack event to the other region, tagged so the receiver does not hop again."""parsed_url = urlparse(request.build_absolute_uri())- target_url = urlunparse(parsed_url._replace(netloc=SLACK_SECONDARY_REGION_DOMAIN))- headers = {key: value for key, value in request.headers.items() if key.lower() != "host"}+ # In dev the EU "region" is plain-HTTP localhost while the incoming URI is HTTPS (ngrok-+ # terminated TLS), so always pick the scheme by target domain rather than copying the+ # inbound one. Production talks HTTPS region-to-region.+ target_scheme = "http" if settings.DEBUG else "https"+ target_url = urlunparse(parsed_url._replace(scheme=target_scheme, netloc=target_domain))+ # Drop Host plus the host-identifying forwarded headers so the receiver computes its own+ # host from the new TCP connection rather than mirroring the sender's edge. X-Forwarded-For+ # is intentionally preserved so the original Slack client IP survives the inter-region hop.+ stripped = {"host", "x-forwarded-host", "forwarded"}+ headers = {key: value for key, value in request.headers.items() if key.lower() not in stripped}+ headers[REGION_PROXY_HEADER] = "1"try:response = requests.request(@@ -531,25 +575,122 @@ def _proxy_to_secondary(request: HttpRequest) -> requests.Response | None:headers=headers,params=dict(request.GET.lists()) if request.GET else None,data=request.body or None,- timeout=3,+ timeout=REGION_PROXY_TIMEOUT_SECONDS,)if 200 <= response.status_code < 300:- logger.info("slack_app_proxy_to_secondary_region", target_url=target_url, status_code=response.status_code)+ logger.info("slack_app_region_proxy_ok", target_url=target_url, status_code=response.status_code)return responselogger.warning(- "slack_app_proxy_to_secondary_region_non_success",+ "slack_app_region_proxy_non_success",target_url=target_url,status_code=response.status_code,)return Noneexcept requests.RequestException as exc:- logger.exception("slack_app_proxy_to_secondary_region_failed", error=str(exc), target_url=target_url)+ logger.exception("slack_app_region_proxy_failed", error=str(exc), target_url=target_url)return None-def proxy_slack_event_to_secondary_region(request: HttpRequest) -> bool:- return _proxy_to_secondary(request) is not None+def _proxy_event_and_return_route(request: HttpRequest, target_domain: str) -> str:+ """Forward and translate the upstream result into a routing outcome string."""+ return ROUTE_PROXIED if _proxy_event_to_region(request, target_domain) is not None else ROUTE_PROXY_FAILED+++def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], incoming_host: str) -> bool | None:+ """Ask the other region whether it claims the given workspace for any of the kinds.++ Returns True/False on a definitive answer, or None on transport failure or bad response.+ Callers must treat None as "unknown" — typically by falling back to local handling so the+ event is not silently dropped.+ """+ target_domain = _other_region_domain(incoming_host)+ scheme = "http" if settings.DEBUG else "https"+ target_url = f"{scheme}://{target_domain}/slack/workspace/claims/"++ body = json.dumps({"slack_team_id": slack_team_id, "kinds": kinds}).encode("utf-8")+ signing_secret = SlackIntegration.posthog_code_slack_config()["SLACK_POSTHOG_CODE_SIGNING_SECRET"]+ signature, ts = sign_slack_request(body, signing_secret)++ try:+ response = requests.post(+ target_url,+ data=body,+ headers={+ "Content-Type": "application/json",+ "X-Slack-Signature": signature,+ "X-Slack-Request-Timestamp": ts,+ REGION_PROXY_HEADER: "1",+ },+ timeout=WORKSPACE_CLAIMS_TIMEOUT_SECONDS,+ )+ except requests.RequestException as exc:+ logger.warning("slack_app_workspace_claims_failed", target_url=target_url, error=str(exc))+ return None++ if response.status_code != 200:+ logger.warning(+ "slack_app_workspace_claims_non_200",+ target_url=target_url,+ status_code=response.status_code,+ )+ return None++ try:+ data = response.json()+ except ValueError:+ logger.warning("slack_app_workspace_claims_bad_json", target_url=target_url)+ return None++ claimed = data.get("claimed")+ if not isinstance(claimed, bool):+ logger.warning("slack_app_workspace_claims_bad_payload", target_url=target_url)+ return None+ return claimed+++_VALID_WORKSPACE_CLAIM_KINDS = frozenset(SLACK_INTEGRATION_KINDS)+++@csrf_exempt+def slack_workspace_claims_view(request: HttpRequest) -> HttpResponse:+ """Cross-region probe: does this region hold an Integration row for the given Slack workspace?++ Both Cloud regions provision the PostHog Code Slack signing secret, so a region can HMAC-sign+ a small JSON body and the receiver can verify it with the same routine that validates real+ Slack webhooks. The signed body covers `slack_team_id` + `kinds`, so a captured signature+ cannot be replayed against a different workspace.+ """+ if request.method != "POST":+ return HttpResponse(status=405)++ try:+ posthog_code_config = SlackIntegration.posthog_code_slack_config()+ validate_slack_request(request, posthog_code_config["SLACK_POSTHOG_CODE_SIGNING_SECRET"])+ except SlackIntegrationError as e:+ logger.warning("slack_app_workspace_claims_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)++ slack_team_id = data.get("slack_team_id")+ kinds = data.get("kinds")+ if not isinstance(slack_team_id, str) or not slack_team_id:+ return HttpResponse("Missing slack_team_id", status=400)+ if not isinstance(kinds, list) or not kinds:+ return HttpResponse("Missing kinds", status=400)+ filtered = [k for k in kinds if isinstance(k, str) and k in _VALID_WORKSPACE_CLAIM_KINDS]+ if not filtered:+ return HttpResponse("No valid kinds", status=400)++ claimed = Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ kind__in=filtered,+ integration_id=slack_team_id,+ ).exists()+ return JsonResponse({"claimed": claimed})def _build_slack_thread_key(slack_workspace_id: str, channel: str, thread_ts: str) -> str:@@ -1347,7 +1488,28 @@ def route_posthog_code_event_to_relevant_region(event_id: str | None = None,) -> str:event_type = event.get("type")- in_region = not (settings.DEBUG and request.get_host() == SLACK_PRIMARY_REGION_DOMAIN)+ incoming_host = request.get_host()+ proxied = _was_proxied(request)+ other_domain = _other_region_domain(incoming_host)+ # In local dev we run a single instance, so cross-region routing is meaningless: the only+ # consumer is this process. Disable both the probe and the proxy hop and always handle+ # locally.+ can_defer_to_other_region = not _is_us_host(incoming_host) and not proxied and not settings.DEBUG++ logger.info(+ "posthog_code_route_enter",+ incoming_host=incoming_host,+ is_us=_is_us_host(incoming_host),+ proxied=proxied,+ other_domain=other_domain,+ can_defer=can_defer_to_other_region,+ event_type=event_type,+ slack_team_id=slack_team_id,+ event_id=event_id,+ debug=settings.DEBUG,+ us_domain=_us_region_domain(),+ eu_domain=_eu_region_domain(),+ )if event_type == "app_mention":ignore_reason = _app_mention_ignore_reason(event)@@ -1371,8 +1533,11 @@ def route_posthog_code_event_to_relevant_region(if isinstance(event.get("thread_ts") or event.get("ts"), str)else None,)- if not result.candidates or not in_region:- return _proxy_or_no_integration(request, slack_team_id)+ if not result.candidates:+ return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)++ if _us_should_handle_instead(slack_team_id, ["slack-posthog-code"], can_defer_to_other_region, incoming_host):+ return _proxy_event_and_return_route(request, other_domain)# Gate the entire @PostHog surface on the rollout flag at the candidate# level so command workflows, pick-a-project hints, and mention workflows@@ -1406,21 +1571,52 @@ def route_posthog_code_event_to_relevant_region(return _start_mention_workflow(event, mention_target, slack_team_id, event_id)# link_shared (unfurl) works with either integration kind.- link_result = load_integrations(slack_team_id=slack_team_id, kinds=["slack", "slack-posthog-code"])+ link_result = load_integrations(slack_team_id=slack_team_id, kinds=list(SLACK_INTEGRATION_KINDS))local_match = link_result.candidates[0] if link_result.candidates else None- if local_match and in_region:+ if local_match:+ if _us_should_handle_instead(+ slack_team_id, list(SLACK_INTEGRATION_KINDS), can_defer_to_other_region, incoming_host+ ):+ return _proxy_event_and_return_route(request, other_domain)if event_type == "link_shared":handle_posthog_link_unfurl(event, local_match)return ROUTE_HANDLED_LOCALLY- return _proxy_or_no_integration(request, slack_team_id)+ return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)+++def _us_should_handle_instead(slack_team_id: str, kinds: list[str], can_defer: bool, incoming_host: str) -> bool:+ """US-precedence guard. EU yields to US when both claim a workspace.++ Skipped when we're already US (we win), when we were proxied to (the other region already+ deferred), or when the lookup transport fails (None) — in that last case the caller should+ prefer handling locally over dropping.+ """+ if not can_defer:+ return False+ claimed = does_other_region_claim_workspace(slack_team_id=slack_team_id, kinds=kinds, incoming_host=incoming_host)+ logger.info(+ "posthog_code_route_us_probe_result",+ slack_team_id=slack_team_id,+ claimed=claimed,+ )+ return bool(claimed)-def _proxy_or_no_integration(request: HttpRequest, slack_team_id: str) -> str:- if request.get_host() == SLACK_PRIMARY_REGION_DOMAIN:- success = proxy_slack_event_to_secondary_region(request)- return ROUTE_PROXIED if success else ROUTE_PROXY_FAILED- logger.warning("posthog_code_no_integration_found", slack_team_id=slack_team_id)- return ROUTE_NO_INTEGRATION+def _route_to_other_region_or_drop(+ request: HttpRequest, slack_team_id: str, *, proxied: bool, other_domain: str+) -> str:+ """No local match: either forward to the other region or drop if we are the second hop.++ In local dev there is no other region to forward to, so we just record the miss and stop.+ """+ if proxied or settings.DEBUG:+ logger.warning(+ "posthog_code_no_integration_found",+ slack_team_id=slack_team_id,+ incoming_host=request.get_host(),+ )+ return ROUTE_NO_INTEGRATION+ return _proxy_event_and_return_route(request, other_domain)def _start_command_workflow(@@ -1530,6 +1726,12 @@ def posthog_code_event_handler(request: HttpRequest) -> HttpResponse:if event.get("type") in HANDLED_EVENT_TYPES:result = route_posthog_code_event_to_relevant_region(request, event, slack_team_id, event_id=event_id)+ logger.info(+ "posthog_code_event_dispatch_result",+ result=result,+ slack_team_id=slack_team_id,+ event_id=event_id,+ )if result == ROUTE_PROXY_FAILED:return HttpResponse(status=502)@@ -1940,6 +2142,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:integration_id=slack_team_id,).exists()+ proxied = _was_proxied(request)+ incoming_host = request.get_host()logger.info("posthog_code_interactivity_resolution",context_token_present=bool(context_token),@@ -1950,29 +2154,60 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:hinted_user=hinted_user_id,terminate_user=terminate_user_id,local=local,- host=request.get_host(),+ host=incoming_host,+ proxied=proxied,)- if not local and request.get_host() == SLACK_PRIMARY_REGION_DOMAIN:- # Proxy to secondary and relay its response back to Slack- upstream = _proxy_to_secondary(request)+ if not local and not proxied and not settings.DEBUG:+ # The payload's integration_id pinpoints exactly one row, so a lookup would tell us+ # nothing new — just forward to the other region. The loop header keeps us at one hop.+ # Skipped in local dev where there is only one region to talk to.+ target = _other_region_domain(incoming_host)+ upstream = _proxy_event_to_region(request, target)if upstream is not None:+ logger.info(+ "posthog_code_interactivity_route",+ outcome="proxied",+ from_host=incoming_host,+ to_domain=target,+ payload_type=payload_type,+ )return HttpResponse(upstream.content,status=upstream.status_code,content_type=upstream.headers.get("Content-Type", "application/json"),)# Proxy failed — return safe defaults+ logger.warning(+ "posthog_code_interactivity_route",+ outcome="proxy_failed",+ from_host=incoming_host,+ to_domain=target,+ payload_type=payload_type,+ )if payload_type == "block_suggestion":return JsonResponse({"options": []})return HttpResponse(status=502)if not local:- logger.warning("posthog_code_interactivity_no_context", context_token=context_token)+ logger.warning(+ "posthog_code_interactivity_route",+ outcome="dropped",+ from_host=incoming_host,+ payload_type=payload_type,+ context_token=context_token,+ )if payload_type == "block_suggestion":return JsonResponse({"options": []})return HttpResponse(status=200)+ logger.info(+ "posthog_code_interactivity_route",+ outcome="handled",+ from_host=incoming_host,+ payload_type=payload_type,+ )+# Handled locallyif payload_type == "block_suggestion":return _handle_repo_picker_options(payload)diff --git a/products/slack_app/backend/tests/helpers.py b/products/slack_app/backend/tests/helpers.pyindex b6c786c25963..93346927dfa0 100644--- a/products/slack_app/backend/tests/helpers.py+++ b/products/slack_app/backend/tests/helpers.py@@ -1,10 +1,3 @@-import hmac-import time-import hashlib+from posthog.models.integration import sign_slack_request--def sign_slack_request(body: bytes, secret: str) -> tuple[str, str]:- ts = str(int(time.time()))- sig_basestring = f"v0:{ts}:{body.decode('utf-8')}"- signature = "v0=" + hmac.new(secret.encode(), sig_basestring.encode(), hashlib.sha256).hexdigest()- return signature, ts+__all__ = ["sign_slack_request"]diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex 10e0a62e5f1e..d2e9eca006ab 100644--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py@@ -121,7 +121,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):@patch("products.slack_app.backend.api.sync_connect")@override_settings(DEBUG=False)def test_local_match_starts_temporal_workflow(self, mock_sync_connect, mock_asyncio_run, _mock_flag):- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region@@ -180,7 +180,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):_mock_flag,mock_get_repos,):- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")mock_get_repos.return_value = repo_list# The route runs _missing_posthog_code_slack_scopes against a real SlackIntegration# before the picker / workflow path. Since SlackIntegration is mocked wholesale here,@@ -268,7 +268,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_asyncio_run,_mock_flag,):- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")ignored_event = {**self.event, **ignore_marker}from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region@@ -290,7 +290,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")event = {**self.event, "text": "<@UBOT123> project 2"}result = route_posthog_code_event_to_relevant_region(request, event, "T12345")@@ -322,7 +322,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")event = {**self.event, "text": "<@UBOT123> project 2"}result = route_posthog_code_event_to_relevant_region(request, event, "T12345")@@ -335,12 +335,13 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):other_integration.id,}+ @patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False)@patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@override_settings(DEBUG=False)def test_rules_add_without_repo_routes_to_command_workflow_for_picker(- self, mock_sync_connect, mock_asyncio_run, _mock_flag+ self, mock_sync_connect, mock_asyncio_run, _mock_flag, _mock_us_claim):# ``rules add "description"`` with no inline repo is still a command, so# the webhook hands it to the command workflow. The command workflow@@ -365,7 +366,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):@patch("products.slack_app.backend.api.sync_connect")@override_settings(DEBUG=False)def test_local_match_flag_off_skips_workflow(self, mock_sync_connect, mock_asyncio_run, _mock_flag):- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region@@ -382,7 +383,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):def test_command_text_with_flag_off_skips_command_workflow(self, mock_sync_connect, mock_asyncio_run, _mock_flag):# Command text from an org outside the rollout must not spawn the command# workflow either — the whole @PostHog surface is gated, not just the agent.- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")event = {**self.event, "text": "<@UBOT123> help"}from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region@@ -421,7 +422,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):route_posthog_code_event_to_relevant_region,)- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")event = {**self.event, "text": "<@UBOT123> help"}result = route_posthog_code_event_to_relevant_region(request, event, "T12345")@@ -435,7 +436,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):@patch("products.slack_app.backend.api.handle_posthog_link_unfurl")@override_settings(DEBUG=False)def test_link_shared_routes_to_unfurl(self, mock_unfurl):- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")link_shared_event = {"type": "link_shared", "channel": "C001", "links": []}from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region@@ -458,7 +459,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):integration_id="T12345",sensitive_config={"access_token": "xoxb-notifications"},)- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")link_shared_event = {"type": "link_shared", "channel": "C001", "links": []}from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region@@ -472,16 +473,15 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):passed_integration = mock_unfurl.call_args[0][1]assert passed_integration.integration_id == "T12345"+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")- @patch("products.slack_app.backend.api.proxy_slack_event_to_secondary_region")- @patch("products.slack_app.backend.api.SLACK_PRIMARY_REGION_DOMAIN", "eu.posthog.com")@override_settings(DEBUG=False)- def test_app_mention_in_primary_with_only_notifications_proxies_to_secondary(- self, mock_proxy, mock_sync_connect, mock_asyncio_run+ def test_app_mention_on_us_with_only_notifications_proxies_to_eu(+ self, mock_sync_connect, mock_asyncio_run, mock_proxy):- # Regression test: the coding-agent install may live in the other region. A notifications-only- # row in the primary region must NOT short-circuit the proxy path for app_mention.+ # US (primary) holds only a notifications install. The coding-agent install may live in EU,+ # so the event must be proxied without consulting the lookup endpoint (US doesn't ask).self.posthog_code_integration.delete()Integration.objects.create(team=self.team,@@ -489,24 +489,29 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):integration_id="T12345",sensitive_config={"access_token": "xoxb-notifications"},)- mock_proxy.return_value = True- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ mock_proxy.return_value = "proxied"+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")from products.slack_app.backend.api import ROUTE_PROXIED, route_posthog_code_event_to_relevant_regionresult = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")assert result == ROUTE_PROXIED- mock_proxy.assert_called_once_with(request)+ mock_proxy.assert_called_once()+ # Target is the EU domain — never the incoming host.+ assert mock_proxy.call_args.args[1] == "eu.posthog.com"mock_sync_connect.assert_not_called()mock_asyncio_run.assert_not_called()+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@override_settings(DEBUG=False)- def test_app_mention_in_secondary_with_only_notifications_noop(self, mock_sync_connect, mock_asyncio_run):- # In the secondary region with only a notifications install, app_mention should- # report no_integration (no coding-agent install anywhere reachable from here).+ def test_loop_header_with_only_notifications_returns_no_integration(+ self, mock_sync_connect, mock_asyncio_run, mock_proxy+ ):+ # The second hop must not bounce the event back. Without local coding-agent install AND+ # the loop header set, we drop with ROUTE_NO_INTEGRATION rather than proxy again.self.posthog_code_integration.delete()Integration.objects.create(team=self.team,@@ -514,36 +519,40 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):integration_id="T12345",sensitive_config={"access_token": "xoxb-notifications"},)- request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ request = self.factory.post(+ "/slack/event-callback/",+ HTTP_HOST="us.posthog.com",+ headers={"x-posthog-region-proxied": "1"},+ )from products.slack_app.backend.api import ROUTE_NO_INTEGRATION, route_posthog_code_event_to_relevant_regionresult = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")assert result == ROUTE_NO_INTEGRATION+ mock_proxy.assert_not_called()mock_sync_connect.assert_not_called()mock_asyncio_run.assert_not_called()- @patch("products.slack_app.backend.api.proxy_slack_event_to_secondary_region")- @patch("products.slack_app.backend.api.SLACK_PRIMARY_REGION_DOMAIN", "eu.posthog.com")+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")@override_settings(DEBUG=False)- def test_proxies_to_secondary_when_no_integration_in_primary(self, mock_proxy):- mock_proxy.return_value = True- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ def test_us_no_local_proxies_to_eu(self, mock_proxy):+ mock_proxy.return_value = "proxied"+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")from products.slack_app.backend.api import ROUTE_PROXIED, route_posthog_code_event_to_relevant_regionresult = route_posthog_code_event_to_relevant_region(request, self.event, "T_UNKNOWN")assert result == ROUTE_PROXIED- mock_proxy.assert_called_once_with(request)+ mock_proxy.assert_called_once()+ assert mock_proxy.call_args.args[1] == "eu.posthog.com"- @patch("products.slack_app.backend.api.proxy_slack_event_to_secondary_region")- @patch("products.slack_app.backend.api.SLACK_PRIMARY_REGION_DOMAIN", "eu.posthog.com")+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")@override_settings(DEBUG=False)def test_proxy_failure_returns_proxy_failed(self, mock_proxy):- mock_proxy.return_value = False- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ mock_proxy.return_value = "proxy_failed"+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")from products.slack_app.backend.api import ROUTE_PROXY_FAILED, route_posthog_code_event_to_relevant_region@@ -551,12 +560,16 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):assert result == ROUTE_PROXY_FAILED+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")- @patch("products.slack_app.backend.api.proxy_slack_event_to_secondary_region")@override_settings(DEBUG=False)- def test_no_integration_in_secondary_returns_no_integration(self, mock_proxy, mock_sync_connect, mock_asyncio_run):- request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ def test_no_local_with_loop_header_returns_no_integration(self, mock_sync_connect, mock_asyncio_run, mock_proxy):+ request = self.factory.post(+ "/slack/event-callback/",+ HTTP_HOST="us.posthog.com",+ headers={"x-posthog-region-proxied": "1"},+ )from products.slack_app.backend.api import ROUTE_NO_INTEGRATION, route_posthog_code_event_to_relevant_region@@ -567,6 +580,115 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_asyncio_run.assert_not_called()mock_proxy.assert_not_called()+ @patch("products.slack_app.backend.api.does_other_region_claim_workspace")+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")+ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_eu_local_match_with_us_lookup_true_proxies_to_us(+ self, mock_sync_connect, mock_asyncio_run, _mock_flag, mock_proxy, mock_lookup+ ):+ # EU has the coding-agent install AND US confirms it has the same workspace.+ # US-precedence: EU must defer rather than handle locally.+ mock_lookup.return_value = True+ mock_proxy.return_value = "proxied"+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")++ from products.slack_app.backend.api import ROUTE_PROXIED, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")++ assert result == ROUTE_PROXIED+ mock_lookup.assert_called_once()+ assert mock_lookup.call_args.kwargs["kinds"] == ["slack-posthog-code"]+ mock_proxy.assert_called_once()+ assert mock_proxy.call_args.args[1] == "us.posthog.com"+ mock_sync_connect.assert_not_called()+ mock_asyncio_run.assert_not_called()++ @patch("products.slack_app.backend.api.does_other_region_claim_workspace")+ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_eu_local_match_with_us_lookup_false_handles_locally(+ self, mock_sync_connect, mock_asyncio_run, _mock_flag, mock_lookup+ ):+ mock_lookup.return_value = False+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_lookup.assert_called_once()+ mock_sync_connect.assert_called_once()+ mock_sync_connect.return_value.start_workflow.assert_called_once()++ @patch("products.slack_app.backend.api.does_other_region_claim_workspace")+ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_eu_local_match_with_us_lookup_failure_falls_back_to_local(+ self, mock_sync_connect, mock_asyncio_run, _mock_flag, mock_lookup+ ):+ # Lookup returns None on transport failure / bad response. Falling back to local handling+ # is safer than dropping — at worst we double-handle if US later turns out to own this.+ mock_lookup.return_value = None+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_lookup.assert_called_once()+ mock_sync_connect.assert_called_once()++ @patch("products.slack_app.backend.api.does_other_region_claim_workspace")+ @patch("products.slack_app.backend.api._proxy_event_and_return_route")+ @override_settings(DEBUG=False)+ def test_eu_no_local_proxies_to_us_without_lookup(self, mock_proxy, mock_lookup):+ mock_proxy.return_value = "proxied"+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")++ from products.slack_app.backend.api import ROUTE_PROXIED, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T_UNKNOWN")++ assert result == ROUTE_PROXIED+ # No need to ask "do you have it" when we know we don't and just have to defer.+ mock_lookup.assert_not_called()+ mock_proxy.assert_called_once()+ assert mock_proxy.call_args.args[1] == "us.posthog.com"++ @patch("products.slack_app.backend.api.does_other_region_claim_workspace")+ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_eu_local_match_with_loop_header_skips_lookup_and_handles(+ self, mock_sync_connect, mock_asyncio_run, _mock_flag, mock_lookup+ ):+ # If the other region forwarded the event to us we already know they couldn't handle it;+ # skipping the lookup avoids ping-pong and a wasted round trip.+ request = self.factory.post(+ "/slack/event-callback/",+ HTTP_HOST="eu.posthog.com",+ headers={"x-posthog-region-proxied": "1"},+ )++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_lookup.assert_not_called()+ mock_sync_connect.assert_called_once()+@parameterized.expand([# Pre-2026-05-04 prod installs only granted the 4 base scopes.@@ -615,7 +737,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):message_ts="1234.7777",)- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")event = {"type": "app_mention","channel": "C001",@@ -640,6 +762,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):if scope_value and "chat:write.customize" in scope_value:assert "chat:write.customize" not in feedback_text+ @patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False)@patch("products.slack_app.backend.api._post_slack_user_feedback")@patch("ee.billing.quota_limiting.is_team_limited", return_value=True)@patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)@@ -655,6 +778,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):_mock_flag,_mock_is_team_limited,mock_post_feedback,+ _mock_us_claim,):mock_slack_instance = mock_slack_cls.return_valuemock_slack_instance.missing_scopes.return_value = set()diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.pyindex da119f043061..a51866a05d08 100644--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py@@ -6,7 +6,7 @@ from typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.core.cache import cache-from django.test import TestCase+from django.test import TestCase, override_settingsfrom rest_framework.test import APIClient@@ -527,3 +527,238 @@ class TestRepoPickerOptions(TestCase):mock_sync_connect.assert_not_called()mock_slack_client.chat_postMessage.assert_not_called()+++@override_settings(DEBUG=False)+class TestInteractivityRegionRouting(TestCase):+ """Region-aware proxying for /slack/interactivity-callback.++ The handler accepts interactivity from whichever region Slack delivers to and either handles+ locally or forwards once to the other region. Unlike event-callback, no cross-region lookup+ is involved — the payload's integration_id uniquely identifies the owning row.+ """++ def setUp(self):+ cache.clear()+ self.client = APIClient()+ self.signing_secret = "posthog-code-test-secret"+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.posthog_code_integration = Integration.objects.create(+ team=self.team,+ kind="slack-posthog-code",+ integration_id="T12345",+ sensitive_config={"access_token": "xoxb-posthog-code-test"},+ )++ def _post(self, payload: dict, *, host: str = "us.posthog.com", **extra_headers) -> Any:+ payload = {"team": {"id": "T12345"}, **payload}+ body_str = f"payload={json.dumps(payload)}"+ body = body_str.encode()+ signature, ts = sign_slack_request(body, self.signing_secret)+ return self.client.post(+ "/slack/interactivity-callback/",+ data=body_str,+ content_type="application/x-www-form-urlencoded",+ HTTP_HOST=host,+ HTTP_X_SLACK_SIGNATURE=signature,+ HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,+ **extra_headers,+ )++ def _local_picker_payload(self) -> dict:+ # block_id "posthog_code_repo_picker_v1:<token>" + a cached context that points at our+ # local integration is the simplest way to drive the "local" branch in the handler.+ token = "ctx-local-1"+ cache.set(+ f"posthog_code_repo_picker_ctx:{token}",+ {+ "integration_id": self.posthog_code_integration.id,+ "channel": "C001",+ "thread_ts": "1234.5678",+ "user_message_ts": "1234.5678",+ "mentioning_slack_user_id": "U123",+ "event_text": "fix the bug",+ "created_at": int(time.time()),+ },+ timeout=900,+ )+ return {+ "type": "block_suggestion",+ "action_id": "posthog_code_repo_select",+ "value": "",+ "user": {"id": "U123"},+ "block_id": f"posthog_code_repo_picker_v1:{token}",+ }++ def _foreign_picker_payload(self) -> dict:+ # Hints/context point at an integration that is NOT in this DB, so the local check misses.+ return {+ "type": "block_suggestion",+ "action_id": "posthog_code_repo_select",+ "value": "",+ "user": {"id": "U999"},+ "block_id": "posthog_code_repo_picker_v1:no-such-token",+ }++ def _foreign_action_payload(self) -> dict:+ return {+ "type": "block_actions",+ "user": {"id": "U999"},+ "actions": [+ {+ "action_id": "posthog_code_repo_select",+ "block_id": "posthog_code_repo_picker_v1:no-such-token",+ "selected_option": {"value": "posthog/posthog"},+ "action_ts": "1700000000.123",+ }+ ],+ "message": {"ts": "1234.9999"},+ }++ @staticmethod+ def _proxy_response(status_code: int, content: bytes = b"", content_type: str = "application/json") -> MagicMock:+ upstream = MagicMock()+ upstream.status_code = status_code+ upstream.content = content+ upstream.headers = {"Content-Type": content_type}+ return upstream++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api._get_full_repo_names", return_value=["posthog/posthog"])+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_local_match_handles_without_proxy(self, mock_config, _mock_repos, mock_proxy):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ response = self._post(self._local_picker_payload(), host="us.posthog.com")+ assert response.status_code == 200+ mock_proxy.assert_not_called()++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_us_no_local_proxies_to_eu(self, mock_config, mock_proxy):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ mock_proxy.return_value = self._proxy_response(200, b'{"forwarded": true}')++ response = self._post(self._foreign_picker_payload(), host="us.posthog.com")++ assert response.status_code == 200+ assert response.content == b'{"forwarded": true}'+ mock_proxy.assert_called_once()+ assert mock_proxy.call_args.args[1] == "eu.posthog.com"++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_eu_no_local_proxies_to_us(self, mock_config, mock_proxy):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ mock_proxy.return_value = self._proxy_response(200, b'{"forwarded": true}')++ response = self._post(self._foreign_picker_payload(), host="eu.posthog.com")++ assert response.status_code == 200+ mock_proxy.assert_called_once()+ assert mock_proxy.call_args.args[1] == "us.posthog.com"++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_loop_header_skips_proxy_block_suggestion_returns_empty_options(self, mock_config, mock_proxy):+ # The loop header is what guarantees at-most-one hop. If we receive a payload that we+ # don't own AND the header is set, the other region already deferred — there is no+ # second region to try, so we must return Slack-safe defaults instead of proxying.+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}++ response = self._post(+ self._foreign_picker_payload(),+ host="eu.posthog.com",+ headers={"x-posthog-region-proxied": "1"},+ )++ assert response.status_code == 200+ assert response.json() == {"options": []}+ mock_proxy.assert_not_called()++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_loop_header_skips_proxy_block_actions_returns_200(self, mock_config, mock_proxy):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}++ response = self._post(+ self._foreign_action_payload(),+ host="eu.posthog.com",+ headers={"x-posthog-region-proxied": "1"},+ )++ assert response.status_code == 200+ mock_proxy.assert_not_called()++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_proxy_failure_returns_502_for_actions(self, mock_config, mock_proxy):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ mock_proxy.return_value = None++ response = self._post(self._foreign_action_payload(), host="us.posthog.com")++ assert response.status_code == 502+ mock_proxy.assert_called_once()++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_proxy_failure_returns_empty_options_for_suggestion(self, mock_config, mock_proxy):+ # block_suggestion has a tight render budget on Slack's side; a 502 would surface as a+ # spinner-then-error in the dropdown. Empty options keeps the UI responsive instead.+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ mock_proxy.return_value = None++ response = self._post(self._foreign_picker_payload(), host="us.posthog.com")++ assert response.status_code == 200+ assert response.json() == {"options": []}+ mock_proxy.assert_called_once()++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_proxy_relays_content_type_verbatim(self, mock_config, mock_proxy):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ mock_proxy.return_value = self._proxy_response(201, b"<xml/>", content_type="application/xml")++ response = self._post(self._foreign_picker_payload(), host="us.posthog.com")++ assert response.status_code == 201+ assert response["Content-Type"] == "application/xml"+ assert response.content == b"<xml/>"++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_terminate_hints_local_handles(self, mock_config, mock_sync_connect, _mock_asyncio_run, mock_proxy):+ # Terminate buttons embed integration_id in the action value (not context_token). When+ # the value points at a row in this DB, we must handle locally without consulting the+ # other region — even when the loop header is absent.+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}++ payload = {+ "type": "block_actions",+ "user": {"id": "U123"},+ "actions": [+ {+ "action_id": "posthog_code_terminate_task",+ "value": json.dumps(+ {+ "run_id": "run-1",+ "integration_id": self.posthog_code_integration.id,+ "mentioning_slack_user_id": "U123",+ }+ ),+ }+ ],+ "channel": {"id": "C001"},+ "message": {"ts": "1234.9999"},+ }++ response = self._post(payload, host="us.posthog.com")++ assert response.status_code == 200+ mock_proxy.assert_not_called()+ mock_sync_connect.assert_called_once()+ mock_sync_connect.return_value.start_workflow.assert_called_once()diff --git a/products/slack_app/backend/tests/test_workspace_claims.py b/products/slack_app/backend/tests/test_workspace_claims.pynew file mode 100644index 000000000000..8ab10fd94744--- /dev/null+++ b/products/slack_app/backend/tests/test_workspace_claims.py@@ -0,0 +1,216 @@+import json+from typing import Any++from unittest.mock import MagicMock, patch++from django.test import RequestFactory, TestCase, override_settings++import requests+from rest_framework.test import APIClient++from posthog.models.integration import Integration, validate_slack_request+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.slack_app.backend.tests.helpers import sign_slack_request+++class TestSlackWorkspaceClaimsView(TestCase):+ """The receiver-side endpoint that the other region calls to ask "do you claim this workspace?".++ Authenticated with the same HMAC scheme Slack uses, against the PostHog Code Slack signing+ secret that both regions already share. The signed body covers `slack_team_id + kinds`, so a+ captured signature cannot be replayed against a different workspace.+ """++ def setUp(self):+ self.client = APIClient()+ self.signing_secret = "posthog-code-workspace-claims-secret"+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")++ def _post(self, payload: dict, signing_secret: str | None = None) -> Any:+ body = json.dumps(payload).encode()+ signature, ts = sign_slack_request(body, signing_secret or self.signing_secret)+ return self.client.post(+ "/slack/workspace/claims/",+ data=body,+ content_type="application/json",+ HTTP_X_SLACK_SIGNATURE=signature,+ HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,+ )++ def test_method_not_allowed(self):+ response = self.client.get("/slack/workspace/claims/")+ assert response.status_code == 405++ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_existing_integration_returns_claimed(self, mock_config):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ Integration.objects.create(+ team=self.team,+ kind="slack-posthog-code",+ integration_id="T_PRESENT",+ sensitive_config={"access_token": "xoxb"},+ )+ response = self._post({"slack_team_id": "T_PRESENT", "kinds": ["slack-posthog-code"]})+ assert response.status_code == 200+ assert response.json() == {"claimed": True}++ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_any_of_kinds_match_returns_claimed(self, mock_config):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T_NOTIF",+ sensitive_config={"access_token": "xoxb"},+ )+ response = self._post({"slack_team_id": "T_NOTIF", "kinds": ["slack", "slack-posthog-code"]})+ assert response.status_code == 200+ assert response.json() == {"claimed": True}++ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_missing_integration_returns_not_claimed(self, mock_config):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ response = self._post({"slack_team_id": "T_UNKNOWN", "kinds": ["slack-posthog-code"]})+ assert response.status_code == 200+ assert response.json() == {"claimed": False}++ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_invalid_signature_returns_403(self, mock_config):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": "different-secret"}+ response = self._post({"slack_team_id": "T_PRESENT", "kinds": ["slack"]})+ assert response.status_code == 403++ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_missing_team_id_returns_400(self, mock_config):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ response = self._post({"kinds": ["slack"]})+ assert response.status_code == 400++ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_no_valid_kinds_returns_400(self, mock_config):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ response = self._post({"slack_team_id": "T_PRESENT", "kinds": ["github", "not-real"]})+ assert response.status_code == 400++ @patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config")+ def test_other_kinds_for_same_id_do_not_count(self, mock_config):+ # Same integration_id can be reused across PostHog integration kinds (e.g. a GitHub install+ # whose external id happens to collide with a Slack workspace). The endpoint must scope+ # to the requested Slack kinds only.+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="T_PRESENT",+ sensitive_config={"access_token": "ghp"},+ )+ response = self._post({"slack_team_id": "T_PRESENT", "kinds": ["slack", "slack-posthog-code"]})+ assert response.status_code == 200+ assert response.json() == {"claimed": False}+++@override_settings(DEBUG=False)+class TestDoesOtherRegionClaimWorkspace(TestCase):+ """The caller-side helper. Constructs and signs the request, parses the response, and+ deliberately returns None on any transport / format failure so the caller falls back to+ local handling instead of silently dropping the event.+ """++ def setUp(self):+ self.signing_secret = "posthog-code-helper-test-secret"++ def _call(self, mock_post_return, **call_overrides) -> bool | None:+ from products.slack_app.backend.api import does_other_region_claim_workspace++ with (+ patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config") as mock_config,+ patch("products.slack_app.backend.api.requests.post") as mock_post,+ ):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ mock_post.return_value = mock_post_return+ kwargs = {+ "slack_team_id": "T123",+ "kinds": ["slack-posthog-code"],+ "incoming_host": "eu.posthog.com",+ **call_overrides,+ }+ result = does_other_region_claim_workspace(**kwargs)+ self.last_call = mock_post.call_args+ return result++ def _response(self, status_code: int, body: Any) -> Any:+ response = MagicMock()+ response.status_code = status_code+ if isinstance(body, Exception):+ response.json.side_effect = body+ else:+ response.json.return_value = body+ return response++ def test_returns_true_when_other_region_claims(self):+ result = self._call(self._response(200, {"claimed": True}))+ assert result is True++ def test_returns_false_when_other_region_does_not_claim(self):+ result = self._call(self._response(200, {"claimed": False}))+ assert result is False++ def test_targets_eu_when_called_from_us(self):+ self._call(self._response(200, {"claimed": False}), incoming_host="us.posthog.com")+ assert "eu.posthog.com" in self.last_call.args[0]+ assert self.last_call.args[0].endswith("/slack/workspace/claims/")++ def test_targets_us_when_called_from_eu(self):+ self._call(self._response(200, {"claimed": False}), incoming_host="eu.posthog.com")+ assert "us.posthog.com" in self.last_call.args[0]+ assert self.last_call.args[0].endswith("/slack/workspace/claims/")++ def test_non_200_returns_none(self):+ result = self._call(self._response(500, {"claimed": True}))+ assert result is None++ def test_bad_json_returns_none(self):+ result = self._call(self._response(200, ValueError("bad json")))+ assert result is None++ def test_unexpected_payload_returns_none(self):+ # Anything other than a bool under "claimed" — including a stringy "true" — is treated as+ # an unknown answer; the caller falls back to local handling rather than guessing.+ result = self._call(self._response(200, {"claimed": "yes"}))+ assert result is None++ def test_request_exception_returns_none(self):+ from products.slack_app.backend.api import does_other_region_claim_workspace++ with (+ patch("products.slack_app.backend.api.SlackIntegration.posthog_code_slack_config") as mock_config,+ patch("products.slack_app.backend.api.requests.post") as mock_post,+ ):+ mock_config.return_value = {"SLACK_POSTHOG_CODE_SIGNING_SECRET": self.signing_secret}+ mock_post.side_effect = requests.ConnectionError("boom")+ result = does_other_region_claim_workspace(+ slack_team_id="T123", kinds=["slack"], incoming_host="us.posthog.com"+ )+ assert result is None++ def test_signed_request_is_accepted_by_validator(self):+ # End-to-end roundtrip: the sent headers + body, fed into the receiver's verifier, must+ # validate cleanly. This is the actual contract we care about — the matched constant-time+ # comparison happens inside validate_slack_request.+ self._call(self._response(200, {"claimed": False}))+ sent_body = self.last_call.kwargs["data"]+ sent_headers = self.last_call.kwargs["headers"]+ request = RequestFactory().post(+ "/slack/workspace/claims/",+ data=sent_body,+ content_type="application/json",+ HTTP_X_SLACK_SIGNATURE=sent_headers["X-Slack-Signature"],+ HTTP_X_SLACK_REQUEST_TIMESTAMP=sent_headers["X-Slack-Request-Timestamp"],+ )+ validate_slack_request(request, self.signing_secret) # raises on mismatch+ # Loop header is included so even if the endpoint URL were ever swapped to the event+ # callback by mistake, the receiver would not re-enter the cross-region machinery.+ assert sent_headers["X-PostHog-Region-Proxied"] == "1"