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(api): tighten URL host validation (#74432)

Tom Piccirello0b5b22b01f80
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 5f920e2a1b1d..f61bdb3df769 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -4202,6 +4202,23 @@ class TestLocalhostLoopbackRedirectUri(APIBaseTest):
response = self.client.get(auth_url)
self.assertNotEqual(response.status_code, status.HTTP_200_OK)
+ @parameterized.expand(
+ [
+ ("percent_encoded_slash", "http://evil.example%2F@localhost:50470/callback"),
+ ("percent_encoded_question_mark", "http://evil.example%3F@localhost:50470/callback"),
+ ("percent_encoded_hash", "http://evil.example%23@localhost:50470/callback"),
+ ("percent_encoded_at", "http://evil.example%40@localhost:50470/callback"),
+ ]
+ )
+ def test_encoded_authority_terminator_in_localhost_redirect_rejected(self, _name, redirect_uri):
+ # urlparse reads hostname='localhost', so the portless reconstruction matches the
+ # registered URI and the port-flexibility branch approves the request. A client that
+ # decodes before splitting the authority delivers the code to evil.example instead.
+ # Asserted against the validator rather than the /authorize response because an
+ # unbuilt frontend also produces a non-200 there.
+ request = SimpleNamespace(client=self.localhost_app)
+ assert OAuthValidator().validate_redirect_uri("test_localhost_client_id", redirect_uri, request) is False
+
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/toolbar_service.py b/posthog/api/oauth/toolbar_service.py
index 5c2669ceba54..8b15e835747a 100644
--- a/posthog/api/oauth/toolbar_service.py
+++ b/posthog/api/oauth/toolbar_service.py
@@ -22,7 +22,7 @@ from django.db import transaction
import requests
import structlog
-from posthog.api.utils import unparsed_hostname_in_allowed_url_list
+from posthog.api.utils import canonicalize_encoded_url, strip_url_userinfo, unparsed_hostname_in_allowed_url_list
from posthog.models import Team, User
from posthog.models.oauth import OAuthApplication, is_loopback_host
from posthog.models.organization import Organization
@@ -101,6 +101,9 @@ class ToolbarOAuthState:
def normalize_and_validate_app_url(team: Team, app_url: str) -> str:
+ # Everything below - the scheme checks, the allowlist check, and the returned redirect target -
+ # has to see the same URL, so canonicalize before any of them run.
+ app_url = canonicalize_encoded_url(app_url)
try:
parsed = urlparse(app_url)
except ValueError as exc:
@@ -122,6 +125,9 @@ def normalize_and_validate_app_url(team: Team, app_url: str) -> str:
403,
)
+ app_url = strip_url_userinfo(app_url)
+ parsed = urlparse(app_url)
+
# Strip __posthog and __posthog_toolbar hash params — posthog-js toolbar
# launch params must not survive the OAuth round-trip or they cause a
# re-initialization loop, and leftover __posthog_toolbar params cause
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index b500e0efc32b..79f2dd67323d 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -71,7 +71,7 @@ from posthog.scopes import (
resolve_ceiling,
scopes_outside_ceiling,
)
-from posthog.security.url_validation import has_authority_bypass_chars
+from posthog.security.url_validation import has_ambiguous_authority
from posthog.user_permissions import UserPermissions
from posthog.utils import absolute_uri, render_template
from posthog.views import login_required
@@ -423,7 +423,9 @@ class OAuthValidator(OAuth2Validator):
http://localhost/callback and request http://localhost:<ephemeral>/callback.
"""
- if has_authority_bypass_chars(redirect_uri):
+ # The authorization code is delivered to this URI as given, with no userinfo stripped,
+ # so the authority has to be unambiguous rather than merely parseable.
+ if has_ambiguous_authority(redirect_uri):
return False
if request.client.redirect_uri_allowed(redirect_uri):
diff --git a/posthog/api/test/test_toolbar_oauth_primitives.py b/posthog/api/test/test_toolbar_oauth_primitives.py
index 364f2e3a72e6..f2336bafd023 100644
--- a/posthog/api/test/test_toolbar_oauth_primitives.py
+++ b/posthog/api/test/test_toolbar_oauth_primitives.py
@@ -610,6 +610,18 @@ class TestNormalizeAndValidateAppUrl(APIBaseTest):
normalize_and_validate_app_url(self.team, "example.com/page")
assert cm.exception.code == "invalid_app_url"
+ @parameterized.expand(
+ [
+ ("unterminated_ipv6_literal", "https://[::1"),
+ ("nfkc_unstable_host", "https://exa℀mple.com/"),
+ ]
+ )
+ def test_rejects_unparseable_app_url(self, _name, app_url):
+ with self.assertRaises(ToolbarOAuthError) as cm:
+ normalize_and_validate_app_url(self.team, app_url)
+ assert cm.exception.code == "invalid_app_url"
+ assert cm.exception.status_code == 400
+
@parameterized.expand(
[
# urlparse sees hostname='example.com' (the allowed domain), but a browser
@@ -617,9 +629,19 @@ class TestNormalizeAndValidateAppUrl(APIBaseTest):
# attacker.example, leaking the toolbar OAuth code.
("raw_backslash", "https://attacker.example\\@example.com/page"),
("percent_encoded_backslash", "https://attacker.example%[email protected]/page"),
+ # Percent-encoded authority terminators: decoded, the authority ends before
+ # the `@`, so the browser lands on attacker.example with the OAuth code.
+ ("percent_encoded_slash", "https://example.com%[email protected]/page"),
+ ("percent_encoded_question_mark", "https://example.com%[email protected]/page"),
+ ("percent_encoded_hash", "https://example.com%[email protected]/page"),
]
)
- def test_rejects_backslash_authority_bypass(self, _name, app_url):
+ def test_rejects_ambiguous_authority(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"
+
+ def test_strips_userinfo_from_returned_app_url(self):
+ assert (
+ normalize_and_validate_app_url(self.team, "https://[email protected]/page") == "https://example.com/page"
+ )
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 45763136a30f..d686cfe3297d 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -2,7 +2,7 @@ import uuid
import datetime
from datetime import timedelta
from typing import cast
-from urllib.parse import quote, unquote
+from urllib.parse import quote, unquote, urlparse
import pytest
from freezegun.api import freeze_time
@@ -1746,6 +1746,53 @@ class TestUserAPI(APIBaseTest):
assert_allowed_url("https://subdomain.otherexample.com")
assert_allowed_url("https://sub.subdomain.otherexample.com")
+ @parameterized.expand(
+ [
+ ("encoded_slash", "%2F"),
+ ("encoded_question_mark", "%3F"),
+ ("encoded_hash", "%23"),
+ ("raw_backslash", "\\"),
+ ]
+ )
+ def test_redirect_to_site_rejects_encoded_authority_terminator(self, _name: str, terminator: str) -> None:
+ self.team.app_urls = ["https://www.example.com"]
+ self.team.save()
+
+ app_url = f"https://www.example.com{terminator}@evil.example.net/"
+ response = self.client.get(f"/api/user/redirect_to_site/?appUrl={quote(app_url, safe='')}")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.headers.get("location") is None
+
+ @parameterized.expand(
+ [
+ ("unterminated_ipv6_literal", "https://[::1"),
+ ("nfkc_unstable_host", "https://exa℀mple.com/"),
+ ]
+ )
+ def test_redirect_to_site_rejects_an_unparseable_app_url(self, _name: str, app_url: str) -> None:
+ self.team.app_urls = ["https://www.example.com"]
+ self.team.save()
+
+ response = self.client.get(f"/api/user/redirect_to_site/?appUrl={quote(app_url, safe='')}")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.headers.get("location") is None
+
+ @parameterized.expand([("http", "http%3A%2F%2Fwww.example.com"), ("https", "https%3A%2F%2Fwww.example.com")])
+ def test_redirect_to_site_accepts_a_fully_encoded_app_url(self, _name: str, encoded: str) -> None:
+ # Some browsers encode the whole redirect target (#23504). The redirect has to go to the
+ # decoded form, so the URL that passed the allowlist is the URL the browser resolves.
+ self.team.app_urls = ["https://www.example.com"]
+ self.team.save()
+
+ response = self.client.get(f"/api/user/redirect_to_site/?appUrl={quote(encoded, safe='')}")
+
+ assert response.status_code == status.HTTP_302_FOUND
+ location = response.headers["location"]
+ assert location.startswith("http")
+ assert urlparse(location).hostname == "www.example.com"
+
@patch("posthog.api.user.secrets.token_urlsafe")
@patch("posthog.api.user.get_flags_from_service")
def test_prepare_toolbar_preloaded_flags_with_feature_flags(self, mock_get_flags, patched_token):
diff --git a/posthog/api/test/test_utils.py b/posthog/api/test/test_utils.py
index 358c5628cff0..076402910744 100644
--- a/posthog/api/test/test_utils.py
+++ b/posthog/api/test/test_utils.py
@@ -3,6 +3,7 @@ import requests
from typing import Any, cast
from django.http import HttpRequest
+from django.test import SimpleTestCase
from django.test.client import RequestFactory
from parameterized import parameterized
from rest_framework import status
@@ -10,6 +11,7 @@ from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.api.utils import (
PaginationMode,
+ canonicalize_encoded_url,
check_definition_ids_inclusion_field_sql,
format_paginated_url,
get_data,
@@ -21,6 +23,7 @@ from posthog.api.utils import (
safe_clickhouse_string,
validate_authorized_url_wildcards,
PublicIPOnlyHttpAdapter,
+ strip_url_userinfo,
unparsed_hostname_in_allowed_url_list,
)
from posthog.models.filters.filter import Filter
@@ -31,6 +34,41 @@ def return_true():
return True
+class TestAppUrlCanonicalization(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("fully encoded url is decoded", "https%3A%2F%2Fexample.com%2Fpage", "https://example.com/page"),
+ # Decoding a URL that already has an authority is what let an encoded terminator
+ # smuggle in a second host, so a parseable URL has to come back untouched.
+ (
+ "url with an authority is untouched",
+ "https://example.com%[email protected]/",
+ "https://example.com%[email protected]/",
+ ),
+ ("double encoded url stays encoded", "https%253A%252F%252Fexample.com", "https%253A%252F%252Fexample.com"),
+ # Callers run this before their own urlparse, so it has to hand malformed input
+ # back rather than raise and turn a 400 into a 500.
+ ("unterminated ipv6 literal", "https://[::1", "https://[::1"),
+ ("nfkc unstable host", "https://exa℀mple.com/", "https://exa℀mple.com/"),
+ ]
+ )
+ def test_canonicalize_encoded_url(self, _name: str, url: str, expected: str) -> None:
+ assert canonicalize_encoded_url(url) == expected
+
+ @parameterized.expand(
+ [
+ ("userinfo is removed", "https://someone:[email protected]/page", "https://example.com/page"),
+ ("port is kept", "https://[email protected]:8443/page", "https://example.com:8443/page"),
+ # urlparse resolves the host after the *last* "@", so splitting on the first one
+ # would hand back a different host than the one the allowlist approved.
+ ("only the last delimiter splits", "https://a@[email protected]/page", "https://example.com/page"),
+ ("url without userinfo is untouched", "https://example.com/page", "https://example.com/page"),
+ ]
+ )
+ def test_strip_url_userinfo(self, _name: str, url: str, expected: str) -> None:
+ assert strip_url_userinfo(url) == expected
+
+
class TestUtils(BaseTest):
def test_get_data(self):
# No data in request
@@ -320,7 +358,24 @@ class TestUtils(BaseTest):
("needle is whitespace", ["http://localhost"], " ", False),
("needle is absent", ["http://localhost"], None, False),
("single element matches", ["http://localhost"], "http://localhost:8123", True),
- ("single element matches but is url encoded", ["http://localhost"], "http%3A%2F%2Flocalhost:8123", True),
+ # A needle encoded whole has no authority to judge, so it is decoded once and the
+ # decoded form is both validated and redirected to. See #23504.
+ ("fully encoded needle is decoded", ["http://localhost"], "http%3A%2F%2Flocalhost:8123", True),
+ (
+ "fully encoded needle still has to match the allowlist",
+ ["http://localhost"],
+ "http%3A%2F%2Fevil.example",
+ False,
+ ),
+ # The decode only applies when there is no authority. A needle that already parses to a
+ # host is judged as-is, so a percent-encoded authority terminator cannot smuggle one in.
+ (
+ "encoded terminator in an authority is not decoded",
+ ["https://localhost"],
+ "https://localhost%[email protected]/",
+ False,
+ ),
+ ("url encoded dot in host", ["https://example.com"], "https://example%2Ecom/", False),
("multi element matches", ["http://localhost", "http://posthog.com"], "http://localhost:8123", True),
("scheme should be ignored", ["ftp://localhost"], "https://localhost:8123", True),
("needle is not in allowlist", ["http://localhost"], "http://posthog.com:8123", False),
@@ -335,6 +390,30 @@ class TestUtils(BaseTest):
"https://www.other.com",
False,
),
+ (
+ "encoded slash terminates the authority early",
+ ["https://example.com"],
+ "https://example.com%[email protected]/",
+ False,
+ ),
+ (
+ "encoded question mark terminates the authority early",
+ ["https://example.com"],
+ "https://example.com%[email protected]/",
+ False,
+ ),
+ (
+ "encoded hash terminates the authority early",
+ ["https://example.com"],
+ "https://example.com%[email protected]/",
+ False,
+ ),
+ (
+ "encoded characters outside the authority are ignored",
+ ["https://example.com"],
+ "https://example.com/inbox?to=someone%40evil.test",
+ True,
+ ),
]
)
def test_unparsed_hostname_in_allowed_url_list(
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 4c78ee846168..153c979af5e8 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -61,7 +61,13 @@ from posthog.api.oauth.toolbar_service import (
from posthog.api.organization import OrganizationSerializer
from posthog.api.services.flags_service import get_flags_from_service
from posthog.api.shared import OrganizationBasicSerializer, TeamBasicSerializer
-from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action, unparsed_hostname_in_allowed_url_list
+from posthog.api.utils import (
+ ClassicBehaviorBooleanFieldSerializer,
+ action,
+ canonicalize_encoded_url,
+ strip_url_userinfo,
+ unparsed_hostname_in_allowed_url_list,
+)
from posthog.auth import (
IDJagAccessTokenAuthentication,
OAuthAccessTokenAuthentication,
@@ -1839,8 +1845,12 @@ def redirect_to_site(request):
if not unparsed_hostname_in_allowed_url_list(team.app_urls, app_url):
REDIRECT_TO_SITE_FAILED_COUNTER.inc()
- parsed_app_url = urllib.parse.urlparse(app_url)
- hostname = parsed_app_url.hostname or app_url
+ try:
+ hostname = urllib.parse.urlparse(app_url).hostname or app_url
+ except ValueError:
+ # A URL too malformed to parse is still a rejection, so report it back as typed
+ # rather than failing the request with a 500.
+ hostname = app_url
logger.error(
"can_only_redirect_to_permitted_domain",
permitted_domains=team.app_urls,
@@ -1862,6 +1872,10 @@ def redirect_to_site(request):
},
status_code=403,
)
+
+ # Redirect to the form that was approved, not the caller's raw string.
+ app_url = strip_url_userinfo(canonicalize_encoded_url(app_url))
+
params = {
"action": "ph_authorize",
"token": team.api_token,
diff --git a/posthog/api/utils.py b/posthog/api/utils.py
index 308483dc8f3c..c2c89c5b7de0 100644
--- a/posthog/api/utils.py
+++ b/posthog/api/utils.py
@@ -40,7 +40,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.security.url_validation import has_ambiguous_authority
from posthog.utils import load_data_from_request
from posthog.utils_cors import cors_response
@@ -498,12 +498,51 @@ class PublicIPOnlyHttpAdapter(HTTPAdapter):
}
+def canonicalize_encoded_url(url: str) -> str:
+ """Decode a URL that arrived fully percent-encoded, so it has an authority to validate.
+
+ Some browsers encode a whole redirect target, turning ``https://permitted.example`` into
+ ``https%3A%2F%2Fpermitted.example`` — a string that parses to no host at all.
+
+ Only a string with no host is decoded, and only once. Decoding a URL that already has an
+ authority is what lets ``https://permitted.example%[email protected]/`` be approved as
+ ``permitted.example`` while a browser resolves ``evil.example``, so that case is left alone.
+ Callers must redirect to what this returns, not to what they passed in, because approving the
+ decoded form and emitting the raw one would reintroduce the same split.
+
+ Callers run their own ``urlparse`` after this and turn its ``ValueError`` into a 400, so a URL
+ that cannot be parsed at all is handed back untouched rather than raised on here.
+ """
+ try:
+ if urlparse(url).hostname:
+ return url
+ decoded = urllib.parse.unquote(url)
+ return decoded if urlparse(decoded).hostname else url
+ except ValueError:
+ return url
+
+
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):
+ if not hostname:
+ return hostname_in_allowed_url_list(allowed_url_list, hostname)
+ candidate = canonicalize_encoded_url(hostname)
+ if has_ambiguous_authority(candidate):
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)
+ return hostname_in_allowed_url_list(allowed_url_list, urlparse(candidate).hostname)
+
+
+def strip_url_userinfo(url: str) -> str:
+ """
+ Rebuild ``url`` so its authority holds only the host and port.
+
+ Redirect targets are approved on the strength of their host, so echoing the
+ caller's authority back keeps a ``user@`` prefix that the approval never looked at.
+ """
+ parsed = urlparse(url)
+ if "@" not in parsed.netloc:
+ return url
+ # urlparse derives the host the same way, by taking everything after the last "@".
+ return urllib.parse.urlunparse(parsed._replace(netloc=parsed.netloc.rpartition("@")[2]))
def _strip_www(host: str) -> str:
diff --git a/posthog/security/test/test_url_validation.py b/posthog/security/test/test_url_validation.py
index d88cb242449b..e2ab20d0f9e4 100644
--- a/posthog/security/test/test_url_validation.py
+++ b/posthog/security/test/test_url_validation.py
@@ -134,6 +134,27 @@ class TestUrlValidation:
ok, err = uv.is_url_allowed("https://example.com/path")
assert ok and err is None
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://user%40corp.example:[email protected]/path",
+ "https://user:p%[email protected]/path",
+ "https://user:p%[email protected]/path",
+ "https://user:p%[email protected]/path",
+ ],
+ )
+ def test_is_url_allowed_permits_percent_encoded_credentials(self, url, monkeypatch):
+ # Integrations and warehouse sources supply connection URLs with basic auth, and an
+ # email username or a password holding a reserved character has to percent-encode it.
+ # Every parser resolves these to example.com, so the fetch path takes the lenient
+ # rule. Swapping it for has_ambiguous_authority would break all of them.
+ 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 ok and err is None
+
@pytest.mark.parametrize(
"url,blocked",
[
@@ -284,7 +305,43 @@ class TestUrlValidation:
("http://example.com/path\\with-backslash", True),
("http://example.com%5Cpath", True),
("http://attacker.com\\@example.com", True),
+ # Percent-encoded credentials are ordinary basic auth. Every parser resolves
+ # these to example.com, so blocking them would break outbound fetches that
+ # carry an email username or a password containing a reserved character.
+ ("https://user%40corp.example:[email protected]/path", False),
+ ("https://user:p%[email protected]/path", False),
+ ("https://user:p%[email protected]/path", False),
],
)
def test_has_authority_bypass_chars(self, url, expected):
assert uv.has_authority_bypass_chars(url) is expected
+
+ @pytest.mark.parametrize(
+ "url,expected",
+ [
+ # A consumer that percent-decodes before splitting the authority sees it end
+ # at the terminator, landing on a different host than urlparse reports.
+ ("https://example.com%[email protected]/", True),
+ ("https://example.com%[email protected]/", True),
+ ("https://example.com%[email protected]/", True),
+ ("https://example.com%[email protected]/", True),
+ ("https://example.com%2Fpath", True),
+ # Credentials are legitimate on a fetch but not on a URL we hand back, and
+ # the encoded characters in them are exactly what makes the authority
+ # ambiguous, so the strict rule rejects them where the lenient one allows.
+ ("https://user%40corp.example:[email protected]/path", True),
+ # The strict rule subsumes the backslash cases.
+ ("http://attacker.com\\@example.com", True),
+ ("http://example.com%5Cpath", True),
+ ("https://example.com/", False),
+ # The same sequences outside the authority are ordinary encoded data.
+ ("https://example.com/repos/group%2Fproject", False),
+ ("https://example.com/send?to=someone%40example.com", False),
+ ("https://example.com/search#q=a%23b", False),
+ # Unparseable authorities fail closed rather than raising.
+ ("https://[::1", True),
+ ("https://exa℀mple.com/", True),
+ ],
+ )
+ def test_has_ambiguous_authority(self, url, expected):
+ assert uv.has_ambiguous_authority(url) is expected
diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.py
index 965b41e8afea..c6f5e3f6f688 100644
--- a/posthog/security/url_validation.py
+++ b/posthog/security/url_validation.py
@@ -31,6 +31,9 @@ DISALLOWED_SCHEMES = {"file", "ftp", "gopher", "ws", "wss", "data", "javascript"
# Cloud metadata service hosts that should be blocked to prevent SSRF
METADATA_HOSTS = {"169.254.169.254", "metadata.google.internal"}
+# Percent-encoded forms of the characters that end a URL authority ("/", "?", "#", "@")
+ENCODED_AUTHORITY_TERMINATORS = ("%2f", "%3f", "%23", "%40")
+
# Internal domain patterns that should never be accessed
# These are common internal TLDs and suffixes used in private networks
INTERNAL_DOMAIN_PATTERNS = (
@@ -149,6 +152,36 @@ def _is_private_ip_literal(host: str) -> bool:
)
+def has_ambiguous_authority(url: str) -> bool:
+ """
+ Reject a URL whose authority any client could read differently than ``urlparse`` does.
+
+ This is the strict rule, for a URL we hand back to a client: a redirect target, an
+ OAuth ``redirect_uri``, a link in an email. Those are delivered with the authority
+ intact, so the host we validated has to be the host the recipient resolves.
+
+ On top of the backslash cases, it rejects ``ENCODED_AUTHORITY_TERMINATORS`` anywhere
+ in the authority. A consumer that percent-decodes before splitting sees the authority
+ end at the terminator, so ``https://good.example%[email protected]/`` reads as
+ ``good.example`` there and as ``evil.example`` under ``urlparse``.
+
+ Outbound fetches deliberately do not get this rule. Percent-encoded characters are
+ ordinary in credentials (an email username encodes ``@`` as ``%40``, a password may
+ encode ``/``, ``?``, or ``#``), so applying it there would reject routine basic auth.
+ A URL we hand to someone else has no business carrying credentials in the first place.
+
+ Pass a full URL: a bare host has no authority to inspect. The same sequences in a
+ path, query, or fragment are ordinary encoded data and are ignored.
+ """
+ if has_authority_bypass_chars(url):
+ return True
+ try:
+ authority = urlparse.urlparse(url).netloc.lower()
+ except ValueError:
+ return True
+ return any(terminator in authority for terminator in ENCODED_AUTHORITY_TERMINATORS)
+
+
def has_authority_bypass_chars(url: str) -> bool:
"""
Detect characters that produce a parser-vs-client disagreement on the URL authority.
@@ -160,6 +193,10 @@ def has_authority_bypass_chars(url: str) -> bool:
URLs containing these characters cannot be safely validated by host, because
the validated host differs from the host the client will actually connect to.
+
+ This is the lenient rule, for URLs we are about to fetch ourselves. Only the SSRF
+ validator in this module uses it. Anything that hands a URL back to a client wants
+ ``has_ambiguous_authority`` instead.
"""
if "\\" in url:
return True
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index fa761ded6de9..c064e177cda4 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -112,6 +112,13 @@ class TestAbsoluteUrls(TestCase):
"https://app.posthog.com",
"https://app.posthog.com/an.external.domain.com/something-outside-posthog",
),
+ # A relative path has no authority to judge, so reserved characters encoded in
+ # its query are ordinary data. absolute_uri builds most of our emailed links.
+ (
+ "/signup?email=someone%40example.com",
+ "https://app.posthog.com",
+ "https://app.posthog.com/signup?email=someone%40example.com",
+ ),
("/api/path", "", "/api/path"), # current behavior whether correct or not
(
"/api/path",
@@ -149,9 +156,14 @@ class TestAbsoluteUrls(TestCase):
# 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"),
+ # urljoin hands an absolute URL straight back, so the authority the caller
+ # embeds in a link or a redirect is the one supplied here.
+ ("percent_encoded_slash", "https://attacker.example%[email protected]/path"),
+ ("percent_encoded_question_mark", "https://attacker.example%[email protected]/path"),
+ ("percent_encoded_hash", "https://attacker.example%[email protected]/path"),
]
)
- def test_absolute_uri_rejects_backslash_authority_bypass(self, _name: str, url: str) -> None:
+ def test_absolute_uri_rejects_ambiguous_authority(self, _name: str, url: str) -> None:
with self.settings(SITE_URL="https://app.posthog.com"):
with pytest.raises(PotentialSecurityProblemException):
absolute_uri(url)
diff --git a/posthog/utils.py b/posthog/utils.py
index cdde8fba6533..6300d7abee59 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -58,7 +58,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
+from posthog.security.url_validation import has_ambiguous_authority
tracer = trace.get_tracer(__name__)
@@ -121,7 +121,7 @@ def absolute_uri(url: Optional[str] = None) -> str:
if not url:
return settings.SITE_URL
- if has_authority_bypass_chars(url):
+ if has_ambiguous_authority(url):
raise PotentialSecurityProblemException(f"It is forbidden to provide an absolute URI using {url}")
provided_url = urlparse(url)
diff --git a/products/conversations/backend/api/serializers.py b/products/conversations/backend/api/serializers.py
index 75a5834de649..35a4dbf7b858 100644
--- a/products/conversations/backend/api/serializers.py
+++ b/products/conversations/backend/api/serializers.py
@@ -8,7 +8,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 posthog.security.url_validation import has_ambiguous_authority
from products.conversations.backend.models import TicketAssignment
from products.conversations.backend.models.constants import Status
@@ -217,7 +217,9 @@ def validate_url_domain(url: str, team: Team) -> bool:
if not domains:
return False
- if has_authority_bypass_chars(url):
+ # The restore link is emailed with this authority intact, so it has to be unambiguous
+ # rather than merely parseable.
+ if has_ambiguous_authority(url):
return False
parsed = urlparse(url)
@@ -259,7 +261,7 @@ 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):
+ if has_ambiguous_authority(url):
return False
parsed_url = urlparse(url)
diff --git a/products/conversations/backend/api/tests/test_restore.py b/products/conversations/backend/api/tests/test_restore.py
index b9800cb0a8fa..1c7bc9115d9d 100644
--- a/products/conversations/backend/api/tests/test_restore.py
+++ b/products/conversations/backend/api/tests/test_restore.py
@@ -559,12 +559,19 @@ class TestRestoreAPI(BaseTest):
# delivers the restore token to attacker.example.
("raw_backslash", "https://attacker.example\\@allowed.com/support"),
("percent_encoded_backslash", "https://attacker.example%[email protected]/support"),
+ # The emailed link keeps the authority as supplied, so a percent-encoded
+ # terminator sends the restore token to attacker.example for any client that
+ # decodes before splitting.
+ ("percent_encoded_slash", "https://attacker.example%[email protected]/support"),
+ ("percent_encoded_question_mark", "https://attacker.example%[email protected]/support"),
+ ("percent_encoded_hash", "https://attacker.example%[email protected]/support"),
+ ("percent_encoded_at", "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(
+ def test_restore_request_rejects_ambiguous_authority(
self,
_name,
request_url,