: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 survey page assets from the app origin (#71893)
Ben Lea414c07fa80db
diff --git a/posthog/templates/surveys/error.html b/posthog/templates/surveys/error.htmlindex cc8baa804b35..f51adfbd6bd2 100644--- a/posthog/templates/surveys/error.html+++ b/posthog/templates/surveys/error.html@@ -4,9 +4,10 @@<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">- <link rel="apple-touch-icon" sizes="180x180" href="/static/icons/apple-touch-icon.png?v=2023-07-07">- <link rel="icon" type="image/png" sizes="32x32" href="/static/icons/favicon-32x32.png?v=2023-07-07">- <link rel="icon" type="image/png" sizes="16x16" href="/static/icons/favicon-16x16.png?v=2023-07-07">+ {# Absolute app-origin URLs: reverse-proxy domains don't serve Django staticfiles. #}+ <link rel="apple-touch-icon" sizes="180x180" href="{{ site_url }}/static/icons/apple-touch-icon.png?v=2023-07-07">+ <link rel="icon" type="image/png" sizes="32x32" href="{{ site_url }}/static/icons/favicon-32x32.png?v=2023-07-07">+ <link rel="icon" type="image/png" sizes="16x16" href="{{ site_url }}/static/icons/favicon-16x16.png?v=2023-07-07"><title>{{ error_title }}</title><style>:root {diff --git a/posthog/templates/surveys/public_survey.html b/posthog/templates/surveys/public_survey.htmlindex ba132ac07c19..370869c0e383 100644--- a/posthog/templates/surveys/public_survey.html+++ b/posthog/templates/surveys/public_survey.html@@ -4,13 +4,22 @@<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">- <link rel="apple-touch-icon" sizes="180x180" href="/static/icons/apple-touch-icon.png?v=2023-07-07">- <link rel="icon" type="image/png" sizes="32x32" href="/static/icons/favicon-32x32.png?v=2023-07-07">- <link rel="icon" type="image/png" sizes="16x16" href="/static/icons/favicon-16x16.png?v=2023-07-07">- <link rel="mask-icon" href="/static/icons/safari-pinned-tab.svg?v=2023-07-07" color="#FF053C">- <link rel="manifest" href="/static/site.webmanifest?v=2023-07-07">- {# Raw path, not the static tag: frontend/public/ ships unhashed, so a manifest-hashed URL 404s. #}- <link rel="stylesheet" href="/static/surveys/hosted-survey.css?v=1">+ {% comment %}+ Asset URLs are absolute to the app origin (site_url): this page is also served through+ reverse-proxy domains, which route /static/* to the SDK asset CDN — Django staticfiles 404+ there. site_url is empty when SITE_URL isn't externally reachable, degrading to relative+ paths. Raw paths, not the static tag: frontend/public/ ships unhashed, so a manifest-hashed+ URL 404s. No webmanifest/mask-icon links: cross-origin manifest fetches need CORS headers+ we don't guarantee, and they add nothing to a hosted survey page.+ {% endcomment %}+ {% if site_url %}+ <link rel="preconnect" href="{{ site_url }}">+ <link rel="dns-prefetch" href="{{ site_url }}">+ {% endif %}+ <link rel="apple-touch-icon" sizes="180x180" href="{{ site_url }}/static/icons/apple-touch-icon.png?v=2023-07-07">+ <link rel="icon" type="image/png" sizes="32x32" href="{{ site_url }}/static/icons/favicon-32x32.png?v=2023-07-07">+ <link rel="icon" type="image/png" sizes="16x16" href="{{ site_url }}/static/icons/favicon-16x16.png?v=2023-07-07">+ <link rel="stylesheet" href="{{ site_url }}/static/surveys/hosted-survey.css?v=1"><meta name="apple-mobile-web-app-title" content="{{ name }}"><meta name="application-name" content="{{ name }}"><title>{{ name }}</title>diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 9841335ef768..f32adb4d6939 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -3473,6 +3473,38 @@ def get_surveys_response(team: Team):}+def _survey_page_site_url() -> str:+ """+ Origin for the hosted survey page's static assets. Assets must load from the app+ origin even when the page is served through a reverse-proxy domain, which doesn't+ serve Django staticfiles. A localhost SITE_URL (the unset default) would emit asset+ URLs no external browser can reach, so fall back to host-relative paths — those at+ least keep direct app-origin access working.+ """+ hostname = urlparse(settings.SITE_URL).hostname+ if hostname in (None, "localhost", "127.0.0.1", "::1"):+ return ""+ return settings.SITE_URL+++def _survey_error_response(+ request: HttpRequest,+ *,+ error_title: str,+ error_message: str,+ status: int,+ appearance: dict[str, Any] | None = None,+) -> HttpResponse:+ context: dict[str, Any] = {+ "error_title": error_title,+ "error_message": error_message,+ "site_url": _survey_page_site_url(),+ }+ if appearance is not None:+ context["appearance"] = appearance+ return render(request, "surveys/error.html", context, status=status)++@csrf_exempt@axes_dispatchdef public_survey_page(request, survey_id: str):@@ -3485,13 +3517,10 @@ def public_survey_page(request, survey_id: str):# Input validationif not UUIDT.is_valid_uuid(survey_id):logger.warning("survey_page_invalid_id", survey_id=survey_id)- return render(+ return _survey_error_response(request,- "surveys/error.html",- {- "error_title": "Invalid request",- "error_message": "The requested survey is not available.",- },+ error_title="Invalid request",+ error_message="The requested survey is not available.",status=400,)@@ -3502,25 +3531,19 @@ def public_survey_page(request, survey_id: str):except Survey.DoesNotExist:logger.info("survey_page_not_found", survey_id=survey_id)# Use generic error message to prevent survey ID enumeration- return render(+ return _survey_error_response(request,- "surveys/error.html",- {- "error_title": "Survey not available",- "error_message": "The requested survey is not available.",- },+ error_title="Survey not available",+ error_message="The requested survey is not available.",status=404,)except Exception as e:logger.exception("survey_page_db_error", error=str(e), survey_id=survey_id)capture_exception(e)- return render(+ return _survey_error_response(request,- "surveys/error.html",- {- "error_title": "Service unavailable",- "error_message": "The service is temporarily unavailable. Please try again later.",- },+ error_title="Service unavailable",+ error_message="The service is temporarily unavailable. Please try again later.",status=503,)@@ -3537,15 +3560,13 @@ def public_survey_page(request, survey_id: str):survey_type=survey.type,)# Pass appearance so the error page still shows the customer's brand.- return render(+ # Use 404 instead of 403 to prevent information leakage.+ return _survey_error_response(request,- "surveys/error.html",- {- "error_title": "Feels quiet in here",- "error_message": "This survey isn't taking responses right now. It might be closed, expired, or not live yet.",- "appearance": survey.appearance or {},- },- status=404, # Use 404 instead of 403 to prevent information leakage+ error_title="Feels quiet in here",+ error_message="This survey isn't taking responses right now. It might be closed, expired, or not live yet.",+ status=404,+ appearance=survey.appearance or {},)# Build project config@@ -3564,6 +3585,7 @@ def public_survey_page(request, survey_id: str):"survey_id": survey_id,"survey_data": survey_data,"project_config": project_config,+ "site_url": _survey_page_site_url(),"display_language": get_hosted_survey_display_language(request),"debug": settings.DEBUG,"embed_mode": request.GET.get("embed") == "true",diff --git a/products/surveys/backend/api/test/test_external_surveys.py b/products/surveys/backend/api/test/test_external_surveys.pyindex b121459427bf..b822ea331465 100644--- a/products/surveys/backend/api/test/test_external_surveys.py+++ b/products/surveys/backend/api/test/test_external_surveys.py@@ -8,12 +8,14 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom django.core.cache import cache-from django.test import TestCase+from django.test import TestCase, override_settingsfrom parameterized import parameterizedfrom products.surveys.backend.models import Survey+EXTERNAL_SITE_URL = "https://app.posthog-test.example"+class TestExternalSurveys(APIBaseTest):"""@@ -295,6 +297,44 @@ class TestExternalSurveys(APIBaseTest):assert "api_host" in project_configassert "token" in project_config+ @override_settings(SITE_URL=EXTERNAL_SITE_URL)+ def test_assets_load_from_app_origin_behind_reverse_proxy(self):+ survey = self.create_external_survey()++ # Simulate serving the page through a reverse-proxy domain+ response = self.client.get(f"/external_surveys/{survey.id}/", HTTP_HOST="surveys.proxy-domain.example.com")+ assert response.status_code == 200++ content = response.content.decode()+ # Proxy domains route /static/* to the SDK asset CDN, which doesn't serve Django+ # staticfiles — asset URLs must point at the app origin, not the serving host.+ assert f'<link rel="stylesheet" href="{EXTERNAL_SITE_URL}/static/surveys/hosted-survey.css' in content+ assert 'href="/static/' not in content+ # Capture must keep following the request host so events route through the proxy+ project_config = self.get_json_script_value(content, "project-config")+ assert isinstance(project_config, dict)+ assert project_config["api_host"] == "http://surveys.proxy-domain.example.com"++ # Error pages are served through proxies too and must not emit relative asset links+ error_response = self.client.get("/external_surveys/not-a-uuid/", HTTP_HOST="surveys.proxy-domain.example.com")+ assert error_response.status_code == 400+ error_content = error_response.content.decode()+ assert f'href="{EXTERNAL_SITE_URL}/static/icons/favicon-32x32.png' in error_content+ assert 'href="/static/' not in error_content++ @override_settings(SITE_URL="http://localhost:8010")+ def test_localhost_site_url_falls_back_to_relative_asset_urls(self):+ survey = self.create_external_survey()++ # A localhost SITE_URL (the unset default) isn't reachable by external browsers —+ # the page must degrade to host-relative asset paths instead of emitting it.+ response = self.client.get(f"/external_surveys/{survey.id}/")+ assert response.status_code == 200++ content = response.content.decode()+ assert '<link rel="stylesheet" href="/static/surveys/hosted-survey.css' in content+ assert "http://localhost:8010" not in content+@parameterized.expand([("base_locale", "es", "es"),