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(csp): serve the api docs ui from our own static files (#108875)

Tom Piccirellob6a7e8010d81
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index f7fe35c638ec..e1ddf9b41245 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -148,6 +148,7 @@ INSTALLED_APPS = [
"axes",
"django_structlog",
"drf_spectacular",
+ "drf_spectacular_sidecar",
*PRODUCTS_APPS,
"django_otp",
"django_otp.plugins.otp_static",
@@ -550,6 +551,12 @@ if DEBUG:
SPECTACULAR_SETTINGS = {
"OAS_VERSION": "3.1.0",
+ # drf-spectacular loads the Swagger and Redoc UIs from a public CDN by default. The app policy
+ # refuses that CDN, which leaves both pages blank, and a third-party script on this origin
+ # would run with the visitor's session. The sidecar package serves them from our static files.
+ "SWAGGER_UI_DIST": "SIDECAR",
+ "SWAGGER_UI_FAVICON_HREF": "SIDECAR",
+ "REDOC_DIST": "SIDECAR",
"SERVERS": [
{"url": "https://us.posthog.com", "description": "PostHog Cloud US"},
{"url": "https://eu.posthog.com", "description": "PostHog Cloud EU"},
diff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.py
index 621b8ede5512..e0b670af33a8 100644
--- a/posthog/test/test_csp_middleware.py
+++ b/posthog/test/test_csp_middleware.py
@@ -1,8 +1,10 @@
+from html.parser import HTMLParser
from urllib.parse import parse_qs, urlsplit
from posthog.test.base import APIBaseTest, override_settings
from unittest.mock import MagicMock, patch
+from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.test import RequestFactory, SimpleTestCase
@@ -29,6 +31,37 @@ def _report_version(policy: dict[str, list[str]]) -> list[str] | None:
return parse_qs(urlsplit(policy.get("report-uri", [""])[0]).query).get("v")
+class _PageLoads(HTMLParser):
+ def __init__(self) -> None:
+ super().__init__()
+ self.scripts: list[tuple[dict[str, str | None], str]] = []
+ self.stylesheets: list[str] = []
+ self._script: dict[str, str | None] | None = None
+ self._script_body = ""
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ if tag == "script":
+ self._script, self._script_body = dict(attrs), ""
+ elif tag == "link" and dict(attrs).get("rel") == "stylesheet":
+ self.stylesheets.append(dict(attrs).get("href") or "")
+
+ def handle_data(self, data: str) -> None:
+ if self._script is not None:
+ self._script_body += data
+
+ def handle_endtag(self, tag: str) -> None:
+ if tag == "script" and self._script is not None:
+ self.scripts.append((self._script, self._script_body.strip()))
+ self._script = None
+
+
+def _admits(sources: list[str], url: str) -> bool:
+ parts = urlsplit(url)
+ if not parts.netloc:
+ return "'self'" in sources
+ return f"{parts.scheme}://{parts.netloc}" in sources
+
+
# Tests run as a self-hosted install, which never enforces. LOCAL enforces without turning on DEBUG.
@override_settings(CLOUD_DEPLOYMENT="LOCAL")
class TestCSPMiddleware(APIBaseTest):
@@ -99,6 +132,39 @@ class TestCSPMiddleware(APIBaseTest):
assert response["Content-Security-Policy"] == "default-src 'none'"
assert "Content-Security-Policy-Report-Only" not in response
+ @parameterized.expand([("swagger", "/api/schema/swagger-ui/"), ("redoc", "/api/schema/redoc/")])
+ @override_settings(
+ TEST=False,
+ DEBUG=False,
+ CLOUD_DEPLOYMENT="US",
+ SITE_URL="https://us.posthog.com",
+ JS_URL="https://app-static-prod.posthog.com",
+ )
+ def test_api_doc_pages_load_only_what_the_app_policy_admits(self, _name: str, path: str) -> None:
+ # drf-spectacular defaults to a public CDN and to an inline init script with no nonce. The
+ # enforced app policy refuses both, and the page renders blank with no error shown.
+ response = self.client.get(path)
+ assert response.status_code == 200
+ policy = next(p for p in _parse_policies(response["Content-Security-Policy"]) if "script-src" in p)
+ page = _PageLoads()
+ page.feed(response.content.decode())
+
+ assert page.scripts
+ for attrs, body in page.scripts:
+ src = attrs.get("src")
+ if src is None:
+ assert f"'nonce-{attrs.get('nonce')}'" in policy["script-src"], body[:80]
+ else:
+ assert _admits(policy["script-src"], src), src
+ if not urlsplit(src).netloc and not src.startswith(settings.STATIC_URL):
+ # The Swagger init script comes from the page's own URL. A response that is not
+ # JavaScript leaves the page blank without any violation to report.
+ script = self.client.get(src)
+ assert script.status_code == 200, src
+ assert "javascript" in script["Content-Type"], src
+ for href in page.stylesheets:
+ assert _admits(policy["style-src"], href), href
+
@parameterized.expand(
[
("app_root", "/", True),
diff --git a/posthog/urls.py b/posthog/urls.py
index 893dbb45184e..651b3416fc16 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -3,7 +3,7 @@ from django.urls import include, path, re_path
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import RedirectView
-from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
+from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerSplitView
from two_factor.urls import urlpatterns as tf_urls
from posthog.api import (
@@ -113,7 +113,9 @@ urlpatterns = [
# Optional UI:
path(
"api/schema/swagger-ui/",
- SpectacularSwaggerView.as_view(url_name="schema"),
+ # The split view serves its init script from this URL with ?script. The plain view inlines
+ # that script without a nonce, and the app policy refuses it.
+ SpectacularSwaggerSplitView.as_view(url_name="schema"),
name="swagger-ui",
),
path(
diff --git a/pyproject.toml b/pyproject.toml
index ae9f130a8e7a..cd677d01410d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -57,6 +57,7 @@ dependencies = [
"drf-exceptions-hog==0.4.0",
"drf-extensions~=0.8.0",
"drf-spectacular~=0.30.0",
+ "drf-spectacular-sidecar~=2026.9.1",
"geoip2==4.6.0",
"google-ads==31.2.0",
"google-cloud-bigquery==3.26",
diff --git a/uv.lock b/uv.lock
index 18a57b35667b..0308bd2002d5 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2318,6 +2318,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c3/56/74dd7b45bbde6d24494220b98d6961cb1200b63a1800332b430daa2c4551/drf_spectacular-0.30.0-py3-none-any.whl", hash = "sha256:006cf5921ebe20a9bd24f7c846261ebbf78780be5961b0d6e87afaa82afd62ff", size = 111150, upload-time = "2026-07-06T11:29:45.12Z" },
]
+[[package]]
+name = "drf-spectacular-sidecar"
+version = "2026.9.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "django" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/67/87/ef9f1693499ac2c1bf3c33ce57e72c423aed51ab51f7ebd5d3a38f20c606/drf_spectacular_sidecar-2026.9.1.tar.gz", hash = "sha256:99c2b845d0a52b01a7a8e96736a48ef2099dc3dedea103012dfea41a9e4e9ecc", size = 2605997, upload-time = "2026-09-01T15:27:00.127Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/19/3b/c4866e6304d09d8813883774dadc5ff70a355279fc2527af3a4004fdb5f0/drf_spectacular_sidecar-2026.9.1-py3-none-any.whl", hash = "sha256:1e521d0ff78c7ab1a873423fc6e6b82ef6bae863f170762e7410ac63b2c7b72f", size = 2628532, upload-time = "2026-09-01T15:26:58.472Z" },
+]
+
[[package]]
name = "duckdb"
version = "1.5.2"
@@ -5816,6 +5828,7 @@ dependencies = [
{ name = "drf-exceptions-hog" },
{ name = "drf-extensions" },
{ name = "drf-spectacular" },
+ { name = "drf-spectacular-sidecar" },
{ name = "duckdb" },
{ name = "elevenlabs" },
{ name = "fastavro" },
@@ -6104,6 +6117,7 @@ requires-dist = [
{ name = "drf-exceptions-hog", specifier = "==0.4.0" },
{ name = "drf-extensions", specifier = "~=0.8.0" },
{ name = "drf-spectacular", specifier = "~=0.30.0" },
+ { name = "drf-spectacular-sidecar", specifier = "~=2026.9.1" },
{ name = "duckdb", specifier = "~=1.5.2" },
{ name = "elevenlabs", specifier = "~=2.1.0" },
{ name = "fastavro", specifier = "~=1.12.0" },