: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
refactor: lift markdown link sanitizer to a shared helper + harden exports (#64730)
Kim Svatos Duganfaea5ba0a434
diff --git a/posthog/helpers/markdown_safety.py b/posthog/helpers/markdown_safety.pynew file mode 100644index 000000000000..e8425a9f9b41--- /dev/null+++ b/posthog/helpers/markdown_safety.py@@ -0,0 +1,59 @@+"""Defang externally-hosted URLs in LLM/markdown content before delivery to surfaces that auto-unfurl links.++Shared helper used across products. Injected/hallucinated URLs become inert code spans before reaching a+surface (e.g. Slack) that would auto-unfurl or linkify them; only PostHog hosts survive.+"""++import re+from urllib.parse import urlparse++from posthog.api.utils import hostname_in_allowed_url_list++_ALLOWED_LINK_URLS = ["https://posthog.com", "https://*.posthog.com"]+# Match all CommonMark title forms (double/single-quoted, parenthesized) and allow whitespace before+# `)` (trailing `\s*`) — otherwise `[x](url "t")`, `[x](url 't')`, or `[x](url\n)` slip past this rule+# and the bare-URL rule (which skips `](`-prefixed URLs), reaching Slack un-defanged.+_MARKDOWN_LINK_RE = re.compile(r"\[([^\]]*)\]\(((?:[^()\s]+|\([^)]*\))+)(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^)]*\)))?\s*\)")+_MARKDOWN_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\([^)]*\)")+# A malformed link the rule above can't span (e.g. `[x](url\nmore)`) leaves its URL after `](`, which+# the bare-URL rule skips — defang it here as a safety net.+_ORPHAN_DEST_RE = re.compile(r"\]\(((?:https?://|www\.)[^\s<>)\]`]+)", re.IGNORECASE)+_AUTOLINK_RE = re.compile(r"<(https?://[^\s>]+)>", re.IGNORECASE)+_BARE_URL_RE = re.compile(r"(?<!\]\()(?<![<`@])((?:https?://|www\.)[^\s<>)\]`]+)", re.IGNORECASE)+++def _is_allowed_link_url(url: str) -> bool:+ if "\\" in url or any(c.isspace() or ord(c) < 0x20 for c in url):+ return False+ try:+ parsed = urlparse(url)+ if parsed.username is not None or parsed.password is not None:+ return False+ host = (parsed.hostname or "").lower()+ except ValueError:+ return False+ if parsed.scheme.lower() not in ("http", "https"):+ return False+ return hostname_in_allowed_url_list(_ALLOWED_LINK_URLS, host)+++def _neutralize_url(url: str, keep_as: str | None = None) -> str:+ check_url = url if url.lower().startswith(("http://", "https://")) else f"https://{url}"+ if _is_allowed_link_url(check_url):+ return keep_as if keep_as is not None else url+ return f"`{url}`"+++def strip_external_links_markdown(markdown: str) -> str:+ """Drop images, keep only PostHog links, and defang every other URL to a code span."""+ md = _MARKDOWN_IMAGE_RE.sub(lambda m: m.group(1) or "", markdown)+ md = _MARKDOWN_LINK_RE.sub(+ lambda m: m.group(0) if _is_allowed_link_url(m.group(2)) else m.group(1),+ md,+ )+ # Backtick-wrap a non-PostHog orphan destination so the bare-URL rule's lookbehind keeps it inert.+ # Wrap only the URL, not the `](`/`)` — the source's own `)` balances it (appending one would dangle).+ md = _ORPHAN_DEST_RE.sub(lambda m: m.group(0) if _is_allowed_link_url(m.group(1)) else f"](`{m.group(1)}`", md)+ md = _AUTOLINK_RE.sub(lambda m: _neutralize_url(m.group(1), keep_as=m.group(0)), md)+ md = _BARE_URL_RE.sub(lambda m: _neutralize_url(m.group(1)), md)+ return mddiff --git a/posthog/helpers/test_markdown_safety.py b/posthog/helpers/test_markdown_safety.pynew file mode 100644index 000000000000..32320147867f--- /dev/null+++ b/posthog/helpers/test_markdown_safety.py@@ -0,0 +1,44 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.helpers.markdown_safety import strip_external_links_markdown+++class TestStripExternalLinks(BaseTest):+ @parameterized.expand(+ [+ ("no_title", "[x](https://evil.example.com)"),+ ("double_quote_title", '[x](https://evil.example.com "t")'),+ ("single_quote_title", "[x](https://evil.example.com 't')"),+ ("paren_title", "[x](https://evil.example.com (t))"),+ ("bare_url", "visit https://evil.example.com now"),+ # Whitespace before `)` is a valid CommonMark link — it must still be defanged, not+ # slip past both the link rule and the bare-URL rule.+ ("newline_before_paren", "[x](https://evil.example.com\n)"),+ ("space_before_paren", "[x](https://evil.example.com )"),+ # Not a CommonMark link, but the destination URL would otherwise survive bare after `](`.+ ("newline_mid_dest", "[x](https://evil.example.com\nmore)"),+ ]+ )+ def test_non_posthog_urls_defanged(self, _label: str, markdown: str) -> None:+ out = strip_external_links_markdown(markdown)+ # The host must never survive as a live link — only inside an inert code span at most.+ self.assertNotIn("](https://evil.example.com", out)+ self.assertNotIn("(https://evil.example.com", out)++ def test_orphan_dest_backticks_without_adding_a_paren(self) -> None:+ # The orphan-dest rule wraps only the URL; the source markdown's own `)` balances the `(`,+ # so the defanged output must not gain a second closing paren.+ out = strip_external_links_markdown("[x](https://evil.example.com\nmore)")+ self.assertEqual(out, "[x](`https://evil.example.com`\nmore)")++ @parameterized.expand(+ [+ ("plain", "[docs](https://posthog.com/docs)"),+ ("trailing_space", "[docs](https://posthog.com/docs )"),+ ]+ )+ def test_posthog_links_preserved(self, _label: str, markdown: str) -> None:+ out = strip_external_links_markdown(markdown)+ self.assertIn("https://posthog.com/docs", out)diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.pyindex c641f6385cec..f2bc5a30ba12 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py@@ -1,15 +1,14 @@-import reimport uuidfrom datetime import datetime-from urllib.parse import urlencode, urlparse+from urllib.parse import urlencodeimport nh3import structlogfrom markdown_it import MarkdownItfrom markdown_to_mrkdwn import SlackMarkdownConverter-from posthog.api.utils import hostname_in_allowed_url_listfrom posthog.email import EmailMessage+from posthog.helpers.markdown_safety import strip_external_links_markdownfrom posthog.helpers.slack_subscription_explore import build_explore_hintfrom posthog.models import Team, Userfrom posthog.models.integration import Integration@@ -70,69 +69,6 @@ _ALLOWED_EMAIL_ATTRS = {"a": {"href", "title"}}# Slack's hard limit is 3000 chars per section block; keep margin for safety.SLACK_MRKDWN_SECTION_LIMIT = 2900-# Only PostHog hosts are allowed in delivered report links. Any other host is stripped from-# the LLM output before rendering — Slack auto-unfurls outbound links server-side, which is-# an exfil channel an injected synthesis prompt could otherwise drive. Wildcard entries cover-# the `<region>.posthog.com` subdomains via `hostname_in_allowed_url_list`'s regex matching.-_ALLOWED_LINK_URLS = ["https://posthog.com", "https://*.posthog.com"]-# URL group supports one level of balanced parens so e.g. wikipedia /Foo_(bar) doesn't truncate-_MARKDOWN_LINK_RE = re.compile(r"\[([^\]]*)\]\(((?:[^()\s]+|\([^)]*\))+)(?:\s+\"[^\"]*\")?\)")-_MARKDOWN_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\([^)]*\)")-# `<scheme://…>` autolinks and bare `scheme://…` / `www.…` URLs — the forms Slack still linkifies and-# unfurls after the markdown-link pass above. Case-insensitive so an uppercase scheme can't slip-# through. The bare matcher skips only the `](url)` markdown-link context, `<` autolinks, backtick code-# spans, and email local-parts (`@`); a URL in plain parentheses is still defanged.-_AUTOLINK_RE = re.compile(r"<(https?://[^\s>]+)>", re.IGNORECASE)-_BARE_URL_RE = re.compile(r"(?<!\]\()(?<![<`@])((?:https?://|www\.)[^\s<>)\]`]+)", re.IGNORECASE)---def _is_allowed_link_url(url: str) -> bool:- # Reject authority-confusion vectors *before* trusting urlparse's hostname. urlparse and a- # browser disagree on the host whenever the authority contains a backslash, control/whitespace- # char, or embedded userinfo (`@`): urlparse reads `evil.example\@posthog.com`,- # `evil.example%[email protected]`, or `[email protected]` as one host, while the browser- # navigates somewhere else. A legitimate PostHog link never has userinfo, so any `@` in the- # authority — however encoded — is disqualifying. Also require an http(s) scheme.- if "\\" in url or any(c.isspace() or ord(c) < 0x20 for c in url):- return False- try:- parsed = urlparse(url)- if parsed.username is not None or parsed.password is not None:- return False- host = (parsed.hostname or "").lower()- except ValueError:- return False- if parsed.scheme.lower() not in ("http", "https"):- return False- return hostname_in_allowed_url_list(_ALLOWED_LINK_URLS, host)---def _neutralize_url(url: str, keep_as: str | None = None) -> str:- # Keep PostHog links live (rendered as `keep_as` when given — e.g. an autolink's `<url>` wrapper —- # otherwise the bare URL); defang anything else into an inert code span so neither Slack (auto-- # unfurl / linkify) nor email can turn an injected URL into a live request or a one-click link. The- # URL stays visible so a reader can see what the report tried to embed. Scheme-less `www.` URLs get- # a scheme prepended only for the host check, never in the output.- check_url = url if url.lower().startswith(("http://", "https://")) else f"https://{url}"- if _is_allowed_link_url(check_url):- return keep_as if keep_as is not None else url- return f"`{url}`"---def _strip_external_links_markdown(markdown: str) -> str:- """Neutralize externally-hosted URLs in LLM-generated report content. Markdown images are- dropped; `[text](url)`, `<url>` autolinks, and bare `http(s)://` / `www.` URLs keep PostHog hosts- live and defang any other host. Defends against an injected synthesis prompt embedding an- exfil/phishing URL that a delivery channel would auto-unfurl or linkify."""- md = _MARKDOWN_IMAGE_RE.sub(lambda m: m.group(1) or "", markdown)- md = _MARKDOWN_LINK_RE.sub(- lambda m: m.group(0) if _is_allowed_link_url(m.group(2)) else m.group(1),- md,- )- md = _AUTOLINK_RE.sub(lambda m: _neutralize_url(m.group(1), keep_as=m.group(0)), md)- md = _BARE_URL_RE.sub(lambda m: _neutralize_url(m.group(1)), md)- return md-def _split_text_into_chunks(text: str, limit: int = SLACK_MRKDWN_SECTION_LIMIT) -> list[str]:if len(text) <= limit:@@ -185,7 +121,7 @@ def _build_feedback_url(subscription_url: str, delivery_id: uuid.UUID, feedback:def render_ai_email_html(markdown: str) -> str:- rendered = _MARKDOWN_RENDERER.render(_strip_external_links_markdown(markdown))+ rendered = _MARKDOWN_RENDERER.render(strip_external_links_markdown(markdown))return nh3.clean(rendered, tags=_ALLOWED_EMAIL_TAGS, attributes=_ALLOWED_EMAIL_ATTRS)@@ -265,7 +201,7 @@ def _build_ai_slack_message() -> SlackMessageData:utm_tags = f"{UTM_TAGS_BASE}&utm_medium=slack"channel = subscription.target_value.split("|")[0]- sections = _split_text_into_chunks(_SLACK_CONVERTER.convert(_strip_external_links_markdown(markdown)))+ sections = _split_text_into_chunks(_SLACK_CONVERTER.convert(strip_external_links_markdown(markdown)))title = subscription.title or "Your PostHog AI report"first_section = sections[0] if sections else "_No report content was generated._"