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.

fix(signals): gate slack notification section blocks (#129968)

Georgiy Tarasovb8b6cf16ffca
diff --git a/products/signals/backend/report_content_gates.py b/products/signals/backend/report_content_gates.py
index 59a0696030a7..7a04c53f6569 100644
--- a/products/signals/backend/report_content_gates.py
+++ b/products/signals/backend/report_content_gates.py
@@ -24,6 +24,7 @@ REPORT_MONITORING_FLAG = "signals-report-monitoring"
FIRST_REPORT_EMAIL_FLAG = "signals-first-report-email"
RESEARCH_REVIEWER_SELECTION_FLAG = "signals-research-reviewer-selection"
INBOX_CACHED_FILTERS_FLAG = "signals-inbox-cached-filters"
+INBOX_SLACK_SECTION_BLOCKS_FLAG = "signals-inbox-slack-section-blocks"
def _organization_flag_enabled(
@@ -102,3 +103,9 @@ def organization_inbox_cached_filters_enabled(organization_id: UUID) -> bool:
return _organization_flag_enabled(
INBOX_CACHED_FILTERS_FLAG, organization_id, enable_in_debug=False, only_evaluate_locally=True
)
+
+
+def organization_inbox_slack_section_blocks_enabled(organization_id: UUID) -> bool:
+ return _organization_flag_enabled(
+ INBOX_SLACK_SECTION_BLOCKS_FLAG, organization_id, enable_in_debug=False, only_evaluate_locally=True
+ )
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 397fc397d138..b748e074a628 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -19,6 +19,7 @@ from collections.abc import Collection, Iterable
from django.conf import settings
+from markdown_to_mrkdwn import SlackMarkdownConverter
from rest_framework import serializers
from slack_sdk.errors import SlackApiError
@@ -44,6 +45,7 @@ from products.signals.backend.models import (
SignalTeamConfig,
SignalUserAutonomyConfig,
)
+from products.signals.backend.report_content_gates import organization_inbox_slack_section_blocks_enabled
from products.signals.backend.report_generation.research import ActionabilityChoice
from products.signals.backend.report_generation.resolve_reviewers import (
enrich_reviewer_dicts_with_org_members,
@@ -56,8 +58,10 @@ from products.signals.backend.report_urls import ReportLinkSource, build_report_
from products.signals.backend.scout_authorship import report_is_hidden_from_inbox
from products.signals.backend.slack_formatting import (
first_sentence as _first_sentence,
+ is_safe_slack_http_url,
prepare_slack_markdown as _prepare_markdown,
strip_chart_references as _strip_chart_references,
+ truncate_slack_text,
)
from products.signals.backend.slack_notification_targets import is_slack_member_target, lookup_slack_user_id_by_email
from products.signals.backend.slack_report_threads import record_report_slack_thread
@@ -340,13 +344,25 @@ def _display_title(title: str | None) -> str:
return description or title
-def _build_message_blocks(report: SignalReport, *, reviewer_mentions: list[str]) -> tuple[list[dict], str]:
+def _section_body(markdown: str) -> str:
+ def safe_token(match: re.Match[str]) -> str:
+ destination = match.group(1).partition("|")[0]
+ return match.group(0) if is_safe_slack_http_url(destination) else _escape_mrkdwn(match.group(0))
+
+ # Conversion creates Slack tokens, so only HTTP links may survive in the untrusted body.
+ converted = SlackMarkdownConverter().convert(markdown)
+ return truncate_slack_text(re.sub(r"<([^<>]*)>", safe_token, converted), 3000)
+
+
+def _build_message_blocks(
+ report: SignalReport, *, reviewer_mentions: list[str], use_section_blocks: bool = False
+) -> tuple[list[dict], str]:
title_line = _display_title(report.title)
header_text = (
title_line if len(title_line) <= _SLACK_HEADER_MAX_LEN else title_line[: _SLACK_HEADER_MAX_LEN - 3] + "..."
)
- # The body is escaped once as a whole below, so the LLM-derived parts assembled here stay raw.
+ # The body is prepared as a whole below, so the LLM-derived parts assembled here stay raw.
# The `**` this adds is the one piece of Markdown the message means, and escaping leaves it be.
body_parts: list[str] = []
# Strip before excerpting so truncation can't slice a chart link mid-syntax.
@@ -360,12 +376,21 @@ def _build_message_blocks(report: SignalReport, *, reviewer_mentions: list[str])
if not body_parts:
body_parts.append(f"**{title_line}**")
+ body = _prepare_markdown("\n\n".join(body_parts))
+ body_block = (
+ {
+ "type": "section",
+ "text": {"type": "mrkdwn", "text": _section_body(body), "verbatim": True},
+ }
+ if use_section_blocks
+ else _markdown_block(body)
+ )
blocks: list[dict] = [
{"type": "header", "text": {"type": "plain_text", "text": header_text}},
- _markdown_block(_prepare_markdown("\n\n".join(body_parts))),
+ body_block,
]
- # Mentions sit in mrkdwn, not plain_text, so the `<@U…>` token still pings the owner.
+ # Plain-text blocks would show the raw mention token instead of resolving the user.
if reviewer_mentions:
owner_label = "Suggested owner" if len(reviewer_mentions) == 1 else "Suggested owners"
blocks.append(
@@ -533,7 +558,11 @@ def _deliver_route_notification(
return False
# The only reviewer a direct message could mention is the person already reading it.
mentions = [] if route.is_direct_message else _resolve_reviewer_mentions(slack, route.users)
- blocks, text = _build_message_blocks(report, reviewer_mentions=mentions)
+ blocks, text = _build_message_blocks(
+ report,
+ reviewer_mentions=mentions,
+ use_section_blocks=organization_inbox_slack_section_blocks_enabled(report.team.organization_id),
+ )
# Added here rather than inside the block builder, which stays free of the integration so it
# can be tested without one. Approval is read now, not assumed from generation time: a
# reviewer can be added to a retained report after the org revoked it.
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index b3bd4edfae66..cf2e97f5e94c 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, patch
from django.apps import apps
from django.conf import settings
+from django.test import override_settings
from rest_framework.exceptions import ValidationError
from slack_sdk.errors import SlackApiError
@@ -104,13 +105,14 @@ def _plain_text_block_texts(blocks: list[dict]) -> list[str]:
return texts
-def test_build_message_blocks_includes_recipient_and_open_in_posthog_button() -> None:
[email protected]("use_section_blocks", [False, True])
+def test_build_message_blocks_includes_recipient_and_open_in_posthog_button(use_section_blocks: bool) -> None:
report = SignalReport(
id="report-uuid",
team_id=42,
title="fix(checkout): Checkout errors spiked",
summary=(
- "Error rate rose after deploy. Ignored second sentence.\nIgnored second line.\n\n"
+ "@here see [errors](https://example.com/errors?a=1&b=2) after deploy. Ignored second sentence.\nIgnored second line.\n\n"
"## Problem\n\nThe payment form throws.\n\n"
"## Impact\n\nAbout **300 buyers** could not pay\nin the last hour. Ignored second sentence.\n\n"
"A second paragraph stays out.\n\n"
@@ -118,12 +120,25 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button() ->
),
signal_count=12,
)
- blocks, text = _build_message_blocks(report, reviewer_mentions=["<@U123>"])
+ blocks, text = _build_message_blocks(report, reviewer_mentions=["<@U123>"], use_section_blocks=use_section_blocks)
assert blocks[0]["text"]["text"] == "Checkout errors spiked"
- assert blocks[1]["text"] == (
- "Error rate rose after deploy.\n\n**Impact:** About **300 buyers** could not pay in the last hour."
- )
+ if use_section_blocks:
+ assert blocks[1] == {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": "@here see <https://example.com/errors?a=1&b=2|errors> after deploy.\n\n"
+ "*Impact:* About *300 buyers* could not pay in the last hour.",
+ "verbatim": True,
+ },
+ }
+ else:
+ assert blocks[1] == {
+ "type": "markdown",
+ "text": "@here see [errors](https://example.com/errors?a=1&b=2) after deploy.\n\n"
+ "**Impact:** About **300 buyers** could not pay in the last hour.",
+ }
# A mention in plain_text would render as the raw token, never pinging anyone.
assert all("<@" not in t for t in _plain_text_block_texts(blocks))
assert blocks[2]["elements"][0]["text"] == "👤 Suggested owner: <@U123>"
@@ -162,27 +177,65 @@ def test_build_message_blocks_mentions_every_routed_reviewer() -> None:
assert blocks[2]["elements"][0]["text"] == "👤 Suggested owners: <@U1> <@U2>"
-def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields() -> None:
+def test_build_message_blocks_caps_section_body_without_truncating_mentions() -> None:
+ report = SignalReport(id="report-uuid", title="🚀" * 2000)
+ blocks, _ = _build_message_blocks(report, reviewer_mentions=["<@U123>"], use_section_blocks=True)
+
+ body = blocks[1]["text"]["text"]
+ assert len(body.encode("utf-16-le")) // 2 <= 3000
+ assert body.endswith("…")
+ assert blocks[2]["elements"][0]["text"] == "👤 Suggested owner: <@U123>"
+
+
[email protected]("use_section_blocks", [False, True])
+ "summary",
+ [
+ "<!here> everyone & <@U999> look\n\n## Impact\n\n<!channel> is affected",
+ "![notify](!here) everyone & ![owner](@U999) look\n\n## Impact\n\n![team](!channel) is affected",
+ "[notify](!here) everyone & [owner](@U999) look\n\n## Impact\n\n[team](!channel) is affected",
+ "![notify](!here) everyone & [channel](#C999) [group](!subteam^S999) [link](javascript:alert)",
+ ],
+)
+def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields(use_section_blocks: bool, summary: str) -> None:
# A crafted summary must not inject Slack mentions (<!here>, <@U…>) into mrkdwn.
report = SignalReport(
id="report-uuid",
title="Injection test",
- summary="<!here> everyone & <@U999> look\n\n## Impact\n\n<!channel> is affected",
+ summary=summary,
signal_count=1,
)
- blocks, _ = _build_message_blocks(report, reviewer_mentions=[])
-
- section_text = blocks[1]["text"]
- assert "<!here>" not in section_text
- assert "<@U999>" not in section_text
- assert "<!channel>" not in section_text
- assert "&lt;!here&gt;" in section_text
+ blocks, _ = _build_message_blocks(report, reviewer_mentions=["<@U123>"], use_section_blocks=use_section_blocks)
+
+ section_text = blocks[1]["text"]["text"] if use_section_blocks else blocks[1]["text"]
+ assert "<!" not in section_text
+ assert "<@" not in section_text
+ assert "<#" not in section_text
+ assert "<javascript:" not in section_text
+ if use_section_blocks or summary.startswith("<"):
+ assert "&lt;!here" in section_text
+ assert blocks[2]["elements"][0]["text"] == "👤 Suggested owner: <@U123>"
# `&` is left alone. Slack decodes an entity without re-reading it as a token, so escaping it
# buys no safety, and it does not decode inside a link destination, where it would corrupt the
# query string of every link a report carries.
assert "everyone & " in section_text
+def test_build_message_blocks_does_not_share_conversion_state_between_reports() -> None:
+ _build_message_blocks(
+ SignalReport(id="first-report", summary="```python\nexample()\n```"),
+ reviewer_mentions=[],
+ use_section_blocks=True,
+ )
+ blocks, _ = _build_message_blocks(
+ SignalReport(id="second-report", summary="**Details** are [here](https://example.com)."),
+ reviewer_mentions=[],
+ use_section_blocks=True,
+ )
+
+ assert blocks[1]["text"]["text"] == "*Details* are <https://example.com|here>."
+
+
def test_resolve_reviewer_mentions_uses_slack_mention_when_lookup_succeeds() -> None:
user = User(first_name="Marcus", last_name="Twix", email="[email protected]")
slack = MagicMock()
@@ -317,8 +370,12 @@ def test_dispatch_no_notification_without_team_channel_or_user_config(org_and_te
("U0123ABC456|@reviewer", "U0123ABC456", False),
],
)
[email protected]("flag_result", [False, True, None, RuntimeError("flag unavailable")])
@pytest.mark.django_db
-def test_dispatch_sends_to_configured_reviewer(org_and_team, target, expected_conversation, expects_mention):
+@override_settings(DEBUG=True)
+def test_dispatch_sends_to_configured_reviewer(
+ org_and_team, target, expected_conversation, expects_mention, flag_result
+):
org, team = org_and_team
user = _make_reviewer_user(org, "[email protected]", "another-bot")
integration = _make_slack_integration(team, user)
@@ -336,6 +393,11 @@ def test_dispatch_sends_to_configured_reviewer(org_and_team, target, expected_co
"products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
return_value="U_REVIEWER",
),
+ patch(
+ "products.signals.backend.report_content_gates.feature_enabled_or_false",
+ side_effect=flag_result if isinstance(flag_result, Exception) else None,
+ return_value=flag_result,
+ ) as evaluate_flag,
):
slack_cls.return_value.client = fake_client
sent = dispatch_inbox_item_notifications(str(report.id), team.id)
@@ -346,6 +408,15 @@ def test_dispatch_sends_to_configured_reviewer(org_and_team, target, expected_co
assert call_kwargs["channel"] == expected_conversation
assert call_kwargs["text"] == "Test report"
blocks = call_kwargs["blocks"]
+ assert blocks[1]["type"] == ("section" if flag_result is True else "markdown")
+ evaluate_flag.assert_called_once_with(
+ "signals-inbox-slack-section-blocks",
+ str(org.id),
+ groups={"organization": str(org.id)},
+ group_properties={"organization": {"id": str(org.id)}},
+ send_feature_flag_events=False,
+ only_evaluate_locally=True,
+ )
assert blocks[0]["text"]["text"] == "Test report"
context_texts = [block["elements"][0]["text"] for block in blocks if block["type"] == "context"]
if expects_mention: