: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): identify Slack user at routing time, reply in-thread on failure (#61643)
Vojta Bartošb6002ad32b00
diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.pyindex 5ab9c2bee624..c07b81f06d1c 100644--- a/posthog/temporal/ai/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/posthog_code_slack_mention.py@@ -163,6 +163,11 @@ class PostHogCodeSlackMentionWorkflowInputs:slack_team_id: str# Event that dispatched the workflowslack_event_id: str | None = None+ # Resolved at routing time. ``None`` only on in-flight workflow histories+ # started before this field existed; those fall back to the in-workflow+ # resolve activity below. Remove the fallback (and this field's optionality)+ # once the workflow history retention window has elapsed.+ user_id: int | None = Nonedef derive_mention_workflow_id(inputs: "PostHogCodeSlackMentionWorkflowInputs") -> str:@@ -279,11 +284,20 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):if followup_handled:return- user_id = await _execute_posthog_code_activity(- resolve_posthog_code_slack_user_activity, inputs, channel, thread_ts, slack_user_id- )- if not user_id:- return+ # New starts carry ``user_id`` from routing-time resolution and skip+ # the activity. Legacy histories started before the field existed+ # deserialize with ``user_id=None`` and replay through the activity so+ # the recorded command stream still matches. Drop this fallback (and+ # make ``user_id`` required on inputs) once the workflow history+ # retention window has elapsed.+ if inputs.user_id is not None:+ user_id = inputs.user_id+ else:+ user_id = await _execute_posthog_code_activity(+ resolve_posthog_code_slack_user_activity, inputs, channel, thread_ts, slack_user_id+ )+ if not user_id:+ returnthread_messages = await _execute_posthog_code_activity(collect_posthog_code_thread_messages_activity,diff --git a/posthog/temporal/ai/posthog_code_slack_mention_command.py b/posthog/temporal/ai/posthog_code_slack_mention_command.pyindex 979e0bb93deb..6ddc5618ef32 100644--- a/posthog/temporal/ai/posthog_code_slack_mention_command.py+++ b/posthog/temporal/ai/posthog_code_slack_mention_command.py@@ -21,6 +21,11 @@ class PostHogCodeSlackMentionCommandWorkflowInputs:event: dict[str, Any]integration_ids: list[int]slack_team_id: str+ # Resolved at routing time. ``None`` only on in-flight workflow histories+ # started before this field existed; those fall back to the in-workflow+ # resolve activity below. Remove the fallback (and this field's optionality)+ # once the workflow history retention window has elapsed.+ user_id: int | None = None@dataclass@@ -76,14 +81,22 @@ class PostHogCodeSlackMentionCommandWorkflow(PostHogWorkflow):post_posthog_code_repo_picker_activity,)- user_id = await workflow.execute_activity(- resolve_posthog_code_slack_command_user_activity,- args=[inputs],- start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ # New starts carry ``user_id`` from routing-time resolution and skip the+ # activity. Legacy histories started before the field existed deserialize+ # with ``user_id=None`` and replay through the activity so the recorded+ # command stream still matches. Drop this fallback (and make ``user_id``+ # required on inputs) once the workflow history retention window has+ # elapsed.+ user_id = inputs.user_idif user_id is None:- return+ user_id = await workflow.execute_activity(+ resolve_posthog_code_slack_command_user_activity,+ args=[inputs],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if user_id is None:+ returnresult = await workflow.execute_activity(handle_posthog_code_slack_mention_command_activity,@@ -107,14 +120,17 @@ class PostHogCodeSlackMentionCommandWorkflow(PostHogWorkflow):return# The picker activities are written against the mention workflow's input- # shape, but they only read ``integration_id`` / ``slack_team_id`` /- # ``event`` from it. Synthesise a compatible record for the resolved+ # shape, but today they only read ``integration_id`` / ``slack_team_id``+ # / ``event`` from it. Synthesise a compatible record for the resolved# target so we can reuse the existing picker plumbing without- # duplicating it.+ # duplicating it. Forward ``user_id`` so any future activity that reads+ # it (e.g. for attribution) stays consistent with the surrounding+ # command workflow's resolved user.picker_inputs = PostHogCodeSlackMentionWorkflowInputs(event=inputs.event,integration_id=target_integration_id,slack_team_id=inputs.slack_team_id,+ user_id=inputs.user_id,)workflow.deprecate_patch("posthog-code-command-block-no-personal-github-2026-06")@@ -177,7 +193,7 @@ def resolve_posthog_code_slack_command_user_activity() -> int | None:from posthog.models.integration import Integration, SlackIntegration- from products.slack_app.backend.api import _resolve_posthog_user_from_event+ from products.slack_app.backend.api import resolve_posthog_user_from_eventevent = inputs.eventchannel = event.get("channel")@@ -197,7 +213,7 @@ def resolve_posthog_code_slack_command_user_activity(return Noneprobe = candidates[0]- posthog_user = _resolve_posthog_user_from_event(+ posthog_user = resolve_posthog_user_from_event(slack_user_id=slack_user_id,probe_integration=probe,candidate_integrations=candidates,diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 728940a41bd7..8e29a8378a06 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -54,7 +54,13 @@ from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.models import SlackChannel, SlackUserProfileCache-from products.slack_app.backend.services.integration_resolver import format_project_candidate_list, load_integrations+from products.slack_app.backend.services.integration_resolver import (+ UserResolutionFailure,+ format_project_candidate_list,+ load_integrations,+ resolve_user_for_workspace,+ user_resolution_failure_reply,+)from products.slack_app.backend.slack_link_unfurl import handle_posthog_link_unfurllogger = structlog.get_logger(__name__)@@ -1394,11 +1400,37 @@ def _notify_missing_slack_scopes(_post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)-def _resolve_posthog_user_from_event(+def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str) -> str | None:+ """Best-effort lookup of the Slack user's email via ``users.info``,+ cache-first then a fresh hit on miss. Returns ``None`` when Slack doesn't+ expose an email for the user (profile email hidden) or the lookup fails.+ """+ slack_client = SlackIntegration(probe_integration)+ try:+ user_info = _get_slack_user_info(slack_client, probe_integration, slack_user_id)+ slack_email = user_info.get("user", {}).get("profile", {}).get("email")+ if not slack_email:+ fresh = _normalize_slack_response(slack_client.client.users_info(user=slack_user_id))+ if fresh:+ _persist_slack_user_info(probe_integration, slack_user_id, fresh)+ slack_email = fresh.get("user", {}).get("profile", {}).get("email")+ return slack_email or None+ except Exception:+ logger.warning(+ "posthog_code_resolve_user_email_failed",+ integration_id=probe_integration.id,+ slack_user_id=slack_user_id,+ exc_info=True,+ )+ return None+++def resolve_posthog_user_from_event(*,slack_user_id: str,probe_integration: Integration,candidate_integrations: list[Integration],+ slack_email: str | None = None,) -> User | None:"""Resolve the acting Slack user to a PostHog ``User`` who is a member ofat least one organization connected to this Slack workspace.@@ -1406,35 +1438,35 @@ def _resolve_posthog_user_from_event(The probe is used to call Slack's ``users.info``; the candidate list scopesthe organization-membership check. A user with no membership in anyconnected org returns ``None`` so the caller can refuse the event.++ ``slack_email`` may be passed by callers that already have it (e.g.+ ``resolve_user_and_integrations``) so we don't repeat the cache lookup."""- slack_client = SlackIntegration(probe_integration)+ if slack_email is None:+ slack_email = get_slack_email_for_user(probe_integration, slack_user_id)+ if not slack_email:+ return None+ org_ids = {c.team.organization_id for c in candidate_integrations}+ if not org_ids:+ return Nonetry:- user_info = _get_slack_user_info(slack_client, probe_integration, slack_user_id)- slack_email = user_info.get("user", {}).get("profile", {}).get("email")- if not slack_email:- fresh = _normalize_slack_response(slack_client.client.users_info(user=slack_user_id))- if fresh:- _persist_slack_user_info(probe_integration, slack_user_id, fresh)- slack_email = fresh.get("user", {}).get("profile", {}).get("email")- if not slack_email:- return None- org_ids = {c.team.organization_id for c in candidate_integrations}- if not org_ids:- return Nonemembership = (OrganizationMembership.objects.filter(organization_id__in=org_ids, user__email__iexact=slack_email).select_related("user").first())- return membership.user if membership else Noneexcept Exception:+ # Don't propagate transient DB errors to the Slack webhook — Slack+ # retries 5xx and would replay the event. The caller gets ``None`` and+ # treats it the same as "no membership found".logger.warning(- "posthog_code_resolve_user_failed",+ "posthog_code_resolve_user_membership_failed",integration_id=probe_integration.id,slack_user_id=slack_user_id,exc_info=True,)- return None+ return None+ return membership.user if membership else Nonedef _post_pick_a_project_hint(@@ -1458,6 +1490,33 @@ def _post_pick_a_project_hint(_post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)+def _post_user_resolution_failure_reply(+ *,+ probe: Integration,+ channel: str | None,+ slack_user_id: str | None,+ thread_ts: str | None,+ failure_reason: UserResolutionFailure | None,+ slack_email: str | None,+) -> None:+ """Tell a Slack user when we can't route their mention to a PostHog project.++ Posts in-thread (with the established ephemeral fallback in+ ``_post_slack_user_feedback``) so the message lands in the place the+ mention happened. ``failure_reason`` is mapped to the user-facing text by+ ``user_resolution_failure_reply``; ``slack_email`` is woven in when known+ so the user sees which address PostHog tried to match.+ """+ if not channel or not thread_ts or not slack_user_id:+ return+ text = user_resolution_failure_reply(failure_reason, slack_email=slack_email)+ if text is None:+ return+ _post_slack_user_feedback(+ SlackIntegration(probe), channel, slack_user_id, thread_ts, text, prefer_thread_message=True+ )++def _start_posthog_code_workflow(workflow_cls: Any,workflow_inputs: Any,@@ -1528,27 +1587,63 @@ def route_posthog_code_event_to_relevant_region()return ROUTE_HANDLED_LOCALLY- result = load_integrations(+ slack_user_id_str = str(event.get("user") or "")+ channel_str = event.get("channel") if isinstance(event.get("channel"), str) else None+ thread_ts_value = event.get("thread_ts") or event.get("ts")+ thread_ts_str = thread_ts_value if isinstance(thread_ts_value, str) else None++ # Workspace lookup first — region routing only needs candidate presence, not+ # user resolution. We defer the Slack ``users.info`` hit and the+ # ``OrganizationMembership`` query until we know this region is handling+ # the event so cross-region proxied events don't pay for work the+ # receiving region will redo.+ workspace_result = load_integrations(slack_team_id=slack_team_id,kinds=[SLACK_INTEGRATION_KIND],- slack_user_id=str(event.get("user") or ""),- user=None,- channel=event.get("channel") if isinstance(event.get("channel"), str) else None,- thread_ts=(event.get("thread_ts") or event.get("ts"))- if isinstance(event.get("thread_ts") or event.get("ts"), str)- else None,+ slack_user_id=slack_user_id_str,+ channel=channel_str,+ thread_ts=thread_ts_str,)- if not result.candidates:+ if not workspace_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_INTEGRATION_KIND], can_defer_to_other_region, incoming_host):return _proxy_event_and_return_route(request, other_domain)- candidates = result.candidates- target = result.integration if result.integration in candidates else None+ resolution = resolve_user_for_workspace(+ workspace_result=workspace_result,+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id_str,+ event_id=event_id,+ )++ if resolution.user is None:+ # Skip the failure reply in an unapproved externally-shared channel —+ # the channel hasn't opted in yet, so a public "Sorry, I couldn't+ # find <email>" post would leak the integration's existence to+ # non-org members. Still capture the mention analytics-side so the+ # unknown-user funnel keeps reporting (it ran on every mention before+ # this PR moved resolution up).+ probe = workspace_result.candidates[0]+ _report_slack_mention_received(event, probe, slack_team_id, posthog_user=None)+ channel_id = event.get("channel") if isinstance(event.get("channel"), str) else None+ if not (is_ext_shared_channel and channel_id and not _channel_is_approved(slack_team_id, channel_id)):+ _post_user_resolution_failure_reply(+ probe=probe,+ channel=channel_str,+ slack_user_id=slack_user_id_str,+ thread_ts=thread_ts_str,+ failure_reason=resolution.failure_reason,+ slack_email=resolution.slack_email,+ )+ return ROUTE_HANDLED_LOCALLY++ posthog_user = resolution.user+ candidates = resolution.candidates+ target = resolution.integrationif _parse_rules_command(event.get("text", "")) is not None:- return _start_command_workflow(event, candidates, slack_team_id, event_id)+ return _start_command_workflow(event, candidates, slack_team_id, event_id, user_id=posthog_user.id)mention_target = target or (candidates[0] if len(candidates) == 1 else None)if mention_target is None:@@ -1566,7 +1661,7 @@ def route_posthog_code_event_to_relevant_region(_post_channel_approval_prompt(slack, mention_target, event)return ROUTE_HANDLED_LOCALLY- return _start_mention_workflow(event, mention_target, slack_team_id, event_id)+ return _start_mention_workflow(event, mention_target, slack_team_id, event_id, posthog_user=posthog_user)# link_shared (unfurl) works with either integration kind.link_result = load_integrations(slack_team_id=slack_team_id, kinds=list(SLACK_INTEGRATION_KINDS))@@ -1624,7 +1719,12 @@ def _route_to_other_region_or_drop(def _start_command_workflow(- event: dict, integrations: list[Integration], slack_team_id: str, event_id: str | None+ event: dict,+ integrations: list[Integration],+ slack_team_id: str,+ event_id: str | None,+ *,+ user_id: int,) -> str:_start_posthog_code_workflow(PostHogCodeSlackMentionCommandWorkflow,@@ -1632,6 +1732,7 @@ def _start_command_workflow(event=event,integration_ids=[i.id for i in integrations],slack_team_id=slack_team_id,+ user_id=user_id,),id_prefix="posthog-code-mention-command",slack_team_id=slack_team_id,@@ -1781,13 +1882,22 @@ def _post_channel_approval_prompt()-def _report_slack_mention_received(event: dict, integration: Integration, slack_team_id: str) -> None:+def _report_slack_mention_received(+ event: dict,+ integration: Integration,+ slack_team_id: str,+ *,+ posthog_user: User | None = None,+) -> None:"""Capture a product-analytics event each time the @PostHog bot is mentioned.A Slack thread is treated as the session: ``thread_ts`` identifies it, and a mention whose``thread_ts`` is absent or equal to its own ``ts`` is the session's first message. The actingSlack user is resolved to a PostHog ``User`` so the event is attributed to a real person whereone exists; otherwise it falls back to a stable Slack-derived distinct id.++ When the caller has already resolved the PostHog user at routing time it passes ``posthog_user``+ so we skip the redundant Slack ``users.info`` + ``OrganizationMembership`` roundtrip."""try:channel = event.get("channel") if isinstance(event.get("channel"), str) else None@@ -1797,15 +1907,12 @@ def _report_slack_mention_received(event: dict, integration: Integration, slack_is_first_message_in_session = raw_thread_ts is None or raw_thread_ts == message_tsslack_user_id = event.get("user") if isinstance(event.get("user"), str) and event.get("user") else None- posthog_user = (- _resolve_posthog_user_from_event(+ if posthog_user is None and slack_user_id:+ posthog_user = resolve_posthog_user_from_event(slack_user_id=slack_user_id,probe_integration=integration,candidate_integrations=[integration],)- if slack_user_id- else None- )# Prefer the resolved PostHog user's distinct id so the event attributes to a real person;# fall back to a stable Slack-derived id so anonymous-but-valid mentions are still captured.identified_distinct_id = posthog_user.distinct_id if posthog_user else None@@ -1845,8 +1952,15 @@ def _report_slack_mention_received(event: dict, integration: Integration, slack_)-def _start_mention_workflow(event: dict, integration: Integration, slack_team_id: str, event_id: str | None) -> str:- _report_slack_mention_received(event, integration, slack_team_id)+def _start_mention_workflow(+ event: dict,+ integration: Integration,+ slack_team_id: str,+ event_id: str | None,+ *,+ posthog_user: User,+) -> str:+ _report_slack_mention_received(event, integration, slack_team_id, posthog_user=posthog_user)if _resolve_pending_repo_picker_from_followup(event, integration):return ROUTE_HANDLED_LOCALLYworkflow_inputs = PostHogCodeSlackMentionWorkflowInputs(@@ -1854,6 +1968,7 @@ def _start_mention_workflow(event: dict, integration: Integration, slack_team_idintegration_id=integration.id,slack_team_id=slack_team_id,slack_event_id=event_id,+ user_id=posthog_user.id,)# Use derive_mention_workflow_id as the single source of truth: the workflow persists the same# value as slack_mention_workflow_id, so dispatch and the debug-tool Temporal link stay consistent@@ -2377,7 +2492,7 @@ def _is_org_member(integration: Integration, clicker_slack_user_id: str) -> User"""Resolve the clicker to a PostHog ``User`` belonging to the integration'sorganization, or ``None`` if no such membership exists."""- return _resolve_posthog_user_from_event(+ return resolve_posthog_user_from_event(slack_user_id=clicker_slack_user_id,probe_integration=integration,candidate_integrations=[integration],diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex 2accbb04bde3..5a39a35cce25 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -3,11 +3,16 @@ from typing import Literalfrom django.db.models import Q+import structlog+from posthog.models.integration import Integrationfrom posthog.models.user import User+from posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping+logger = structlog.get_logger(__name__)+ResolutionSource = Literal["thread","user_default",@@ -16,6 +21,39 @@ ResolutionSource = Literal["needs_picker",]+UserResolutionFailure = Literal["user_not_found", "no_team_access"]+++def user_resolution_failure_reply(+ failure_reason: UserResolutionFailure | None, *, slack_email: str | None+) -> str | None:+ """Map a ``UserAndIntegrationsResolution.failure_reason`` to the user-facing+ text, mentioning ``slack_email`` when known so the user sees which address+ PostHog tried to match. Returns ``None`` for unknown values so callers can+ no-op safely until a new failure mode is wired up here.++ Wording mirrors the per-integration ``resolve_slack_user`` precedent in+ ``api.py`` — same "Sorry, …" register, same actionable next step.+ """+ if failure_reason == "user_not_found":+ if slack_email:+ return (+ f"Sorry, I couldn't find {slack_email} in any PostHog organization connected to this "+ "Slack workspace. Ask an admin to invite you, then mention me again."+ )+ return (+ "Sorry, I couldn't find your email address in Slack. "+ "Please make sure your email is visible in your Slack profile."+ )+ if failure_reason == "no_team_access":+ # The membership lookup succeeded by email, so it's always known here.+ subject = slack_email or "your account"+ return (+ f"Sorry, {subject} doesn't have access to any PostHog project connected to this Slack "+ "workspace. Ask an admin to grant you access, then try again."+ )+ return None+@dataclassclass ResolutionResult:@@ -50,10 +88,18 @@ def resolve_from_candidates(``slack_user_id=""``; the SlackSettings lookup is skipped and the resultfalls through to ``sole_candidate`` / ``needs_picker``."""- accessible_team_ids: set[int] | None = set(user.teams.values_list("id", flat=True)) if user is not None else None- accessible = (- candidates if accessible_team_ids is None else [i for i in candidates if i.team_id in accessible_team_ids]- )+ # ``user.teams`` keys its access-control filter off a single arbitrary+ # ``Organization.first()`` row's feature flags, so a user whose AC-enabled+ # org isn't the one picked sees private projects from that org. Per-team+ # ``effective_membership_level`` is the right check — it consults each+ # team's own organization's feature flags.+ if user is None:+ accessible_team_ids: set[int] | None = None+ accessible = candidates+ else:+ permissions = UserPermissions(user=user)+ accessible = [c for c in candidates if permissions.team(c.team).effective_membership_level is not None]+ accessible_team_ids = {c.team_id for c in accessible}candidate_ids = {c.id for c in candidates}candidates_by_team_id = {c.team_id: c for c in candidates}@@ -134,3 +180,111 @@ def load_integrations(channel=channel,thread_ts=thread_ts,)+++@dataclass+class UserAndIntegrationsResolution:+ """Outcome of the user identification + access-filter step.++ ``user`` is ``None`` when no PostHog user resolved or none had access — both+ cases are silently logged inside ``resolve_user_for_workspace`` under+ ``posthog_code_no_integration_found``, and the specific case is exposed via+ ``failure_reason`` so the caller can post an actionable reply in-thread.+ ``integration`` and ``candidates`` are only populated on the happy path;+ ``source`` mirrors ``ResolutionResult.source`` (or ``needs_picker`` if the+ resolved target was inaccessible and got dropped).+ """++ user: User | None = None+ integration: Integration | None = None+ candidates: list[Integration] = field(default_factory=list)+ source: ResolutionSource = "needs_picker"+ failure_reason: UserResolutionFailure | None = None+ slack_email: str | None = None+++def resolve_user_for_workspace(+ *,+ workspace_result: ResolutionResult,+ slack_team_id: str,+ slack_user_id: str,+ event_id: str | None = None,+) -> UserAndIntegrationsResolution:+ """Given a pre-loaded workspace ``ResolutionResult``, identify the acting+ Slack user and filter the workspace candidates down to ones they can+ access. Split from ``resolve_user_and_integrations`` so the caller can+ decide region routing (proxy / drop) before paying for the Slack API hit+ and the membership query.+ """+ # The user resolver lives in api.py alongside the Slack-API helpers it+ # depends on (``_get_slack_user_info`` etc). Inline-imported to break the+ # cycle until those helpers are factored out into a shared module.+ from products.slack_app.backend.api import get_slack_email_for_user, resolve_posthog_user_from_event++ if not slack_user_id:+ logger.warning(+ "posthog_code_no_integration_found",+ reason="user_not_found",+ slack_team_id=slack_team_id,+ slack_user_id=None,+ event_id=event_id,+ )+ return UserAndIntegrationsResolution(failure_reason="user_not_found")++ # Look the Slack email up once and pass it through so the user resolver+ # doesn't repeat the cache hit and so the routing layer can mention it in+ # the user-facing failure reply.+ probe = workspace_result.candidates[0]+ slack_email = get_slack_email_for_user(probe, slack_user_id)++ posthog_user = resolve_posthog_user_from_event(+ slack_user_id=slack_user_id,+ probe_integration=probe,+ candidate_integrations=workspace_result.candidates,+ slack_email=slack_email,+ )+ if posthog_user is None:+ logger.warning(+ "posthog_code_no_integration_found",+ reason="user_not_found",+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ event_id=event_id,+ )+ return UserAndIntegrationsResolution(failure_reason="user_not_found", slack_email=slack_email)++ # Filter to integrations the user can access. A resolved target the user can't+ # reach is dropped so the caller falls through to the picker / sole-candidate+ # path rather than auto-redirecting to a default the thread didn't imply.+ # Use per-team ``effective_membership_level`` rather than ``user.teams``: the+ # latter gates its access-control filter on an arbitrary ``Organization.first()``+ # row's feature flags, so a Slack user spanning multiple orgs can otherwise+ # be treated as having access to a private project in a different org than+ # the one that drove the AC check.+ permissions = UserPermissions(user=posthog_user)+ accessible_candidates = [+ c for c in workspace_result.candidates if permissions.team(c.team).effective_membership_level is not None+ ]+ accessible_team_ids = {c.team_id for c in accessible_candidates}+ if not accessible_candidates:+ logger.warning(+ "posthog_code_no_integration_found",+ reason="no_team_access",+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ user_id=posthog_user.id,+ event_id=event_id,+ )+ return UserAndIntegrationsResolution(failure_reason="no_team_access", slack_email=slack_email)++ target = (+ workspace_result.integration+ if workspace_result.integration is not None and workspace_result.integration.team_id in accessible_team_ids+ else None+ )+ return UserAndIntegrationsResolution(+ user=posthog_user,+ integration=target,+ candidates=accessible_candidates,+ source=workspace_result.source if target is not None else "needs_picker",+ )diff --git a/products/slack_app/backend/tests/test_mention_analytics.py b/products/slack_app/backend/tests/test_mention_analytics.pyindex d00611bdd8a8..31dfdeebba10 100644--- a/products/slack_app/backend/tests/test_mention_analytics.py+++ b/products/slack_app/backend/tests/test_mention_analytics.py@@ -71,7 +71,7 @@ class TestReportSlackMentionReceived:)@patch("products.slack_app.backend.api.SlackIntegration")@patch("products.slack_app.backend.api.posthoganalytics.capture")- @patch("products.slack_app.backend.api._resolve_posthog_user_from_event")+ @patch("products.slack_app.backend.api.resolve_posthog_user_from_event")def test_capture_properties(self,_name,@@ -113,7 +113,7 @@ class TestReportSlackMentionReceived:assert ("$set" in props) is exp_identified@patch("products.slack_app.backend.api.posthoganalytics.capture")- @patch("products.slack_app.backend.api._resolve_posthog_user_from_event")+ @patch("products.slack_app.backend.api.resolve_posthog_user_from_event")def test_capture_failure_is_swallowed(self, mock_resolve, mock_capture):mock_resolve.side_effect = Exception("boom")event = {"channel": "C001", "ts": "1700.0001", "user": "U123"}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 462e901fc11e..92339e015c91 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@@ -11,10 +11,11 @@ from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.models.integration import Integration-from posthog.models.organization import Organization+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 SlackUserProfileCachefrom products.slack_app.backend.tests.helpers import sign_slack_request@@ -109,6 +110,10 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")self.user = User.objects.create(email="[email protected]", distinct_id="user-1")+ OrganizationMembership.objects.create(organization=self.organization, user=self.user)+ self.user.current_organization = self.organization+ self.user.current_team = self.team+ self.user.save()self.posthog_code_integration = Integration.objects.create(team=self.team,kind="slack",@@ -116,8 +121,24 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):config={"scope": ",".join(sorted(POSTHOG_CODE_REQUIRED_SLACK_SCOPES))},sensitive_config={"access_token": "xoxb-posthog-code-test"},)+ # Seed the Slack-user → email cache so routing can resolve U123 → self.user+ # without calling the Slack API. New tests that exercise the unauthorised+ # paths override this row (or delete it) deliberately.+ self._seed_slack_user_cache("U123", "[email protected]")self.event = {"type": "app_mention", "channel": "C001", "user": "U123", "ts": "1234.5678"}+ def _seed_slack_user_cache(self, slack_user_id: str, email: str | None) -> SlackUserProfileCache:+ from django.utils import timezone++ return SlackUserProfileCache.objects.create(+ integration=self.posthog_code_integration,+ slack_user_id=slack_user_id,+ email=email,+ display_name="Dev",+ real_name="Dev User",+ refreshed_at=timezone.now(),+ )+@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@override_settings(DEBUG=False)@@ -277,6 +298,187 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_sync_connect.assert_not_called()mock_asyncio_run.assert_not_called()+ @patch("products.slack_app.backend.api.posthoganalytics.capture")+ @patch("products.slack_app.backend.api._post_slack_user_feedback")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_app_mention_from_unknown_user_posts_in_thread_failure_reply(+ self, mock_sync_connect, mock_asyncio_run, mock_post_feedback, mock_capture+ ):+ # A Slack user whose email doesn't map to any PostHog ``User`` in any connected+ # org gets a public in-thread "Sorry, I couldn't find <email>…" reply that names+ # the looked-up Slack email so they can self-correct. The mention is still+ # captured to product analytics so the unknown-user funnel keeps its coverage.+ # No workflow starts.+ SlackUserProfileCache.objects.filter(slack_user_id="U123").delete()+ self._seed_slack_user_cache("U123", "[email protected]")++ 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, self.event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_sync_connect.assert_not_called()+ mock_asyncio_run.assert_not_called()++ # Failure reply is posted in-thread and names the looked-up Slack email so the+ # user can spot a wrong-email mismatch against their PostHog account.+ mock_post_feedback.assert_called_once()+ feedback_text = mock_post_feedback.call_args.args[4]+ assert "[email protected]" in feedback_text+ assert mock_post_feedback.call_args.kwargs.get("prefer_thread_message") is True++ # The mention is still reported to analytics with ``posthog_user_identified=False``+ # so the unknown-user volume stays comparable to the known-user funnel.+ mock_capture.assert_called_once()+ capture_kwargs = mock_capture.call_args.kwargs+ assert capture_kwargs.get("event") == "posthog code slack mention received"+ assert capture_kwargs.get("properties", {}).get("posthog_user_identified") is False++ @patch("products.slack_app.backend.api.posthoganalytics.capture")+ @patch("products.slack_app.backend.api._post_slack_user_feedback")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_unknown_user_in_unapproved_ext_shared_channel_suppresses_failure_reply(+ self, mock_sync_connect, mock_asyncio_run, mock_post_feedback, mock_capture+ ):+ # Externally-shared channels that haven't been approved must not receive a+ # public "Sorry, I couldn't find <email>" post — that leaks the integration's+ # existence (and the user's email) to non-org members. The approval prompt+ # itself requires a resolved user, so we stay completely silent in this case.+ # Analytics still records the event for funnel coverage.+ SlackUserProfileCache.objects.filter(slack_user_id="U123").delete()+ self._seed_slack_user_cache("U123", "[email protected]")++ 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, self.event, "T12345", is_ext_shared_channel=True)++ assert result == ROUTE_HANDLED_LOCALLY+ mock_sync_connect.assert_not_called()+ mock_asyncio_run.assert_not_called()+ mock_post_feedback.assert_not_called()+ mock_capture.assert_called_once()++ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_app_mention_filters_candidates_to_user_accessible_only(self, mock_sync_connect, mock_asyncio_run):+ # When the workspace spans two orgs and the resolved PostHog user only+ # belongs to one of them, ``resolve_from_candidates`` filters the other+ # out so the workflow runs against the accessible integration.+ other_org = Organization.objects.create(name="Other Org")+ other_team = Team.objects.create(organization=other_org, name="Other Team")+ other_integration = Integration.objects.create(+ team=other_team,+ kind="slack",+ integration_id="T12345",+ config=self.posthog_code_integration.config,+ sensitive_config={"access_token": "xoxb-other"},+ )++ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ route_posthog_code_event_to_relevant_region(request, self.event, "T12345")++ mock_sync_connect.return_value.start_workflow.assert_called_once()+ workflow_inputs = mock_sync_connect.return_value.start_workflow.call_args.args[1]+ # The user belongs to ``self.organization`` only, so only that integration+ # should be the mention target — ``other_integration`` is filtered out.+ assert workflow_inputs.integration_id == self.posthog_code_integration.id+ assert workflow_inputs.integration_id != other_integration.id++ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_app_mention_excludes_private_team_when_user_lacks_access_control_grant(+ self, mock_sync_connect, mock_asyncio_run+ ):+ # Regression: ``user.teams`` reads its access-control flag from a single+ # ``Organization.first()`` row, so a Slack user spanning an+ # ACCESS_CONTROL-enabled org and a non-AC org can otherwise appear to+ # have access to a private project they were never granted. The+ # per-team ``effective_membership_level`` check must drop that+ # integration before the workflow starts.+ from posthog.constants import AvailableFeature++ from ee.models.rbac.access_control import AccessControl++ ac_org = Organization.objects.create(name="AC Org")+ # The ``pre_save`` signal on ``Organization`` resets+ # ``available_product_features`` to ``[]`` on insert, so set it after the+ # initial save to opt the org into per-team access-control checks.+ ac_org.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ ac_org.save()+ private_team = Team.objects.create(organization=ac_org, name="Private Team")+ AccessControl.objects.create(+ team=private_team,+ resource="project",+ resource_id=str(private_team.id),+ organization_member=None,+ role=None,+ access_level="none",+ )+ OrganizationMembership.objects.create(organization=ac_org, user=self.user)+ private_integration = Integration.objects.create(+ team=private_team,+ kind="slack",+ integration_id="T12345",+ config=self.posthog_code_integration.config,+ sensitive_config={"access_token": "xoxb-private"},+ )++ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ route_posthog_code_event_to_relevant_region(request, self.event, "T12345")++ mock_sync_connect.return_value.start_workflow.assert_called_once()+ workflow_inputs = mock_sync_connect.return_value.start_workflow.call_args.args[1]+ assert workflow_inputs.integration_id == self.posthog_code_integration.id+ assert workflow_inputs.integration_id != private_integration.id++ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_app_mention_passes_resolved_user_id_into_workflow_inputs(self, mock_sync_connect, mock_asyncio_run):+ # The routing layer must propagate the resolved PostHog user id into the+ # mention workflow inputs so the workflow can skip its legacy in-workflow+ # resolve activity.+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ route_posthog_code_event_to_relevant_region(request, self.event, "T12345")++ mock_sync_connect.return_value.start_workflow.assert_called_once()+ workflow_inputs = mock_sync_connect.return_value.start_workflow.call_args.args[1]+ assert workflow_inputs.user_id == self.user.id++ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_command_workflow_receives_resolved_user_id(self, mock_sync_connect, mock_asyncio_run):+ # Command path mirrors the mention path: routing resolves the user once+ # and the command workflow gets ``user_id`` so it skips its legacy+ # resolve-user activity on replay-safe code paths.+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ event = {**self.event, "text": "<@UBOT123> project 2"}++ route_posthog_code_event_to_relevant_region(request, event, "T12345")++ mock_sync_connect.return_value.start_workflow.assert_called_once()+ workflow_inputs = mock_sync_connect.return_value.start_workflow.call_args.args[1]+ assert workflow_inputs.user_id == self.user.id+@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@override_settings(DEBUG=False)@@ -676,6 +878,8 @@ class TestChannelApprovalGate(TestCase):"""def setUp(self):+ from django.utils import timezone+from products.slack_app.backend.api import POSTHOG_CODE_REQUIRED_SLACK_SCOPEScache.clear()@@ -683,6 +887,10 @@ class TestChannelApprovalGate(TestCase):self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")self.user = User.objects.create(email="[email protected]", distinct_id="user-1")+ OrganizationMembership.objects.create(organization=self.organization, user=self.user)+ self.user.current_organization = self.organization+ self.user.current_team = self.team+ self.user.save()self.integration = Integration.objects.create(team=self.team,kind="slack",@@ -690,6 +898,17 @@ class TestChannelApprovalGate(TestCase):config={"scope": ",".join(sorted(POSTHOG_CODE_REQUIRED_SLACK_SCOPES))},sensitive_config={"access_token": "xoxb-posthog-code-test"},)+ # Routing now resolves the Slack user to a PostHog user before any+ # channel-approval logic runs. Seed the cache so the gate has something+ # to resolve without calling Slack.+ SlackUserProfileCache.objects.create(+ integration=self.integration,+ slack_user_id="U123",+ email="[email protected]",+ display_name="Dev",+ real_name="Dev User",+ refreshed_at=timezone.now(),+ )self.event = {"type": "app_mention","channel": "C_EXT",