: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
fix(slack): route unfurls to the linked project (#80521)
Shy Alterc0ccfd38680d
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 7f8242dbe017..bb3a50a62e6a 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -628,19 +628,22 @@ def _proxy_event_and_return_route(request: HttpRequest, target_domain: str) -> sreturn ROUTE_PROXIED if _proxy_event_to_region(request, target_domain) is not None else ROUTE_PROXY_FAILED-def _workspace_claims_cache_key(slack_team_id: str, kinds: list[str]) -> str:+def _workspace_claims_cache_key(slack_team_id: str, kinds: list[str], team_id: int | None = None) -> str:kinds_token = ",".join(sorted(kinds))- return f"slack_app:ws_claims:{slack_team_id}:{kinds_token}"+ team_token = team_id if team_id is not None else "*"+ return f"slack_app:ws_claims:{slack_team_id}:{kinds_token}:{team_token}"-def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], incoming_host: str) -> bool | None:+def does_other_region_claim_workspace(+ *, slack_team_id: str, kinds: list[str], incoming_host: str, team_id: int | None = None+) -> 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.Definitive answers are cached for ``WORKSPACE_CLAIMS_CACHE_TTL_SECONDS`` so a single probeflake does not reroute the next event. None is never cached so the next event re-probes."""- cache_key = _workspace_claims_cache_key(slack_team_id, kinds)+ cache_key = _workspace_claims_cache_key(slack_team_id, kinds, team_id)cached = cache.get(cache_key)if isinstance(cached, bool):logger.info(@@ -654,7 +657,7 @@ def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], ischeme = "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")+ body = json.dumps({"slack_team_id": slack_team_id, "kinds": kinds, "team_id": team_id}).encode("utf-8")signing_secret = SlackIntegration.slack_config()["SLACK_APP_SIGNING_SECRET"]signed = sign_slack_request(body, signing_secret)@@ -706,8 +709,8 @@ def slack_workspace_claims_view(request: HttpRequest) -> HttpResponse:Both Cloud regions provision the PostHog Desktop Slack signing secret, so a region can HMAC-signa 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.+ Slack webhooks. The signed body covers every filter, so a captured signature cannot be replayed+ against a different workspace or project."""if request.method != "POST":return HttpResponse(status=405)@@ -726,6 +729,7 @@ def slack_workspace_claims_view(request: HttpRequest) -> HttpResponse:slack_team_id = data.get("slack_team_id")kinds = data.get("kinds")+ team_id = data.get("team_id")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:@@ -733,11 +737,16 @@ def slack_workspace_claims_view(request: HttpRequest) -> HttpResponse: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)+ if team_id is not None and (not isinstance(team_id, int) or isinstance(team_id, bool)):+ return HttpResponse("Invalid team_id", status=400)- claimed = Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ integrations = Integration.objects.filter( # nosemgrep: idor-lookup-without-teamkind__in=filtered,integration_id=slack_team_id,- ).exists()+ )+ if team_id is not None:+ integrations = integrations.filter(team_id=team_id)+ claimed = integrations.exists()return JsonResponse({"claimed": claimed})@@ -2211,10 +2220,14 @@ def route_posthog_code_event_to_relevant_region(# link_shared (unfurl) works with either integration kind.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+ local_match = _link_shared_integration(event, link_result.candidates)if local_match:if _us_should_handle_instead(- slack_team_id, list(SLACK_INTEGRATION_KINDS), can_defer_to_other_region, incoming_host+ slack_team_id,+ list(SLACK_INTEGRATION_KINDS),+ can_defer_to_other_region,+ incoming_host,+ team_id=local_match.team_id,):return _proxy_event_and_return_route(request, other_domain)if event_type == "link_shared":@@ -2233,7 +2246,9 @@ def route_posthog_code_event_to_relevant_region(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:+def _us_should_handle_instead(+ slack_team_id: str, kinds: list[str], can_defer: bool, incoming_host: str, *, team_id: int | None = None+) -> bool:"""US-precedence guard. EU yields to US when both claim a workspace.Skipped when we're already US (we win) or when we were proxied to (the other region already@@ -2245,7 +2260,9 @@ def _us_should_handle_instead(slack_team_id: str, kinds: list[str], can_defer: b"""if not can_defer:return False- claimed = does_other_region_claim_workspace(slack_team_id=slack_team_id, kinds=kinds, incoming_host=incoming_host)+ claimed = does_other_region_claim_workspace(+ slack_team_id=slack_team_id, kinds=kinds, incoming_host=incoming_host, team_id=team_id+ )decision = True if claimed is None else claimedlogger.info("slack_app_route_us_probe_result",@@ -3050,6 +3067,31 @@ def _link_shared_resource_refs(event: dict[str, Any]) -> list[dict[str, str]]:return resources+def _link_shared_integration(event: dict[str, Any], candidates: list[Integration]) -> Integration | None:+ team_ids: set[int] = set()+ links = event.get("links")+ if isinstance(links, list):+ for link in links:+ if not isinstance(link, dict):+ continue+ url = link.get("url")+ if not isinstance(url, str):+ continue+ parts = [part for part in urlparse(url).path.split("/") if part]+ if len(parts) >= 2 and parts[0] == "project":+ try:+ team_ids.add(int(parts[1]))+ except ValueError:+ continue++ if len(team_ids) == 1:+ team_id = next(iter(team_ids))+ return next((candidate for candidate in candidates if candidate.team_id == team_id), None)+ if team_ids:+ return None+ return candidates[0] if candidates else None++def _extract_context_token(payload: dict) -> str:"""Extract the context token from a block_id (block_suggestion) or message metadata (block_actions)."""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 57e7ab40db9a..9e0ee9e33edc 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@@ -719,6 +719,34 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):passed_integration = mock_unfurl.call_args[0][1]assert passed_integration.id == self.posthog_code_integration.id+ @patch("products.slack_app.backend.api.handle_posthog_link_unfurl")+ @patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False)+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_link_shared_routes_to_project_integration(self, mock_claims, mock_unfurl):+ other_team = Team.objects.create(organization=self.organization, name="Other")+ other_integration = Integration.objects.create(+ team=other_team,+ kind="slack",+ integration_id="T12345",+ config=self.posthog_code_integration.config,+ sensitive_config=self.posthog_code_integration.sensitive_config,+ )+ task_id = "e1452e73-2055-4305-a9de-c9912efa78a3"+ event = {+ "type": "link_shared",+ "channel": "C001",+ "links": [{"url": f"https://us.posthog.com/project/{other_team.id}/tasks/{task_id}"}],+ }++ 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")+ result = route_posthog_code_event_to_relevant_region(request, event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ assert mock_claims.call_args.kwargs["team_id"] == other_team.id+ mock_unfurl.assert_called_once_with(event, other_integration)+@patch("products.slack_app.backend.api.handle_posthog_link_unfurl")@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")def test_link_shared_works_with_only_notifications_integration(self, mock_unfurl):diff --git a/products/slack_app/backend/tests/test_workspace_claims.py b/products/slack_app/backend/tests/test_workspace_claims.pyindex 42d9e239ada0..3f7d6cf4fa98 100644--- a/products/slack_app/backend/tests/test_workspace_claims.py+++ b/products/slack_app/backend/tests/test_workspace_claims.py@@ -20,8 +20,8 @@ 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 Slack app 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.+ both regions already share. The signature covers every request filter, so a captured request+ cannot be replayed against a different workspace or project."""def setUp(self):@@ -58,6 +58,22 @@ class TestSlackWorkspaceClaimsView(TestCase):assert response.status_code == 200assert response.json() == {"claimed": True}+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")+ def test_team_id_limits_claim_to_that_project(self, mock_config):+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}+ Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T_PRESENT",+ sensitive_config={"access_token": "xoxb"},+ )+ other_team = Team.objects.create(organization=self.organization, name="Other")++ response = self._post({"slack_team_id": "T_PRESENT", "kinds": ["slack"], "team_id": other_team.id})++ assert response.status_code == 200+ assert response.json() == {"claimed": False}+@patch("products.slack_app.backend.api.SlackIntegration.slack_config")def test_any_of_kinds_match_returns_claimed(self, mock_config):mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}@@ -275,6 +291,23 @@ class TestDoesOtherRegionClaimWorkspace(TestCase):does_other_region_claim_workspace(slack_team_id="T_KIND", kinds=["slack"], incoming_host="eu.posthog.com")assert mock_post.call_count == 1+ def test_cache_is_keyed_by_team_id(self):+ from products.slack_app.backend.api import does_other_region_claim_workspace++ with (+ patch("products.slack_app.backend.api.SlackIntegration.slack_config") as mock_config,+ patch("products.slack_app.backend.api.requests.post") as mock_post,+ ):+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}+ mock_post.return_value = self._response(200, {"claimed": True})+ does_other_region_claim_workspace(+ slack_team_id="T_TEAM", kinds=["slack"], incoming_host="eu.posthog.com", team_id=1+ )+ does_other_region_claim_workspace(+ slack_team_id="T_TEAM", kinds=["slack"], incoming_host="eu.posthog.com", team_id=2+ )+ assert mock_post.call_count == 2+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