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(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.py
index 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 `&lt;` 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"&lt;(?![@!])")
+
+
+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. `&amp;` decodes last so a user-typed literal `&lt;`
+ (wire form `&amp;lt;`) comes out as `&lt;` instead of double-decoding to `<`.
+ """
+ text = _RE_DECODABLE_LT.sub("<", text)
+ return text.replace("&gt;", ">").replace("&amp;", "&")
+
+
+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 the
token verbatim to ping the user back. Centralised here so a new trigger
handler 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 `&gt;` 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.py
index 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 &lt; b &gt; c &amp; d", "a < b > c & d"),
+ ("decodes_double_escaped_input_once", "&amp;gt; &amp;lt; &amp;amp;", "&gt; &lt; &amp;"),
+ ("keeps_escaped_mention_shaped_text_inert", "&lt;@U123|boss&gt; ok", "&lt;@U123|boss> ok"),
+ ("keeps_escaped_broadcast_inert", "&lt;!here&gt; deploy", "&lt;!here> deploy"),
+ ("leaves_literal_html_entities_alone", "say &quot;hi&quot; &#62;", "say &quot;hi&quot; &#62;"),
+ ]
+ )
+ 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 &amp;gt; beta")
+
+ assert result == "alpha &gt; 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 &gt; 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].text
assert "Result count *42* exceeded threshold *10*" in result[0].text
assert result[1].user == "andy"
- assert "was that really an anomaly?" in result[1].text
+ assert "was that really > expected?" in result[1].text
def 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