: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
chore(email): tighten property sanitization (#57246)
Tom Piccirellobbd3a0bd01f8
diff --git a/posthog/email.py b/posthog/email.pyindex 127c274d94f9..c4844a6b046e 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -6,7 +6,7 @@ import uuidimport datetimeimport dataclassesfrom decimal import Decimal-from typing import TYPE_CHECKING, Any, Optional+from typing import TYPE_CHECKING, Any, Literal, Optionalif TYPE_CHECKING:from posthog.models import User@@ -26,6 +26,7 @@ from celery import shared_taskfrom lxml import html as lxml_htmlfrom posthog.exceptions_capture import capture_exception+from posthog.helpers.email_utils import sanitize_email_stringfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.messaging import MessagingRecordfrom posthog.tasks.utils import CeleryQueue@@ -267,11 +268,49 @@ def _send_via_smtp()+# `utm_tags` carries hardcoded query-string fragments (`a=1&b=2`) and is never+# user-controlled. It must pass through verbatim so the `&` separators don't+# get HTML-escaped before reaching Customer.io — Liquid renders the value raw,+# and mail clients expect the literal `&` between query parameters.+_PASSTHROUGH_KEYS = {"utm_tags"}++# Keys whose values are PostHog-generated URLs (built from `settings.SITE_URL`+# + a path) and should remain clickable in the rendered email. Defanging would+# break every "click here" button, so URL-shape characters (`:`, `/`, `.`) are+# preserved — but attribute-injection characters (`<`, `>`, `"`, `'`, `&`) are+# still html-escaped, so a user-controlled path segment (e.g. the `slug`+# appended in `build_comment_item_url`) cannot break out of `<a href="...">`.+_TRUSTED_URL_KEYS = {"url", "href", "link", "site_url"}+_TRUSTED_URL_KEY_SUFFIXES = ("_url", "_link", "_href")++_KeyPolicy = Literal["passthrough", "trusted_url", "default"]+++def _classify_key(key: Any) -> _KeyPolicy:+ if not isinstance(key, str):+ return "default"+ lower = key.lower()+ if lower in _PASSTHROUGH_KEYS:+ return "passthrough"+ if lower in _TRUSTED_URL_KEYS or lower.endswith(_TRUSTED_URL_KEY_SUFFIXES):+ return "trusted_url"+ return "default"++def sanitize_email_properties(properties: dict[str, Any] | None) -> dict[str, Any]:"""- Sanitizes properties that will be used in email templates to prevent HTML injection.- This function recursively processes dictionaries, lists, and scalar values to ensure- all string values are properly escaped.+ Sanitizes properties that will be used in email templates to prevent HTML+ injection and to defang URL-shaped strings so mail clients don't auto-link+ user-controlled content like display names or organization names.+ Recursively processes dictionaries, lists, and scalar values. Keys are+ handled in three tiers:++ - `_PASSTHROUGH_KEYS` (e.g. `utm_tags`) — value returned unchanged.+ - `_TRUSTED_URL_KEYS` and `*_url` / `*_link` / `*_href` — html-escaped only,+ no defang, so the link stays clickable but a user-controlled portion of+ the URL can't escape the href attribute.+ - everything else — full `sanitize_email_string` (NFKC + invisible-strip ++ html-escape + URL defang).Args:properties: Dictionary of properties to sanitize@@ -285,53 +324,42 @@ def sanitize_email_properties(properties: dict[str, Any] | None) -> dict[str, Anif properties is None:return {}- # Special keys that should not be sanitized (e.g., URL query parameters)- skip_sanitization_keys = ["utm_tags"]-- # Supported types (besides containers like dict and list)supported_types = (str, int, float, bool, type(None), Decimal, uuid.UUID, datetime.datetime, datetime.date)- def sanitize_value(value: Any) -> Any:+ def sanitize_value(value: Any, *, key: Any = None) -> Any:+ policy = _classify_key(key) if key is not None else "default"+ if policy == "passthrough":+ return valueif isinstance(value, str):- return html.escape(value)+ if policy == "trusted_url":+ return html.escape(value)+ return sanitize_email_string(value)elif isinstance(value, dict):- return {k: sanitize_value(v) for k, v in value.items()}+ return {k: sanitize_value(v, key=k) for k, v in value.items()}elif isinstance(value, list):return [sanitize_value(item) for item in value]elif isinstance(value, uuid.UUID):- # Handle UUID by converting to string and escaping- return html.escape(str(value))+ return sanitize_email_string(str(value))elif isinstance(value, datetime.datetime | datetime.date):- # Convert datetime/date to ISO-8601 string and escape — reached via- # dataclasses.asdict() for facade contracts with created_at-style fields- return html.escape(value.isoformat())+ # Reached via dataclasses.asdict() for facade contracts with created_at-style fields.+ return sanitize_email_string(value.isoformat())elif hasattr(value, "_meta") and hasattr(value, "pk"):- # Handle Django models by converting to string and escaping- return html.escape(str(value))+ # str(model) often contains user-controlled fields (Team.name, Organization.name)+ # that mail clients would otherwise auto-link.+ return sanitize_email_string(str(value))elif isinstance(value, Decimal):- # Convert Decimal to float for JSON serializationreturn float(value)elif isinstance(value, int | float | bool | type(None)):- # These types are safe as-isreturn valueelif dataclasses.is_dataclass(value) and not isinstance(value, type):- # Convert dataclass instances to a dict and recurse so their string fields get escaped- return {k: sanitize_value(v) for k, v in dataclasses.asdict(value).items()}+ return {k: sanitize_value(v, key=k) for k, v in dataclasses.asdict(value).items()}else:- # Raise an error for unsupported types - this is a security measure to prevent uncaught injectionsraise TypeError(f"Unsupported type in email properties: {type(value).__name__}. "f"Only {', '.join(t.__name__ for t in supported_types)}, dict, list, dataclasses, and Django models are supported.")- result = {}- for k, v in properties.items():- if k in skip_sanitization_keys:- result[k] = v # Skip sanitization for special keys- else:- result[k] = sanitize_value(v)-- return result+ return {k: sanitize_value(v, key=k) for k, v in properties.items()}@shared_task(**EMAIL_TASK_KWARGS)diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.pyindex 98140d7dfb95..8d1406451f67 100644--- a/posthog/helpers/email_utils.py+++ b/posthog/helpers/email_utils.py@@ -1,9 +1,10 @@"""-Email-related helpers: address normalisation, ESP suppression lookups, user+Email-related helpers: address normalization, ESP suppression lookups, userlookup by email, and display-name / message validation."""import re+import htmlimport hashlibimport unicodedatafrom collections.abc import Callable@@ -36,7 +37,7 @@ _URL_SCHEME_RE = re.compile(re.IGNORECASE,)_BARE_DOMAIN_RE = re.compile(- r"\b[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.[a-z]{2,24}\b",+ r"\b(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.)+[a-z]{2,24}\b",re.IGNORECASE,)_CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f\u0085\u2028\u2029]")@@ -50,20 +51,18 @@ _BRACKET_ERROR = "Angle brackets are not allowed in this field."_INVISIBLE_ERROR = "Invisible or direction-override characters are not allowed in this field."-def _check_shared(value: str, *, check_bare_domains: bool) -> None:+def _check_shared(value: str) -> None:"""Run the checks shared between display names and message bodies against an- NFKC-normalised copy of `value`. Normalisation folds fullwidth / compat+ NFKC-normalized copy of `value`. Normalization folds fullwidth / compatvariants (e.g. `http://` \u2192 `http://`) before regex matching."""- normalised = unicodedata.normalize("NFKC", value)- if _INVISIBLE_CHAR_RE.search(normalised):+ normalized = unicodedata.normalize("NFKC", value)+ if _INVISIBLE_CHAR_RE.search(normalized):raise serializers.ValidationError(_INVISIBLE_ERROR, code="invalid_invisible_char")- if _BRACKET_RE.search(normalised):+ if _BRACKET_RE.search(normalized):raise serializers.ValidationError(_BRACKET_ERROR, code="invalid_bracket")- if _URL_SCHEME_RE.search(normalised):- raise serializers.ValidationError(_URL_ERROR, code="invalid_url")- if check_bare_domains and _BARE_DOMAIN_RE.search(normalised):+ if _URL_SCHEME_RE.search(normalized):raise serializers.ValidationError(_URL_ERROR, code="invalid_url")@@ -78,10 +77,12 @@ def validate_display_name(value: None) -> None: ...def validate_display_name(value: str | None) -> str | None:"""Validate identity fields (`first_name`, `last_name`, organization name,- invite recipient name). Rejects URLs (including bare domains), line- breaks, control characters, angle brackets, and zero-width / bidi- characters. Returns the stripped value; empty / blank input passes- through.+ invite recipient name). Rejects URL schemes (`https://`, `javascript:`,+ `www.`), line breaks, control characters, angle brackets, and zero-width /+ bidi characters. Bare domains (`google.com`) are allowed — users+ legitimately set those as org names, and `sanitize_email_string` defangs+ them at email render time. Returns the stripped value; empty / blank input+ passes through."""if value is None:return None@@ -90,7 +91,7 @@ def validate_display_name(value: str | None) -> str | None:return strippedif _CONTROL_CHAR_RE.search(stripped):raise serializers.ValidationError(_CONTROL_ERROR, code="invalid_control_char")- _check_shared(stripped, check_bare_domains=True)+ _check_shared(stripped)return stripped@@ -99,13 +100,13 @@ def validate_message_body(value: str | None) -> str | None:Validate a free-text message body. Newlines and tabs are allowed; URLschemes (`http://`, `javascript:`, `www.`, ...), non-newline controlchars, angle brackets, and invisible chars are not. Bare domains are- permitted here to keep messages like "see the foo.py file" usable.+ permitted so messages like "see the foo.py file" stay usable."""if value is None:return Noneif _NON_NEWLINE_CONTROL_RE.search(value):raise serializers.ValidationError(_CONTROL_ERROR, code="invalid_control_char")- _check_shared(value, check_bare_domains=False)+ _check_shared(value)return value@@ -182,6 +183,49 @@ sanitize_message_body = partial()+# Zero-width space inserted after `.` and `:` to break auto-link patterns.+# We previously used `.` / `:` HTML entities, but Customer.io's+# template engine (TinyMCE-backed) decodes them on output, defeating the+# defang. ZWSP is a real Unicode codepoint, so it survives JSON transit and+# the ESP's template rendering. It's invisible to the recipient, but breaks+# the `\w+\.\w+` and `[a-z]+://` patterns mail-client auto-linkers scan for.+_ZWSP = ""+++def _defang_match(match: "re.Match[str]") -> str:+ return match.group(0).replace(".", f".{_ZWSP}").replace(":", f":{_ZWSP}")+++def sanitize_email_string(value: str) -> str:+ """+ Sanitize a string for inclusion in email content (Customer.io+ `message_data` properties or Django email templates). Steps:++ 1. NFKC-normalize so fullwidth / compatibility forms can't bypass the+ URL regexes (e.g. `http://` → `http://`).+ 2. Strip zero-width / direction-override / line-separator characters that+ could hide URL structure (`evil.com` → `evil.com`). This runs *before*+ step 4 reintroduces zero-width spaces, so attacker-supplied invisibles+ can't survive but our defang ones can.+ 3. HTML-escape so any embedded markup renders as text in the final email.+ 4. Defang URL-shaped substrings: insert a zero-width space after each `.`+ and `:` inside a URL scheme (`https://`, `javascript:`, `www.`, ...) or+ a bare domain (`evil.com`) so mail clients do not auto-link them.++ Step 4 breaks the contiguous `\\w+\\.\\w+` / `[a-z]+://` patterns that+ mail-client auto-linkers scan for. The recipient still reads `evil.com`+ (the ZWSP is invisible) but the link is no longer clickable.+ """+ normalized = unicodedata.normalize("NFKC", value)+ cleaned = _INVISIBLE_CHAR_RE.sub("", normalized)+ escaped = html.escape(cleaned)+ # No `.` or `:` means neither regex can match — skip the two passes.+ if "." not in escaped and ":" not in escaped:+ return escaped+ defanged = _URL_SCHEME_RE.sub(_defang_match, escaped)+ return _BARE_DOMAIN_RE.sub(_defang_match, defanged)++class EmailNormalizer:@staticmethoddef normalize(email: str) -> str:diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.pyindex b2aab328f526..890a767dacf3 100644--- a/posthog/helpers/tests/test_email_utils.py+++ b/posthog/helpers/tests/test_email_utils.py@@ -19,6 +19,7 @@ from posthog.helpers.email_utils import (_get_esp_suppression_cache_key,check_esp_suppression,sanitize_display_name,+ sanitize_email_string,sanitize_message_body,validate_display_name,validate_message_body,@@ -325,6 +326,14 @@ class TestValidateDisplayName(SimpleTestCase):("trims", " Marius ", "Marius"),("empty", "", ""),("whitespace_only", " ", ""),+ # Bare domains are allowed — users legitimately set org names like+ # `google.com`. Render-time defang in `sanitize_email_string` neutralizes+ # mail-client auto-linking.+ ("bare_domain_org", "google.com", "google.com"),+ ("bare_domain_titlecase", "Acme.com", "Acme.com"),+ ("bare_domain_io", "mycompany.io", "mycompany.io"),+ ("bare_domain_subdomain", "sub.example.com", "sub.example.com"),+ ("bare_domain_embedded", "join evil.com now", "join evil.com now"),])def test_accepts(self, _name: str, value: str, expected: str) -> None:@@ -351,8 +360,6 @@ class TestValidateDisplayName(SimpleTestCase):("paragraph_separator", "foo\u2029bar", "invalid_control_char"),("next_line", "foo\u0085bar", "invalid_control_char"),("www_embedded", "myname www.scam.io", "invalid_url"),- ("bare_domain", "join evil.com now", "invalid_url"),- ("bare_domain_at_start", "Acme.com", "invalid_url"),("javascript_scheme", "click javascript:alert(1)", "invalid_url"),("data_scheme", "see data:text/html,x", "invalid_url"),("vbscript_scheme", "run vbscript:msgbox", "invalid_url"),@@ -424,6 +431,9 @@ class TestSanitizeDisplayName(SimpleTestCase):("plain", "Acme Inc", "Acme Inc"),("strips_whitespace", " Acme Inc ", "Acme Inc"),("unicode_name", "\u00c9mile", "\u00c9mile"),+ # Bare-domain org names round-trip; the defang happens later in+ # `sanitize_email_properties` at render time.+ ("bare_domain", "acme.com", "acme.com"),])def test_returns_validated_value(self, _name: str, value: str, expected: str) -> None:@@ -433,7 +443,6 @@ class TestSanitizeDisplayName(SimpleTestCase):[("url", "https://acme.example.com"),("www", "www.scam.io"),- ("bare_domain", "acme.com"),("javascript_scheme", "javascript:alert(1)"),("bracket", "<acme>"),("zero_width", "foo\u200bbar"),@@ -488,3 +497,68 @@ class TestSanitizeMessageBody(SimpleTestCase):# fallback so callers can rely on getting a non-None string back.self.assertEqual(sanitize_message_body(None), "")self.assertEqual(sanitize_message_body(""), "")+++class TestSanitizeEmailString(SimpleTestCase):+ @parameterized.expand(+ [+ # Plain text passes through (with html.escape only).+ ("plain", "Marius", "Marius"),+ ("apostrophe", "O'Brien", "O'Brien"),+ ("emoji", "Marius 🦔", "Marius 🦔"),+ ("hello_world", "Hello, world.", "Hello, world."),+ # Numeric / punctuation strings without a TLD aren't defanged.+ ("ip_v4", "192.168.1.1", "192.168.1.1"),+ ("time", "12:34", "12:34"),+ ("version", "v1.2.3", "v1.2.3"),+ # HTML is escaped — preserves existing sanitize_email_properties behavior.+ ("script_tag", "<script>x</script>", "<script>x</script>"),+ ("ampersand", "Ben & Jerry's", "Ben & Jerry's"),+ # URL-shaped substrings are defanged so mail clients don't auto-link.+ # `` is a zero-width space — invisible to the recipient but breaks the+ # `\w+\.\w+` / `[a-z]+://` patterns auto-linkers scan for. Chosen over HTML+ # entities because Customer.io's TinyMCE-backed template engine decodes+ # entities on output, defeating an entity-based defang.+ ("https_url", "Visit https://evil.com today", "Visit https://evil.com today"),+ ("http_url", "see http://phish.me/", "see http://phish.me/"),+ ("www_only", "go www.scam.io", "go www.scam.io"),+ ("bare_domain", "join evil.com now", "join evil.com now"),+ ("subdomain_domain", "join sub.evil.com today", "join sub.evil.com today"),+ ("deep_subdomain", "see a.b.c.example.io", "see a.b.c.example.io"),+ ("tld_only_legit_org", "Acme.com", "Acme.com"),+ ("javascript_scheme", "click javascript:alert(1)", "click javascript:alert(1)"),+ ("data_scheme", "see data:text/html,x", "see data:text/html,x"),+ ("ftp_scheme", "grab ftp://x.io", "grab ftp://x.io"),+ # Fullwidth / compatibility characters are NFKC-folded then defanged so+ # `http://evil.com` cannot bypass the URL regex.+ (+ "fullwidth_url",+ "go http://evil.com",+ "go http://evil.com",+ ),+ # Attacker-supplied zero-width / direction-override characters are stripped+ # before defang runs, so they can't hide URL structure (`evil.com` ->+ # `evil.com` -> defanged). Our defang then re-inserts ZWSPs.+ ("zero_width_in_domain", "evil.com", "evil.com"),+ ("rtl_override", "foobar", "foobar"),+ # Combined: HTML-escape an injected attribute that smuggles a URL scheme,+ # the scheme is then defanged (regression for the existing+ # `javascript:alert(1)` test in test_sanitize_email_properties).+ (+ "escaped_then_defanged",+ '<img src="x" onerror="javascript:alert(1)">',+ "<img src="x" onerror="javascript:alert(1)">",+ ),+ ]+ )+ def test_sanitizes(self, _name: str, value: str, expected: str) -> None:+ self.assertEqual(sanitize_email_string(value), expected)++ def test_empty_string(self) -> None:+ self.assertEqual(sanitize_email_string(""), "")++ def test_does_not_double_encode_already_escaped(self) -> None:+ # `&` survives a second pass — html.escape would re-encode the `&` in+ # the entity, which is the existing trade-off of running sanitize_email_string+ # over already-sanitized data. Documented as a guardrail.+ self.assertEqual(sanitize_email_string("&"), "&amp;")diff --git a/posthog/test/test_email.py b/posthog/test/test_email.pyindex e3495e791381..9a787901a2d6 100644--- a/posthog/test/test_email.py+++ b/posthog/test/test_email.py@@ -1,6 +1,7 @@import datetimeimport dataclassesfrom decimal import Decimal+from typing import Anyfrom uuid import UUIDfrom freezegun import freeze_time@@ -206,10 +207,11 @@ class TestEmail(BaseTest):self.assertEqual(sanitized["name"], "Test User"><img src=1 onerror=alert(1)>")self.assertEqual(sanitized["project_name"], "<script>alert("XSS")</script>")- # Check that nested dictionaries are sanitized+ # Check that nested dictionaries are sanitized — `javascript:` is defanged so+ # mail clients don't auto-link / treat it as a clickable scheme.self.assertEqual(sanitized["nested"]["html_content"],- "<b>Bold text</b><img src="x" onerror="javascript:alert(1)">",+ "<b>Bold text</b><img src="x" onerror="javascript:alert(1)">",)# Check that numbers and booleans are preserved@@ -226,6 +228,75 @@ class TestEmail(BaseTest):# Check that utm_tags are not sanitized (to preserve valid URL query parameters)self.assertEqual(sanitized["utm_tags"], "utm_source=posthog&utm_medium=email&utm_campaign=test")+ def test_sanitize_email_properties_preserves_trusted_url_keys(self) -> None:+ # Clean PostHog-built URLs survive sanitization unchanged: html.escape is a+ # no-op on URL-shape characters (`:` `/` `.`), and trusted URL keys skip the+ # defang step so the link stays clickable.+ section: dict[str, str] = {"team_url": "https://app.posthog.com/project/3", "team_name": "Acme.com"}+ properties: dict[str, Any] = {+ "href": "http://localhost:8010/replay/test#panel=discussion",+ "url": "https://app.posthog.com/project/1/insights",+ "site_url": "https://app.posthog.com",+ "link": "/reset/uuid/token",+ "next_url": "https://app.posthog.com/dashboard",+ "dashboard_url": "https://app.posthog.com/dashboard/2",+ "error_tracking_url": "https://app.posthog.com/error_tracking",+ "verify_link": "/verify/abc",+ "section": section,+ }++ sanitized = sanitize_email_properties(properties)++ for key in [+ "href",+ "url",+ "site_url",+ "link",+ "next_url",+ "dashboard_url",+ "error_tracking_url",+ "verify_link",+ ]:+ self.assertEqual(sanitized[key], properties[key], f"trusted URL key {key} should pass through")+ self.assertEqual(sanitized["section"]["team_url"], section["team_url"])+ # ...but a user-controlled name nested under a non-URL key still gets defanged.+ self.assertEqual(sanitized["section"]["team_name"], "Acme.com")++ def test_sanitize_email_properties_html_escapes_trusted_url_keys(self) -> None:+ # When a user-controlled fragment leaks into a trusted URL key (e.g. the+ # comment `slug` appended to settings.SITE_URL in build_comment_item_url),+ # attribute-injection characters are still escaped — the link works, but+ # the attacker can't break out of `<a href="...">`. URL-shape chars+ # (`:` `/` `.`) survive because we don't defang trusted keys.+ properties = {+ "href": 'https://app.posthog.com/x"><script>alert(1)</script>',+ "verify_link": "https://app.posthog.com/x?a=1&b=2",+ }++ sanitized = sanitize_email_properties(properties)++ self.assertEqual(+ sanitized["href"],+ "https://app.posthog.com/x"><script>alert(1)</script>",+ )+ # `&` becomes `&` — correct HTML attribute encoding for query strings.+ self.assertEqual(sanitized["verify_link"], "https://app.posthog.com/x?a=1&b=2")++ def test_sanitize_email_properties_defangs_urls_embedded_in_user_content(self) -> None:+ # Realistic phishing-by-display-name: attacker sets first_name to a URL.+ # Mail clients should not auto-link this.+ properties = {+ "commenter": {"first_name": "Visit https://evil.com NOW"},+ "team": {"name": "evil.com"},+ "organization_name": "http://phish.io", # fullwidth bypass attempt+ }++ sanitized = sanitize_email_properties(properties)++ self.assertEqual(sanitized["commenter"]["first_name"], "Visit https://evil.com NOW")+ self.assertEqual(sanitized["team"]["name"], "evil.com")+ self.assertEqual(sanitized["organization_name"], "http://phish.io")+def test_sanitize_email_properties_handles_dataclasses(self) -> None:# Regression test: facade contracts (frozen dataclasses) used to raise TypeError,# silently killing tasks like send_error_tracking_issue_assigned via autoretry.