: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): unfurl links against the project they belong to (#81053)
Vojta Bartoš303e12418905
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex c81a7718fc81..640350589924 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -72,6 +72,7 @@ from products.slack_app.backend.services.integration_resolver import (UserResolutionFailure,format_project_candidate_list,load_integrations,+ resolve_from_candidates,resolve_user_for_workspace,user_resolution_failure_reply,)@@ -2198,9 +2199,28 @@ 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_shared_integration(event, link_result.candidates)+ if event_type == "link_shared":+ link_target = _link_shared_target(event, link_result.candidates, slack_team_id=slack_team_id)+ logger.info(+ "slack_app_link_unfurl_target_selected",+ slack_team_id=slack_team_id,+ event_id=event_id,+ source=link_target.source,+ candidate_count=len(link_result.candidates),+ integration_id=link_target.integration.id if link_target.integration else None,+ team_id=link_target.integration.team_id if link_target.integration else None,+ )+ else:+ # Every other event type reaching this fallthrough (``app_uninstalled``) is workspace-wide,+ # so any install for the workspace serves it.+ link_target = LinkSharedTarget(link_result.resolved_or_first(), "workspace")++ local_match = link_target.integrationif local_match:- if _us_should_handle_instead(+ # A link naming a project this region holds is an unambiguous claim on the event, so skip+ # the precedence probe: a probe flake proxies to a region that has no row for the+ # workspace, which drops the event and loses an unfurl we could have served.+ if not link_target.explicit and _us_should_handle_instead(slack_team_id,list(SLACK_INTEGRATION_KINDS),can_defer_to_other_region,@@ -3045,29 +3065,84 @@ 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:+@dataclass(frozen=True)+class LinkSharedTarget:+ """The install that serves a ``link_shared`` event, and how it was chosen.++ ``explicit`` is set only when one of the shared links names a ``/project/:id`` this region+ holds. That is an unambiguous claim on the event, which lets the caller skip the cross-region+ precedence probe.+ """++ integration: Integration | None+ source: str+ explicit: bool = False+++def _link_shared_url_team_ids(event: dict[str, Any]) -> set[int]:+ """Team ids named by ``/project/:id`` in the event's links, counting only unfurlable ones.++ A shared replay or settings link carries a project id but can never produce an unfurl, so+ letting it name the project would route a resource link in the same message to a project that+ doesn't hold it.+ """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):+ if not isinstance(links, list):+ return team_ids+ for link in links:+ if not isinstance(link, dict):+ continue+ url = link.get("url")+ if not isinstance(url, str) or parse_posthog_resource_link(url) is None:+ 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- 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+ return team_ids+++def _link_shared_target(+ event: dict[str, Any], candidates: list[Integration], *, slack_team_id: str+) -> LinkSharedTarget:+ """Pick the install to unfurl with, preferring the project the link itself names."""+ team_ids = _link_shared_url_team_ids(event)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)+ match = next((candidate for candidate in candidates if candidate.team_id == team_id), None)+ if match is not None:+ return LinkSharedTarget(match, "url_project", explicit=True)+ # The link names a project no install in this region covers. Refusing lets the caller fall+ # through to the other region rather than unfurling out of an unrelated project.+ return LinkSharedTarget(None, "url_project_not_local")+if team_ids:- return None- return candidates[0] if candidates else None+ # Links naming different projects cannot be served by one install, and picking either one+ # would leak the wrong project's data, so serve none of them.+ return LinkSharedTarget(None, "url_projects_conflict")++ # Links with no project id (short ``/i/:short_id`` links, ticket links) go through the same+ # precedence ladder mentions use, so a workspace with several connected projects lands on the+ # project the user actually works in rather than on whichever install happens to be oldest.+ # Resolving without a ``user`` only picks which project to look in — ``handle_posthog_link_unfurl``+ # still resolves the sharer against that project and access-checks every resource it unfurls.+ slack_user_id = str(event.get("user") or "")+ thread_ts = event.get("thread_ts") or event.get("message_ts")+ resolution = resolve_from_candidates(+ candidates,+ slack_team_id=slack_team_id,+ slack_user_id="" if slack_user_id == SLACK_PLACEHOLDER_USER_ID else slack_user_id,+ channel=event.get("channel") if isinstance(event.get("channel"), str) else None,+ thread_ts=thread_ts if isinstance(thread_ts, str) else None,+ )+ # No thread mapping and no default in a multi-project workspace: there is no picker to fall+ # back on for a pasted link, so ``resolved_or_first`` still answers with an install — the same+ # id-ordered tie-break the other must-pick-something surfaces use.+ return LinkSharedTarget(resolution.resolved_or_first(), resolution.source)def _extract_context_token(payload: dict) -> str:diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.pyindex ad2b0ee3723d..04a5057f57ed 100644--- a/products/slack_app/backend/slack_link_unfurl.py+++ b/products/slack_app/backend/slack_link_unfurl.py@@ -390,6 +390,12 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:post_feedback=False,)if not user_context:+ logger.info(+ "slack_app_link_unfurl_user_unresolved",+ team_id=integration.team_id,+ integration_id=integration.id,+ slack_user_id=slack_user_id,+ )returnuser = user_context.user@@ -397,6 +403,9 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:uac = UserAccessControl(user, team=team)unfurls: dict[str, dict] = {}+ # Every resource we recognized but chose not to unfurl, so a report of "no unfurl appeared"+ # can be answered from logs instead of by re-deriving the path by hand.+ skipped: list[dict[str, str]] = []for link_obj in links:raw_url = link_obj.get("url")@@ -414,9 +423,11 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:continueinsight = Insight.objects.filter(team_id=team.pk, short_id=ref).first()if not insight:+ skipped.append({"kind": kind, "ref": ref, "reason": "not_found"})continuelevel = uac.get_user_access_level(insight)if not level or not access_level_satisfied_for_resource("insight", level, "viewer"):+ skipped.append({"kind": kind, "ref": ref, "reason": "no_access"})continuetitle = insight.name or insight.derived_name or "Untitled"desc = (insight.description or "").strip() or None@@ -428,9 +439,11 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:continuedashboard = Dashboard.objects.filter(pk=ref, team_id=team.pk).first()if not dashboard:+ skipped.append({"kind": kind, "ref": str(ref), "reason": "not_found"})continuelevel = uac.get_user_access_level(dashboard)if not level or not access_level_satisfied_for_resource("dashboard", level, "viewer"):+ skipped.append({"kind": kind, "ref": str(ref), "reason": "no_access"})continuetitle = dashboard.name or "Untitled"desc = (dashboard.description or "").strip() or None@@ -444,9 +457,14 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:# of the same number — refuse rather than show the wrong ticket.url_team_id = _url_team_id(raw_url)if url_team_id is not None and url_team_id != team.pk:+ skipped.append({"kind": kind, "ref": ref, "reason": "other_project"})continueticket = _find_ticket(team.pk, ref)- if not ticket or not uac.check_access_level_for_object(ticket, required_level="viewer"):+ if not ticket:+ skipped.append({"kind": kind, "ref": ref, "reason": "not_found"})+ continue+ if not uac.check_access_level_for_object(ticket, required_level="viewer"):+ skipped.append({"kind": kind, "ref": ref, "reason": "no_access"})continueunfurls[raw_url] = _ticket_unfurl_payload(url=raw_url,@@ -459,9 +477,11 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:continueurl_team_id = _url_team_id(raw_url)if url_team_id is not None and url_team_id != team.pk:+ skipped.append({"kind": kind, "ref": ref, "reason": "other_project"})continuetask = tasks_facade.get_task_for_slack_unfurl(ref, team.pk, user.id)if task is None:+ skipped.append({"kind": kind, "ref": ref, "reason": "not_found_or_no_access"})continuelabel = "Task" if task.latest_run_status is None else f"Task · {task.latest_run_status}"unfurls[raw_url] = _unfurl_payload(resource_label=label, title=_escape_mrkdwn(task.title), description=None)@@ -478,6 +498,15 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:except Exception:logger.exception("slack_task_reference_attach_failed", task_id=str(task.id), team_id=team.pk)+ logger.info(+ "slack_app_link_unfurl_result",+ team_id=team.pk,+ integration_id=integration.id,+ channel=channel,+ unfurled=len(unfurls),+ skipped=skipped,+ )+if not unfurls:returndiff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.pyindex 3a8d899bca2a..e3b07c261c2c 100644--- a/products/slack_app/backend/tests/test_link_unfurl.py+++ b/products/slack_app/backend/tests/test_link_unfurl.py@@ -7,6 +7,7 @@ from django.test.client import RequestFactoryfrom django.utils import timezonefrom parameterized import parameterized+from structlog.testing import capture_logsfrom posthog.constants import AvailableFeaturefrom posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES@@ -273,6 +274,39 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):mock_client.chat_unfurl.assert_not_called()+ @patch("products.slack_app.backend.api.resolve_slack_user")+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")+ def test_reports_why_recognized_links_were_not_unfurled(+ self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock+ ) -> None:+ # Every reason to skip a link used to be a bare `continue`, so "no unfurl appeared" was+ # indistinguishable from "Slack never delivered the event" once it reached production.+ mock_resolve.return_value = MagicMock(user=self.user)+ mock_slack_integration_class.return_value.client = MagicMock()++ with capture_logs() as logs:+ handle_posthog_link_unfurl(+ {+ "channel": "C1",+ "message_ts": "123.456",+ "user": "U1",+ "links": [+ {"url": f"http://testserver/project/{self.team.pk}/insights/nosuchid"},+ {"url": f"http://testserver/project/{self.team.pk}/dashboard/424242"},+ {"url": "https://example.com/somewhere-else"},+ ],+ },+ self.integration,+ )++ mock_slack_integration_class.return_value.client.chat_unfurl.assert_not_called()+ result = next(log for log in logs if log["event"] == "slack_app_link_unfurl_result")+ assert result["unfurled"] == 0+ assert result["skipped"] == [+ {"kind": "insight", "ref": "nosuchid", "reason": "not_found"},+ {"kind": "dashboard", "ref": "424242", "reason": "not_found"},+ ]+@patch("products.slack_app.backend.api.resolve_slack_user")@patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")def test_unfurls_insight_when_project_segment_mismatched(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 9e0ee9e33edc..6174d24fe40c 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@@ -16,7 +16,7 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.slack_app.backend.models import SlackUserProfileCache+from products.slack_app.backend.models import SlackSettings, SlackUserProfileCachefrom products.slack_app.backend.tests.helpers import sign_slack_request@@ -744,9 +744,100 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):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.idmock_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_without_project_id_follows_workspace_default(self, mock_unfurl):+ # A short ``/i/:short_id`` link names no project, so the workspace default is the only+ # signal about which connected project the workspace works in. Picking the oldest install+ # instead sends the lookup to a team that doesn't hold the insight, and nothing unfurls.+ 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,+ )+ SlackSettings.objects.create(+ slack_workspace_id="T12345",+ slack_user_id=None,+ default_integration=other_integration,+ )+ event = {+ "type": "link_shared",+ "channel": "C001",+ "user": "U123",+ "message_ts": "1234.5678",+ "links": [{"url": "https://us.posthog.com/i/abc123"}],+ }++ 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="us.posthog.com")+ result = route_posthog_code_event_to_relevant_region(request, event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ 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_ignores_project_named_only_by_an_unfurlable_link(self, mock_unfurl):+ # Sharing a replay link next to an insight link is routine. The replay carries a project id+ # but can never be unfurled, so letting it name the project sends the insight lookup to a+ # team that doesn't hold it — or, across two projects, suppresses the message entirely.+ other_team = Team.objects.create(organization=self.organization, name="Other")+ 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,+ )+ event = {+ "type": "link_shared",+ "channel": "C001",+ "user": "U123",+ "message_ts": "1234.5678",+ "links": [+ {"url": f"https://us.posthog.com/project/{other_team.id}/replay/abc"},+ {"url": f"https://us.posthog.com/project/{self.team.pk}/insights/abc123"},+ ],+ }++ 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="us.posthog.com")+ result = route_posthog_code_event_to_relevant_region(request, event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_unfurl.assert_called_once_with(event, self.posthog_code_integration)++ @patch("products.slack_app.backend.api.handle_posthog_link_unfurl")+ @patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=None)+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_link_shared_for_local_project_ignores_inconclusive_region_probe(self, mock_claims, mock_unfurl):+ # The link names a project this region holds, which settles ownership on its own. Deferring+ # to the other region on an inconclusive probe would hand the event to a region with no row+ # for the workspace, where it is dropped and the unfurl is lost.+ event = {+ "type": "link_shared",+ "channel": "C001",+ "user": "U123",+ "message_ts": "1234.5678",+ "links": [{"url": f"https://eu.posthog.com/project/{self.team.pk}/insights/abc123"}],+ }++ 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+ mock_claims.assert_not_called()+ mock_unfurl.assert_called_once_with(event, self.posthog_code_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):