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(conversations): keep inbound email links whole in the inbox (#94255)

Alex Vf2492c66dd4b
diff --git a/products/conversations/backend/services/email_links.py b/products/conversations/backend/services/email_links.py
index f45ca310bf7a..8fc83aadfca6 100644
--- a/products/conversations/backend/services/email_links.py
+++ b/products/conversations/backend/services/email_links.py
@@ -1,12 +1,19 @@
-"""Recover hyperlinks that Mailgun drops when it flattens HTML-only mail.
-
-Mailgun builds `body-plain` for an HTML-only email by stripping tags, which keeps
-the anchor text but loses the `href`. Inbound support and customer-communication
-messages store that plain text, so a call-to-action link (for example an email
-forwarding activation link) never reaches the inbox. We read the links back out
-of `body-html` and fold them into the stored text as Markdown, which the inbox
-already renders. The stripped body is kept as-is, so quoted-reply trimming and
-threading are unaffected.
+"""Keep inbound-email hyperlinks intact all the way to the inbox.
+
+Two things break links between Mailgun and the rendered message:
+
+1. Mailgun builds `body-plain` for an HTML-only email by stripping tags, which
+ keeps the anchor text but loses the `href`. A call-to-action link (for example
+ an email forwarding activation link) never reaches the inbox. We read the links
+ back out of `body-html` and fold them into the stored text as Markdown.
+2. The inbox renders message text with GFM autolink literals, which trim trailing
+ punctuation (`~`, `.`, `?`, ...) from a bare URL. Click-tracking links such as
+ Mailgun/SparkPost `.../<token>~` end in that punctuation, so the rendered link
+ loses its last character and no longer resolves. We wrap bare URLs in angle
+ brackets so the renderer takes them verbatim.
+
+The stripped body is kept as-is, so quoted-reply trimming and threading are
+unaffected.
"""
from __future__ import annotations
@@ -19,9 +26,18 @@ from bs4 import BeautifulSoup
logger = structlog.get_logger(__name__)
_HTTP_SCHEME_RE = re.compile(r"^https?://", re.IGNORECASE)
+# Sentence punctuation that trails a URL in prose but is never part of an opaque
+# tracking token (base64url uses `-`/`_`, SparkPost ends in `~`). Trimmed before
+# wrapping so a URL ending a sentence does not carry the punctuation into the link.
+_URL_TRAILING_PUNCTUATION = ".,;:!?"
# Cap the anchors we scan so a large marketing email can't turn one message into
# an expensive parse.
_MAX_ANCHORS = 100
+# A bare URL, scanned in one linear pass so a hostile body can't force quadratic
+# work. The class keeps parentheses so a URL like `.../Markdown_(language)` stays
+# whole; any unbalanced trailing parenthesis (from a `(url)` wrapper) is peeled back
+# off in `_wrap_bare_urls`.
+_BARE_URL_RE = re.compile(r"https?://[^\s<>\[\]]+", re.IGNORECASE)
def _md_safe_href(href: str) -> str:
@@ -30,15 +46,81 @@ def _md_safe_href(href: str) -> str:
def recover_links_from_html(text: str, html: str) -> str:
+ """Recover links lost by flattening, then keep every URL whole for the renderer.
+
+ First fold any anchor whose `href` was dropped from `text` back in as Markdown,
+ then wrap the remaining bare URLs so the Markdown renderer keeps them intact.
+ """
+ if not text:
+ return text
+ recovered = _recover_from_html(text, html) if html else text
+ return _wrap_bare_urls(recovered)
+
+
+def _wrap_bare_urls(text: str) -> str:
+ """Wrap bare URLs in angle brackets so the Markdown renderer keeps them whole.
+
+ The inbox renders message text with GFM autolink literals, which trim trailing
+ punctuation from a bare URL. An explicit `<url>` autolink is taken verbatim, so
+ the full token survives. A URL already inside an angle autolink or a Markdown
+ link (as its destination or its text) is left as-is.
+
+ Sentence punctuation and an unbalanced trailing parenthesis are peeled off the
+ end and left outside the link, so a URL ending a sentence or wrapped in `(...)`
+ stays clean while a balanced `(...)` inside the URL is kept. Token characters
+ (`~`, `-`, `_`) are kept, since dropping one would break the links this protects.
+
+ The whole pass is linear: URLs are found with a single non-backtracking scan and
+ protection is an O(1) look-behind, so a hostile body cannot force quadratic work.
+ """
+
+ def is_protected(start: int) -> bool:
+ # `<url…` is an angle autolink; `[url…` is link text; `](url…` is a link
+ # destination. Any of these means the URL is already linked — leave it be.
+ if start > 0 and text[start - 1] in "<[":
+ return True
+ return start >= 2 and text[start - 2 : start] == "]("
+
+ result: list[str] = []
+ last = 0
+ for match in _BARE_URL_RE.finditer(text):
+ start, end = match.span()
+ if is_protected(start):
+ continue
+ url = match.group(0)
+ # Count parentheses once, then walk back from the end in a single pass so a
+ # long run of trailing ")" or punctuation stays O(len(url)).
+ open_count = url.count("(")
+ close_count = url.count(")")
+ stop = len(url)
+ while stop > 0:
+ char = url[stop - 1]
+ if char in _URL_TRAILING_PUNCTUATION:
+ pass
+ elif char == ")" and close_count > open_count:
+ close_count -= 1
+ else:
+ break
+ stop -= 1
+ core = url[:stop]
+ scheme = _HTTP_SCHEME_RE.match(core)
+ # Nothing left after the scheme (e.g. "https://.") — leave the text alone.
+ if not scheme or len(core) == scheme.end():
+ continue
+ result.append(text[last:start])
+ result.append(f"<{core}>{url[stop:]}")
+ last = end
+ result.append(text[last:])
+ return "".join(result)
+
+
+def _recover_from_html(text: str, html: str) -> str:
"""Fold links from `html` into `text` as Markdown when they were lost.
Only a link whose URL is missing from `text` and whose anchor text still
appears verbatim in `text` is rewritten, once, to `[label](href)`. Anything
else is left untouched, so already-linked URLs and stripped quotes are safe.
"""
- if not text or not html:
- return text
-
try:
soup = BeautifulSoup(html, "html.parser")
except Exception: # noqa: BLE001 — a malformed HTML part must never fail ingestion
diff --git a/products/conversations/backend/tests/test_email_links.py b/products/conversations/backend/tests/test_email_links.py
index 9381f964bb3e..92b7606c5c93 100644
--- a/products/conversations/backend/tests/test_email_links.py
+++ b/products/conversations/backend/tests/test_email_links.py
@@ -37,10 +37,76 @@ class TestRecoverLinksFromHtml:
result = recover_links_from_html(text, html)
assert "[Attiva l'inoltro](https://host.example/activate?t=abc)" in result
- def test_leaves_text_untouched_when_url_already_present(self) -> None:
+ def test_wraps_url_already_present_instead_of_relinking(self) -> None:
text = "Confirm at https://host.example/activate?t=abc now"
html = '<a href="https://host.example/activate?t=abc">Confirm</a>'
- assert recover_links_from_html(text, html) == text
+ assert recover_links_from_html(text, html) == "Confirm at <https://host.example/activate?t=abc> now"
+
+ @parameterized.expand(
+ [
+ ("trailing_tilde", "https://clicks.example/f/a/token~"),
+ ("trailing_tildes", "https://clicks.example/f/a/token~~/enc~"),
+ ("trailing_underscore", "https://clicks.example/f/a/token_"),
+ ("trailing_hyphen", "https://clicks.example/f/a/token-"),
+ ]
+ )
+ def test_wraps_bare_url_preserving_token_characters(self, _name: str, url: str) -> None:
+ # A tracking token keeps its terminal character only when wrapped; the
+ # renderer's GFM autolink literal would otherwise trim it and break the link.
+ result = recover_links_from_html(f"Open {url} please", "")
+ assert f"<{url}> please" in result
+
+ @parameterized.expand(
+ [
+ ("period", "See https://example.com/page. Thanks", "https://example.com/page", "."),
+ ("comma", "See https://example.com/page, then go", "https://example.com/page", ","),
+ ("question", "Seen https://example.com/page? Yes", "https://example.com/page", "?"),
+ ]
+ )
+ def test_excludes_trailing_sentence_punctuation_from_link(
+ self, _name: str, text: str, url: str, punctuation: str
+ ) -> None:
+ # Sentence punctuation trailing a prose URL must stay outside the link so a
+ # click does not navigate to an altered address.
+ result = recover_links_from_html(text, "")
+ assert f"<{url}>{punctuation}" in result
+
+ @parameterized.expand(
+ [
+ ("balanced_parens", "Read https://en.wikipedia.org/wiki/Markdown_(language) now"),
+ ("mid_path_parens", "Read https://example.com/path(param) now"),
+ ]
+ )
+ def test_keeps_balanced_parentheses_inside_url(self, _name: str, text: str) -> None:
+ # GFM autolinks balance parentheses, so a URL that legitimately contains them
+ # must stay whole rather than truncate at the first "(".
+ url = text.split("Read ", 1)[1].rsplit(" now", 1)[0]
+ result = recover_links_from_html(text, "")
+ assert f"<{url}> now" in result
+
+ def test_peels_unbalanced_wrapping_parenthesis(self) -> None:
+ result = recover_links_from_html("(https://example.com/x)", "")
+ assert result == "(<https://example.com/x>)"
+
+ def test_peels_many_unbalanced_trailing_parentheses(self) -> None:
+ result = recover_links_from_html("https://example.com/x" + ")" * 1000, "")
+ assert result == "<https://example.com/x>" + ")" * 1000
+
+ def test_handles_many_unmatched_brackets_without_backtracking(self) -> None:
+ # A body of unmatched "[" must not trigger quadratic link scanning; the text
+ # has no URL, so it is returned untouched.
+ text = "[" * 50000
+ assert recover_links_from_html(text, "") == text
+
+ def test_does_not_double_wrap_recovered_link(self) -> None:
+ text = "Please confirm.\nAttiva l'inoltro"
+ html = '<a href="https://clicks.example/f/a/token~">Attiva l\'inoltro</a>'
+ result = recover_links_from_html(text, html)
+ assert result == "Please confirm.\n[Attiva l'inoltro](https://clicks.example/f/a/token~)"
+
+ def test_leaves_existing_angle_autolink_untouched(self) -> None:
+ text = "Confirm at <https://host.example/activate~> now"
+ assert recover_links_from_html(text, "") == text
def test_only_first_occurrence_is_linked(self) -> None:
text = "click here and also click here"