: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): require approval before answering in externally-shared channels (#61571)
Vojta Bartoš3527e8400d6f
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex bc799724a6f1..35189b110224 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -208,6 +208,10 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"SessionRecordingComment","SessionSummary","SharePassword",+ # Per-(Slack workspace, Slack channel) approval state — looked up by+ # `(slack_workspace_id, slack_channel_id)` from the Slack event handler,+ # never by user-supplied ID. `approved_by` is for audit only.+ "SlackChannel","UserActivity","UserGroup","UserGroupMembership",diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 8f19bdbf3073..fb8348dd0f8b 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -53,7 +53,7 @@ from posthog.temporal.ai.posthog_code_slack_mention_command import (from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissions-from products.slack_app.backend.models import SlackUserProfileCache+from products.slack_app.backend.models import SlackChannel, SlackUserProfileCachefrom products.slack_app.backend.services.integration_resolver import format_project_candidate_list, load_integrationsfrom products.slack_app.backend.slack_link_unfurl import handle_posthog_link_unfurl@@ -89,6 +89,11 @@ PICKER_TOKEN_SALT = "posthog_code_repo_picker"PICKER_TOKEN_MAX_AGE_SECONDS = 900SLACK_USER_PROFILE_TTL = timedelta(hours=1)+CHANNEL_APPROVAL_BLOCK_ID_PREFIX = "posthog_code_channel_approval"+CHANNEL_APPROVAL_ACTION_APPROVE = "posthog_code_channel_approve"+CHANNEL_APPROVAL_ACTION_DENY = "posthog_code_channel_deny"+CHANNEL_APPROVAL_CONTEXT_KIND = "channel_approval"+_MAX_GITHUB_REPOS = 500REPO_LIST_CACHE_TTL_SECONDS = 300PENDING_REPO_PICKER_TTL_SECONDS = PICKER_TOKEN_MAX_AGE_SECONDS@@ -1484,6 +1489,8 @@ def route_posthog_code_event_to_relevant_region(event: dict,slack_team_id: str,event_id: str | None = None,+ *,+ is_ext_shared_channel: bool = False,) -> str:event_type = event.get("type")incoming_host = request.get_host()@@ -1554,6 +1561,11 @@ def route_posthog_code_event_to_relevant_region(_notify_missing_slack_scopes(slack, event, missing)return ROUTE_HANDLED_LOCALLY+ channel_id = event.get("channel") if isinstance(event.get("channel"), str) else None+ if channel_id and is_ext_shared_channel and not _channel_is_approved(mention_target.integration_id, channel_id):+ _post_channel_approval_prompt(slack, mention_target, event)+ return ROUTE_HANDLED_LOCALLY+return _start_mention_workflow(event, mention_target, slack_team_id, event_id)# link_shared (unfurl) works with either integration kind.@@ -1653,6 +1665,121 @@ def _count_session_thread_messages(integration: Integration, channel: str | Nonereturn None+def _channel_is_approved(slack_workspace_id: str, channel_id: str) -> bool:+ """True iff a user in this channel has already granted PostHog approval.++ The ``is_ext_shared_channel`` flag that gates whether approval is required+ at all lives on the Slack event envelope — see ``posthog_code_event_handler``+ — so this only needs to answer the persistence question.+ """+ return SlackChannel.objects.filter(+ slack_workspace_id=slack_workspace_id,+ slack_channel_id=channel_id,+ approved_at__isnull=False,+ ).exists()+++def _post_channel_approval_prompt(+ slack: SlackIntegration,+ integration: Integration,+ event: dict[str, Any],+) -> None:+ """Post the approval prompt as an ephemeral message to the mentioner.++ The prompt itself stays ephemeral — only the mentioner sees the+ buttons — but every click *outcome* (approve, deny, non-member+ rejection) is posted as a public threaded reply under the original+ mention so the whole channel has a permanent record.++ The ephemeral is **not** threaded: Slack only renders ephemerals on+ the surface the user is currently viewing, so an ephemeral with+ ``thread_ts`` is invisible from the channel main view — i.e. the+ place where the mentioner usually is right after typing the mention.+ Dropping ``thread_ts`` here is what makes the prompt actually visible.+ """+ channel = event.get("channel") if isinstance(event.get("channel"), str) else None+ slack_user_id = event.get("user") if isinstance(event.get("user"), str) else None+ if not channel or not slack_user_id:+ return++ raw_thread_ts = event.get("thread_ts") if isinstance(event.get("thread_ts"), str) else None+ message_ts = event.get("ts") if isinstance(event.get("ts"), str) else None+ thread_ts = raw_thread_ts or message_ts++ context_data = {+ "kind": CHANNEL_APPROVAL_CONTEXT_KIND,+ "integration_id": integration.id,+ "slack_workspace_id": integration.integration_id,+ "slack_channel_id": channel,+ "thread_ts": thread_ts,+ "created_at": int(time.time()),+ }+ context_token = uuid.uuid4().hex+ cache.set(+ _picker_context_cache_key(context_token),+ context_data,+ timeout=PICKER_TOKEN_MAX_AGE_SECONDS,+ )++ org_label = _org_label(integration)+ text = (+ ":wave: This is an externally-shared Slack channel. Anything I answer here can be "+ f"seen by every member, including people outside {org_label}'s workspace. "+ f"A member of {org_label} can enable me below."+ )++ blocks: list[dict[str, Any]] = [+ {+ "type": "section",+ "block_id": f"{CHANNEL_APPROVAL_BLOCK_ID_PREFIX}:{context_token}",+ "text": {"type": "mrkdwn", "text": text},+ },+ {+ "type": "actions",+ "block_id": f"{CHANNEL_APPROVAL_BLOCK_ID_PREFIX}_actions:{context_token}",+ "elements": [+ {+ "type": "button",+ "action_id": CHANNEL_APPROVAL_ACTION_APPROVE,+ "style": "primary",+ "text": {"type": "plain_text", "text": "✅ Allow PostHog in this channel"},+ "value": context_token,+ },+ {+ "type": "button",+ "action_id": CHANNEL_APPROVAL_ACTION_DENY,+ "text": {"type": "plain_text", "text": "✋ Not here"},+ "value": context_token,+ },+ ],+ },+ ]++ logger.info(+ "slack_app_channel_approval_prompt_requested",+ integration_id=integration.id,+ slack_workspace_id=integration.integration_id,+ slack_channel_id=channel,+ slack_user_id=slack_user_id,+ )++ try:+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ text="The PostHog Slack app needs approval before answering in this externally-shared channel.",+ blocks=blocks,+ )+ except Exception:+ logger.warning(+ "slack_app_channel_approval_prompt_failed",+ integration_id=integration.id,+ slack_workspace_id=integration.integration_id,+ slack_channel_id=channel,+ exc_info=True,+ )++def _report_slack_mention_received(event: dict, integration: Integration, slack_team_id: str) -> None:"""Capture a product-analytics event each time the @PostHog bot is mentioned.@@ -1806,7 +1933,17 @@ def posthog_code_event_handler(request: HttpRequest) -> HttpResponse:event_id = data.get("event_id")if event.get("type") in HANDLED_EVENT_TYPES:- result = route_posthog_code_event_to_relevant_region(request, event, slack_team_id, event_id=event_id)+ # ``is_ext_shared_channel`` lives on the event envelope (Slack adds it for+ # any event delivered from a Slack Connect channel). Reading it here avoids+ # a per-mention ``conversations.info`` round-trip.+ is_ext_shared = bool(data.get("is_ext_shared_channel", False))+ result = route_posthog_code_event_to_relevant_region(+ request,+ event,+ slack_team_id,+ event_id=event_id,+ is_ext_shared_channel=is_ext_shared,+ )logger.info("posthog_code_event_dispatch_result",result=result,@@ -2149,6 +2286,207 @@ def _handle_no_repo_needed_submit(payload: dict) -> HttpResponse:return HttpResponse(status=200)+def _delete_ephemeral_via_response_url(response_url: str) -> None:+ """Remove the original ephemeral prompt via the interactivity ``response_url``.++ Every click outcome is recorded as a public threaded message — the+ ephemeral prompt has done its job by then and only the public message+ should remain. Failures are logged but never raised: a click handler+ that can't reach Slack still finished its DB work.+ """+ if not response_url:+ return+ try:+ requests.post(response_url, json={"delete_original": True}, timeout=3)+ except Exception:+ logger.warning("slack_app_channel_approval_response_url_failed", exc_info=True)+++def _post_channel_approval_outcome(+ integration: Integration,+ channel_id: str,+ thread_ts: str | None,+ text: str,+) -> None:+ """Post a public threaded reply documenting a click outcome.++ The prompt itself is ephemeral, so this is the only channel-visible+ record of what happened. ``thread_ts`` ties the message to the+ original mention so the audit trail sits next to the trigger.+ """+ if not thread_ts:+ return+ try:+ SlackIntegration(integration).client.chat_postMessage(+ channel=channel_id,+ thread_ts=thread_ts,+ text=text,+ )+ except Exception:+ logger.warning(+ "slack_app_channel_approval_outcome_post_failed",+ integration_id=integration.id,+ channel=channel_id,+ exc_info=True,+ )+++def _resolve_channel_approval_context(+ payload: dict,+) -> tuple[Integration, dict, str, str] | None:+ """Decode the click context and load the prompt's integration in one place.++ Returns ``(integration, context, channel_id, clicker_slack_user_id)`` on+ success, or ``None`` after silently cleaning up the ephemeral. Used by+ both approve and deny so they share the same context + integration+ resolution path.+ """+ response_url = payload.get("response_url", "")+ context_token = _extract_context_token(payload)+ context = _decode_picker_context(context_token) if context_token else None+ if not context or context.get("kind") != CHANNEL_APPROVAL_CONTEXT_KIND:+ _delete_ephemeral_via_response_url(response_url)+ return None++ integration_id = context.get("integration_id")+ channel_id = context.get("slack_channel_id")+ slack_team_id = payload.get("team", {}).get("id", "")+ clicker_slack_user_id = payload.get("user", {}).get("id", "")+ if not integration_id or not channel_id or not clicker_slack_user_id or not slack_team_id:+ _delete_ephemeral_via_response_url(response_url)+ return None++ integration = (+ Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ kind=SLACK_INTEGRATION_KIND,+ integration_id=slack_team_id,+ )+ .select_related("team__organization")+ .first()+ )+ if integration is None:+ _delete_ephemeral_via_response_url(response_url)+ return None++ return integration, context, channel_id, clicker_slack_user_id+++def _is_org_member(integration: Integration, clicker_slack_user_id: str) -> User | None:+ """Resolve the clicker to a PostHog ``User`` belonging to the integration's+ organization, or ``None`` if no such membership exists.+ """+ return _resolve_posthog_user_from_event(+ slack_user_id=clicker_slack_user_id,+ probe_integration=integration,+ candidate_integrations=[integration],+ )+++def _org_label(integration: Integration) -> str:+ try:+ org_name = integration.team.organization.name+ except Exception:+ org_name = ""+ return f"*{org_name}*" if org_name else "this PostHog organization"+++def _reject_non_member_click(+ integration: Integration,+ channel_id: str,+ thread_ts: str | None,+ response_url: str,+) -> None:+ """Post the public "only members can manage" rejection and clear the ephemeral.++ Shared between approve and deny so the rejection wording, the public+ placement, and the ephemeral cleanup all stay in one place.+ """+ _post_channel_approval_outcome(+ integration,+ channel_id,+ thread_ts,+ f":warning: Only members of {_org_label(integration)} can manage the PostHog Slack app in this channel.",+ )+ _delete_ephemeral_via_response_url(response_url)+++def _handle_channel_approval_submit(payload: dict) -> HttpResponse:+ """Approve the bot for this Slack channel after verifying the clicker is a+ member of the integration's PostHog organization.++ The prompt is ephemeral to the mentioner; every outcome (approve, deny,+ non-member rejection) is posted as a public threaded reply so the whole+ channel sees the result.+ """+ resolved = _resolve_channel_approval_context(payload)+ if resolved is None:+ return HttpResponse(status=200)+ integration, context, channel_id, clicker_slack_user_id = resolved+ response_url = payload.get("response_url", "")+ thread_ts = context.get("thread_ts") if isinstance(context.get("thread_ts"), str) else None++ posthog_user = _is_org_member(integration, clicker_slack_user_id)+ if posthog_user is None:+ _reject_non_member_click(integration, channel_id, thread_ts, response_url)+ return HttpResponse(status=200)++ workspace_id = context.get("slack_workspace_id") or integration.integration_id+ SlackChannel.objects.update_or_create(+ slack_workspace_id=workspace_id,+ slack_channel_id=channel_id,+ defaults={+ "approved_at": timezone.now(),+ "approved_by": posthog_user,+ },+ )+ context_token = _extract_context_token(payload)+ if context_token:+ cache.delete(_picker_context_cache_key(context_token))++ _post_channel_approval_outcome(+ integration,+ channel_id,+ thread_ts,+ f"✅ <@{clicker_slack_user_id}> enabled the PostHog Slack app in this channel.",+ )+ _delete_ephemeral_via_response_url(response_url)+ return HttpResponse(status=200)+++def _handle_channel_approval_deny(payload: dict) -> HttpResponse:+ """Dismiss the approval prompt without recording any state.++ Same membership gate as approve, since only the mentioner sees the+ ephemeral and a non-member mentioner's dismissal would otherwise just+ silently consume the prompt.+ """+ resolved = _resolve_channel_approval_context(payload)+ if resolved is None:+ return HttpResponse(status=200)+ integration, context, channel_id, clicker_slack_user_id = resolved+ response_url = payload.get("response_url", "")+ thread_ts = context.get("thread_ts") if isinstance(context.get("thread_ts"), str) else None++ posthog_user = _is_org_member(integration, clicker_slack_user_id)+ if posthog_user is None:+ _reject_non_member_click(integration, channel_id, thread_ts, response_url)+ return HttpResponse(status=200)++ context_token = _extract_context_token(payload)+ if context_token:+ cache.delete(_picker_context_cache_key(context_token))++ _post_channel_approval_outcome(+ integration,+ channel_id,+ thread_ts,+ f"✋ <@{clicker_slack_user_id}> dismissed the PostHog Slack app for this channel. Mention me again to retry.",+ )+ _delete_ephemeral_via_response_url(response_url)+ return HttpResponse(status=200)++def _handle_terminate_task_submit(payload: dict) -> HttpResponse:"""Start Temporal workflow for task termination and return 200 immediately."""action = next((a for a in payload.get("actions", []) if a.get("action_id") == "posthog_code_terminate_task"), None)@@ -2309,5 +2647,9 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return _handle_no_repo_needed_submit(payload)if action.get("action_id") == "posthog_code_terminate_task":return _handle_terminate_task_submit(payload)+ if action.get("action_id") == CHANNEL_APPROVAL_ACTION_APPROVE:+ return _handle_channel_approval_submit(payload)+ if action.get("action_id") == CHANNEL_APPROVAL_ACTION_DENY:+ return _handle_channel_approval_deny(payload)return HttpResponse(status=200)diff --git a/products/slack_app/backend/migrations/0005_slackchannel.py b/products/slack_app/backend/migrations/0005_slackchannel.pynew file mode 100644index 000000000000..c0f30d3ce328--- /dev/null+++ b/products/slack_app/backend/migrations/0005_slackchannel.py@@ -0,0 +1,55 @@+# Generated by Django 5.2.14 on 2026-06-04 08:36++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("slack_app", "0004_slackuserprofilecache_refreshed_at"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="SlackChannel",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("slack_workspace_id", models.CharField(max_length=64)),+ ("slack_channel_id", models.CharField(max_length=64)),+ ("approved_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "approved_by",+ models.ForeignKey(+ blank=True,+ help_text="The PostHog user who clicked Approve. Carries the email and audit trail.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="approved_slack_channels",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "constraints": [+ models.UniqueConstraint(+ fields=("slack_workspace_id", "slack_channel_id"),+ name="uniq_slack_channel",+ )+ ],+ },+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex 579142254ca3..4fb742fda7e4 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0004_slackuserprofilecache_refreshed_at+0005_slackchanneldiff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex ae053bda1436..23544256e717 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -113,3 +113,52 @@ class SlackSettings(UUIDModel):def __str__(self) -> str:who = self.slack_user_id or "(workspace default)"return f"{self.slack_workspace_id} / {who} → integration {self.default_integration_id}"+++class SlackChannel(UUIDModel):+ """Per-(Slack workspace, Slack channel) state.++ Today the only meaning of a row with ``approved_at`` set is that a user+ in the channel has acknowledged that PostHog data answered there may be+ visible to external (cross-workspace) members. Absence of a row — or a+ row with ``approved_at`` null — for an externally-shared channel means+ the bot must refuse to answer and post the approval prompt instead.+ Non-externally-shared channels skip the lookup entirely.++ The approval is workspace-scoped, not integration-scoped: a single+ workspace can be connected to multiple PostHog projects, and once any+ member of any of those orgs has consented to the bot answering in this+ channel the consent applies to all of them. Per-mention data access+ remains gated by the existing email → ``OrganizationMembership`` check,+ so workspace-scope here only governs the channel-level question+ ("can the bot speak here at all?"), not which project's data is read.++ Reserved for future per-channel configuration (denials, routing+ overrides, etc.) without needing another model.+ """++ slack_workspace_id = models.CharField(max_length=64)+ slack_channel_id = models.CharField(max_length=64)+ approved_at = models.DateTimeField(null=True, blank=True)+ approved_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="approved_slack_channels",+ help_text="The PostHog user who clicked Approve. Carries the email and audit trail.",+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["slack_workspace_id", "slack_channel_id"],+ name="uniq_slack_channel",+ )+ ]++ @property+ def is_approved(self) -> bool:+ return self.approved_at is not Nonediff --git a/products/slack_app/backend/tests/test_channel_approval_interactivity.py b/products/slack_app/backend/tests/test_channel_approval_interactivity.pynew file mode 100644index 000000000000..a10d2b945af1--- /dev/null+++ b/products/slack_app/backend/tests/test_channel_approval_interactivity.py@@ -0,0 +1,281 @@+import json+import time+from typing import Any++from unittest.mock import patch++from django.core.cache import cache+from django.test import TestCase, override_settings+from django.utils import timezone++from rest_framework.test import APIClient++from posthog.models.integration import Integration+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.team.team import Team+from posthog.models.user import User++from products.slack_app.backend.api import (+ CHANNEL_APPROVAL_ACTION_APPROVE,+ CHANNEL_APPROVAL_ACTION_DENY,+ CHANNEL_APPROVAL_BLOCK_ID_PREFIX,+ CHANNEL_APPROVAL_CONTEXT_KIND,+ _picker_context_cache_key,+)+from products.slack_app.backend.models import SlackChannel+from products.slack_app.backend.tests.helpers import sign_slack_request+++@override_settings(DEBUG=True)+class _ChannelApprovalTestBase(TestCase):+ # DEBUG=True keeps the interactivity handler local-only — without it, an+ # un-decodable / foreign-workspace payload triggers a real cross-region+ # proxy attempt and Django returns 502 in tests.++ signing_secret = "posthog-code-test-secret"+ slack_team_id = "T12345"+ slack_channel_id = "C_EXT"+ response_url = "https://hooks.slack.example/response/abc"++ def setUp(self):+ cache.clear()+ self.client = APIClient()++ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.member_user = User.objects.create(email="[email protected]", distinct_id="user-member")+ OrganizationMembership.objects.create(user=self.member_user, organization=self.organization)+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id=self.slack_team_id,+ sensitive_config={"access_token": "xoxb-test"},+ )++ self.context_token = "approval-token-123"+ self.thread_ts = "1700000000.000001"+ cache.set(+ _picker_context_cache_key(self.context_token),+ {+ "kind": CHANNEL_APPROVAL_CONTEXT_KIND,+ "integration_id": self.integration.id,+ "slack_workspace_id": self.slack_team_id,+ "slack_channel_id": self.slack_channel_id,+ "thread_ts": self.thread_ts,+ "created_at": int(time.time()),+ },+ timeout=900,+ )++ def _post_interactivity(self, payload: dict[str, Any]) -> Any:+ payload = {"team": {"id": self.slack_team_id}, **payload}+ body_str = f"payload={json.dumps(payload)}"+ body = body_str.encode()+ signature, ts = sign_slack_request(body, self.signing_secret)+ return self.client.post(+ "/slack/interactivity-callback/",+ data=body_str,+ content_type="application/x-www-form-urlencoded",+ headers={"x-slack-signature": signature, "x-slack-request-timestamp": ts},+ )++ def _approve_payload(self, slack_user_id: str) -> dict[str, Any]:+ return self._click_payload(slack_user_id, CHANNEL_APPROVAL_ACTION_APPROVE)++ def _deny_payload(self, slack_user_id: str) -> dict[str, Any]:+ return self._click_payload(slack_user_id, CHANNEL_APPROVAL_ACTION_DENY)++ def _click_payload(self, slack_user_id: str, action_id: str) -> dict[str, Any]:+ return {+ "type": "block_actions",+ "user": {"id": slack_user_id},+ "response_url": self.response_url,+ "actions": [+ {+ "action_id": action_id,+ "block_id": f"{CHANNEL_APPROVAL_BLOCK_ID_PREFIX}_actions:{self.context_token}",+ "value": self.context_token,+ }+ ],+ }+++@patch("products.slack_app.backend.api.requests.post")+@patch("products.slack_app.backend.api.SlackIntegration")+class TestChannelApprovalInteractivity(_ChannelApprovalTestBase):+ # We mock the whole ``SlackIntegration`` class so that:+ # - ``SlackIntegration.slack_config()`` returns our test signing secret+ # (needed to pass the Slack request validation at the endpoint).+ # - ``SlackIntegration(integration).client.chat_postMessage`` is auto-mocked,+ # so the approval handler's public threaded reply is assertable without+ # hitting Slack.++ def _set_signing_secret(self, mock_slack_cls: Any) -> None:+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}++ def _stub_slack_user_email(self, email: str) -> Any:+ return patch(+ "products.slack_app.backend.api._get_slack_user_info",+ return_value={"user": {"profile": {"email": email}}},+ )++ def _assert_ephemeral_deleted(self, mock_post: Any) -> None:+ # Every click outcome cleans up the ephemeral prompt via ``response_url``.+ mock_post.assert_called_once()+ assert mock_post.call_args.args[0] == self.response_url+ assert mock_post.call_args.kwargs["json"] == {"delete_original": True}++ def _assert_outcome_posted(self, mock_slack_cls: Any, fragment: str) -> None:+ # The channel-visible record is a public threaded ``chat_postMessage``.+ mock_chat = mock_slack_cls.return_value.client.chat_postMessage+ mock_chat.assert_called_once()+ assert mock_chat.call_args.kwargs["channel"] == self.slack_channel_id+ assert mock_chat.call_args.kwargs["thread_ts"] == self.thread_ts+ assert fragment in mock_chat.call_args.kwargs["text"]++ def test_approve_by_org_member_creates_row(self, mock_slack_cls, mock_post):+ self._set_signing_secret(mock_slack_cls)++ with self._stub_slack_user_email(self.member_user.email):+ response = self._post_interactivity(self._approve_payload("U_MEMBER"))++ assert response.status_code == 200+ row = SlackChannel.objects.get(slack_workspace_id=self.slack_team_id, slack_channel_id=self.slack_channel_id)+ assert row.approved_at is not None+ assert row.approved_by_id == self.member_user.id++ self._assert_outcome_posted(mock_slack_cls, "enabled the PostHog Slack app")+ self._assert_ephemeral_deleted(mock_post)+ # Context cache cleared so a forwarded click can't replay this approval.+ assert cache.get(_picker_context_cache_key(self.context_token)) is None++ def test_approve_by_non_member_does_not_create_row(self, mock_slack_cls, mock_post):+ self._set_signing_secret(mock_slack_cls)++ with self._stub_slack_user_email("[email protected]"):+ response = self._post_interactivity(self._approve_payload("U_OUTSIDER"))++ assert response.status_code == 200+ assert not SlackChannel.objects.filter(+ slack_workspace_id=self.slack_team_id, slack_channel_id=self.slack_channel_id+ ).exists()++ self._assert_outcome_posted(mock_slack_cls, "Only members of")+ self._assert_ephemeral_deleted(mock_post)+ # Token preserved: a legit org member could still mention the bot to get+ # a fresh prompt; we don't burn the token just because someone unauthorised clicked.+ assert cache.get(_picker_context_cache_key(self.context_token)) is not None++ def test_approve_with_no_resolvable_email_does_not_create_row(self, mock_slack_cls, mock_post):+ self._set_signing_secret(mock_slack_cls)++ with patch(+ "products.slack_app.backend.api._get_slack_user_info",+ return_value={"user": {"profile": {}}},+ ):+ response = self._post_interactivity(self._approve_payload("U_NO_EMAIL"))++ assert response.status_code == 200+ assert not SlackChannel.objects.filter(+ slack_workspace_id=self.slack_team_id, slack_channel_id=self.slack_channel_id+ ).exists()+ self._assert_outcome_posted(mock_slack_cls, "Only members of")+ self._assert_ephemeral_deleted(mock_post)++ def test_approve_with_foreign_workspace_is_silently_dropped(self, mock_slack_cls, mock_post):+ # The interactivity dispatcher's "is this local?" gate already refuses payloads+ # whose ``team.id`` doesn't match the context's integration's workspace, so a+ # forwarded/replayed click never reaches the approval handler at all.+ self._set_signing_secret(mock_slack_cls)++ with self._stub_slack_user_email(self.member_user.email):+ payload = self._approve_payload("U_MEMBER")+ payload["team"] = {"id": "T_OTHER_WORKSPACE"}+ response = self._post_interactivity(payload)++ assert response.status_code == 200+ assert not SlackChannel.objects.filter(+ slack_workspace_id=self.slack_team_id, slack_channel_id=self.slack_channel_id+ ).exists()+ mock_post.assert_not_called()+ mock_slack_cls.return_value.client.chat_postMessage.assert_not_called()++ def test_approve_with_expired_context_is_silently_dropped(self, mock_slack_cls, mock_post):+ self._set_signing_secret(mock_slack_cls)+ cache.delete(_picker_context_cache_key(self.context_token))++ with self._stub_slack_user_email(self.member_user.email):+ response = self._post_interactivity(self._approve_payload("U_MEMBER"))++ assert response.status_code == 200+ assert not SlackChannel.objects.filter(+ slack_workspace_id=self.slack_team_id, slack_channel_id=self.slack_channel_id+ ).exists()+ # The outer dispatcher drops payloads it can't tie to a local integration; the+ # approval handler is never reached, so neither outcome nor cleanup happens.+ mock_post.assert_not_called()+ mock_slack_cls.return_value.client.chat_postMessage.assert_not_called()++ def test_concurrent_approve_clicks_yield_single_row(self, mock_slack_cls, mock_post):+ self._set_signing_secret(mock_slack_cls)++ # Simulate the second click landing while the row already exists.+ SlackChannel.objects.create(+ slack_workspace_id=self.slack_team_id,+ slack_channel_id=self.slack_channel_id,+ approved_at=timezone.now(),+ approved_by=self.member_user,+ )+ # Re-seed the context (the first click would have cleared it).+ cache.set(+ _picker_context_cache_key(self.context_token),+ {+ "kind": "channel_approval",+ "integration_id": self.integration.id,+ "slack_workspace_id": self.slack_team_id,+ "slack_channel_id": self.slack_channel_id,+ "thread_ts": self.thread_ts,+ "created_at": int(time.time()),+ },+ timeout=900,+ )++ with self._stub_slack_user_email(self.member_user.email):+ response = self._post_interactivity(self._approve_payload("U_MEMBER"))++ assert response.status_code == 200+ # ``update_or_create`` preserves uniqueness; only one row ever.+ assert (+ SlackChannel.objects.filter(+ slack_workspace_id=self.slack_team_id, slack_channel_id=self.slack_channel_id+ ).count()+ == 1+ )+ self._assert_outcome_posted(mock_slack_cls, "enabled the PostHog Slack app")+ self._assert_ephemeral_deleted(mock_post)++ def test_deny_by_org_member_posts_dismissal(self, mock_slack_cls, mock_post):+ self._set_signing_secret(mock_slack_cls)++ with self._stub_slack_user_email(self.member_user.email):+ response = self._post_interactivity(self._deny_payload("U_MEMBER"))++ assert response.status_code == 200+ assert not SlackChannel.objects.filter(+ slack_workspace_id=self.slack_team_id, slack_channel_id=self.slack_channel_id+ ).exists()+ assert cache.get(_picker_context_cache_key(self.context_token)) is None+ self._assert_outcome_posted(mock_slack_cls, "dismissed the PostHog Slack app")+ self._assert_ephemeral_deleted(mock_post)++ def test_deny_by_non_member_posts_rejection(self, mock_slack_cls, mock_post):+ self._set_signing_secret(mock_slack_cls)++ with self._stub_slack_user_email("[email protected]"):+ response = self._post_interactivity(self._deny_payload("U_OUTSIDER"))++ assert response.status_code == 200+ self._assert_outcome_posted(mock_slack_cls, "Only members of")+ self._assert_ephemeral_deleted(mock_post)+ # Token preserved for any future legit member click.+ assert cache.get(_picker_context_cache_key(self.context_token)) is not Nonediff --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 0747ad064fb0..462e901fc11e 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@@ -665,3 +665,150 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_sync_connect.assert_called_once()mock_asyncio_run.assert_called_once()mock_post_feedback.assert_not_called()+++class TestChannelApprovalGate(TestCase):+ """Gate covering the externally-shared-channel approval flow.++ The gate fires only when the Slack event envelope reports+ ``is_ext_shared_channel=True`` and no ``SlackChannel`` row with+ ``approved_at`` exists for ``(workspace, channel)``.+ """++ 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")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-1")+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ 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": "C_EXT",+ "user": "U123",+ "ts": "1234.5678",+ }++ @patch("products.slack_app.backend.api._post_channel_approval_prompt")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_external_channel_without_approval_posts_prompt(self, mock_sync_connect, mock_asyncio_run, mock_prompt):+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345", is_ext_shared_channel=True)++ assert result == ROUTE_HANDLED_LOCALLY+ mock_prompt.assert_called_once()+ mock_sync_connect.assert_not_called()+ mock_asyncio_run.assert_not_called()++ @patch("products.slack_app.backend.api._post_channel_approval_prompt")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_external_channel_with_approval_starts_workflow(self, mock_sync_connect, mock_asyncio_run, mock_prompt):+ from django.utils import timezone++ from products.slack_app.backend.models import SlackChannel++ SlackChannel.objects.create(+ slack_workspace_id="T12345",+ slack_channel_id="C_EXT",+ approved_at=timezone.now(),+ approved_by=self.user,+ )+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345", is_ext_shared_channel=True)++ assert result == ROUTE_HANDLED_LOCALLY+ mock_prompt.assert_not_called()+ mock_sync_connect.assert_called_once()+ mock_sync_connect.return_value.start_workflow.assert_called_once()+ mock_asyncio_run.assert_called_once()++ @patch("products.slack_app.backend.api._post_channel_approval_prompt")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_non_external_channel_starts_workflow_without_prompt(+ self, mock_sync_connect, mock_asyncio_run, mock_prompt+ ):+ # ``is_ext_shared_channel=False`` mirrors the envelope flag being absent /+ # false; the gate doesn't fire and the workflow starts normally.+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345", is_ext_shared_channel=False)++ assert result == ROUTE_HANDLED_LOCALLY+ mock_prompt.assert_not_called()+ mock_sync_connect.return_value.start_workflow.assert_called_once()+ mock_asyncio_run.assert_called_once()++ @patch("products.slack_app.backend.api._post_channel_approval_prompt")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_pending_row_without_approval_still_prompts(self, mock_sync_connect, mock_asyncio_run, mock_prompt):+ # A row with ``approved_at`` NULL has no semantic weight today, but must not bypass the+ # gate — only ``approved_at`` being set counts as approval.+ from products.slack_app.backend.models import SlackChannel++ SlackChannel.objects.create(+ slack_workspace_id="T12345",+ slack_channel_id="C_EXT",+ approved_at=None,+ )+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345", is_ext_shared_channel=True)++ assert result == ROUTE_HANDLED_LOCALLY+ mock_prompt.assert_called_once()+ mock_sync_connect.assert_not_called()+ mock_asyncio_run.assert_not_called()++ @patch("products.slack_app.backend.api.route_posthog_code_event_to_relevant_region")+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")+ def test_envelope_ext_shared_flag_is_forwarded_to_router(self, mock_config, mock_route):+ # End-to-end through the HTTP endpoint: the envelope's ``is_ext_shared_channel``+ # must flow into the routing function — otherwise the gate would silently never+ # fire on real Slack traffic.+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": "secret"}+ mock_route.return_value = "handled_locally"++ envelope = {+ "type": "event_callback",+ "team_id": "T12345",+ "is_ext_shared_channel": True,+ "event": {"type": "app_mention", "channel": "C_EXT", "user": "U123", "ts": "1.0"},+ }+ body = json.dumps(envelope).encode()+ signature, ts = sign_slack_request(body, "secret")+ APIClient().post(+ "/slack/event-callback/",+ data=body,+ content_type="application/json",+ HTTP_X_SLACK_SIGNATURE=signature,+ HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,+ )++ mock_route.assert_called_once()+ assert mock_route.call_args.kwargs["is_ext_shared_channel"] is True