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.

feat(report): ingest browser crash reports as events (#81949)

Thomas Obermüllerdbecc3fb9f08
diff --git a/posthog/api/csp.py b/posthog/api/csp.py
index d19790bd5844..f1f4054241b3 100644
--- a/posthog/api/csp.py
+++ b/posthog/api/csp.py
@@ -1,6 +1,8 @@
+import re
import json
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Optional
+from urllib.parse import urlsplit, urlunsplit
from django.conf import settings
from django.http import HttpResponse
@@ -130,6 +132,83 @@ def is_csp_violation(data: dict) -> bool:
return "type" in data and data["type"] == "csp-violation"
+# Browsers only deliver crash reports to the Reporting-Endpoints entry named `default`,
+# so these arrive here only for sites whose header defines one.
+# https://developer.mozilla.org/en-US/docs/Web/API/Reporting_API#crash_reports
+def is_crash_report(data: dict) -> bool:
+ return "type" in data and data["type"] == "crash"
+
+
+# Crash reports carry the crashed document's URL, and auth routes embed live credentials
+# as path segments (password reset, 2FA reset, email verification, invite and sharing
+# links), so storing the URL verbatim would put redeemable tokens into events. Query
+# strings are dropped wholesale, and a path segment is masked when it is token-shaped:
+# 16+ URL-safe characters including a digit, which matches Django auth tokens, UUIDs,
+# and sharing tokens but not route names.
+_TOKEN_LIKE_PATH_SEGMENT = re.compile(r"[A-Za-z0-9_.~-]{16,}")
+
+
+def sanitize_crash_report_url(url: object) -> Optional[str]:
+ if not isinstance(url, str) or not url:
+ return None
+ try:
+ parts = urlsplit(url)
+ except ValueError:
+ return None
+ path = "/".join(
+ "<redacted>" if _TOKEN_LIKE_PATH_SEGMENT.fullmatch(segment) and any(c.isdigit() for c in segment) else segment
+ for segment in parts.path.split("/")
+ )
+ return urlunsplit((parts.scheme, parts.netloc, path, "", ""))
+
+
+def parse_crash_report(data: dict) -> dict:
+ body = data.get("body")
+ if not isinstance(body, dict):
+ # A malformed body still leaves the envelope's signal: the tab crashed.
+ body = {}
+ document_url = sanitize_crash_report_url(data.get("url"))
+ return {
+ "reason": body.get("reason") or "unknown",
+ "id": body.get("crashId"),
+ "is_top_level": body.get("is_top_level"),
+ "visibility_state": body.get("visibility_state"),
+ "age_ms": data.get("age"),
+ "document_url": document_url,
+ "user_agent": data.get("user_agent"),
+ # Keep the raw report for debugging, but not its unsanitized url.
+ "raw_report": {**data, "url": document_url},
+ }
+
+
+# The browser queues crash reports and delivers them on a later visit to the origin, so
+# receipt time can be far from the crash itself; `age` recovers the actual crash time.
+# Bounded so a garbage value can't backdate the event arbitrarily.
+MAX_CRASH_REPORT_AGE_MS = 7 * 24 * 3600 * 1000
+
+
+def build_crash_event(props: dict, distinct_id: str, session_id: str, user_agent: Optional[str]) -> dict:
+ timestamp = datetime.now(UTC)
+ age_ms = props.get("age_ms")
+ if isinstance(age_ms, (int, float)) and 0 <= age_ms <= MAX_CRASH_REPORT_AGE_MS:
+ timestamp -= timedelta(milliseconds=age_ms)
+
+ props = {f"$browser_crash_{k}": v for k, v in props.items()}
+
+ return {
+ "event": "$browser_crash_report",
+ "distinct_id": distinct_id,
+ "timestamp": timestamp.isoformat(),
+ "properties": {
+ "$session_id": session_id,
+ "$current_url": props["$browser_crash_document_url"],
+ "$process_person_profile": False,
+ "$raw_user_agent": props.get("$browser_crash_user_agent") or user_agent,
+ **props,
+ },
+ }
+
+
class CSPReportTooLarge(Exception):
pass
@@ -154,10 +233,11 @@ def build_csp_event(props: dict, distinct_id: str, session_id: str, version: str
def process_csp_report(request):
"""
- Process a Content Security Policy (CSP) report from a browser.
+ Process a Reporting API payload from a browser.
- Takes the incoming CSP report JSON, formats it as a PostHog event,
- and returns it for ingestion through the regular event pipeline.
+ Takes the incoming report JSON (CSP violations, plus crash reports when the site
+ routes its `default` reporting endpoint here), formats each report as a PostHog
+ event, and returns them for ingestion through the regular event pipeline.
Returns:
tuple: (csp_report, error_response)
@@ -183,13 +263,13 @@ def process_csp_report(request):
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.
+ # alongside the entries we ingest (csp-violation, crash); only those 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:
+ report_count = sum(1 for item in csp_data if is_csp_violation(item) or is_crash_report(item))
+ if report_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")
+ raise CSPReportTooLarge(f"CSP report bundle of {report_count} reports exceeds the limit")
distinct_id = request.GET.get("distinct_id") or str(uuid7())
session_id = request.GET.get("session_id") or str(uuid7())
@@ -231,18 +311,27 @@ def process_csp_report(request):
if request.content_type == "application/reports+json":
if isinstance(csp_data, list):
- violations_props = [parse_report_to(item) for item in csp_data if is_csp_violation(item)]
- elif isinstance(csp_data, dict) and is_csp_violation(csp_data):
- violations_props = [parse_report_to(csp_data)]
+ items = csp_data
+ elif isinstance(csp_data, dict) and (is_csp_violation(csp_data) or is_crash_report(csp_data)):
+ items = [csp_data]
else:
raise ValueError("Invalid CSP report")
+ violations_props = [parse_report_to(item) for item in items if is_csp_violation(item)]
+ crash_props = [parse_crash_report(item) for item in items if is_crash_report(item)]
+
sampled_violations = []
for prop in violations_props:
if sample_csp_report(prop, sample_rate, add_metadata=True):
sampled_violations.append(prop)
- if not sampled_violations:
+ # Crash reports skip sampling: they are rare and each one is a dead tab, so
+ # applying the CSP sample rate would silently discard most of the signal.
+ events = [
+ build_csp_event(prop, distinct_id, session_id, version, user_agent) for prop in sampled_violations
+ ] + [build_crash_event(prop, distinct_id, session_id, user_agent) for prop in crash_props]
+
+ if not events:
logger.warning(
"CSP report sampled out - report-to format",
total_violations=len(violations_props),
@@ -250,9 +339,7 @@ def process_csp_report(request):
)
return None, cors_response(request, HttpResponse(status=status.HTTP_204_NO_CONTENT))
- return [
- build_csp_event(prop, distinct_id, session_id, version, user_agent) for prop in sampled_violations
- ], None
+ return events, None
else:
raise ValueError("Invalid CSP report")
diff --git a/posthog/api/test/test_report.py b/posthog/api/test/test_report.py
index 33cf422b9fd7..1366b0e7e8ee 100644
--- a/posthog/api/test/test_report.py
+++ b/posthog/api/test/test_report.py
@@ -1,5 +1,6 @@
import json
+from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -31,6 +32,14 @@ NON_VIOLATION_REPORT = {
"body": {"id": "some-deprecated-api"},
}
+CRASH_REPORT = {
+ "type": "crash",
+ "age": 42000,
+ "url": "https://app.example.com/dashboard/1",
+ "user_agent": "Mozilla/5.0 (Macintosh) Chrome/151.0",
+ "body": {"reason": "oom", "crashId": "abc123", "is_top_level": True, "visibility_state": "visible"},
+}
+
class TestCspReport(BaseTest):
"""
@@ -74,6 +83,13 @@ class TestCspReport(BaseTest):
{"CSP_REPORT_MAX_REPORTS": 2, "CSP_REPORT_BUFFERED_FORWARD": True},
"too_many_reports",
),
+ (
+ "crash_reports_over_count_cap",
+ "application/reports+json",
+ [CRASH_REPORT] * 3,
+ {"CSP_REPORT_MAX_REPORTS": 2},
+ "too_many_reports",
+ ),
]
)
def test_oversized_csp_report_is_rejected_before_expansion(
@@ -122,6 +138,84 @@ class TestCspReport(BaseTest):
mock_batch_capture.assert_called_once()
assert len(mock_batch_capture.call_args.kwargs["events"]) == 1
+ @patch("posthog.api.report.capture_batch_internal")
+ def test_crash_report_becomes_backdated_event(self, mock_batch_capture):
+ mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
+
+ with freeze_time("2026-08-12T10:00:00Z"):
+ response = self.client.post(
+ f"/report/?token={self.team.api_token}&distinct_id=user-distinct-id",
+ data=json.dumps([CRASH_REPORT]),
+ content_type="application/reports+json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ events = mock_batch_capture.call_args.kwargs["events"]
+ assert len(events) == 1
+ event = events[0]
+ assert event["event"] == "$browser_crash_report"
+ assert event["distinct_id"] == "user-distinct-id"
+ assert event["properties"]["$browser_crash_reason"] == "oom"
+ assert event["properties"]["$browser_crash_is_top_level"] is True
+ assert event["properties"]["$current_url"] == "https://app.example.com/dashboard/1"
+ # the report's `age` (42s here) recovers the crash time; delivery happens on a later visit
+ assert event["timestamp"] == "2026-08-12T09:59:18+00:00"
+
+ @patch("posthog.api.report.capture_batch_internal")
+ def test_crash_reports_bypass_csp_sampling(self, mock_batch_capture):
+ mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
+
+ response = self.client.post(
+ f"/report/?token={self.team.api_token}&sample_rate=0",
+ data=json.dumps([SINGLE_VIOLATION_REPORT_TO, CRASH_REPORT]),
+ content_type="application/reports+json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ events = mock_batch_capture.call_args.kwargs["events"]
+ assert [e["event"] for e in events] == ["$browser_crash_report"]
+
+ @patch("posthog.api.report.capture_batch_internal")
+ def test_malformed_crash_body_does_not_abort_the_bundle(self, mock_batch_capture):
+ mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
+
+ response = self.client.post(
+ f"/report/?token={self.team.api_token}",
+ data=json.dumps([SINGLE_VIOLATION_REPORT_TO, {**CRASH_REPORT, "body": "corrupted"}]),
+ content_type="application/reports+json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ events = mock_batch_capture.call_args.kwargs["events"]
+ assert [e["event"] for e in events] == ["$csp_violation", "$browser_crash_report"]
+ assert events[1]["properties"]["$browser_crash_reason"] == "unknown"
+
+ @patch("posthog.api.report.capture_batch_internal")
+ def test_crash_url_credentials_are_redacted(self, mock_batch_capture):
+ mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
+ # shaped like a Django reset token, so the length-plus-digit heuristic must mask it
+ reset_token = "abc123-0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"
+ crash_on_reset_page = {
+ **CRASH_REPORT,
+ "url": f"https://app.example.com/reset/0198aaaa-bbbb-cccc-dddd-eeeeffff0000/{reset_token}?next=/replay",
+ }
+
+ response = self.client.post(
+ f"/report/?token={self.team.api_token}",
+ data=json.dumps([crash_on_reset_page]),
+ content_type="application/reports+json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ events = mock_batch_capture.call_args.kwargs["events"]
+ assert len(events) == 1
+ event = events[0]
+ assert reset_token not in json.dumps(event)
+ assert event["properties"]["$current_url"] == "https://app.example.com/reset/<redacted>/<redacted>"
+ assert event["properties"]["$browser_crash_raw_report"]["url"] == (
+ "https://app.example.com/reset/<redacted>/<redacted>"
+ )
+
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())
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 9b8e31f4c257..7fedf71b35d1 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1173,8 +1173,11 @@ class CSPMiddleware:
"report-to posthog",
]
+ # Browsers only deliver crash reports to the endpoint named `default`; the CSP
+ # `report-to posthog` directive keeps routing violations to `posthog`.
+ admin_report_endpoint = "https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&v=2"
response.headers["Reporting-Endpoints"] = (
- 'posthog="https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&v=2"'
+ f'posthog="{admin_report_endpoint}", default="{admin_report_endpoint}"'
)
response.headers["Content-Security-Policy"] = "; ".join(csp_parts)
else:
@@ -1205,9 +1208,16 @@ class CSPMiddleware:
"report-to posthog",
]
- response.headers["Reporting-Endpoints"] = (
- 'posthog="https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&sample_rate=0.1&v=2"'
- )
+ report_endpoint = "https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&sample_rate=0.1&v=2"
+ user = getattr(request, "user", None)
+ if user is not None and user.is_authenticated and getattr(user, "distinct_id", None):
+ # Crash reports arrive after the tab already died, so the report body is the
+ # only chance to attribute them; carrying the distinct_id in the endpoint URL
+ # ties the event to the person instead of a random per-report id.
+ report_endpoint += "&" + urlencode({"distinct_id": user.distinct_id})
+ # Browsers only deliver crash reports to the endpoint named `default`; the CSP
+ # `report-to posthog` directive keeps routing violations to `posthog`.
+ response.headers["Reporting-Endpoints"] = f'posthog="{report_endpoint}", default="{report_endpoint}"'
response.headers["Content-Security-Policy-Report-Only"] = "; ".join(csp_parts)
return response
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index c8c19b079a9a..25a3c9691eeb 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1868,6 +1868,22 @@ class TestCSPMiddleware(APIBaseTest):
assert "Content-Security-Policy-Report-Only" in response
assert "Content-Security-Policy" not in response
+ def test_html_response_declares_default_reporting_endpoint_with_distinct_id(self):
+ # Browsers only deliver crash reports to the endpoint named `default`, so dropping or
+ # renaming it silently stops crash ingestion.
+ response = self.client.get("/")
+ header = response["Reporting-Endpoints"]
+ assert 'posthog="https://us.i.posthog.com/report/' in header
+ assert 'default="https://us.i.posthog.com/report/' in header
+ assert f"distinct_id={self.user.distinct_id}" in header
+
+ def test_reporting_endpoints_omit_distinct_id_when_logged_out(self):
+ self.client.logout()
+ response = self.client.get("/login")
+ header = response["Reporting-Endpoints"]
+ assert 'default="https://us.i.posthog.com/report/' in header
+ assert "distinct_id" not in header
+
class TestSocialAuthExceptionMiddleware(APIBaseTest):
CONFIG_AUTO_LOGIN = False