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): admit the presigned upload endpoint to connect-src (#106840)

Vojta Bartoš9595a27012bc
diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.py
index 9c51e50684cf..be3e3a6656ed 100644
--- a/posthog/csp_middleware.py
+++ b/posthog/csp_middleware.py
@@ -43,6 +43,30 @@ def csp_report_endpoint(**params: str) -> str:
return parts._replace(query=urlencode(query)).geturl()
+def object_storage_upload_source() -> str:
+ """The `connect-src` source a browser POSTs a presigned upload to, or "" when there is none.
+
+ A file the user attaches goes straight from the page to object storage: the API hands out a
+ presigned POST and the bytes never pass through Django, so the store's public endpoint has to
+ be a `connect-src` the policy names. The bucket is part of the source because in cloud that
+ endpoint is shared S3, and an origin on its own would let injected script POST to every other
+ bucket on the same host.
+
+ Returns "" for a deployment that serves object storage from its own origin, which `'self'`
+ already covers, and for one that has not configured the store at all.
+
+ The source is https whatever the endpoint says, because a bucket reached over plaintext is
+ not something to admit. The dev store runs on http, so it keeps its scheme the way the other
+ localhost sources in this policy do.
+ """
+ parts = urlsplit(settings.OBJECT_STORAGE_PUBLIC_ENDPOINT)
+ bucket = settings.OBJECT_STORAGE_BUCKET
+ if parts.scheme not in ("http", "https") or not parts.netloc or not bucket:
+ return ""
+ scheme = parts.scheme if settings.DEBUG or settings.TEST else "https"
+ return f"{scheme}://{parts.netloc}/{bucket}"
+
+
# The full path, matched exactly. Django sends every unmatched path to the app catch-all, so a
# prefix match would also hand the app document this policy and stop it from starting.
REPLAY_PLAYER_FRAME_PATH = "/replay_player_frame/index.html"
@@ -258,6 +282,7 @@ class CSPMiddleware:
frame_ancestors += " http://localhost:8001"
connect_debug_url = "ws://localhost:8234" if settings.DEBUG or settings.TEST else ""
+ object_storage_source = object_storage_upload_source()
js_url = urlsplit(settings.JS_URL)
bundle_origin = f"{js_url.scheme}://{js_url.netloc}" if js_url.scheme and js_url.netloc else ""
csp_parts = [
@@ -339,7 +364,7 @@ class CSPMiddleware:
frame_ancestors,
# The live debugger's repo browser reads PostHog/posthog from the GitHub API. The path keeps
# the rest of the API, and every other repository, out of reach of injected script.
- f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://api.github.com/repos/PostHog/posthog/ https://raw.githubusercontent.com/PostHog/terminal-assets/",
+ f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://api.github.com/repos/PostHog/posthog/ https://raw.githubusercontent.com/PostHog/terminal-assets/ {object_storage_source}",
# https: lets heatmaps frame a customer's site. 'self' is for the replay player
# frame, whose document is same-origin: an http origin does not match https:.
"frame-src 'self' https:",
diff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.py
index 8dc9711495e9..8c0e4ca27279 100644
--- a/posthog/test/test_csp_middleware.py
+++ b/posthog/test/test_csp_middleware.py
@@ -13,6 +13,7 @@ from posthog.csp_middleware import (
CSPMiddleware,
app_csp_header_name,
narrowed_app_policy,
+ object_storage_upload_source,
)
@@ -295,6 +296,22 @@ class TestCSPMiddleware(APIBaseTest):
# Allowing the other region would hide a request that crossed regions by mistake.
assert not any(other_region in (urlsplit(source).hostname or "").split(".") for source in connect_src)
+ @override_settings(
+ OBJECT_STORAGE_PUBLIC_ENDPOINT="https://s3.us-east-1.amazonaws.com",
+ OBJECT_STORAGE_BUCKET="posthog-test-bucket",
+ )
+ def test_connect_src_admits_the_presigned_upload_endpoint(self) -> None:
+ # Narrowing must keep it: cloud enforces the narrowed policy, and an upload it drops
+ # fails in the browser with nothing logged server-side.
+ with override_settings(
+ TEST=False, DEBUG=False, CLOUD_DEPLOYMENT="US", SITE_URL="https://us.posthog.com", E2E_TESTING=False
+ ):
+ response = self.client.get("/")
+
+ policy = response["Content-Security-Policy"]
+ connect_src = next(part for part in policy.split("; ") if part.startswith("connect-src ")).split()
+ assert "https://s3.us-east-1.amazonaws.com/posthog-test-bucket" in connect_src
+
@override_settings(CLOUD_DEPLOYMENT="LOCAL")
class TestAppCspHeaderName(SimpleTestCase):
@@ -418,6 +435,39 @@ class TestNarrowedAppPolicy(SimpleTestCase):
]
+class TestObjectStorageUploadSource(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "shared_s3",
+ "https://s3.us-east-1.amazonaws.com",
+ "posthog-cloud-prod-us-east-1-app-assets",
+ "https://s3.us-east-1.amazonaws.com/posthog-cloud-prod-us-east-1-app-assets",
+ ),
+ ("dev_store_keeps_http", "http://objectstorage:19000", "posthog", "http://objectstorage:19000/posthog"),
+ ("endpoint_unset", "", "posthog", ""),
+ ("bucket_unset", "https://s3.us-east-1.amazonaws.com", "", ""),
+ ("not_a_fetchable_scheme", "s3://posthog-bucket", "posthog", ""),
+ ]
+ )
+ def test_source_carries_the_bucket_or_is_left_out(
+ self, _name: str, endpoint: str, bucket: str, expected: str
+ ) -> None:
+ with override_settings(OBJECT_STORAGE_PUBLIC_ENDPOINT=endpoint, OBJECT_STORAGE_BUCKET=bucket):
+ assert object_storage_upload_source() == expected
+
+ def test_a_plaintext_endpoint_is_named_over_https_outside_dev(self) -> None:
+ # Only the dev store is reached over http. Anywhere else the policy must not bless a
+ # bucket served in plaintext, whatever the endpoint is configured as.
+ with override_settings(
+ OBJECT_STORAGE_PUBLIC_ENDPOINT="http://storage.example.com",
+ OBJECT_STORAGE_BUCKET="posthog",
+ TEST=False,
+ DEBUG=False,
+ ):
+ assert object_storage_upload_source() == "https://storage.example.com/posthog"
+
+
class TestViewManagedCsp(SimpleTestCase):
@parameterized.expand(
[