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): bound report payloads and drop debug logging (#74440)

Tom Piccirelloc9cbeb6f9ad9
diff --git a/posthog/api/csp.py b/posthog/api/csp.py
index e0f694ba3619..d19790bd5844 100644
--- a/posthog/api/csp.py
+++ b/posthog/api/csp.py
@@ -2,10 +2,12 @@ import json
from datetime import UTC, datetime
from typing import Optional
+from django.conf import settings
from django.http import HttpResponse
from django.utils.html import escape
import structlog
+from prometheus_client import Counter
from rest_framework import status
from posthog.exceptions import generate_exception_response
@@ -15,6 +17,12 @@ from posthog.utils_cors import cors_response
logger = structlog.get_logger(__name__)
+CSP_REPORT_REJECTED = Counter(
+ "csp_report_rejected",
+ "CSP reports rejected before processing, by reason.",
+ labelnames=["reason"],
+)
+
CSP_REPORT_TYPES_MAPPING_TABLE = """
| Normalized Key | report-to format | report-uri format |
| -------------------------- | ------------------------------------ | ---------------------------------- |
@@ -122,6 +130,10 @@ def is_csp_violation(data: dict) -> bool:
return "type" in data and data["type"] == "csp-violation"
+class CSPReportTooLarge(Exception):
+ pass
+
+
def build_csp_event(props: dict, distinct_id: str, session_id: str, version: str, user_agent: Optional[str]) -> dict:
props = {f"$csp_{k}": v for k, v in props.items()}
@@ -163,8 +175,22 @@ def process_csp_report(request):
)
return None, None
+ body_size = len(request.body)
+ if body_size > settings.CSP_REPORT_MAX_BODY_BYTES:
+ CSP_REPORT_REJECTED.labels(reason="body_too_large").inc()
+ raise CSPReportTooLarge(f"CSP report body of {body_size} bytes exceeds the limit")
+
csp_data = json.loads(request.body)
+ # A reports+json bundle can carry other Reporting API types (deprecation, intervention, ...)
+ # alongside csp-violation entries; only the latter become events, so bound on that count
+ # rather than the raw bundle length to avoid rejecting legitimate mixed-type batches.
+ if isinstance(csp_data, list):
+ violation_count = sum(1 for item in csp_data if is_csp_violation(item))
+ if violation_count > settings.CSP_REPORT_MAX_REPORTS:
+ CSP_REPORT_REJECTED.labels(reason="too_many_reports").inc()
+ raise CSPReportTooLarge(f"CSP report bundle of {violation_count} violations exceeds the limit")
+
distinct_id = request.GET.get("distinct_id") or str(uuid7())
session_id = request.GET.get("session_id") or str(uuid7())
version = request.GET.get("v") or "unknown"
@@ -231,6 +257,17 @@ def process_csp_report(request):
else:
raise ValueError("Invalid CSP report")
+ except CSPReportTooLarge as e:
+ logger.warning("CSP report rejected - too large", reason=str(e))
+ return None, cors_response(
+ request,
+ generate_exception_response(
+ "capture",
+ "CSP report too large",
+ code="csp_report_too_large",
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
+ ),
+ )
except json.JSONDecodeError as e:
logger.exception("Invalid CSP report JSON format", error=e)
return None, cors_response(
diff --git a/posthog/api/report.py b/posthog/api/report.py
index e7ff6de7be6d..242b59f3139f 100644
--- a/posthog/api/report.py
+++ b/posthog/api/report.py
@@ -24,20 +24,6 @@ def get_csp_event(request):
if request.method == "OPTIONS":
return cors_response(request, JsonResponse({"status": 1}))
- debug_enabled = request.GET.get("debug", "").lower() == "true"
- if debug_enabled:
- logger.exception(
- "CSP debug request",
- error=ValueError("CSP debug request"),
- method=request.method,
- url=request.build_absolute_uri(),
- content_type=request.content_type,
- headers=dict(request.headers),
- query_params=dict(request.GET),
- body_size=len(request.body) if request.body else 0,
- body=request.body.decode("utf-8", errors="ignore") if request.body else None,
- )
-
csp_report, error_response = process_csp_report(request)
if error_response:
return error_response
diff --git a/posthog/api/test/test_report.py b/posthog/api/test/test_report.py
index c0c9af0a271a..33cf422b9fd7 100644
--- a/posthog/api/test/test_report.py
+++ b/posthog/api/test/test_report.py
@@ -5,7 +5,31 @@ from unittest.mock import MagicMock, patch
from django.test.client import Client
+from parameterized import parameterized
from rest_framework import status
+from structlog.testing import capture_logs
+
+from posthog.api.csp import CSP_REPORT_REJECTED
+
+SINGLE_VIOLATION_REPORT_URI = {
+ "csp-report": {
+ "document-uri": "https://example.com/foo/bar",
+ "violated-directive": "default-src self",
+ }
+}
+
+SINGLE_VIOLATION_REPORT_TO = {
+ "type": "csp-violation",
+ "body": {
+ "documentURL": "https://example.com/foo/bar",
+ "effectiveDirective": "script-src",
+ },
+}
+
+NON_VIOLATION_REPORT = {
+ "type": "deprecation",
+ "body": {"id": "some-deprecated-api"},
+}
class TestCspReport(BaseTest):
@@ -20,6 +44,103 @@ class TestCspReport(BaseTest):
# it is really important to know that /capture is CSRF exempt. Enforce checking in the client
self.client = Client(enforce_csrf_checks=True)
+ @parameterized.expand(
+ [
+ (
+ "report_to_over_count_cap",
+ "application/reports+json",
+ [SINGLE_VIOLATION_REPORT_TO] * 3,
+ {"CSP_REPORT_MAX_REPORTS": 2},
+ "too_many_reports",
+ ),
+ (
+ "report_to_over_body_cap",
+ "application/reports+json",
+ [SINGLE_VIOLATION_REPORT_TO] * 3,
+ {"CSP_REPORT_MAX_BODY_BYTES": 64},
+ "body_too_large",
+ ),
+ (
+ "report_uri_over_body_cap",
+ "application/csp-report",
+ SINGLE_VIOLATION_REPORT_URI,
+ {"CSP_REPORT_MAX_BODY_BYTES": 64},
+ "body_too_large",
+ ),
+ (
+ "report_to_over_count_cap_buffered",
+ "application/reports+json",
+ [SINGLE_VIOLATION_REPORT_TO] * 3,
+ {"CSP_REPORT_MAX_REPORTS": 2, "CSP_REPORT_BUFFERED_FORWARD": True},
+ "too_many_reports",
+ ),
+ ]
+ )
+ def test_oversized_csp_report_is_rejected_before_expansion(
+ self, _name, content_type, payload, overrides, expected_reason
+ ):
+ rejected_before = CSP_REPORT_REJECTED.labels(reason=expected_reason)._value.get()
+
+ with (
+ self.settings(**overrides),
+ patch("posthog.api.report.capture_batch_internal") as mock_batch_capture,
+ patch("posthog.api.report.capture_internal") as mock_capture,
+ patch("posthog.api.report.csp_report_buffer") as mock_buffer,
+ ):
+ mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
+ mock_capture.return_value = MagicMock(raise_for_status=MagicMock())
+
+ response = self.client.post(
+ f"/report/?token={self.team.api_token}",
+ data=json.dumps(payload),
+ content_type=content_type,
+ )
+
+ assert response.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
+ mock_batch_capture.assert_not_called()
+ mock_capture.assert_not_called()
+ mock_buffer.enqueue.assert_not_called()
+ assert CSP_REPORT_REJECTED.labels(reason=expected_reason)._value.get() - rejected_before == 1
+
+ @patch("posthog.api.report.capture_batch_internal")
+ def test_mixed_report_types_not_rejected_by_violation_count_cap(self, mock_batch_capture):
+ # A reports+json bundle can legitimately carry non-CSP report types (deprecation,
+ # intervention, ...) alongside csp-violation entries; the count cap must bound the
+ # number of violations that become events, not the raw bundle length.
+ mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
+
+ bundle = [SINGLE_VIOLATION_REPORT_TO, NON_VIOLATION_REPORT, NON_VIOLATION_REPORT]
+
+ with self.settings(CSP_REPORT_MAX_REPORTS=1):
+ response = self.client.post(
+ f"/report/?token={self.team.api_token}",
+ data=json.dumps(bundle),
+ content_type="application/reports+json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ mock_batch_capture.assert_called_once()
+ assert len(mock_batch_capture.call_args.kwargs["events"]) == 1
+
+ def test_csp_report_never_logs_request_headers(self):
+ with capture_logs() as logs, patch("posthog.api.report.capture_internal") as mock_capture:
+ mock_capture.return_value = MagicMock(raise_for_status=MagicMock())
+
+ response = self.client.post(
+ f"/report/?token={self.team.api_token}&debug=true",
+ data=json.dumps(SINGLE_VIOLATION_REPORT_URI),
+ content_type="application/csp-report",
+ headers={
+ "cookie": "sessionid=sentinel-session-credential",
+ "authorization": "Bearer sentinel-bearer-credential",
+ },
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ rendered_logs = json.dumps(logs, default=str)
+ assert "sentinel-session-credential" not in rendered_logs
+ assert "sentinel-bearer-credential" not in rendered_logs
+
@patch("posthog.api.report.capture_internal")
def test_submit_csp_report_to_new_internal_capture(self, mock_capture) -> None:
payload = {
@@ -317,93 +438,6 @@ class TestCspReport(BaseTest):
mock_capture.assert_called_once()
assert len(mock_capture.call_args.kwargs["events"]) == 2
- @patch("posthog.api.report.capture_internal")
- @patch("posthog.api.report.logger")
- def test_csp_debug_logging_enabled(self, mock_logger, mock_capture):
- mock_capture.return_value = MagicMock(status_code=204)
-
- """Test that debug logging is enabled when debug=true parameter is present"""
- csp_report = {
- "csp-report": {
- "document-uri": "https://example.com/foo/bar",
- "violated-directive": "default-src self",
- }
- }
-
- response = self.client.post(
- f"/report/?token={self.team.api_token}&debug=true",
- data=json.dumps(csp_report),
- content_type="application/csp-report",
- )
-
- assert status.HTTP_204_NO_CONTENT == response.status_code
- mock_capture.assert_called_once()
-
- mock_logger.exception.assert_called_once()
- call_args = mock_logger.exception.call_args
- assert call_args[0][0] == "CSP debug request"
- assert call_args[1]["method"] == "POST"
- assert "debug=true" in call_args[1]["url"]
- assert call_args[1]["content_type"] == "application/csp-report"
- assert "body" in call_args[1]
-
- @patch("posthog.api.report.capture_internal")
- @patch("posthog.api.report.logger")
- def test_csp_debug_logging_disabled(self, mock_logger, mock_capture):
- mock_capture.return_value = MagicMock(status_code=204)
-
- csp_report = {
- "csp-report": {
- "document-uri": "https://example.com/foo/bar",
- "violated-directive": "default-src self",
- }
- }
-
- response = self.client.post(
- f"/report/?token={self.team.api_token}",
- data=json.dumps(csp_report),
- content_type="application/csp-report",
- )
-
- assert status.HTTP_204_NO_CONTENT == response.status_code
- mock_capture.assert_called_once()
- mock_logger.exception.assert_not_called()
-
- @patch("posthog.api.report.capture_internal")
- @patch("posthog.api.report.logger")
- def test_csp_debug_logging_case_insensitive(self, mock_logger, mock_capture):
- mock_capture.return_value = MagicMock(status_code=204)
-
- csp_report = {
- "csp-report": {
- "document-uri": "https://example.com/foo/bar",
- "violated-directive": "default-src self",
- }
- }
-
- response = self.client.post(
- f"/report/?token={self.team.api_token}&debug=TRUE",
- data=json.dumps(csp_report),
- content_type="application/csp-report",
- )
-
- assert status.HTTP_204_NO_CONTENT == response.status_code
- mock_logger.exception.assert_called_once()
- mock_capture.assert_called_once()
-
- mock_logger.reset_mock()
- mock_capture.reset_mock()
-
- response = self.client.post(
- f"/report/?token={self.team.api_token}&debug=True",
- data=json.dumps(csp_report),
- content_type="application/csp-report",
- )
-
- assert status.HTTP_204_NO_CONTENT == response.status_code
- mock_logger.exception.assert_called_once()
- mock_capture.assert_called_once()
-
def test_csp_sampled_out_report_uri_does_not_return_400(self):
csp_report = {
"csp-report": {
diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.py
index b5ae6200bc47..42c4e1b1195b 100644
--- a/posthog/settings/ingestion.py
+++ b/posthog/settings/ingestion.py
@@ -83,6 +83,15 @@ CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS = get_from_env(
# Chunk fan-out reuses CAPTURE_INTERNAL_MAX_WORKERS (above) for its thread pool.
CAPTURE_INTERNAL_BATCH_CHUNK_SIZE = get_from_env("CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", type_cast=int, default=200)
+# Inbound bounds for /report/. The endpoint is unauthenticated and expands each CSP violation in
+# the body into its own event (a reports+json bundle may also carry other Reporting API types,
+# which are accepted but ignored), so without these the generic upload limit
+# (DATA_UPLOAD_MAX_MEMORY_SIZE) is the only ceiling and one request can fan out into an unbounded
+# batch. A real browser report bundle is a handful of violations of a few KB each, so both caps sit
+# far above legitimate traffic.
+CSP_REPORT_MAX_BODY_BYTES = get_from_env("CSP_REPORT_MAX_BODY_BYTES", type_cast=int, default=256 * 1024)
+CSP_REPORT_MAX_REPORTS = get_from_env("CSP_REPORT_MAX_REPORTS", type_cast=int, default=100)
+
# Buffered CSP capture-forward: when enabled, /report/ enqueues accepted reports to a
# bounded in-process buffer and returns 204 immediately; a background thread batches
# them to capture-rs. Keeps request-worker hold time independent of capture-rs latency,