: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
fix(slack_app): decode escaped entities in task titles and context (#99984)
Adam Leitha424e2ddf42e
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex 9aaa884bb4c0..9437751f7182 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -115,6 +115,43 @@ def resolve_user_mentions_text(return resolved+# A `<` that would begin a mention (`<@`) or broadcast (`<!`) token stays escaped:+# decoded user text must never mint a token that downstream mention handling or the+# outbound relay could turn into a real ping.+_RE_DECODABLE_LT = re.compile(r"<(?![@!])")+++def decode_slack_entities(text: str) -> str:+ """Decode the three entities Slack escapes in message text: `&`, `<`, `>`.++ Slack escapes only these three+ (https://docs.slack.dev/messaging/formatting-message-text#escaping), so three+ targeted replaces rather than `html.unescape`, which would also decode entities+ the user typed literally. `&` decodes last so a user-typed literal `<`+ (wire form `&lt;`) comes out as `<` instead of double-decoding to `<`.+ """+ text = _RE_DECODABLE_LT.sub("<", text)+ return text.replace(">", ">").replace("&", "&")+++def _resolve_and_decode(+ slack: SlackIntegration,+ integration: Integration,+ text: str,+ *,+ strip_bot_user_id: str | None = None,+) -> str:+ """Resolve mentions, then decode escaped entities: the one order that is safe.++ Mention resolution must run first so its regex only ever sees genuine+ wire-format tokens; the decode guard then keeps user-typed text from minting+ new ones behind it. Every inbound path goes through here so no path can+ apply one step without the other.+ """+ resolved = resolve_user_mentions_text(slack, integration, text, strip_bot_user_id=strip_bot_user_id)+ return decode_slack_entities(resolved)++def decode_slack_event_text(slack: SlackIntegration, integration: Integration, text: str) -> str:"""Strip the bot's own self-mention from a Slack event and label the rest for the agent.@@ -123,9 +160,13 @@ def decode_slack_event_text(slack: SlackIntegration, integration: Integration, t`<@U…>` reference with a `|displayname` label so the agent can echo thetoken verbatim to ping the user back. Centralised here so a new triggerhandler can't drift back into the original mention-eating bug.++ Also decodes Slack's escaped entities, because this text feeds task titles and+ descriptions that render in the PostHog UI, where an undecoded `>` shows up+ literally."""bot_user_id = get_cached_bot_user_id(slack, integration)- return resolve_user_mentions_text(slack, integration, text, strip_bot_user_id=bot_user_id).strip()+ return _resolve_and_decode(slack, integration, text, strip_bot_user_id=bot_user_id).strip()def labeled_mentions_to_display_names(text: str) -> str:@@ -543,7 +584,7 @@ def collect_thread_messages(SlackThreadMessage(user=username,user_id=user_id or "",- text=resolve_user_mentions_text(slack, integration, extract_message_text(msg)),+ text=_resolve_and_decode(slack, integration, extract_message_text(msg)),ts=msg.get("ts") or "",files_json=encode_slack_file_refs(parse_slack_file_refs(msg.get("files"))),)diff --git a/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.py b/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.pyindex e172edc55124..ac24db123005 100644--- a/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.py+++ b/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.py@@ -13,6 +13,7 @@ from products.slack_app.backend.services.slack_messages import (SlackFileRef,SlackThreadMessage,collect_thread_messages,+ decode_slack_entities,decode_slack_event_text,extract_message_text,flatten_block_text,@@ -309,6 +310,20 @@ class TestResolveUserMentionsText:assert result == "ping <@UCLEO|Unknown>"+class TestDecodeSlackEntities:+ @parameterized.expand(+ [+ ("decodes_the_three_slack_entities", "a < b > c & d", "a < b > c & d"),+ ("decodes_double_escaped_input_once", "&gt; &lt; &amp;", "> < &"),+ ("keeps_escaped_mention_shaped_text_inert", "<@U123|boss> ok", "<@U123|boss> ok"),+ ("keeps_escaped_broadcast_inert", "<!here> deploy", "<!here> deploy"),+ ("leaves_literal_html_entities_alone", "say "hi" >", "say "hi" >"),+ ]+ )+ def test_decode_cases(self, _name: str, text: str, expected: str) -> None:+ assert decode_slack_entities(text) == expected++class TestDecodeSlackEventText:"""The wrapper at the 3 trigger sites — look up the bot, label the rest, strip."""@@ -349,6 +364,14 @@ class TestDecodeSlackEventText:assert result == "hello world"+ @patch("products.slack_app.backend.services.slack_messages.get_cached_bot_user_id")+ def test_decodes_slack_text_entities_once(self, mock_get_bot_user_id):+ mock_get_bot_user_id.return_value = "UBOT"++ result = decode_slack_event_text(self.slack, self.integration, "alpha &gt; beta")++ assert result == "alpha > beta"+class TestLabeledMentionsToDisplayNames:def test_unwraps_labeled_mention(self):@@ -413,7 +436,7 @@ class TestCollectThreadMessages:},],},- {"user": "U_ANDY", "text": "<@UBOT> was that really an anomaly?"},+ {"user": "U_ANDY", "text": "<@UBOT> was that really > expected?"},])self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}@@ -425,7 +448,7 @@ class TestCollectThreadMessages:assert "🔴 Log alert 'High Error Rate' is firing" in result[0].textassert "Result count *42* exceeded threshold *10*" in result[0].textassert result[1].user == "andy"- assert "was that really an anomaly?" in result[1].text+ assert "was that really > expected?" in result[1].textdef test_carries_attachment_metadata_needed_to_fetch_the_file(self):# The screenshot a thread opens with is usually the one the request is about, so