: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
fix(api): bound authorized-URL wildcard matching (#74438)
Tom Piccirello8008faab5584
diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 55d075e8bd0d..1594d23a0152 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -45,6 +45,7 @@ from posthog.api.team import (validate_secret_token_generation,validate_team_attrs,)+from posthog.api.utils import validate_authorized_url_wildcardsfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.cloud_utils import get_cached_instance_license, is_cloudfrom posthog.constants import AvailableFeature@@ -595,7 +596,9 @@ class ProjectBackwardCompatSerializer(def validate_app_urls(self, value: list[str | None] | None) -> list[str] | None:if value is None:return value- return [url for url in value if url]+ urls = [url for url in value if url]+ validate_authorized_url_wildcards(urls)+ return urlsdef validate_recording_domains(self, value: list[str | None] | None) -> list[str] | None:if value is None:@@ -608,6 +611,7 @@ class ProjectBackwardCompatSerializer(# Filter out None values from widget_domains if presentif "widget_domains" in value and value["widget_domains"] is not None:value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]+ validate_authorized_url_wildcards(value["widget_domains"])return valueclass Meta:diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 21779cdf88b1..bd2c7993ac9e 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -42,7 +42,7 @@ from posthog.schema import (from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import TeamBasicSerializer-from posthog.api.utils import action+from posthog.api.utils import action, validate_authorized_url_wildcardsfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS, AvailableFeaturefrom posthog.decorators import disallow_if_impersonated@@ -1393,7 +1393,9 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixindef validate_app_urls(self, value: list[str | None] | None) -> list[str] | None:if value is None:return value- return [url for url in value if url]+ urls = [url for url in value if url]+ validate_authorized_url_wildcards(urls)+ return urlsdef validate_recording_domains(self, value: list[str | None] | None) -> list[str] | None:if value is None:@@ -1406,6 +1408,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin# Filter out None values from widget_domains if presentif "widget_domains" in value and value["widget_domains"] is not None:value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]+ validate_authorized_url_wildcards(value["widget_domains"])# Strip widget_public_token from user input - it's auto-generated onlyif "widget_public_token" in value:value.pop("widget_public_token")diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex dfba56138956..13faa804736b 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -3437,6 +3437,9 @@ class TestTeamAdminFieldAuthorization(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDEN+_TOO_MANY_WILDCARDS = ["https://*.*.*.*.*.*.example.com"]++class TestTeamSerializerValidationNoDB(SimpleTestCase):# Field-level input validation runs inside `is_valid()` (in `to_internal_value`),# before the object-level `validate()` that needs request context — so these never@@ -3577,6 +3580,43 @@ class TestTeamSerializerValidationNoDB(SimpleTestCase):def test_invalid_session_replay_config_ai_config(self, _name: str, value: Any, expected_detail: str) -> None:self._assert_field_error("session_replay_config", {"ai_config": value}, "invalid", expected_detail)+ # `ProjectBackwardCompatSerializer` keeps its own copy of these validators, so both+ # serializers are exercised here rather than only the Team one.+ @parameterized.expand(+ [+ ["team app urls", TeamSerializer, "app_urls", _TOO_MANY_WILDCARDS],+ ["team widget domains", TeamSerializer, "conversations_settings", {"widget_domains": _TOO_MANY_WILDCARDS}],+ ["project app urls", ProjectBackwardCompatSerializer, "app_urls", _TOO_MANY_WILDCARDS],+ [+ "project widget domains",+ ProjectBackwardCompatSerializer,+ "conversations_settings",+ {"widget_domains": _TOO_MANY_WILDCARDS},+ ],+ ]+ )+ def test_rejects_url_with_too_many_wildcards(+ self, _name: str, serializer_class: type, field: str, value: Any+ ) -> None:+ serializer = serializer_class(data={field: value}, partial=True)+ assert not serializer.is_valid()+ assert str(serializer.errors[field][0]) == (+ "Each URL can include up to 5 wildcards. Remove the extra ones from this entry."+ )++ @parameterized.expand(+ [+ ["number", 123],+ ["object", {"nested": "value"}],+ ["list", ["https://example.com"]],+ ["boolean", True],+ ]+ )+ def test_rejects_non_string_widget_domain(self, _name: str, entry: Any) -> None:+ # widget_domains rides in on a raw JSONField, so entries reach validation untyped.+ serializer = TeamSerializer(data={"conversations_settings": {"widget_domains": [entry]}}, partial=True)+ assert not serializer.is_valid()+def test_invalid_autocapture_exceptions_opt_in_not_a_boolean(self) -> None:# `autocapture_exceptions_errors_to_ignore` is deliberately not here: its validation# lives in the object-level `validate()` (via `validate_team_attrs`), which needsdiff --git a/posthog/api/test/test_utils.py b/posthog/api/test/test_utils.pyindex 4e69abdcc07a..358c5628cff0 100644--- a/posthog/api/test/test_utils.py+++ b/posthog/api/test/test_utils.py@@ -6,6 +6,7 @@ from django.http import HttpRequestfrom django.test.client import RequestFactoryfrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom posthog.api.utils import (PaginationMode,@@ -13,10 +14,12 @@ from posthog.api.utils import (format_paginated_url,get_data,get_target_entity,+ hostname_in_allowed_url_list,is_async_query,is_insight_query,raise_if_user_provided_url_unsafe,safe_clickhouse_string,+ validate_authorized_url_wildcards,PublicIPOnlyHttpAdapter,unparsed_hostname_in_allowed_url_list,)@@ -338,3 +341,48 @@ class TestUtils(BaseTest):self, _name: str, allowlist: list[str], needle: str | None, expected: bool) -> None:assert unparsed_hostname_in_allowed_url_list(allowlist, needle) == expected++ @parameterized.expand(+ [+ ("wildcard spans several labels", ["https://*.example.com"], "a.b.example.com", True),+ ("wildcard does not match the bare domain", ["https://*.example.com"], "example.com", False),+ ("bare wildcard matches any host", ["https://*"], "attacker.test", True),+ ("several wildcards in one entry", ["https://*.*.example.com"], "a.b.c.example.com", True),+ ("wildcard inside a label", ["https://app*.example.com"], "app-eu.example.com", True),+ ("wildcard inside a label may match nothing", ["https://foo*bar.example.com"], "foobar.example.com", True),+ (+ "literals between wildcards must appear in order",+ ["https://a*b*c.example.com"],+ "acb.example.com",+ False,+ ),+ ("prefix and suffix may not overlap", ["https://a*a.com"], "a.com", False),+ ("trailing literal still has to match", ["https://*.example.com"], "a.example.com.attacker.test", False),+ ("leading literal still has to match", ["https://app.*.com"], "notapp.eu.com", False),+ ]+ )+ def test_hostname_in_allowed_url_list_wildcards(+ self, _name: str, allowlist: list[str], hostname: str, expected: bool+ ) -> None:+ assert hostname_in_allowed_url_list(allowlist, hostname) == expected++ def test_hostname_in_allowed_url_list_skips_unparseable_entry(self) -> None:+ assert hostname_in_allowed_url_list(["http://[", "https://example.com"], "example.com") is True++ @parameterized.expand(+ [+ ("no wildcards", ["https://example.com"], False),+ ("wildcard count at the cap", ["https://*.*.*.*.*.example.com"], False),+ ("wildcard count over the cap", ["https://*.*.*.*.*.*.example.com"], True),+ ("only one entry is over the cap", ["https://example.com", "https://*.*.*.*.*.*.com"], True),+ ("wildcards in the path are not counted", ["https://example.com/*/*/*/*/*/*/*/*"], False),+ ("entry with no parseable host", ["*.*.*.*.*.*.*.example.com"], False),+ ("entry that cannot be parsed at all", ["http://["], True),+ ]+ )+ def test_validate_authorized_url_wildcards(self, _name: str, urls: list[str], expect_error: bool) -> None:+ if not expect_error:+ validate_authorized_url_wildcards(urls)+ return+ with self.assertRaises(DRFValidationError):+ validate_authorized_url_wildcards(urls)diff --git a/posthog/api/utils.py b/posthog/api/utils.pyindex 17e353d7bb33..3cc8791b9e12 100644--- a/posthog/api/utils.py+++ b/posthog/api/utils.py@@ -509,6 +509,35 @@ def _strip_www(host: str) -> str:return host[4:] if host.startswith("www.") else host+def _matches_wildcard_host(pattern: str, hostname: str) -> bool:+ """Match a host pattern whose `*` spans any run of characters, dots included.++ Scanning the literals greedily from left to right decides this grammar exactly, in a+ single pass, so the cost stays linear in the hostname length however many wildcards+ the pattern carries.+ """+ parts = pattern.split("*")+ if len(parts) == 1:+ return pattern == hostname++ prefix, suffix = parts[0], parts[-1]+ if len(hostname) < len(prefix) + len(suffix):+ return False+ if not hostname.startswith(prefix) or not hostname.endswith(suffix):+ return False++ start, end = len(prefix), len(hostname) - len(suffix)+ for part in parts[1:-1]:+ if not part:+ continue+ found = hostname.find(part, start, end)+ if found == -1:+ return False+ start = found + len(part)++ return True++def hostname_in_allowed_url_list(allowed_url_list: Optional[list[str]], hostname: Optional[str]) -> bool:if not hostname:return False@@ -516,14 +545,18 @@ def hostname_in_allowed_url_list(allowed_url_list: Optional[list[str]], hostnamepermitted_domains = []if allowed_url_list:for url in allowed_url_list:- host = parse_domain(url)+ try:+ host = parse_domain(url)+ except ValueError:+ # Entries stored before write-time validation can still be unparseable, and+ # one of them must not take down every allowlist check the team makes.+ continueif host:permitted_domains.append(host)for permitted_domain in permitted_domains:if "*" in permitted_domain:- pattern = "^{}$".format(re.escape(permitted_domain).replace("\\*", "(.*)"))- if re.search(pattern, hostname):+ if _matches_wildcard_host(permitted_domain, hostname):return Trueelif _strip_www(permitted_domain) == _strip_www(hostname):return True@@ -535,6 +568,33 @@ def parse_domain(url: Any) -> Optional[str]:return urlparse(url).hostname+MAX_WILDCARDS_PER_AUTHORIZED_URL = 5+++def validate_authorized_url_wildcards(urls: list[str]) -> None:+ """Keep stored allowlist entries to the shape real deployments use.++ Genuine entries carry one wildcard, occasionally two. Entries far beyond that only ever+ make matching more expensive, so they are rejected at write time.+ """+ for url in urls:+ if not isinstance(url, str):+ # widget_domains arrives on a raw JSONField, so entries are not string-coerced for us.+ raise ValidationError("Each URL must be a string.")+ try:+ host = parse_domain(url)+ except ValueError:+ # urlparse raises on an unterminated IPv6 bracket, and every later allowlist+ # check re-parses the stored entry, so accepting one here turns each of those+ # checks into a 500 for the whole team.+ raise ValidationError("One of these URLs can't be parsed. Check for a typo, like an unclosed bracket.")+ if host and host.count("*") > MAX_WILDCARDS_PER_AUTHORIZED_URL:+ raise ValidationError(+ f"Each URL can include up to {MAX_WILDCARDS_PER_AUTHORIZED_URL} wildcards. "+ "Remove the extra ones from this entry."+ )++def on_permitted_recording_domain(permitted_domains: list[str], request: HttpRequest) -> bool:origin = parse_domain(request.headers.get("Origin"))referer = parse_domain(request.headers.get("Referer"))