Skip to content

: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.

fix(slack_app): fail closed when the App Home viewer has no PostHog account (#98894)

posthog[bot]8ed1296b9c11
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index f8271068ff35..9e9d7805ddfa 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -1611,7 +1611,7 @@ def resolve_posthog_user_from_event(
candidate_org_ids=org_ids,
)
if linked_user is not None and is_slack_app_oauth_enabled(probe_integration):
- return linked_user if linked_user.is_active else None
+ return linked_user
if slack_email is None:
slack_email = get_slack_email_for_user(probe_integration, slack_user_id)
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
index 335ae6d44edb..7670d8e5522e 100644
--- a/products/slack_app/backend/services/slack_app_home.py
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -18,7 +18,7 @@ from __future__ import annotations
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, replace
from datetime import datetime, timedelta
-from typing import Any
+from typing import Any, Literal
from django.conf import settings
from django.core.exceptions import ValidationError
@@ -407,6 +407,7 @@ def render_home_view(
stats_state: StatsState | None = None,
untagged_followup_mode: UntaggedFollowupMode | None = None,
has_project_access: bool = True,
+ account_settings_url: str | None = None,
) -> dict:
"""Render the Block Kit payload for `views.publish` on the App Home tab."""
@@ -420,7 +421,7 @@ def render_home_view(
# and stop, rather than drawing empty cards that read as "you have no tasks yet".
if not has_project_access:
blocks.append({"type": "divider"})
- blocks.extend(_no_project_access_blocks())
+ blocks.extend(_no_project_access_blocks(account_settings_url))
return {"type": "home", "callback_id": HOME_CALLBACK_ID, "blocks": blocks}
# Section 1 — workspace activity: aggregates across everyone's Slack-started work,
@@ -536,12 +537,17 @@ def _header_blocks() -> list[dict]:
]
-def _no_project_access_blocks() -> list[dict]:
+def _no_project_access_blocks(account_settings_url: str | None = None) -> list[dict]:
"""Shown when the viewer can't reach any PostHog project connected to this workspace.
- Covers both halves of the same dead end — no project is connected yet, or one is but
- the viewer isn't a member of its organization — because from Slack the two are
- indistinguishable and the next step is the same page either way.
+ Covers three causes that look identical from Slack: no project is connected yet, one
+ is but the viewer isn't a member of its organization, or they are a member under an
+ address that doesn't match their Slack profile. Only the third has a different next
+ step, so it gets its own line rather than its own screen.
+
+ The signed account-link URL is deliberately absent. Landing here means nobody could
+ be identified, which is also what a Slack Connect guest from another company looks
+ like, so the remedy points at PostHog's own settings behind a login instead.
"""
site_url = (settings.SITE_URL or "").rstrip("/")
blocks: list[dict] = [
@@ -557,21 +563,38 @@ def _no_project_access_blocks() -> list[dict]:
"text": ("Connect a project in PostHog, or ask an admin to add you to one that's already connected."),
},
},
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": (
+ "If you already belong to one, check that your PostHog account uses the same email "
+ "address as your Slack profile. When the two differ, link them from Personal "
+ "integrations in PostHog and this tab will find you."
+ ),
+ },
+ },
]
+ elements: list[dict] = []
if site_url:
- blocks.append(
+ elements.append(
{
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "url": f"{site_url}/settings/project-integrations",
- "text": {"type": "plain_text", "text": "Connect PostHog to Slack", "emoji": True},
- "style": "primary",
- }
- ],
+ "type": "button",
+ "url": f"{site_url}/settings/project-integrations",
+ "text": {"type": "plain_text", "text": "Connect PostHog to Slack", "emoji": True},
+ "style": "primary",
+ }
+ )
+ if account_settings_url:
+ elements.append(
+ {
+ "type": "button",
+ "url": account_settings_url,
+ "text": {"type": "plain_text", "text": "Personal integrations", "emoji": True},
}
)
+ if elements:
+ blocks.append({"type": "actions", "elements": elements})
return blocks
@@ -1541,7 +1564,7 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespo
return HttpResponse(status=200)
if action_id == ACTION_SET_PROJECT_PERSONAL:
- _apply_project_pick(integration, slack_user_id=slack_user_id, action=action, scope="personal")
+ _apply_project_pick(integration, actor_slack_user_id=slack_user_id, action=action, scope="personal")
republish()
return HttpResponse(status=200)
@@ -1555,7 +1578,7 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespo
if not _is_admin(slack, integration, slack_user_id):
_post_ephemeral_admin_only(slack, payload)
return HttpResponse(status=200)
- _apply_project_pick(integration, slack_user_id=None, action=action, scope="workspace")
+ _apply_project_pick(integration, actor_slack_user_id=slack_user_id, action=action, scope="workspace")
republish()
return HttpResponse(status=200)
@@ -1993,6 +2016,8 @@ def _build_home_view(
stats_state=stats_state,
untagged_followup_mode=resolve_untagged_followup_mode(integration, slack_user_id),
has_project_access=bool(accessible),
+ # The same settings page the GitHub card deep-links to.
+ account_settings_url=github_state.settings_url,
)
return _HomeRender(
view=view,
@@ -2292,7 +2317,7 @@ def _resolve_home_user(integration: Integration, slack_user_id: str) -> User | N
candidate_org_ids=candidate_org_ids,
)
if linked_user is not None:
- return linked_user if linked_user.is_active else None
+ return linked_user
profile = SlackUserProfileCache.objects.filter(integration_id=integration.id, slack_user_id=slack_user_id).first()
if profile is None or not profile.email:
@@ -2474,20 +2499,15 @@ def _filter_accessible_integrations(
) -> list[Integration]:
"""The candidates this Slack identity can reach.
- A viewer we cannot identify is narrowed to the one project the tab is already being
- rendered for, rather than shown the whole list. A Slack workspace can carry several
- organizations, so the old behaviour of returning every candidate published the
- project and organization names of orgs the viewer has no membership in to anyone in
- the workspace. Narrowing keeps every card working and the routing picker usable,
- which is what returning the full list was protecting, without that disclosure.
+ `views.publish` answers whoever opens the tab, including a Slack Connect guest with no
+ PostHog account, so a viewer this cannot resolve must reach no project at all.
- `_apply_project_pick` gates on this too, so the same narrowing stops an unidentified
- viewer saving a personal default for any team in the workspace, which the old
- behaviour allowed. Such a default is rejected on the mention path anyway.
+ `_apply_project_pick` gates on this too, so an unidentified viewer also cannot save a
+ default for any team in the workspace.
"""
user = _resolve_home_user(integration, slack_user_id)
if user is None:
- return [c for c in candidates if c.id == integration.id]
+ return []
permissions = UserPermissions(user=user)
return [c for c in candidates if permissions.team(c.team).effective_membership_level is not None]
@@ -2495,10 +2515,15 @@ def _filter_accessible_integrations(
def _apply_project_pick(
integration: Integration,
*,
- slack_user_id: str | None,
+ actor_slack_user_id: str,
action: dict,
- scope: str,
+ scope: Literal["personal", "workspace"],
) -> None:
+ """Point a default at the picked project, for the clicker or for the whole workspace.
+
+ `scope` chooses whose default moves; the clicker is who both scopes are
+ authorized against.
+ """
selected = (action.get("selected_option") or {}).get("value")
if not selected:
return
@@ -2513,23 +2538,20 @@ def _apply_project_pick(
)
if target is None:
return
- # Personal-scope picks are user-driven, so re-check that the picker
- # actually had this team in its accessible set. The renderer hides
- # inaccessible options but a hand-crafted block_actions can still arrive
- # with any team_id in the workspace.
- if scope == "personal" and slack_user_id:
- accessible = _filter_accessible_integrations(integration, slack_user_id, [target] if target else [])
- if not accessible:
- return
+ # The renderer hides options the clicker can't reach, but a hand-crafted
+ # block_actions — or one replayed from a view Slack published before access was
+ # removed — can still carry any team id in the workspace.
+ if not _filter_accessible_integrations(integration, actor_slack_user_id, [target]):
+ return
SlackSettings.objects.update_or_create(
slack_workspace_id=integration.integration_id,
- slack_user_id=slack_user_id,
+ slack_user_id=actor_slack_user_id if scope == "personal" else None,
defaults={"default_integration": target},
)
logger.info(
"slack_app_home_project_default_set",
slack_workspace_id=integration.integration_id,
- slack_user_id=slack_user_id,
+ slack_user_id=actor_slack_user_id,
scope=scope,
team_id=team_id,
)
diff --git a/products/slack_app/backend/services/slack_user_oauth.py b/products/slack_app/backend/services/slack_user_oauth.py
index a12f2a3c9b5c..bb7c6cdd32e6 100644
--- a/products/slack_app/backend/services/slack_user_oauth.py
+++ b/products/slack_app/backend/services/slack_user_oauth.py
@@ -56,7 +56,11 @@ def find_linked_posthog_user(
**most-recently-linked** one — they just authenticated, presumably with
intent — and emit a warn-log so the rare collision is visible in prod.
- Returns ``None`` when no link exists or none of the linked users are
+ Deactivated accounts are dropped before that pick, so an offboarded person
+ can't be reached through a Slack identity that still points at them, and a
+ stale link of theirs can't hide a colleague's older active one.
+
+ Returns ``None`` when no link exists or none of the linked users are active
members of a connected org. Caller still owns the access-level
(``effective_membership_level``) check on the resolved user.
"""
@@ -74,6 +78,7 @@ def find_linked_posthog_user(
kind=UserIntegration.IntegrationKind.SLACK,
integration_id=slack_user_id,
config__slack_team_id=slack_team_id,
+ user__is_active=True,
)
.select_related("user")
.order_by("-created_at")
diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.py
index 058ae9854fad..138ce2c9bd3b 100644
--- a/products/slack_app/backend/tests/services/test_slack_app_home.py
+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py
@@ -38,6 +38,7 @@ from products.slack_app.backend.services.slack_app_home import (
ACTION_EDIT_PERSONAL,
ACTION_RESET_PERSONAL,
ACTION_RESET_PROJECT_PERSONAL,
+ ACTION_SET_PROJECT_WORKSPACE,
ACTION_SET_UNTAGGED_FOLLOWUP_MODE,
ACTION_TASKS_FILTER_REPO,
ACTION_TASKS_PAGE_NEXT,
@@ -331,14 +332,18 @@ def _block_action_payload(
slack_user_id: str,
trigger_id: str | None = None,
channel: str | None = None,
+ selected_value: str | None = None,
) -> dict:
+ action: dict[str, Any] = {"action_id": action_id}
+ if selected_value is not None:
+ action["selected_option"] = {"value": selected_value}
return {
"type": "block_actions",
"team": {"id": SLACK_WORKSPACE_ID},
"user": {"id": slack_user_id},
"trigger_id": trigger_id,
"channel": {"id": channel} if channel else None,
- "actions": [{"action_id": action_id}],
+ "actions": [action],
}
@@ -1000,6 +1005,13 @@ class TestTasksControlsRepublishTheList:
"""
def _seed(self, integration) -> None:
+ # The card is scoped to the projects the clicker can reach, so U001 needs an identity.
+ viewer = User.objects.create_and_join(integration.team.organization, "[email protected]", None)
+ SlackUserProfileCache.objects.create(
+ integration=integration,
+ slack_user_id="U001",
+ email=viewer.email,
+ )
# More than one page, so a Next click has somewhere to go.
for index in range(12):
task = Task.objects.create(
@@ -1151,6 +1163,35 @@ class TestHandleAppHomeOpened:
assert "opener-gh" in text
assert "colleague-gh" not in text
+ @pytest.mark.parametrize(
+ "viewer_email, is_member, reaches_project",
+ [
+ (None, False, False),
+ ("[email protected]", False, False),
+ ("[email protected]", True, True),
+ ],
+ ids=["viewer_we_cannot_identify", "viewer_outside_every_connected_org", "organization_member"],
+ )
+ def test_only_an_organization_member_reaches_the_connected_project(
+ self, slack_integration, mock_slack_client, flag_on, admin_user, viewer_email, is_member, reaches_project
+ ):
+ slack_integration.team.name = "Zephyr Analytics"
+ slack_integration.team.save(update_fields=["name"])
+ if is_member:
+ User.objects.create_and_join(slack_integration.team.organization, viewer_email, None)
+ if viewer_email:
+ SlackUserProfileCache.objects.create(
+ integration=slack_integration,
+ slack_user_id="U001",
+ email=viewer_email,
+ )
+
+ handle_app_home_opened({"user": "U001"}, SLACK_WORKSPACE_ID, integration=slack_integration)
+
+ text = _all_text(mock_slack_client.views_publish.call_args.kwargs["view"])
+ assert ("Zephyr Analytics" in text) is reaches_project
+ assert ("No project to show yet" in text) is not reaches_project
+
def test_deactivated_user_is_not_resolved_from_their_slack_identity(
self, slack_integration, mock_slack_client, flag_on, admin_user
):
@@ -1169,7 +1210,7 @@ class TestHandleAppHomeOpened:
text = _all_text(mock_slack_client.views_publish.call_args.kwargs["view"])
assert "offboarded-gh" not in text
- assert "Link your PostHog account first" in text
+ assert "No project to show yet" in text
# ---------------------------------------------------------------------------
@@ -1262,6 +1303,63 @@ class TestResetProjectPersonal:
assert mock_slack_client.views_publish.called
+class TestSetProjectWorkspace:
+ """The workspace default is one setting for everyone in the Slack workspace.
+
+ Slack's admin flag gates the control upstream and says nothing about PostHog, so
+ these cover the second gate: the clicker must reach the project they picked. Every
+ case arrives as a `block_actions` payload, which is what a view Slack published
+ before access was removed replays.
+ """
+
+ def _click(self, slack_user_id: str, team_id: int) -> dict:
+ return _block_action_payload(
+ action_id=ACTION_SET_PROJECT_WORKSPACE,
+ slack_user_id=slack_user_id,
+ selected_value=str(team_id),
+ )
+
+ def test_slack_admin_with_no_posthog_account_cannot_set_the_default(
+ self, slack_integration, mock_slack_client, flag_on, admin_user
+ ):
+ payload = self._click("U001", slack_integration.team_id)
+
+ handle_ai_preferences_block_action(payload, payload["actions"][0])
+
+ assert not SlackSettings.objects.filter(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id=None).exists()
+
+ def test_slack_admin_who_is_an_organization_member_sets_the_default(
+ self, slack_integration, mock_slack_client, flag_on, admin_user
+ ):
+ member = User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)
+ SlackUserProfileCache.objects.create(integration=slack_integration, slack_user_id="U001", email=member.email)
+ payload = self._click("U001", slack_integration.team_id)
+
+ handle_ai_preferences_block_action(payload, payload["actions"][0])
+
+ row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id=None)
+ assert row.default_integration_id == slack_integration.id
+
+ def test_member_of_one_connected_organization_cannot_pick_another_ones_project(
+ self, slack_integration, mock_slack_client, flag_on, admin_user
+ ):
+ 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=SLACK_WORKSPACE_ID,
+ sensitive_config={"access_token": "xoxb"},
+ )
+ member = User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)
+ SlackUserProfileCache.objects.create(integration=slack_integration, slack_user_id="U001", email=member.email)
+ payload = self._click("U001", other_integration.team_id)
+
+ handle_ai_preferences_block_action(payload, payload["actions"][0])
+
+ assert not SlackSettings.objects.filter(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id=None).exists()
+
+
# ---------------------------------------------------------------------------
# Handler tests — view_submission
# ---------------------------------------------------------------------------
@@ -1535,18 +1633,34 @@ class TestNoProjectAccessCard:
kwargs.update(overrides)
return render_home_view(**kwargs)
- def test_explains_the_dead_end_and_links_to_the_settings_page(self):
- text = _all_text(self._view())
-
- assert "No project to show yet" in text
- assert "ask an admin" in text
- urls = [
+ @staticmethod
+ def _urls(view: dict) -> list[str]:
+ return [
element["url"]
- for block in self._view()["blocks"]
+ for block in view["blocks"]
for element in block.get("elements", []) or []
if "url" in element
]
- assert urls == ["http://localhost:8010/settings/project-integrations"]
+
+ def test_explains_the_dead_end_and_links_to_the_settings_page(self):
+ view = self._view()
+
+ assert "No project to show yet" in _all_text(view)
+ assert "ask an admin" in _all_text(view)
+ assert self._urls(view) == ["http://localhost:8010/settings/project-integrations"]
+
+ def test_names_the_address_mismatch_and_routes_it_to_personal_integrations(self):
+ personal = "http://localhost:8010/project/7/settings/user-personal-integrations"
+ view = self._view(account_settings_url=personal)
+
+ assert "same email address as your Slack profile" in _all_text(view)
+ assert personal in self._urls(view)
+
+ def test_withholds_the_signed_account_link_from_a_viewer_who_was_not_identified(self):
+ # The URL is in `account_state` on this path, so its absence has to be asserted.
+ view = self._view(account_settings_url="http://localhost:8010/project/7/settings/user-personal-integrations")
+
+ assert "https://app/link" not in json.dumps(view)
def test_suppresses_every_card_that_needs_a_project(self):
# Each of these would otherwise render from the states passed above.
@@ -1565,7 +1679,7 @@ class TestUnidentifiedViewerProjectList:
"""What the tab lists for a Slack user it cannot map to a PostHog account.
The regression to catch is the list widening again. A Slack workspace can connect
- several organizations, so returning every candidate publishes the project and
+ several organizations, so reaching any candidate publishes the project and
organization names of orgs the viewer is not a member of to anyone in the workspace.
"""
@@ -1590,7 +1704,7 @@ class TestUnidentifiedViewerProjectList:
sensitive_config={"access_token": "xoxb"},
)
- def test_shows_only_the_project_the_tab_renders_for(self):
+ def test_reaches_no_project_at_all(self):
from products.slack_app.backend.services.slack_app_home import _filter_accessible_integrations
# No SlackUserProfileCache row and no OAuth link, so the viewer is unidentifiable.
@@ -1598,5 +1712,4 @@ class TestUnidentifiedViewerProjectList:
self.rendered_for, "U_STRANGER", [self.rendered_for, self.other_org_install]
)
- assert [i.id for i in accessible] == [self.rendered_for.id]
- assert self.other_org_install.id not in {i.id for i in accessible}
+ assert accessible == []
diff --git a/products/slack_app/backend/tests/services/test_slack_app_home_stats.py b/products/slack_app/backend/tests/services/test_slack_app_home_stats.py
index 08e35cb0eec6..402a265e18b6 100644
--- a/products/slack_app/backend/tests/services/test_slack_app_home_stats.py
+++ b/products/slack_app/backend/tests/services/test_slack_app_home_stats.py
@@ -13,6 +13,7 @@ from django.utils import timezone
from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+from posthog.models.user import User
from products.slack_app.backend.models import SlackThreadTaskMapping, SlackUserProfileCache
from products.slack_app.backend.services.slack_app_home import handle_app_home_opened, render_home_view
@@ -478,6 +479,13 @@ class TestResolveStatsState:
class TestStatsCardGating:
@pytest.mark.parametrize("is_admin, expected_visible", [(True, True), (False, False)])
def test_card_is_admin_only(self, slack_integration, mock_slack_client, flag_on, is_admin, expected_visible):
+ # The card is scoped to the viewer's projects, so isolating the admin gate needs an identity.
+ admin = User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)
+ SlackUserProfileCache.objects.create(
+ integration=slack_integration,
+ slack_user_id=SLACK_USER,
+ email=admin.email,
+ )
with patch(
"products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin",
return_value=is_admin,
@@ -486,3 +494,14 @@ class TestStatsCardGating:
view = mock_slack_client.views_publish.call_args.kwargs["view"]
assert ("Workspace activity" in str(view)) is expected_visible
+
+ def test_card_is_withheld_from_an_admin_with_no_posthog_account(
+ self, slack_integration, mock_slack_client, flag_on
+ ):
+ with patch(
+ "products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin",
+ return_value=True,
+ ):
+ handle_app_home_opened({"user": SLACK_USER}, WORKSPACE, integration=slack_integration)
+
+ assert "Workspace activity" not in str(mock_slack_client.views_publish.call_args.kwargs["view"])
diff --git a/products/slack_app/backend/tests/services/test_slack_user_oauth.py b/products/slack_app/backend/tests/services/test_slack_user_oauth.py
index e6ab534a29df..aad06f9a536d 100644
--- a/products/slack_app/backend/tests/services/test_slack_user_oauth.py
+++ b/products/slack_app/backend/tests/services/test_slack_user_oauth.py
@@ -121,6 +121,33 @@ class TestFindLinkedPosthogUser:
assert found is not None
assert found.id == first_user.id
+ def test_most_recent_link_skipped_when_that_user_is_deactivated(self, org_team_user, link_user):
+ org, _, first_user = org_team_user
+ # Both accounts are in `org`, so only `is_active` separates them.
+ second_user = User.objects.create(email="[email protected]", distinct_id="user-2", is_active=False)
+ OrganizationMembership.objects.create(user=second_user, organization=org)
+ link_user(first_user)
+ link_user(second_user)
+
+ found = find_linked_posthog_user(
+ slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids={org.id}
+ )
+ assert found is not None
+ assert found.id == first_user.id
+
+ def test_returns_none_when_the_only_linked_user_is_deactivated(self, org_team_user, link_user):
+ org, _, user = org_team_user
+ link_user(user)
+ user.is_active = False
+ user.save(update_fields=["is_active"])
+
+ assert (
+ find_linked_posthog_user(
+ slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids={org.id}
+ )
+ is None
+ )
+
class TestUserSlackIntegrationFromIdentity:
"""Tests for the model factory that the OAuth callback hands off to.