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.

feat(slack-app): gate mention flow on granted Slack scopes (#59416)

Vojta Bartošed5f3fbd1001
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 54d8b83d51fb..6e68dda6c3fd 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -232,6 +232,38 @@ class TestSlackIntegration:
assert not channel["is_private"]
assert not channel["is_private_without_access"]
+ def test_granted_scopes_parses_comma_separated_string(self):
+ self.integration.config["scope"] = "chat:write,users:read,users:read.email"
+ slack = SlackIntegration(self.integration)
+ assert slack.granted_scopes() == frozenset({"chat:write", "users:read", "users:read.email"})
+
+ def test_granted_scopes_tolerates_whitespace_and_empty_entries(self):
+ self.integration.config["scope"] = " chat:write , ,users:read"
+ slack = SlackIntegration(self.integration)
+ assert slack.granted_scopes() == frozenset({"chat:write", "users:read"})
+
+ def test_granted_scopes_returns_empty_when_field_missing(self):
+ self.integration.config.pop("scope", None)
+ slack = SlackIntegration(self.integration)
+ assert slack.granted_scopes() == frozenset()
+
+ def test_granted_scopes_returns_empty_when_field_is_empty_string(self):
+ self.integration.config["scope"] = ""
+ slack = SlackIntegration(self.integration)
+ assert slack.granted_scopes() == frozenset()
+
+ def test_missing_scopes_returns_difference(self):
+ self.integration.config["scope"] = "chat:write,users:read"
+ slack = SlackIntegration(self.integration)
+ required = {"chat:write", "users:read", "users:read.email", "reactions:write"}
+ assert slack.missing_scopes(required) == frozenset({"users:read.email", "reactions:write"})
+
+ def test_missing_scopes_returns_empty_when_all_granted(self):
+ required = {"chat:write", "users:read"}
+ self.integration.config["scope"] = "chat:write,users:read,extra:scope"
+ slack = SlackIntegration(self.integration)
+ assert slack.missing_scopes(required) == frozenset()
+
class TestEmailIntegration:
@pytest.fixture(autouse=True)
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index b1bbaa7de5da..ed7fdc9a1973 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -4,6 +4,7 @@ import time
import base64
import socket
import hashlib
+from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional
@@ -1145,6 +1146,14 @@ class SlackIntegration:
def async_client(self, session: Optional["aiohttp.ClientSession"] = None) -> AsyncWebClient:
return AsyncWebClient(self.integration.sensitive_config["access_token"], session=session)
+ def granted_scopes(self) -> frozenset[str]:
+ """OAuth scopes Slack granted this install, stored on Integration.config["scope"]."""
+ raw = self.integration.config.get("scope") or ""
+ return frozenset(scope.strip() for scope in raw.split(",") if scope.strip())
+
+ def missing_scopes(self, required: Iterable[str]) -> frozenset[str]:
+ return frozenset(required) - self.granted_scopes()
+
def list_channels(self, should_include_private_channels: bool, authed_user: str) -> list[dict]:
# NOTE: Annoyingly the Slack API has no search so we have to load all channels...
# We load public and private channels separately as when mixed, the Slack API pagination is buggy
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index c77f49950049..2330cc753683 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -51,6 +51,21 @@ HANDLED_EVENT_TYPES = ["app_mention", "link_shared"]
POSTHOG_CODE_SLACK_AVAILABILITY_FLAG = "posthog-code-slack-availability"
+# Scopes the coding-agent flow exercises end-to-end. Slack stores the granted scope set
+# per install, so tenants who connected the Slack integration before the full scope set
+# was requested in prod (2026-05-04, #57177) must reconnect before mentions can work.
+POSTHOG_CODE_REQUIRED_SLACK_SCOPES: frozenset[str] = frozenset(
+ {
+ "app_mentions:read",
+ "users:read",
+ "users:read.email",
+ "chat:write",
+ "channels:history",
+ "groups:history",
+ "reactions:write",
+ }
+)
+
ROUTE_HANDLED_LOCALLY = "handled_locally"
ROUTE_PROXIED = "proxied"
ROUTE_PROXY_FAILED = "proxy_failed"
@@ -1220,6 +1235,41 @@ def _posthog_code_enabled_for_integration(integration: Integration) -> bool:
return False
+def _notify_missing_slack_scopes(
+ slack: SlackIntegration,
+ event: dict,
+ missing: frozenset[str],
+) -> None:
+ """Tell the user the install is missing scopes and how to fix it.
+
+ `chat:write` has been part of the base Slack scope set since the integration existed,
+ so the feedback post itself is safe to attempt even when other scopes are absent.
+ """
+ channel = event.get("channel", "")
+ thread_ts = event.get("thread_ts") or event.get("ts", "")
+ slack_user_id = event.get("user", "")
+ integration = slack.integration
+
+ logger.warning(
+ "posthog_code_slack_missing_scopes",
+ integration_id=integration.id,
+ team_id=integration.team_id,
+ missing=sorted(missing),
+ )
+
+ if not channel or not thread_ts or not slack_user_id:
+ return
+
+ settings_url = f"{settings.SITE_URL}/settings/project-integrations"
+ text = (
+ ":warning: PostHog can't reply because the Slack integration is missing required "
+ f"permissions: `{', '.join(sorted(missing))}`.\n"
+ f"A project admin needs to reconnect Slack from project settings: {settings_url}"
+ )
+
+ _post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
+
+
def route_posthog_code_event_to_relevant_region(
request: HttpRequest,
event: dict,
@@ -1258,6 +1308,11 @@ def route_posthog_code_event_to_relevant_region(
organization_id=str(local_match.team.organization_id),
)
return ROUTE_HANDLED_LOCALLY
+ slack = SlackIntegration(local_match)
+ missing_scopes = slack.missing_scopes(POSTHOG_CODE_REQUIRED_SLACK_SCOPES)
+ if missing_scopes:
+ _notify_missing_slack_scopes(slack, event, missing_scopes)
+ return ROUTE_HANDLED_LOCALLY
if _resolve_pending_repo_picker_from_followup(event, local_match):
return ROUTE_HANDLED_LOCALLY
workflow_inputs = PostHogCodeSlackMentionWorkflowInputs(
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.py
index fa03bc212afd..0ec27409b139 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
@@ -101,6 +101,8 @@ class TestPostHogCodeEventHandler(TestCase):
class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
def setUp(self):
+ from products.slack_app.backend.api import POSTHOG_CODE_REQUIRED_SLACK_SCOPES
+
cache.clear()
self.factory = RequestFactory()
self.organization = Organization.objects.create(name="Test Org")
@@ -109,6 +111,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
team=self.team,
kind="slack-posthog-code",
integration_id="T12345",
+ config={"scope": ",".join(sorted(POSTHOG_CODE_REQUIRED_SLACK_SCOPES))},
sensitive_config={"access_token": "xoxb-posthog-code-test"},
)
self.event = {"type": "app_mention", "channel": "C001", "user": "U123", "ts": "1234.5678"}
@@ -179,6 +182,10 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
):
request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")
mock_get_repos.return_value = repo_list
+ # The route runs _missing_posthog_code_slack_scopes against a real SlackIntegration
+ # before the picker / workflow path. Since SlackIntegration is mocked wholesale here,
+ # explicitly say no scopes are missing so the gate passes through.
+ mock_slack_cls.return_value.missing_scopes.return_value = frozenset()
from products.slack_app.backend.api import (
ROUTE_HANDLED_LOCALLY,
@@ -387,3 +394,76 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
mock_sync_connect.assert_not_called()
mock_asyncio_run.assert_not_called()
mock_proxy.assert_not_called()
+
+ @parameterized.expand(
+ [
+ # Pre-2026-05-04 prod installs only granted the 4 base scopes.
+ ("four_base_scopes", "channels:read,groups:read,chat:write,chat:write.customize", False),
+ # Fail-closed when the scope field is absent entirely.
+ ("no_scope_field", None, False),
+ # Follow-up mentions in an existing thread must also be gated.
+ ("followup_with_partial_scopes", "channels:read,chat:write", True),
+ ]
+ )
+ @patch("products.slack_app.backend.api._post_slack_user_feedback")
+ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)
+ @patch("products.slack_app.backend.api.asyncio.run")
+ @patch("products.slack_app.backend.api.sync_connect")
+ @override_settings(DEBUG=False)
+ def test_app_mention_with_missing_scopes_posts_reauth_and_skips_workflow(
+ self,
+ _name,
+ scope_value: str | None,
+ seed_pending_picker: bool,
+ mock_sync_connect,
+ mock_asyncio_run,
+ _mock_flag,
+ mock_post_feedback,
+ ):
+ if scope_value is None:
+ self.posthog_code_integration.config = {}
+ else:
+ self.posthog_code_integration.config["scope"] = scope_value
+ self.posthog_code_integration.save(update_fields=["config"])
+
+ from products.slack_app.backend.api import (
+ ROUTE_HANDLED_LOCALLY,
+ _set_pending_repo_picker,
+ route_posthog_code_event_to_relevant_region,
+ )
+
+ if seed_pending_picker:
+ _set_pending_repo_picker(
+ integration_id=self.posthog_code_integration.id,
+ channel="C001",
+ thread_ts="1234.5678",
+ slack_user_id="U123",
+ workflow_id="posthog-code-mention-T12345:pending",
+ context_token="ctx-1",
+ message_ts="1234.7777",
+ )
+
+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")
+ event = {
+ "type": "app_mention",
+ "channel": "C001",
+ "user": "U123",
+ "ts": "1234.5678",
+ "thread_ts": "1234.5678",
+ }
+
+ result = route_posthog_code_event_to_relevant_region(request, event, "T12345")
+
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_sync_connect.assert_not_called()
+ mock_sync_connect.return_value.get_workflow_handle.assert_not_called()
+ mock_asyncio_run.assert_not_called()
+ mock_post_feedback.assert_called_once()
+
+ feedback_text = mock_post_feedback.call_args.args[4]
+ assert "missing" in feedback_text.lower() and "reconnect" in feedback_text.lower()
+ # The message enumerates scopes that are actually missing (e.g. app_mentions:read is
+ # never in a pre-2026-05-04 install). Scopes the install already has must not appear.
+ assert "app_mentions:read" in feedback_text
+ if scope_value and "chat:write.customize" in scope_value:
+ assert "chat:write.customize" not in feedback_text