: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(signals): render signal description markdown in Slack threads (#65163)
Michael Matloka61fe3092be4c
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex 506e2fe253f4..f99d3cb418fe 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -11,11 +11,13 @@ All sends are best-effort.from __future__ import annotations+import reimport jsonimport loggingfrom django.conf import settings+from markdown_to_mrkdwn import SlackMarkdownConverterfrom slack_sdk.errors import SlackApiErrorfrom posthog.models import User@@ -45,6 +47,8 @@ _ACTIONABLE_VALUES = frozenset(logger = logging.getLogger(__name__)+_SLACK_MRKDWN_CONVERTER = SlackMarkdownConverter()+_SUMMARY_EXCERPT_MAX_LEN = 600_SLACK_HEADER_MAX_LEN = 150# Bound message size / avoid pinging a crowd.@@ -278,9 +282,43 @@ def lookup_slack_user_id_by_email(slack: SlackIntegration, email: str) -> str |def _escape_mrkdwn(text: str) -> str:+ """Neutralize Slack control syntax (`&`, `<`, `>`) so untrusted text can't inject mentions/links."""return text.replace("&", "&").replace("<", "<").replace(">", ">")+# Matches a converter-emitted Slack angle token: `<dest>` or `<dest|label>`. Input `<`/`>`+# are escaped before conversion, so any literal angle bracket here was produced by the converter.+_SLACK_ANGLE_TOKEN_RE = re.compile(r"<([^<>|]*)(\|[^<>]*)?>")+++def _defang_unsafe_slack_tokens(text: str) -> str:+ """Render any non-URL `<dest|label>` token the converter emitted as inert literal text.++ `markdown_to_mrkdwn` turns `[text](dest)` into Slack's `<dest|label>` form without checking+ the scheme, so untrusted signal content could smuggle a broadcast or ping via `[x](!channel)`+ or `[x](@U123)`. Tokens whose destination isn't a plain http(s) URL get their angle brackets+ escaped so Slack shows the text instead of firing a mention.+ """++ def _replace(match: re.Match[str]) -> str:+ if _is_safe_http_url(match.group(1)):+ return match.group(0)+ return match.group(0).replace("<", "<").replace(">", ">")++ return _SLACK_ANGLE_TOKEN_RE.sub(_replace, text)+++def _markdown_to_slack_mrkdwn(text: str) -> str:+ """Convert signal markdown to Slack mrkdwn, then neutralize any injected mentions.++ Escaping runs first so raw `<@U…>`/`<!channel>` in untrusted content can't reach Slack;+ after conversion, `_defang_unsafe_slack_tokens` strips any mention/broadcast the converter+ synthesized from a `[text](!channel)`-style link. Kept local rather than shared with the+ other `SlackMarkdownConverter` call sites: they render trusted LLM output, signals does not.+ """+ return _defang_unsafe_slack_tokens(_SLACK_MRKDWN_CONVERTER.convert(_escape_mrkdwn(text)))++def _resolve_reviewer_mentions(slack: SlackIntegration, reviewer_users: list[User]) -> list[str]:# `<@U…>` mention when the reviewer's email resolves in this workspace, else escaped name.mentions: list[str] = []@@ -506,9 +544,14 @@ def _build_signal_thread_blocks(signal: dict) -> tuple[list[dict], str]:content = (signal.get("content") or "").strip()if content:- if len(content) > _SIGNAL_CONTENT_MAX_LEN:- content = content[: _SIGNAL_CONTENT_MAX_LEN - 1].rstrip() + "…"- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": _escape_mrkdwn(content)}})+ # Render markdown to mrkdwn first, then truncate the rendered output: truncating raw+ # markdown could slice a link/emphasis token mid-syntax, and conversion can lengthen+ # text past Slack's section limit. Truncating post-defang output stays safe — a+ # trailing cut can't synthesize a live mention (no closing `>` can appear).+ rendered = _markdown_to_slack_mrkdwn(content)+ if len(rendered) > _SIGNAL_CONTENT_MAX_LEN:+ rendered = rendered[: _SIGNAL_CONTENT_MAX_LEN - 1].rstrip() + "…"+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered}})detail_parts = _signal_detail_parts(source_product, extra)if detail_parts:diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.pyindex aae7ebf3c851..2acaf0ec7618 100644--- a/products/signals/backend/test/test_slack_inbox_notifications.py+++ b/products/signals/backend/test/test_slack_inbox_notifications.py@@ -973,6 +973,68 @@ def test_build_signal_thread_blocks_rejects_unsafe_detail_url() -> None:assert "javascript:" not in detail+def test_build_signal_thread_blocks_renders_markdown_content_as_mrkdwn() -> None:+ # Markdown in the description (headings, bullets, emphasis, links) renders as Slack mrkdwn+ # rather than showing literal `##`, `**`, and `[text](url)` noise.+ signal = {+ "source_product": "github",+ "source_type": "issue",+ "weight": 1.0,+ "content": "## Bug\n**Export** is broken, see [issue](https://example.com/i?a=1&b=2)\n- step one\n- step two",+ "extra": {},+ }+ blocks, _ = _build_signal_thread_blocks(signal)+ content_text = blocks[1]["text"]["text"]+ assert "*Bug*" in content_text+ assert "*Export*" in content_text+ assert "<https://example.com/i?a=1&b=2|issue>" in content_text+ assert "• step one" in content_text+ # No raw markdown syntax should survive the conversion.+ assert "##" not in content_text+ assert "**" not in content_text+ assert "[issue]" not in content_text+++def test_build_signal_thread_blocks_neutralizes_injection_in_markdown_content() -> None:+ # Even when converting markdown, raw mention/link syntax in untrusted content stays inert.+ signal = {+ "source_product": "github",+ "source_type": "issue",+ "weight": 1.0,+ "content": "**Heads up** <!here> and <@U999> and a fake <https://evil.com|click here>",+ "extra": {},+ }+ blocks, _ = _build_signal_thread_blocks(signal)+ content_text = blocks[1]["text"]["text"]+ assert "*Heads up*" in content_text # markdown still rendered+ assert "<!here>" not in content_text+ assert "<@U999>" not in content_text+ assert "<https://evil.com|click here>" not in content_text+ assert "<!here>" in content_text+ assert "<@U999>" in content_text+++def test_build_signal_thread_blocks_defangs_mention_injection_via_markdown_links() -> None:+ # `markdown_to_mrkdwn` turns `[text](dest)` into Slack's `<dest|label>` form; an untrusted+ # description could smuggle a broadcast/ping by pointing the link at `!channel` / `@U123`.+ signal = {+ "source_product": "github",+ "source_type": "issue",+ "weight": 1.0,+ "content": "[ping everyone](!channel) and [dm me](@U12345678) but [real](https://example.com) is fine",+ "extra": {},+ }+ blocks, _ = _build_signal_thread_blocks(signal)+ content_text = blocks[1]["text"]["text"]+ # No live mention/broadcast token survives.+ assert "<!channel|" not in content_text+ assert "<@U12345678|" not in content_text+ assert "<!channel|ping everyone>" in content_text+ assert "<@U12345678|dm me>" in content_text+ # A genuine http(s) link is still rendered as a clickable Slack link.+ assert "<https://example.com|real>" in content_text++@pytest.mark.django_dbdef test_dispatch_posts_signal_evidence_into_thread(org_and_team):org, team = org_and_team