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): show uploaded files and restyle the discussion card (#79689)

Luke Belton7897a31ecf93
diff --git a/posthog/api/test/test_comment_slack_sync.py b/posthog/api/test/test_comment_slack_sync.py
index 44da065b77c3..2e8ea18a9112 100644
--- a/posthog/api/test/test_comment_slack_sync.py
+++ b/posthog/api/test/test_comment_slack_sync.py
@@ -11,7 +11,7 @@ from rest_framework import status
from slack_sdk.errors import SlackApiError
from posthog.api.comments import _slack_thread_url
-from posthog.helpers.slack_thread_mirror import escape_slack_mrkdwn
+from posthog.helpers.slack_thread_mirror import _discussion_card_blocks, escape_slack_mrkdwn
from posthog.models.comment import Comment, CommentSlackThread
from posthog.models.integration import Integration
from posthog.tasks.comment_slack_sync import (
@@ -23,6 +23,25 @@ from posthog.tasks.comment_slack_sync import (
)
+class TestDiscussionCardBlocks(APIBaseTest):
+ def _card_text(self, body: str) -> str:
+ blocks = _discussion_card_blocks(
+ body_mrkdwn=body, author_name="Ann", item_url="https://app.posthog.com/i/1", item_label="Insight"
+ )
+ return blocks[0]["text"]["text"]
+
+ def test_every_line_of_a_multiline_body_stays_in_the_quote(self):
+ # mrkdwn's ">" quotes one line, so without a prefix per line the tail of a comment
+ # renders as the card's own text rather than as the quoted comment.
+ text = self._card_text("first line\nsecond line\n\nfourth line")
+
+ quoted = text.split("in PostHog:\n\n", 1)[1]
+ assert quoted == "> first line\n> second line\n> \n> fourth line"
+
+ def test_empty_body_still_renders_a_quoted_placeholder(self):
+ assert self._card_text("").endswith("> _(no text)_")
+
+
class TestSendCommentToSlack(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/comment/formatting.py b/posthog/comment/formatting.py
index 57f4dc25704b..876fe6492568 100644
--- a/posthog/comment/formatting.py
+++ b/posthog/comment/formatting.py
@@ -5,6 +5,7 @@ import html as html_mod
import unicodedata
from collections.abc import Iterable
from typing import Any
+from urllib.parse import urlparse
from uuid import UUID
JSON = dict[str, Any]
@@ -775,6 +776,79 @@ def slack_to_content_and_rich_content(
return _normalize_single_newlines_to_markdown(markdown_content), None
+# Hosts Slack serves file permalinks from. A file object is attacker-controlled (anyone in an
+# externally-shared channel can upload), so its permalink only becomes a link when it points at
+# one of these — otherwise it would be an arbitrary outbound link rendered inside a discussion.
+_SLACK_FILE_HOST_SUFFIXES = ("slack.com", "slack-edge.com", "slack-files.com")
+
+# One Slack message can carry many files; render a bounded number so an upload burst can't
+# flood the mirrored comment.
+MAX_SLACK_FILE_PLACEHOLDERS = 10
+
+
+def _slack_file_permalink(url: object) -> str | None:
+ """The permalink to hang a placeholder off, or None when it isn't safely linkable."""
+ if not isinstance(url, str) or not url:
+ return None
+ # Whitespace or a closing paren ends the markdown link early, spilling the rest of the URL
+ # out as text and leaving the link pointing somewhere other than it appears to.
+ if ")" in url or any(char.isspace() for char in url):
+ return None
+ # urlparse reads a backslash as an ordinary character, while the WHATWG parser browsers use
+ # reads it as a path separator. That splits the host checked below from the host a reader
+ # lands on, so reject the character instead of depending on who normalizes it first.
+ if "\\" in url:
+ return None
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ if parsed.scheme != "https":
+ return None
+ host = (parsed.hostname or "").lower()
+ if not any(host == suffix or host.endswith(f".{suffix}") for suffix in _SLACK_FILE_HOST_SUFFIXES):
+ return None
+ return url
+
+
+def _escape_slack_file_name(name: object) -> str:
+ """Escape a Slack-supplied filename for use as markdown link text."""
+ # Collapse every run of whitespace, not just the ends. A blank line inside the name would
+ # close the paragraph holding the link, dropping the rest of the name into one of its own
+ # where a bare URL renders as a live autolink.
+ text = " ".join(name.split()) if isinstance(name, str) else ""
+ if not text:
+ # A truncated file object still deserves a visible marker — "something was attached"
+ # is strictly better than the message appearing to be empty.
+ return "Attachment"
+ # Brackets would close the link text early. Escaping "[" also neutralizes a leading "!["
+ # for free, so a crafted filename can't turn the placeholder into an inline image.
+ return text.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]")
+
+
+def slack_files_to_placeholder_lines(files: list[Any] | None) -> list[str]:
+ """Render one markdown placeholder line per file attached to an inbound Slack message.
+
+ PostHog never downloads the file: the discussion shows a link back to it in Slack, which
+ needs nothing beyond the metadata Slack already puts in the message event. That keeps this
+ working on installs that never granted ``files:read``, where downloading is impossible.
+
+ ``files`` is the raw array off the Slack event, so every element is checked rather than
+ assumed to be a well-formed file object.
+ """
+ if not files:
+ return []
+
+ lines: list[str] = []
+ for file in files[:MAX_SLACK_FILE_PLACEHOLDERS]:
+ if not isinstance(file, dict):
+ continue
+ name = _escape_slack_file_name(file.get("name") or file.get("title"))
+ permalink = _slack_file_permalink(file.get("permalink"))
+ lines.append(f"📎 [{name}]({permalink})" if permalink else f"📎 {name}")
+ return lines
+
+
def _escape_html(text: str) -> str:
return html_mod.escape(text)
diff --git a/posthog/tasks/comment_slack_sync.py b/posthog/tasks/comment_slack_sync.py
index d9943acaf83c..66210d75dd7b 100644
--- a/posthog/tasks/comment_slack_sync.py
+++ b/posthog/tasks/comment_slack_sync.py
@@ -7,7 +7,7 @@ from celery import Task, shared_task
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
-from posthog.comment.formatting import slack_to_content_and_rich_content
+from posthog.comment.formatting import slack_files_to_placeholder_lines, slack_to_content_and_rich_content
from posthog.helpers.slack_identity import resolve_posthog_user_for_slack, resolve_slack_user
from posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_user
from posthog.models.comment import Comment, CommentSlackThread
@@ -188,6 +188,8 @@ def ingest_slack_discussion_reply(
text: str,
blocks: list | None,
message_ts: str,
+ # Defaulted so replies enqueued under the previous signature still run during a deploy.
+ files: list | None = None,
) -> None:
"""Save a Slack thread reply as a discussion comment (the inbound mirror half).
@@ -219,7 +221,8 @@ def ingest_slack_discussion_reply(
return
content, rich_content = slack_to_content_and_rich_content(text, blocks)
- if not content and not rich_content:
+ file_placeholders = slack_files_to_placeholder_lines(files)
+ if not content and not rich_content and not file_placeholders:
return
# Slack text has no markdown image syntax, so neutralizing it is lossless — and keeps an
# external participant's reply from making the discussion UI load remote images. The UI
@@ -228,6 +231,22 @@ def ingest_slack_discussion_reply(
content = content.replace("![", "!\\[")
_neutralize_rich_content_images(rich_content)
+ if file_placeholders:
+ # Appended after the image neutralization above, which would otherwise escape the very
+ # markdown links being added. Their filenames are escaped at construction instead.
+ placeholder_text = "\n\n".join(file_placeholders)
+ content = f"{content}\n\n{placeholder_text}" if content else placeholder_text
+ # The UI prefers rich_content whenever it's set, so placeholders added only to content
+ # would be invisible for any upload that arrived with a caption (and so with blocks).
+ if isinstance(rich_content, dict):
+ nodes = rich_content.get("content")
+ if not isinstance(nodes, list):
+ nodes = []
+ rich_content["content"] = nodes
+ nodes.extend(
+ {"type": "paragraph", "content": [{"type": "text", "text": line}]} for line in file_placeholders
+ )
+
try:
client = SlackIntegration(mirror.integration).client
client.timeout = 10
diff --git a/products/slack_app/backend/discussion_replies.py b/products/slack_app/backend/discussion_replies.py
index e043811cc79c..960f583d150e 100644
--- a/products/slack_app/backend/discussion_replies.py
+++ b/products/slack_app/backend/discussion_replies.py
@@ -70,6 +70,9 @@ def try_ingest_discussion_reply(
text=str(event.get("text") or ""),
blocks=event.get("blocks") if isinstance(event.get("blocks"), list) else None,
message_ts=str(event.get("ts") or ""),
+ # Only metadata is forwarded — the discussion links back to the file in Slack rather
+ # than downloading it, so this works even on installs without files:read.
+ files=event.get("files") if isinstance(event.get("files"), list) else None,
)
logger.info(
"slack_discussion_reply_enqueued",
diff --git a/products/slack_app/backend/tests/test_discussion_replies.py b/products/slack_app/backend/tests/test_discussion_replies.py
index d8b1979da647..f9b6717afb49 100644
--- a/products/slack_app/backend/tests/test_discussion_replies.py
+++ b/products/slack_app/backend/tests/test_discussion_replies.py
@@ -9,6 +9,8 @@ from products.slack_app.backend.discussion_replies import try_ingest_discussion_
# The Slack profile lookup happens inside the ingest Celery task (eager in tests).
RESOLVE = "posthog.tasks.comment_slack_sync.resolve_slack_user"
+PERMALINK = "https://acme.slack.com/files/U1/F1/screenshot.png"
+
class TestIngestDiscussionReply(APIBaseTest):
def setUp(self):
@@ -135,6 +137,120 @@ class TestIngestDiscussionReply(APIBaseTest):
assert handled is True
assert not Comment.objects.filter(source_comment=self.root).exists()
+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
+ def test_caption_less_upload_creates_comment_with_placeholder(self, _resolve):
+ # A file-only upload has no text and no blocks; without placeholders it produced no
+ # comment at all, so the PostHog side never learned anything had been sent.
+ event = self._event(
+ text="",
+ blocks=None,
+ subtype="file_share",
+ files=[{"id": "F1", "name": "screenshot.png", "mimetype": "image/png", "permalink": PERMALINK}],
+ )
+
+ assert self._ingest(event) is True
+
+ reply = Comment.objects.get(source_comment=self.root)
+ assert reply.content == f"📎 [screenshot.png]({PERMALINK})"
+
+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
+ def test_caption_and_placeholder_both_land_in_content_and_rich_content(self, _resolve):
+ # An upload with a caption arrives with blocks, so rich_content is set — and the UI
+ # prefers it, meaning a placeholder added only to content would never be seen.
+ blocks = [
+ {
+ "type": "rich_text",
+ "elements": [{"type": "rich_text_section", "elements": [{"type": "text", "text": "here's the bug"}]}],
+ }
+ ]
+ event = self._event(
+ text="here's the bug",
+ blocks=blocks,
+ subtype="file_share",
+ files=[{"id": "F1", "name": "screenshot.png", "permalink": PERMALINK}],
+ )
+
+ self._ingest(event)
+
+ reply = Comment.objects.get(source_comment=self.root)
+ assert reply.content is not None
+ assert "here's the bug" in reply.content
+ assert f"📎 [screenshot.png]({PERMALINK})" in reply.content
+ assert reply.rich_content is not None
+ rendered = [
+ node["content"][0]["text"] for node in reply.rich_content["content"] if node.get("type") == "paragraph"
+ ]
+ assert rendered == ["here's the bug", f"📎 [screenshot.png]({PERMALINK})"]
+
+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
+ def test_hostile_filename_cannot_break_out_of_placeholder_link(self, _resolve):
+ # Anyone in an externally-shared channel can name a file whatever they like.
+ event = self._event(
+ text="",
+ blocks=None,
+ files=[{"id": "F1", "name": "![x](https://attacker.example/pixel).png", "permalink": PERMALINK}],
+ )
+
+ self._ingest(event)
+
+ reply = Comment.objects.get(source_comment=self.root)
+ assert reply.content is not None
+ assert "![" not in reply.content
+ assert "attacker.example" not in reply.content.split("](")[-1]
+ assert reply.content.endswith(f"]({PERMALINK})")
+
+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
+ def test_non_slack_permalink_degrades_to_unlinked_placeholder(self, _resolve):
+ # A permalink is only trusted to the extent it points at Slack; the attachment still
+ # gets a marker, just not a link to somewhere arbitrary.
+ event = self._event(
+ text="",
+ blocks=None,
+ files=[{"id": "F1", "name": "notes.pdf", "permalink": "https://attacker.example/steal"}],
+ )
+
+ self._ingest(event)
+
+ reply = Comment.objects.get(source_comment=self.root)
+ assert reply.content == "📎 notes.pdf"
+
+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
+ def test_newline_in_filename_cannot_escape_the_link_text(self, _resolve):
+ # A blank line inside the name ends the paragraph holding the link, and the bare URL
+ # left behind renders as its own autolink.
+ event = self._event(
+ text="",
+ blocks=None,
+ files=[{"id": "F1", "name": "x\n\nhttps://attacker.example/phish", "permalink": PERMALINK}],
+ )
+
+ self._ingest(event)
+
+ reply = Comment.objects.get(source_comment=self.root)
+ assert reply.content == f"📎 [x https://attacker.example/phish]({PERMALINK})"
+
+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
+ def test_backslash_permalink_is_not_trusted(self, _resolve):
+ # urlparse reads the host as x.slack.com, but the WHATWG parser browsers use reads the
+ # backslash as a path separator and lands on evil.example.
+ event = self._event(
+ text="",
+ blocks=None,
+ files=[{"id": "F1", "name": "a.png", "permalink": "https://evil.example\\[email protected]/"}],
+ )
+
+ self._ingest(event)
+
+ reply = Comment.objects.get(source_comment=self.root)
+ assert reply.content == "📎 a.png"
+
+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
+ def test_file_without_name_still_gets_a_marker(self, _resolve):
+ self._ingest(self._event(text="", blocks=None, files=[{"id": "F1"}]))
+
+ reply = Comment.objects.get(source_comment=self.root)
+ assert reply.content == "📎 Attachment"
+
@patch("posthog.tasks.comment_slack_sync.posthoganalytics.feature_enabled", return_value=False)
@patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})
def test_kill_switch_stops_ingestion(self, _resolve, _flag):