: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(surveys): serve hosted surveys on a managed proxy domain only for its owner (#118882)
Lucas Fariaf263f42cf0bf
diff --git a/posthog/api/proxy_record.py b/posthog/api/proxy_record.pyindex 47b4424f6d66..4b603b0a589b 100644--- a/posthog/api/proxy_record.py+++ b/posthog/api/proxy_record.py@@ -139,6 +139,15 @@ class ProxyRecordSerializer(serializers.ModelSerializer):organization_id = getattr(getattr(view, "organization", None), "id", None)if organization_id is None or not org_may_register_reserved_domain(organization_id, value):raise serializers.ValidationError("This domain belongs to PostHog. Enter a domain you own instead.")+ # DNS names ignore case, but the unique constraint does not. A case variant would let one+ # organization register another organization's domain without its DNS. Older rows can hold+ # uppercase, so the lookup ignores case. New rows are lowercase, so the constraint also+ # stops two concurrent registrations.+ value = value.lower()+ if ProxyRecord.objects.filter(domain__iexact=value).exists():+ raise serializers.ValidationError(+ "This domain already has a managed reverse proxy. Enter a different domain."+ )return valuediff --git a/posthog/api/test/test_proxy_record.py b/posthog/api/test/test_proxy_record.pyindex d11e69ec0886..2376af60d5f8 100644--- a/posthog/api/test/test_proxy_record.py+++ b/posthog/api/test/test_proxy_record.py@@ -111,15 +111,16 @@ class TestProxyRecordAPI(APIBaseTest):"legacy.example.com": False,}+ @parameterized.expand([("lowercase", "test.example.com"), ("mixed_case", "Test.Example.com")])@patch("posthog.api.proxy_record.sync_connect")@patch("posthoganalytics.capture")- def test_create_proxy_record(self, mock_capture, mock_sync_connect):+ def test_create_proxy_record(self, _name, domain, mock_capture, mock_sync_connect):mock_temporal = AsyncMock()mock_sync_connect.return_value = mock_temporalresponse = self.client.post(f"/api/organizations/{self.organization.id}/proxy_records/",- {"domain": "test.example.com"},+ {"domain": domain},)assert response.status_code == status.HTTP_201_CREATEDdata = response.json()@@ -348,6 +349,29 @@ class TestProxyRecordAPI(APIBaseTest):assert not ProxyRecord.objects.filter(organization=self.organization, domain=domain).exists()mock_sync_connect.assert_not_called()+ @parameterized.expand(+ [+ ("same_case", "surveys.taken.example.com"),+ ("case_variant", "Surveys.Taken.example.com"),+ ]+ )+ @patch("posthog.api.proxy_record.sync_connect")+ def test_create_rejects_a_domain_another_organization_registered(self, _name, domain, mock_sync_connect):+ ProxyRecord.objects.create(+ organization=Organization.objects.create(name="Other organization"),+ domain="surveys.taken.example.com",+ target_cname="other.proxy.example.com",+ )++ 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).exists()+ mock_sync_connect.assert_not_called()+@parameterized.expand([("apex", "posthog.com"),diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex a048ff3c22ae..6bdea9e2dcc2 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -11,6 +11,7 @@ from django.core.cache import cachefrom django.db import models, transactionfrom django.db.models import QuerySetfrom django.http import HttpRequest, HttpResponse+from django.http.request import split_domain_portfrom django.shortcuts import renderfrom django.utils.text import slugifyfrom django.views.decorators.csrf import csrf_exempt@@ -57,6 +58,7 @@ from posthog.helpers.trigram_search import ()from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params+from posthog.models.proxy_record import ProxyRecordfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import UUIDT@@ -3943,6 +3945,24 @@ def _survey_error_response(return _isolate_public_survey_response(request, render(request, "surveys/error.html", context, status=status))+def _survey_not_available_response(request: HttpRequest) -> HttpResponse:+ # Use generic error message to prevent survey ID enumeration+ return _survey_error_response(+ request,+ error_title="Survey not available",+ error_message="The requested survey is not available.",+ status=404,+ )+++def _is_another_organizations_proxy_domain(request: HttpRequest, survey: Survey) -> bool:+ # get_host() prefers X-Forwarded-Host, which a client can set. The managed proxy keeps the visitor's Host header.+ domain, _ = split_domain_port(request.META.get("HTTP_HOST", ""))+ return (+ ProxyRecord.objects.filter(domain__iexact=domain).exclude(organization_id=survey.team.organization_id).exists()+ )++@csrf_exempt@axes_dispatchdef public_survey_page(request: HttpRequest, survey_id: str) -> HttpResponse:@@ -3966,15 +3986,10 @@ def public_survey_page(request: HttpRequest, survey_id: str) -> HttpResponse:try:# nosemgrep: idor-lookup-without-team (public survey page, intentionally unauthenticated)survey = Survey.objects.select_related("team").get(id=survey_id)+ is_another_organizations_proxy_domain = _is_another_organizations_proxy_domain(request, survey)except Survey.DoesNotExist:logger.info("survey_page_not_found", survey_id=survey_id)- # Use generic error message to prevent survey ID enumeration- return _survey_error_response(- request,- error_title="Survey not available",- error_message="The requested survey is not available.",- status=404,- )+ return _survey_not_available_response(request)except Exception as e:logger.exception("survey_page_db_error", error=str(e), survey_id=survey_id)capture_exception(e)@@ -3985,6 +4000,10 @@ def public_survey_page(request: HttpRequest, survey_id: str) -> HttpResponse:status=503,)+ if is_another_organizations_proxy_domain:+ logger.info("survey_page_foreign_proxy_domain", survey_id=survey_id, host=request.META.get("HTTP_HOST"))+ return _survey_not_available_response(request)+survey_is_running = (survey.start_date is not None and survey.start_date <= datetime.now(UTC) and survey.end_date is None)diff --git a/products/surveys/backend/api/test/test_external_surveys.py b/products/surveys/backend/api/test/test_external_surveys.pyindex d554f0a0f60d..1e5c31c1d7f9 100644--- a/products/surveys/backend/api/test/test_external_surveys.py+++ b/products/surveys/backend/api/test/test_external_surveys.py@@ -12,9 +12,13 @@ from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized+from posthog.models import Organization, ProxyRecord+from products.surveys.backend.models import SurveyEXTERNAL_SITE_URL = "https://app.posthog-test.example"+OWN_PROXY_DOMAIN = "surveys.own-org.example.com"+OTHER_PROXY_DOMAIN = "surveys.other-org.example.com"class TestExternalSurveys(APIBaseTest):@@ -381,6 +385,79 @@ class TestExternalSurveys(APIBaseTest):assert f'href="{EXTERNAL_SITE_URL}/static/icons/favicon-32x32.png' in error_contentassert 'href="/static/' not in error_content+ @parameterized.expand(+ [+ ("own_proxy_domain", OWN_PROXY_DOMAIN, {}, {}, 200, "Quarterly feedback"),+ ("unregistered_host", "surveys.self-run-proxy.example.com", {}, {}, 200, "Quarterly feedback"),+ ("other_org_proxy_domain", OTHER_PROXY_DOMAIN, {}, {}, 404, "Survey not available"),+ (+ "other_org_domain_stored_mixed_case",+ OTHER_PROXY_DOMAIN,+ {"domain": "Surveys.Other-Org.example.com"},+ {},+ 404,+ "Survey not available",+ ),+ (+ "other_org_record_being_deleted",+ OTHER_PROXY_DOMAIN,+ {"status": ProxyRecord.Status.DELETING},+ {},+ 404,+ "Survey not available",+ ),+ (+ "other_org_record_retrying",+ OTHER_PROXY_DOMAIN,+ {"status": ProxyRecord.Status.WAITING},+ {},+ 404,+ "Survey not available",+ ),+ (+ "other_org_proxy_domain_archived_survey",+ OTHER_PROXY_DOMAIN,+ {},+ {"archived": True},+ 404,+ "Survey not available",+ ),+ ]+ )+ @override_settings(USE_X_FORWARDED_HOST=True)+ def test_managed_proxy_domain_serves_only_its_own_organization_surveys(+ self,+ _name: str,+ host: str,+ other_record_overrides: dict,+ survey_overrides: dict,+ expected_status: int,+ expected_text: str,+ ) -> None:+ survey = self.create_external_survey(name="Quarterly feedback", **survey_overrides)+ ProxyRecord.objects.create(+ organization=self.organization,+ domain=OWN_PROXY_DOMAIN,+ target_cname="own.proxy.example.com",+ status=ProxyRecord.Status.VALID,+ )+ ProxyRecord.objects.create(+ **{+ "organization": Organization.objects.create(name="Other organization"),+ "domain": OTHER_PROXY_DOMAIN,+ "target_cname": "other.proxy.example.com",+ "status": ProxyRecord.Status.VALID,+ **other_record_overrides,+ }+ )++ response = self.client.get(+ f"/external_surveys/{survey.id}/", HTTP_HOST=host, HTTP_X_FORWARDED_HOST="testserver"+ )++ assert response.status_code == expected_status+ assert expected_text in response.content.decode()+@override_settings(SITE_URL="http://localhost:8010")def test_localhost_site_url_falls_back_to_relative_asset_urls(self):survey = self.create_external_survey()