: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(proxy): reject proxy domains that posthog itself owns (#83292)
Tom Piccirello7b25b0c63642
diff --git a/posthog/api/proxy_record.py b/posthog/api/proxy_record.pyindex 2360986b1bd1..c1885e66e291 100644--- a/posthog/api/proxy_record.py+++ b/posthog/api/proxy_record.py@@ -25,7 +25,7 @@ from posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import ProxyRecordfrom posthog.models.organization import Organization-from posthog.models.proxy_record import is_valid_proxy_domain+from posthog.models.proxy_record import is_reserved_proxy_domain, is_valid_proxy_domainfrom posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermissionfrom posthog.tasks.proxy import reconcile_proxy_root_redirectfrom posthog.temporal.common.client import sync_connect@@ -129,6 +129,8 @@ class ProxyRecordSerializer(serializers.ModelSerializer):raise serializers.ValidationError("Enter a domain name on its own, like e.example.com, with no protocol, port, or path.")+ if is_reserved_proxy_domain(value):+ raise serializers.ValidationError("This domain belongs to PostHog. Enter a domain you own instead.")return value@@ -484,6 +486,15 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):status=status.HTTP_400_BAD_REQUEST,)+ # The row can predate this check (created before it shipped, or written directly+ # by the ORM), so retry has to refuse re-dispatching provisioning for a reserved+ # domain rather than trusting a value validate_domain would reject on write today.+ if is_reserved_proxy_domain(record.domain):+ return Response(+ {"detail": "This domain belongs to PostHog and cannot be provisioned as a proxy domain."},+ status=status.HTTP_400_BAD_REQUEST,+ )+record.status = ProxyRecord.Status.WAITINGrecord.message = Nonerecord.save()diff --git a/posthog/api/test/test_proxy_record.py b/posthog/api/test/test_proxy_record.pyindex 6912e5d6a79c..daaf2feda259 100644--- a/posthog/api/test/test_proxy_record.py+++ b/posthog/api/test/test_proxy_record.py@@ -354,6 +354,26 @@ class TestProxyRecordAPI(APIBaseTest):assert not ProxyRecord.objects.filter(organization=self.organization, domain=domain).exists()mock_sync_connect.assert_not_called()+ @parameterized.expand(+ [+ ("apex", "posthog.com"),+ ("subdomain", "app.posthog.com"),+ # The literal Cloudflare CNAME target other tenants' domains already point+ # to; claiming it as your own `domain` would collide with their routing.+ ("shared_cloudflare_target", "cf-prod-eu-proxy.europehog.com"),+ ]+ )+ @patch("posthog.api.proxy_record.sync_connect")+ def test_create_rejects_posthog_owned_domains(self, _name, domain, mock_sync_connect):+ response = self.client.post(+ f"/api/organizations/{self.organization.id}/proxy_records/",+ {"domain": domain},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not ProxyRecord.objects.filter(organization=self.organization, domain=domain).exists()+ mock_sync_connect.assert_not_called()+@patch("posthog.api.proxy_record.sync_connect")def test_create_cleans_up_on_temporal_failure(self, mock_sync_connect):mock_sync_connect.side_effect = Exception("connection failed")@@ -486,6 +506,28 @@ class TestProxyRecordAPI(APIBaseTest):record.refresh_from_db()assert record.status == ProxyRecord.Status.ERRORING+ @patch("posthog.api.proxy_record.sync_connect")+ def test_retry_refuses_a_stored_domain_that_is_reserved(self, mock_sync_connect):+ # Rows can predate this check (a legacy row, or a direct ORM write outside the+ # serializer), so retry has to refuse re-dispatching provisioning for one rather+ # than trusting a value validate_domain would reject today.+ record = ProxyRecord.objects.create(+ organization=self.organization,+ created_by=self.user,+ domain="app.posthog.com",+ target_cname="abc123.proxy.posthog.com",+ status=ProxyRecord.Status.ERRORING,+ )++ response = self.client.post(+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/retry/",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_sync_connect.assert_not_called()+ record.refresh_from_db()+ assert record.status == ProxyRecord.Status.ERRORING+def test_non_admin_cannot_retry_proxy_record(self):self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.pyindex b08ea2ebfff8..fbef59736716 100644--- a/posthog/api/test/test_proxy_record_diagnostics.py+++ b/posthog/api/test/test_proxy_record_diagnostics.py@@ -10,7 +10,7 @@ import dns.resolverfrom parameterized import parameterizedfrom posthog.api import proxy_record_diagnostics as diagnostics-from posthog.models.proxy_record import is_valid_proxy_domain+from posthog.models.proxy_record import is_reserved_proxy_domain, is_valid_proxy_domainfrom posthog.security.pinned_requests import SSRFBlockedErrorfrom posthog.security.url_validation import PinnedUrlVerdictfrom posthog.temporal.proxy_service.cloudflare import (@@ -408,6 +408,35 @@ class TestIsValidProxyDomain(TestCase):self.assertFalse(is_valid_proxy_domain(domain))+class TestIsReservedProxyDomain(TestCase):+ @parameterized.expand(+ [+ ("apex", "posthog.com"),+ ("subdomain", "app.posthog.com"),+ ("deep_subdomain", "us.i.posthog.com"),+ ("other_tld", "posthog.dev"),+ ("mixed_case", "App.PostHog.COM"),+ # The literal Cloudflare CNAME target every other tenant's domain already+ # points to (CLOUDFLARE_PROXY_BASE_CNAME in prod-eu). Claiming it collides+ # with every other customer's proxy routing, not just PostHog's own traffic.+ ("shared_cloudflare_target", "cf-prod-eu-proxy.europehog.com"),+ ]+ )+ def test_rejects_posthog_owned_domains(self, _name, domain):+ self.assertTrue(is_reserved_proxy_domain(domain))++ @parameterized.expand(+ [+ ("unrelated_domain", "e.example.com"),+ # Shares a label with a reserved domain but isn't a subdomain of it.+ ("lookalike_suffix", "notposthog.com"),+ ("lookalike_prefix", "posthog.com.attacker.example"),+ ]+ )+ def test_accepts_domains_that_are_not_posthog_owned(self, _name, domain):+ self.assertFalse(is_reserved_proxy_domain(domain))++CF_TARGET = "abc.cf-prod-eu-proxy.europehog.com."LEGACY_TARGET = "abc.proxy-us.posthog.com."diff --git a/posthog/models/proxy_record.py b/posthog/models/proxy_record.pyindex c4e531a468ee..a0f76d4c0bb8 100644--- a/posthog/models/proxy_record.py+++ b/posthog/models/proxy_record.py@@ -11,6 +11,43 @@ MAX_PROXY_DOMAIN_LABEL_LENGTH = 63_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"_PROXY_DOMAIN_RE = re.compile(rf"{_LABEL}(?:\.{_LABEL})*")+# Every apex domain PostHog itself registers or serves production traffic on: the+# Route53 zones in posthog-cloud-infra's terraform/environments/aws-accnt-root/route53-zones.tf,+# plus postwh.com, posthogusercontent.com, and the literal CLOUDFLARE_PROXY_BASE_CNAME /+# PROXY_BASE_CNAME targets from charts' shared/posthog-django/common.<env>.yaml (europehog.com,+# proxyhog.com, livehog.com are the Cloudflare/legacy CNAME targets that every other tenant's+# proxy domain already points to).+RESERVED_PROXY_DOMAINS = frozenset(+ {+ "posthog.com",+ "posthog.dev",+ "posthog.net",+ "posthog.io",+ "posthog.eu",+ "posthog.click",+ "posthog.lol",+ "posthog.biz",+ "posthog.cc",+ "hog.dev",+ "deskhog.com",+ "posthug.com",+ "productforengineers.com",+ "hedgehog.vc",+ "postvar.com",+ "productautonomy.com",+ "producthog.com",+ "phog.gg",+ "prehog.net",+ "ph-proxy.com",+ "livehog.com",+ "warmhog.com",+ "postwh.com",+ "posthogusercontent.com",+ "europehog.com",+ "proxyhog.com",+ }+)+def is_valid_proxy_domain(domain: str) -> bool:"""Whether `domain` is a bare hostname that means the same thing to a DNS resolver@@ -42,6 +79,20 @@ def is_valid_proxy_domain(domain: str) -> bool:return not labels[-1].isdigit()+def is_reserved_proxy_domain(domain: str) -> bool:+ """Whether `domain` is, or is a subdomain of, a domain PostHog itself owns.++ A registered `domain` is the Host this system will route through PostHog's shared+ reverse-proxy ingress (Cloudflare custom hostnames, or the legacy Caddy CNAME target)+ once the CNAME is verified. Letting an org claim one of PostHog's own domains would+ hand them routing, SNI matching, or certificate issuance for a hostname other+ tenants', or PostHog's own, traffic depends on. See `RESERVED_PROXY_DOMAINS` for the+ source of the list.+ """+ domain = domain.lower()+ return any(domain == reserved or domain.endswith(f".{reserved}") for reserved in RESERVED_PROXY_DOMAINS)++class ProxyRecord(UUIDTModel):organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="proxy_records")domain = models.CharField(max_length=64, unique=True)