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 task links on PostHog Code access (#60659)

Vojta Bartošcb17233abd71
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index 2095ab3a11db..6653c3b5af46 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -277,70 +277,74 @@ class SlackThreadHandler:
except Exception as e:
logger.exception("slack_progress_update_failed", error=str(e))
- def post_pr_opened_sandbox_cleaned(self, pr_url: str, task_url: str) -> None:
+ def post_pr_opened_sandbox_cleaned(self, pr_url: str, task_url: str | None) -> None:
"""Post final PR message after sandbox cleanup."""
header = "*Pull request opened* :rocket:"
- blocks: list[dict[str, Any]] = [
- {"type": "section", "text": {"type": "mrkdwn", "text": header}},
+ buttons: list[dict[str, Any]] = [
{
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "View PR",
- "emoji": True,
- },
- "url": pr_url,
- },
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "Open in PostHog",
- "emoji": True,
- },
- "url": task_url,
- },
- ],
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "View PR",
+ "emoji": True,
+ },
+ "url": pr_url,
},
]
+ if task_url:
+ buttons.append(
+ {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "Open in PostHog Code",
+ "emoji": True,
+ },
+ "url": task_url,
+ }
+ )
+
+ blocks: list[dict[str, Any]] = [
+ {"type": "section", "text": {"type": "mrkdwn", "text": header}},
+ {"type": "actions", "elements": buttons},
+ ]
self._delete_progress_and_post(header, blocks)
- def post_pr_opened(self, pr_url: str, task_url: str) -> None:
+ def post_pr_opened(self, pr_url: str, task_url: str | None) -> None:
"""Post PR opened message with action buttons."""
mention_prefix = f"<@{self.context.mentioning_slack_user_id}> " if self.context.mentioning_slack_user_id else ""
header = f"{mention_prefix}Pull request opened."
- blocks: list[dict[str, Any]] = [
- {"type": "section", "text": {"type": "mrkdwn", "text": header}},
+ buttons: list[dict[str, Any]] = [
{
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "View PR",
- "emoji": True,
- },
- "url": pr_url,
- },
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "Open in PostHog",
- "emoji": True,
- },
- "url": task_url,
- },
- ],
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "View PR",
+ "emoji": True,
+ },
+ "url": pr_url,
},
]
+ if task_url:
+ buttons.append(
+ {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "Open in PostHog Code",
+ "emoji": True,
+ },
+ "url": task_url,
+ }
+ )
+
+ blocks: list[dict[str, Any]] = [
+ {"type": "section", "text": {"type": "mrkdwn", "text": header}},
+ {"type": "actions", "elements": buttons},
+ ]
try:
self._get_client().chat_postMessage(
@@ -363,7 +367,7 @@ class SlackThreadHandler:
except Exception as e:
logger.warning("slack_post_thread_message_failed", error=str(e))
- def post_completion(self, pr_url: str | None, task_url: str) -> None:
+ def post_completion(self, pr_url: str | None, task_url: str | None) -> None:
"""Post completion message with PR link."""
if pr_url:
header = "*Pull Request Created* :rocket:"
@@ -383,23 +387,25 @@ class SlackThreadHandler:
"url": pr_url,
}
)
- buttons.append(
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "Open in PostHog",
- "emoji": True,
- },
- "url": task_url,
- }
- )
+ if task_url:
+ buttons.append(
+ {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "Open in PostHog Code",
+ "emoji": True,
+ },
+ "url": task_url,
+ }
+ )
- blocks.append({"type": "actions", "elements": buttons})
+ if buttons:
+ blocks.append({"type": "actions", "elements": buttons})
self._delete_progress_and_post(header, blocks)
- def post_error(self, error: str, task_url: str) -> None:
+ def post_error(self, error: str, task_url: str | None) -> None:
"""Post error message with link to PostHog for details."""
header = "*Task Failed* :x:"
error = _format_task_error(error)
@@ -408,45 +414,51 @@ class SlackThreadHandler:
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": header}},
{"type": "section", "text": {"type": "mrkdwn", "text": truncated_error}},
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "See details in PostHog",
- "emoji": True,
- },
- "url": task_url,
- },
- ],
- },
]
+ if task_url:
+ blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "See details in PostHog Code",
+ "emoji": True,
+ },
+ "url": task_url,
+ },
+ ],
+ }
+ )
self._delete_progress_and_post(f"{header}\n{truncated_error}", blocks)
- def post_cancelled(self, task_url: str) -> None:
+ def post_cancelled(self, task_url: str | None) -> None:
"""Post cancelled message with link to PostHog for details."""
header = "*Sandbox stopped* :hedgehog:"
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": header}},
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "Open in PostHog",
- "emoji": True,
- },
- "url": task_url,
- },
- ],
- },
]
+ if task_url:
+ blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "Open in PostHog Code",
+ "emoji": True,
+ },
+ "url": task_url,
+ },
+ ],
+ }
+ )
self._delete_progress_and_post(header, blocks)
diff --git a/products/slack_app/backend/tests/test_post_slack_update.py b/products/slack_app/backend/tests/test_post_slack_update.py
index 06a302a2131d..c96dfdcffc94 100644
--- a/products/slack_app/backend/tests/test_post_slack_update.py
+++ b/products/slack_app/backend/tests/test_post_slack_update.py
@@ -22,6 +22,14 @@ class TestPostSlackUpdate(TestCase):
"thread_ts": "1111.0000",
"user_message_ts": "2222.0000",
}
+ # Default the access gate to allow so existing call/URL assertions remain meaningful;
+ # tests that exercise the deny / error paths re-patch it locally.
+ self._access_patcher = patch(
+ "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
+ return_value=True,
+ )
+ self._access_patcher.start()
+ self.addCleanup(self._access_patcher.stop)
def _make_mock_run(self, status: str, **kwargs):
mock_run = MagicMock()
@@ -336,6 +344,154 @@ class TestPostSlackUpdate(TestCase):
"http://localhost:8000/project/1/tasks/10?runId=run-1",
)
+ @patch.object(SlackThreadHandler, "post_completion")
+ @patch.object(SlackThreadHandler, "post_or_update_progress")
+ @patch.object(SlackThreadHandler, "post_error")
+ @patch.object(SlackThreadHandler, "post_cancelled")
+ @patch.object(SlackThreadHandler, "post_pr_opened_sandbox_cleaned")
+ @patch.object(SlackThreadHandler, "post_pr_opened")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch.object(SlackThreadHandler, "__init__", return_value=None)
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_user_without_posthog_code_access_omits_task_url(
+ self,
+ mock_task_run_class,
+ _mock_handler_init,
+ _mock_update_reaction,
+ mock_post_pr_opened,
+ mock_post_pr_opened_sandbox_cleaned,
+ mock_post_cancelled,
+ mock_post_error,
+ mock_post_progress,
+ mock_post_completion,
+ ):
+ # When the task creator is not a PostHog Code user, every handler call
+ # receives ``task_url=None`` (and the progress handler receives
+ # ``logs_deeplink=None``) so the deep-link / web buttons are skipped.
+ self._access_patcher.stop()
+ deny_patcher = patch(
+ "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
+ return_value=False,
+ )
+ deny_patcher.start()
+ self.addCleanup(deny_patcher.stop)
+
+ scenarios: list[tuple[MagicMock, MagicMock]] = []
+
+ completed = self._make_mock_run(
+ mock_task_run_class.Status.COMPLETED, output={"pr_url": "https://github.com/org/repo/pull/1"}
+ )
+ scenarios.append((completed, mock_post_completion))
+
+ failed = self._make_mock_run(mock_task_run_class.Status.FAILED, error_message="boom")
+ scenarios.append((failed, mock_post_error))
+
+ cancelled = self._make_mock_run(mock_task_run_class.Status.CANCELLED)
+ scenarios.append((cancelled, mock_post_cancelled))
+
+ in_progress = self._make_mock_run(mock_task_run_class.Status.IN_PROGRESS, stage="Building")
+ scenarios.append((in_progress, mock_post_progress))
+
+ in_progress_with_pr = self._make_mock_run(
+ mock_task_run_class.Status.IN_PROGRESS,
+ stage="Opening PR",
+ output={"pr_url": "https://github.com/org/repo/pull/2"},
+ state={},
+ )
+ scenarios.append((in_progress_with_pr, mock_post_pr_opened))
+
+ cleaned_with_pr = self._make_mock_run(
+ mock_task_run_class.Status.COMPLETED,
+ output={"pr_url": "https://github.com/org/repo/pull/3"},
+ state={},
+ )
+
+ for run, handler_mock in scenarios:
+ handler_mock.reset_mock()
+ mock_task_run_class.objects.select_related.return_value.get.return_value = run
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+ handler_mock.assert_called_once()
+ # ``task_url`` is always the trailing positional argument on every
+ # handler signature; passing ``None`` is the contract for "no access".
+ assert handler_mock.call_args.args[-1] is None
+
+ mock_post_pr_opened_sandbox_cleaned.reset_mock()
+ mock_task_run_class.objects.select_related.return_value.get.return_value = cleaned_with_pr
+ post_slack_update(
+ PostSlackUpdateInput(
+ run_id="run-1",
+ slack_thread_context=self.slack_thread_context,
+ sandbox_cleaned=True,
+ )
+ )
+ mock_post_pr_opened_sandbox_cleaned.assert_called_once()
+ assert mock_post_pr_opened_sandbox_cleaned.call_args.args[-1] is None
+
+ @patch.object(SlackThreadHandler, "post_completion")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch.object(SlackThreadHandler, "__init__", return_value=None)
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_missing_created_by_omits_task_url(
+ self,
+ mock_task_run_class,
+ _mock_handler_init,
+ _mock_update_reaction,
+ mock_post_completion,
+ ):
+ # ``has_tasks_access`` is never reached when the run has no creator —
+ # a None viewer short-circuits to "no access" without consulting the
+ # flag service.
+ self._access_patcher.stop()
+
+ sentinel = MagicMock(name="should_not_be_called")
+ sentinel_patcher = patch(
+ "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
+ sentinel,
+ )
+ sentinel_patcher.start()
+ self.addCleanup(sentinel_patcher.stop)
+
+ run = self._make_mock_run(
+ mock_task_run_class.Status.COMPLETED, output={"pr_url": "https://github.com/org/repo/pull/1"}
+ )
+ run.task.created_by = None
+ mock_task_run_class.objects.select_related.return_value.get.return_value = run
+
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+
+ sentinel.assert_not_called()
+ mock_post_completion.assert_called_once_with("https://github.com/org/repo/pull/1", None)
+
+ @patch.object(SlackThreadHandler, "post_completion")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch.object(SlackThreadHandler, "__init__", return_value=None)
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_access_check_exception_fails_closed(
+ self,
+ mock_task_run_class,
+ _mock_handler_init,
+ _mock_update_reaction,
+ mock_post_completion,
+ ):
+ # A flag-service blip must not surface the link to a user we can't
+ # confirm has access — and must not break the surrounding update.
+ self._access_patcher.stop()
+ boom_patcher = patch(
+ "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
+ side_effect=RuntimeError("flag service down"),
+ )
+ boom_patcher.start()
+ self.addCleanup(boom_patcher.stop)
+
+ run = self._make_mock_run(
+ mock_task_run_class.Status.COMPLETED, output={"pr_url": "https://github.com/org/repo/pull/1"}
+ )
+ mock_task_run_class.objects.select_related.return_value.get.return_value = run
+
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+
+ mock_post_completion.assert_called_once_with("https://github.com/org/repo/pull/1", None)
+
@patch.object(SlackThreadHandler, "post_pr_opened_sandbox_cleaned")
@patch.object(SlackThreadHandler, "update_reaction")
@patch.object(SlackThreadHandler, "__init__", return_value=None)
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index c1f19840f020..cc5e8d9d3d06 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -154,7 +154,7 @@ class TestSlackThreadHandler(TestCase):
assert "Pull request opened" in kwargs["text"]
actions = kwargs["blocks"][1]["elements"]
assert actions[0]["text"]["text"] == "View PR"
- assert actions[1]["text"]["text"] == "Open in PostHog"
+ assert actions[1]["text"]["text"] == "Open in PostHog Code"
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
@patch.object(SlackThreadHandler, "_get_client")
@@ -178,3 +178,123 @@ class TestSlackThreadHandler(TestCase):
kwargs = mock_client.chat_postMessage.call_args.kwargs
assert kwargs["text"] == f"*Task Failed* :x:\n{UPSTREAM_PROVIDER_FAILURE_MESSAGE}"
assert kwargs["blocks"][1]["text"]["text"] == UPSTREAM_PROVIDER_FAILURE_MESSAGE
+
+
+def _action_blocks(call_kwargs: dict) -> list[dict]:
+ return [block for block in call_kwargs["blocks"] if block.get("type") == "actions"]
+
+
+def _button_texts(action_block: dict) -> list[str]:
+ return [element["text"]["text"] for element in action_block["elements"]]
+
+
+class TestSlackThreadHandlerWithoutTaskUrl(TestCase):
+ """A ``task_url=None`` payload signals the recipient does not have PostHog Code access.
+
+ Each renderer must drop the PostHog button (or the entire actions block when
+ that was the only button) so the message stays useful without dangling at a
+ URL the recipient can't reach.
+ """
+
+ def _make_context(self) -> SlackThreadContext:
+ return SlackThreadContext(
+ integration_id=1,
+ channel="C001",
+ thread_ts="1234.5678",
+ user_message_ts="1234.5678",
+ mentioning_slack_user_id="U123",
+ )
+
+ @patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_post_or_update_progress_without_task_url_drops_button(self, mock_get_client, _mock_find_progress):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(self._make_context())
+
+ handler.post_or_update_progress("Building", task_url=None)
+
+ mock_client.chat_postMessage.assert_called_once()
+ assert _action_blocks(mock_client.chat_postMessage.call_args.kwargs) == []
+
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_post_pr_opened_sandbox_cleaned_without_task_url_keeps_pr_button(
+ self, mock_get_client, _mock_delete_progress
+ ):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(self._make_context())
+
+ handler.post_pr_opened_sandbox_cleaned("https://github.com/org/repo/pull/1", task_url=None)
+
+ mock_client.chat_postMessage.assert_called_once()
+ actions = _action_blocks(mock_client.chat_postMessage.call_args.kwargs)
+ assert len(actions) == 1
+ assert _button_texts(actions[0]) == ["View PR"]
+
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_post_pr_opened_without_task_url_keeps_pr_button(self, mock_get_client):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(self._make_context())
+
+ handler.post_pr_opened("https://github.com/org/repo/pull/1", task_url=None)
+
+ mock_client.chat_postMessage.assert_called_once()
+ actions = _action_blocks(mock_client.chat_postMessage.call_args.kwargs)
+ assert len(actions) == 1
+ assert _button_texts(actions[0]) == ["View PR"]
+
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_post_completion_without_task_url_keeps_pr_button(self, mock_get_client, _mock_delete_progress):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(self._make_context())
+
+ handler.post_completion("https://github.com/org/repo/pull/1", task_url=None)
+
+ mock_client.chat_postMessage.assert_called_once()
+ actions = _action_blocks(mock_client.chat_postMessage.call_args.kwargs)
+ assert len(actions) == 1
+ assert _button_texts(actions[0]) == ["View PR"]
+
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_post_completion_without_pr_or_task_url_drops_actions(self, mock_get_client, _mock_delete_progress):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(self._make_context())
+
+ handler.post_completion(pr_url=None, task_url=None)
+
+ mock_client.chat_postMessage.assert_called_once()
+ assert _action_blocks(mock_client.chat_postMessage.call_args.kwargs) == []
+
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_post_error_without_task_url_drops_actions(self, mock_get_client, _mock_delete_progress):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(self._make_context())
+
+ handler.post_error("boom", task_url=None)
+
+ mock_client.chat_postMessage.assert_called_once()
+ kwargs = mock_client.chat_postMessage.call_args.kwargs
+ assert _action_blocks(kwargs) == []
+ # The error body itself must still surface — only the action block is gated.
+ assert kwargs["blocks"][1]["text"]["text"] == "boom"
+
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_post_cancelled_without_task_url_drops_actions(self, mock_get_client, _mock_delete_progress):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(self._make_context())
+
+ handler.post_cancelled(task_url=None)
+
+ mock_client.chat_postMessage.assert_called_once()
+ assert _action_blocks(mock_client.chat_postMessage.call_args.kwargs) == []
diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
index 1c39b5979bb6..0496437eecfd 100644
--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
@@ -5,8 +5,11 @@ from django.conf import settings
from temporalio import activity
+from posthog.models.user import User
from posthog.temporal.common.logger import get_logger
+from products.tasks.backend.access import has_tasks_access
+
logger = get_logger(__name__)
@@ -17,6 +20,23 @@ class PostSlackUpdateInput:
sandbox_cleaned: bool = False
+def _viewer_has_posthog_code_access(viewer: User | None) -> bool:
+ """Fail closed: missing creator or any flag-service error suppresses the link.
+
+ The PostHog Code app is rolled out via cohort + invite redemption; surfacing
+ deep links to users who can't open them sends them into an install flow we
+ don't want to scale right now. Errors from the flag service therefore default
+ to "no access" rather than "show the link anyway".
+ """
+ if viewer is None:
+ return False
+ try:
+ return has_tasks_access(viewer)
+ except Exception:
+ logger.exception("post_slack_update_access_check_failed", user_id=getattr(viewer, "id", None))
+ return False
+
+
@activity.defn
def post_slack_update(input: PostSlackUpdateInput) -> None:
"""Post Slack update based on current task run state. Idempotent."""
@@ -24,7 +44,7 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:
from products.tasks.backend.models import TaskRun
try:
- task_run = TaskRun.objects.select_related("task").get(id=input.run_id)
+ task_run = TaskRun.objects.select_related("task", "task__created_by").get(id=input.run_id)
except TaskRun.DoesNotExist:
logger.warning("post_slack_update_task_run_not_found", run_id=input.run_id)
return
@@ -32,8 +52,15 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:
try:
context = SlackThreadContext.from_dict(input.slack_thread_context)
handler = SlackThreadHandler(context)
- task_url = f"{settings.SITE_URL}/project/{task_run.task.team_id}/tasks/{task_run.task_id}?runId={task_run.id}"
- logs_deeplink = f"posthog-code://task/{task_run.task_id}/run/{task_run.id}"
+ creator_has_access = _viewer_has_posthog_code_access(task_run.task.created_by)
+ task_url: str | None = (
+ f"{settings.SITE_URL}/project/{task_run.task.team_id}/tasks/{task_run.task_id}?runId={task_run.id}"
+ if creator_has_access
+ else None
+ )
+ logs_deeplink: str | None = (
+ f"posthog-code://task/{task_run.task_id}/run/{task_run.id}" if creator_has_access else None
+ )
pr_url = (task_run.output or {}).get("pr_url")
if input.sandbox_cleaned:
@@ -94,7 +121,7 @@ def _get_stage_from_status(status: str, stage: str | None = None) -> str:
return status_map.get(status, "In progress...")
-def _post_pr_opened_notification_once(task_run, handler, pr_url: str, task_url: str) -> None:
+def _post_pr_opened_notification_once(task_run, handler, pr_url: str, task_url: str | None) -> None:
if _is_pr_opened_notified(task_run, pr_url):
return