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.

chore(utils): normalize URL authority parsing consistency (#60482)

Tom Piccirello2cddb035ed24
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 4405f7673b09..a1b4854a24c9 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -2877,6 +2877,25 @@ class TestLocalhostLoopbackRedirectUri(APIBaseTest):
# DOT returns a redirect with error params or an error response
self.assertNotEqual(response.status_code, status.HTTP_200_OK)
+ @parameterized.expand(
+ [
+ # urlparse sees hostname='localhost' so the portless reconstruction matches the
+ # registered URI, but the browser following the redirect interprets the backslash
+ # as a path separator and delivers the authorization code to evil.example.
+ ("raw_backslash", "http://evil.example\\@localhost:50470/callback"),
+ # Same trick with the percent-encoded form `%5c`.
+ ("percent_encoded_backslash", "http://evil.example%5C@localhost:50470/callback"),
+ ]
+ )
+ def test_backslash_authority_bypass_in_localhost_redirect_rejected(self, _name, redirect_uri):
+ auth_url = (
+ f"/oauth/authorize/?client_id=test_localhost_client_id"
+ f"&redirect_uri={redirect_uri}"
+ f"&response_type=code&code_challenge={self.code_challenge}&code_challenge_method=S256"
+ )
+ response = self.client.get(auth_url)
+ self.assertNotEqual(response.status_code, status.HTTP_200_OK)
+
def test_non_localhost_port_mismatch_still_rejected(self):
"""Port flexibility only applies to loopback addresses, not arbitrary hosts."""
https_app = OAuthApplication.objects.create(
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 7959577efacb..62072626b68f 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -48,6 +48,7 @@ from posthog.middleware import is_read_only_impersonation
from posthog.models import OAuthAccessToken, OAuthApplication, Team, User
from posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken
from posthog.scopes import downgrade_scopes_to_read_only, get_oauth_scopes_supported
+from posthog.security.url_validation import has_authority_bypass_chars
from posthog.user_permissions import UserPermissions
from posthog.utils import render_template
from posthog.views import login_required
@@ -253,6 +254,9 @@ class OAuthValidator(OAuth2Validator):
http://localhost/callback and request http://localhost:<ephemeral>/callback.
"""
+ if has_authority_bypass_chars(redirect_uri):
+ return False
+
if request.client.redirect_uri_allowed(redirect_uri):
return True
diff --git a/posthog/api/test/test_toolbar_oauth_primitives.py b/posthog/api/test/test_toolbar_oauth_primitives.py
index 19fc161f735e..c2f323855ab2 100644
--- a/posthog/api/test/test_toolbar_oauth_primitives.py
+++ b/posthog/api/test/test_toolbar_oauth_primitives.py
@@ -602,3 +602,17 @@ class TestNormalizeAndValidateAppUrl(APIBaseTest):
with self.assertRaises(ToolbarOAuthError) as cm:
normalize_and_validate_app_url(self.team, "example.com/page")
assert cm.exception.code == "invalid_app_url"
+
+ @parameterized.expand(
+ [
+ # urlparse sees hostname='example.com' (the allowed domain), but a browser
+ # following the redirect treats `\` as a path separator and routes to
+ # attacker.example, leaking the toolbar OAuth code.
+ ("raw_backslash", "https://attacker.example\\@example.com/page"),
+ ("percent_encoded_backslash", "https://attacker.example%[email protected]/page"),
+ ]
+ )
+ def test_rejects_backslash_authority_bypass(self, _name, app_url):
+ with self.assertRaises(ToolbarOAuthError) as cm:
+ normalize_and_validate_app_url(self.team, app_url)
+ assert cm.exception.code == "forbidden_app_url"
diff --git a/posthog/api/utils.py b/posthog/api/utils.py
index fbc84965e52e..5440b32985eb 100644
--- a/posthog/api/utils.py
+++ b/posthog/api/utils.py
@@ -39,6 +39,7 @@ from posthog.models.activity_logging.activity_log import Detail, changes_between
from posthog.models.entity import MathType
from posthog.models.filters.filter import Filter
from posthog.models.filters.stickiness_filter import StickinessFilter
+from posthog.security.url_validation import has_authority_bypass_chars
from posthog.utils import load_data_from_request
from posthog.utils_cors import cors_response
@@ -468,6 +469,8 @@ class PublicIPOnlyHttpAdapter(HTTPAdapter):
def unparsed_hostname_in_allowed_url_list(allowed_url_list: Optional[list[str]], hostname: Optional[str]) -> bool:
+ if hostname and has_authority_bypass_chars(hostname):
+ return False
# if the browser url encodes the hostname, we need to decode it first
hostname = urlparse(urllib.parse.unquote(hostname)).hostname if hostname else hostname
return hostname_in_allowed_url_list(allowed_url_list, hostname)
diff --git a/posthog/security/test/test_url_validation.py b/posthog/security/test/test_url_validation.py
index 281ed575fd08..32d853d11fa3 100644
--- a/posthog/security/test/test_url_validation.py
+++ b/posthog/security/test/test_url_validation.py
@@ -183,3 +183,37 @@ class TestUrlValidation:
monkeypatch.setattr(uv, "resolve_host_ips", fake_resolve)
ok, err = uv.is_url_allowed("http://xn--n3h.com/")
assert ok and err is None
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ # urlparse extracts "example.com", but requests/urllib3 connect to 169.254.169.254.
+ "http://169.254.169.254\\@example.com/latest/meta-data/",
+ # Same trick, percent-encoded backslash. Browsers decode and follow to localhost.
+ "http://localhost%[email protected]/",
+ "http://127.0.0.1\\@example.com/",
+ "https://attacker.com\\@example.com/",
+ ],
+ )
+ def test_backslash_authority_bypass_blocked(self, url, monkeypatch):
+ """Backslash (raw or %5c) before @ breaks urlparse-vs-client agreement on the host."""
+
+ def fake_resolve(host: str):
+ return {ipaddress.ip_address("93.184.216.34")}
+
+ monkeypatch.setattr(uv, "resolve_host_ips", fake_resolve)
+ ok, err = uv.is_url_allowed(url)
+ assert not ok
+ assert err == "Invalid URL: ambiguous authority"
+
+ @pytest.mark.parametrize(
+ "url,expected",
+ [
+ ("http://example.com/", False),
+ ("http://example.com/path\\with-backslash", True),
+ ("http://example.com%5Cpath", True),
+ ("http://attacker.com\\@example.com", True),
+ ],
+ )
+ def test_has_authority_bypass_chars(self, url, expected):
+ assert uv.has_authority_bypass_chars(url) is expected
diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.py
index 2f9a39645fd1..14e0449b903a 100644
--- a/posthog/security/url_validation.py
+++ b/posthog/security/url_validation.py
@@ -89,6 +89,25 @@ def _is_private_ip_literal(host: str) -> bool:
)
+def has_authority_bypass_chars(url: str) -> bool:
+ """
+ Detect characters that produce a parser-vs-client disagreement on the URL authority.
+
+ ``urllib.parse.urlparse`` treats ``\\`` before ``@`` as part of the userinfo and
+ returns the host after the ``@``, while ``requests``/``urllib3`` and browsers
+ interpret ``\\`` as the end of the authority (a path separator) and connect to
+ the host before it. ``%5c`` decodes to ``\\`` and produces the same divergence.
+
+ URLs containing these characters cannot be safely validated by host, because
+ the validated host differs from the host the client will actually connect to.
+ """
+ if "\\" in url:
+ return True
+ if "%5c" in url.lower():
+ return True
+ return False
+
+
def _dev_bypass_enabled() -> bool:
"""
Dev mode short-circuits is_url_allowed unless POSTHOG_FORCE_URL_VALIDATION is set.
@@ -142,6 +161,8 @@ def _validate_url_with_ips(
logger.warning("url_validation.blocked", reason=reason, **log_kwargs)
return False, reason, empty
+ if has_authority_bypass_chars(raw_url):
+ return _blocked("Invalid URL: ambiguous authority")
try:
u = urlparse.urlparse(raw_url)
except Exception:
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index 1f6018e5efbd..bb43fbbaa409 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -121,6 +121,19 @@ class TestAbsoluteUrls(TestCase):
with pytest.raises(PotentialSecurityProblemException):
(absolute_uri("https://an.external.domain.com/something-outside-posthog"),)
+ @parameterized.expand(
+ [
+ # `urlparse` returns hostname='app.posthog.com' so the SITE_URL host check
+ # passes, but HTTP clients/browsers route to attacker.example.
+ ("raw_backslash", "https://attacker.example\\@app.posthog.com/path"),
+ ("percent_encoded_backslash", "https://attacker.example%[email protected]/path"),
+ ]
+ )
+ def test_absolute_uri_rejects_backslash_authority_bypass(self, _name: str, url: str) -> None:
+ with self.settings(SITE_URL="https://app.posthog.com"):
+ with pytest.raises(PotentialSecurityProblemException):
+ absolute_uri(url)
+
class TestFormatUrls(TestCase):
factory = RequestFactory()
diff --git a/posthog/utils.py b/posthog/utils.py
index a2a56381cde5..acfa1ea5b1ed 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -59,6 +59,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.git import get_git_branch, get_git_commit_short
from posthog.metrics import KLUDGES_COUNTER
from posthog.redis import get_client
+from posthog.security.url_validation import has_authority_bypass_chars
tracer = trace.get_tracer(__name__)
@@ -120,6 +121,9 @@ def absolute_uri(url: Optional[str] = None) -> str:
if not url:
return settings.SITE_URL
+ if has_authority_bypass_chars(url):
+ raise PotentialSecurityProblemException(f"It is forbidden to provide an absolute URI using {url}")
+
provided_url = urlparse(url)
if provided_url.hostname and provided_url.scheme:
site_url = urlparse(settings.SITE_URL)
diff --git a/products/conversations/backend/api/serializers.py b/products/conversations/backend/api/serializers.py
index f5e132d796bf..e3af1d359abc 100644
--- a/products/conversations/backend/api/serializers.py
+++ b/products/conversations/backend/api/serializers.py
@@ -7,6 +7,7 @@ from rest_framework import serializers
from posthog.api.utils import on_permitted_recording_domain
from posthog.models import Team
+from posthog.security.url_validation import has_authority_bypass_chars
from products.conversations.backend.models import TicketAssignment
from products.conversations.backend.models.constants import Status
@@ -207,6 +208,9 @@ def validate_url_domain(url: str, team: Team) -> bool:
if not domains:
return False
+ if has_authority_bypass_chars(url):
+ return False
+
parsed = urlparse(url)
url_host = (parsed.hostname or parsed.netloc).lower()
if not url_host:
@@ -245,6 +249,10 @@ def validate_url_matches_request_origin(request, url: str) -> bool:
"""
origin = request.headers.get("Origin") or request.headers.get("Referer") or ""
+
+ if has_authority_bypass_chars(url):
+ return False
+
parsed_url = urlparse(url)
# Restrict request_url scheme — exotic schemes (javascript:, data:, file:) have
diff --git a/products/conversations/backend/api/tests/test_restore.py b/products/conversations/backend/api/tests/test_restore.py
index 404da4f051de..b9800cb0a8fa 100644
--- a/products/conversations/backend/api/tests/test_restore.py
+++ b/products/conversations/backend/api/tests/test_restore.py
@@ -552,6 +552,47 @@ class TestRestoreAPI(BaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
mock_send_email.delay.assert_called_once()
+ @parameterized.expand(
+ [
+ # urlparse sees hostname='allowed.com', so a naive check would accept this.
+ # The browser following the emailed link decodes `\` as a path separator and
+ # delivers the restore token to attacker.example.
+ ("raw_backslash", "https://attacker.example\\@allowed.com/support"),
+ ("percent_encoded_backslash", "https://attacker.example%[email protected]/support"),
+ ]
+ )
+ @patch("products.conversations.backend.api.restore.RestoreRequestThrottle.allow_request", return_value=True)
+ @patch("products.conversations.backend.api.restore.validate_origin", return_value=True)
+ @patch("products.conversations.backend.api.restore.send_conversation_restore_email")
+ def test_restore_request_rejects_backslash_authority_bypass(
+ self,
+ _name,
+ request_url,
+ mock_send_email,
+ mock_validate_origin,
+ mock_throttle,
+ ):
+ self.team.conversations_settings = {
+ "widget_public_token": self.widget_token,
+ "widget_domains": ["allowed.com"],
+ }
+ self.team.save()
+ Ticket.objects.create_with_number(
+ team=self.team,
+ widget_session_id=self.widget_session_id,
+ distinct_id="user-1",
+ anonymous_traits={"email": self.customer_email},
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/widget/restore/request",
+ {"email": self.customer_email, "request_url": request_url},
+ **self._get_headers(origin="https://allowed.com"),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ mock_send_email.delay.assert_not_called()
+
def test_restore_redeem_success(self):
old_session_id = str(uuid.uuid4())
new_session_id = str(uuid.uuid4())