: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
refactor(csp): sanitize urls in violation reports like crash reports (#104048)
Tom Piccirello626ff968a2f8
diff --git a/posthog/api/csp.py b/posthog/api/csp.pyindex f1f4054241b3..9b3554548e16 100644--- a/posthog/api/csp.py+++ b/posthog/api/csp.py@@ -2,7 +2,7 @@ import reimport jsonfrom datetime import UTC, datetime, timedeltafrom typing import Optional-from urllib.parse import urlsplit, urlunsplit+from urllib.parse import unquote, urlsplit, urlunsplitfrom django.conf import settingsfrom django.http import HttpResponse@@ -72,9 +72,51 @@ def sample_csp_report(properties: dict, percent: float, add_metadata: bool = Falreturn should_ingest_report+# Reports carry the URL of the document they came from, and auth routes embed live+# credentials as path segments (password reset, 2FA reset, email verification, invite and+# sharing links), so storing a URL verbatim would put redeemable tokens into events. A+# violation report repeats the document URL as its source file and, for a same-origin+# resource, its blocked URL. Query strings are dropped wholesale, and a path segment is+# masked when it is token-shaped: 16+ URL-safe characters that include a digit or mix upper and+# lower case. That matches Django auth tokens, UUIDs and base64url tokens such as sharing tokens,+# which can lack a digit, but not route names, which are lowercase. The check reads the decoded+# segment, because a link rewriter can percent-encode a token character and Django still decodes+# the path before it checks the token.+_TOKEN_LIKE_PATH_SEGMENT = re.compile(r"[A-Za-z0-9_.~-]{16,}")+++def _is_token_like(segment: str) -> bool:+ segment = unquote(segment)+ if not _TOKEN_LIKE_PATH_SEGMENT.fullmatch(segment):+ return False+ return any(c.isdigit() for c in segment) or (segment.lower() != segment and segment.upper() != segment)+++def sanitize_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 _is_token_like(segment) else segment for segment in parts.path.split("/"))+ return urlunsplit((parts.scheme, parts.netloc, path, "", ""))+++_REPORT_URI_URL_KEYS = frozenset({"document-uri", "referrer", "blocked-uri", "source-file"})+_REPORT_TO_URL_KEYS = frozenset({"documentURL", "document-uri", "referrer", "blockedURL", "blocked-uri", "sourceFile"})+# The endpoint also accepts report-to items that carry report-uri field names beside `type`+# rather than inside `body`, so the envelope can hold any of these.+_REPORT_ENVELOPE_URL_KEYS = _REPORT_TO_URL_KEYS | _REPORT_URI_URL_KEYS | {"url"}+++def _with_sanitized_urls(report: dict, url_keys: frozenset[str]) -> dict:+ return {key: sanitize_report_url(value) if key in url_keys else value for key, value in report.items()}++# https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/report-uridef parse_report_uri(data: dict) -> dict:- report_uri_data = data["csp-report"]+ report_uri_data = _with_sanitized_urls(data["csp-report"], _REPORT_URI_URL_KEYS)report_uri_data["script-sample"] = escape(report_uri_data.get("script-sample") or "")@@ -93,22 +135,23 @@ def parse_report_uri(data: dict) -> dict:"source_file": report_uri_data.get("source-file"),"status_code": report_uri_data.get("status-code"),"script_sample": report_uri_data.get("script-sample"),- # Keep the raw report for debugging- "raw_report": data,+ # Keep the raw report for debugging, but not its unsanitized urls.+ "raw_report": {**data, "csp-report": report_uri_data},}return properties# https://developer.mozilla.org/en-US/docs/Web/API/CSPViolationReportBodydef parse_report_to(data: dict) -> dict:- report_to_data = data.get("body", {})+ report_to_data = _with_sanitized_urls(data.get("body", {}), _REPORT_TO_URL_KEYS)+ envelope = _with_sanitized_urls(data, _REPORT_ENVELOPE_URL_KEYS)user_agent = data.get("user_agent") or report_to_data.get("user-agent")report_to_data["sample"] = escape(report_to_data.get("sample") or "")report_to_data["script-sample"] = escape(report_to_data.get("sample") or "")properties = {"report_type": data.get("type"),- "document_url": report_to_data.get("documentURL") or report_to_data.get("document-uri") or data.get("url"),+ "document_url": report_to_data.get("documentURL") or report_to_data.get("document-uri") or envelope.get("url"),"referrer": report_to_data.get("referrer"),"violated_directive": report_to_data.get("effectiveDirective")or report_to_data.get("violated-directive"), # Inferring from effectiveDirective@@ -122,8 +165,8 @@ def parse_report_to(data: dict) -> dict:"status_code": report_to_data.get("statusCode"),"script_sample": report_to_data.get("sample"),"user_agent": user_agent,- # Keep the raw report for debugging- "raw_report": data,+ # Keep the raw report for debugging, but not its unsanitized urls.+ "raw_report": {**envelope, "body": report_to_data},}return properties@@ -139,35 +182,12 @@ 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"))+ document_url = sanitize_report_url(data.get("url"))return {"reason": body.get("reason") or "unknown","id": body.get("crashId"),diff --git a/posthog/api/test/test_csp.py b/posthog/api/test/test_csp.pyindex 337c64bebf54..3b59fc645e9f 100644--- a/posthog/api/test/test_csp.py+++ b/posthog/api/test/test_csp.py@@ -5,10 +5,18 @@ from html import escapeimport time_machinefrom unittest.mock import patch-from django.test import TestCase+from django.test import SimpleTestCase, TestCasefrom django.test.client import RequestFactory-from posthog.api.csp import parse_report_to, parse_report_uri, process_csp_report, sample_csp_report+from parameterized import parameterized++from posthog.api.csp import (+ parse_report_to,+ parse_report_uri,+ process_csp_report,+ sample_csp_report,+ sanitize_report_url,+)from posthog.sampling import sample_on_property@@ -682,3 +690,34 @@ class TestCSPModule(TestCase):result2 = sample_csp_report(properties1.copy(), 0.5)assert result1 == result2, "Same URL+time should produce consistent sampling results within the same minute"+++class TestSanitizeReportUrl(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "django_reset_token",+ "https://app.example.com/reset/0198aaaa-bbbb-cccc-dddd-eeeeffff0000/abc123-0f0f0f0f0f0f0f0f",+ "https://app.example.com/reset/<redacted>/<redacted>",+ ),+ # token_urlsafe output lacks a digit about once in 165 sharing tokens.+ (+ "sharing_token_without_a_digit",+ "https://app.example.com/shared/AbcdEfghIjklMnop_QrstUvwxYz-AbCd",+ "https://app.example.com/shared/<redacted>",+ ),+ (+ "percent_encoded_token_character",+ "https://app.example.com/reset/0198aaaa-bbbb-cccc-dddd-eeeeffff0000/abc123%2D0f0f0f0f0f0f0f0f",+ "https://app.example.com/reset/<redacted>/<redacted>",+ ),+ # Triage groups reports by route, so a long lowercase route name must survive.+ (+ "long_route_names",+ "https://app.example.com/project/2/session-recordings/authorize_and_redirect",+ "https://app.example.com/project/2/session-recordings/authorize_and_redirect",+ ),+ ]+ )+ def test_masks_tokens_but_keeps_route_names(self, _name: str, url: str, expected: str) -> None:+ assert sanitize_report_url(url) == expecteddiff --git a/posthog/api/test/test_report.py b/posthog/api/test/test_report.pyindex b96c06f376fa..8775217c34f0 100644--- a/posthog/api/test/test_report.py+++ b/posthog/api/test/test_report.py@@ -190,31 +190,84 @@ class TestCspReport(BaseTest):assert [e["event"] for e in events] == ["$csp_violation", "$browser_crash_report"]assert events[1]["properties"]["$browser_crash_reason"] == "unknown"+ @parameterized.expand(+ [+ ("crash_report", "application/reports+json", lambda url: [{**CRASH_REPORT, "url": url}]),+ # A violation repeats the document URL as its source file, and a same-origin resource puts it+ # in the blocked URL too, so masking the document URL alone would still store the token.+ (+ "violation_report_to",+ "application/reports+json",+ lambda url: [+ {+ "type": "csp-violation",+ "url": url,+ "body": {+ "documentURL": url,+ "referrer": url,+ "blockedURL": url,+ "sourceFile": url,+ "effectiveDirective": "img-src",+ },+ }+ ],+ ),+ # Not a shape browsers send, but the endpoint accepts it, so it must not store URLs verbatim.+ (+ "violation_report_to_with_top_level_fields",+ "application/reports+json",+ lambda url: [+ {+ "type": "csp-violation",+ "url": url,+ "document-uri": url,+ "referrer": url,+ "blocked-uri": url,+ "source-file": url,+ "effective-directive": "img-src",+ }+ ],+ ),+ (+ "violation_report_uri",+ "application/csp-report",+ lambda url: {+ "csp-report": {+ "document-uri": url,+ "referrer": url,+ "blocked-uri": url,+ "source-file": url,+ "violated-directive": "img-src",+ }+ },+ ),+ ]+ )@patch("posthog.api.report.capture_batch_internal")- def test_crash_url_credentials_are_redacted(self, mock_batch_capture):+ @patch("posthog.api.report.capture_internal")+ def test_report_url_credentials_are_redacted(+ self, _name, content_type, build_payload, mock_capture, mock_batch_capture+ ):+ mock_capture.return_value = MagicMock(raise_for_status=MagicMock())mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())# shaped like a Django reset token, so the length-plus-digit heuristic must mask itreset_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",- }+ reset_page = 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",+ data=json.dumps(build_payload(reset_page)),+ content_type=content_type,)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>"- )+ if mock_batch_capture.called:+ (event,) = mock_batch_capture.call_args.kwargs["events"]+ properties = event["properties"]+ else:+ properties = mock_capture.call_args.kwargs["properties"]+ assert reset_token not in json.dumps(properties)+ assert properties["$current_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: