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): record the reporting browser's ip on reports (#105594)

posthog[bot]2991ad92804b
diff --git a/posthog/api/csp.py b/posthog/api/csp.py
index 9b3554548e16..09d6b377195c 100644
--- a/posthog/api/csp.py
+++ b/posthog/api/csp.py
@@ -15,6 +15,7 @@ from rest_framework import status
from posthog.exceptions import generate_exception_response
from posthog.models.utils import uuid7
from posthog.sampling import sample_on_property
+from posthog.utils import get_ip_address
from posthog.utils_cors import cors_response
logger = structlog.get_logger(__name__)
@@ -207,7 +208,9 @@ def parse_crash_report(data: dict) -> dict:
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:
+def build_crash_event(
+ props: dict, distinct_id: str, session_id: str, user_agent: Optional[str], ip: Optional[str] = None
+) -> 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:
@@ -224,16 +227,30 @@ def build_crash_event(props: dict, distinct_id: str, session_id: str, user_agent
"$current_url": props["$browser_crash_document_url"],
"$process_person_profile": False,
"$raw_user_agent": props.get("$browser_crash_user_agent") or user_agent,
+ **_ip_property(ip),
**props,
},
}
+# capture-rs records 127.0.0.1 for every internal capture, so the event carries the browser's
+# address as `$ip`. Ingestion keeps an explicit `$ip` and still drops it for teams that anonymize IPs.
+def _ip_property(ip: Optional[str]) -> dict:
+ return {"$ip": ip} if ip else {}
+
+
class CSPReportTooLarge(Exception):
pass
-def build_csp_event(props: dict, distinct_id: str, session_id: str, version: str, user_agent: Optional[str]) -> dict:
+def build_csp_event(
+ props: dict,
+ distinct_id: str,
+ session_id: str,
+ version: str,
+ user_agent: Optional[str],
+ ip: Optional[str] = None,
+) -> dict:
props = {f"$csp_{k}": v for k, v in props.items()}
return {
@@ -246,6 +263,7 @@ def build_csp_event(props: dict, distinct_id: str, session_id: str, version: str
"$current_url": props["$csp_document_url"],
"$process_person_profile": False,
"$raw_user_agent": user_agent,
+ **_ip_property(ip),
**props,
},
}
@@ -295,6 +313,7 @@ def process_csp_report(request):
session_id = request.GET.get("session_id") or str(uuid7())
version = request.GET.get("v") or "unknown"
user_agent = request.headers.get("User-Agent")
+ ip = get_ip_address(request)
try:
sample_rate = request.GET.get("sample_rate", 1.0)
@@ -325,6 +344,7 @@ def process_csp_report(request):
session_id,
version,
user_agent,
+ ip,
),
None,
)
@@ -348,8 +368,8 @@ def process_csp_report(request):
# 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]
+ build_csp_event(prop, distinct_id, session_id, version, user_agent, ip) for prop in sampled_violations
+ ] + [build_crash_event(prop, distinct_id, session_id, user_agent, ip) for prop in crash_props]
if not events:
logger.warning(
diff --git a/posthog/api/test/test_report.py b/posthog/api/test/test_report.py
index 8775217c34f0..db770049de5e 100644
--- a/posthog/api/test/test_report.py
+++ b/posthog/api/test/test_report.py
@@ -400,6 +400,38 @@ class TestCspReport(BaseTest):
assert status.HTTP_204_NO_CONTENT == response.status_code
assert mock_capture.call_count == 1
+ @parameterized.expand(
+ [
+ ("report_uri", "application/csp-report", SINGLE_VIOLATION_REPORT_URI, "$csp_violation"),
+ ("report_to", "application/reports+json", [SINGLE_VIOLATION_REPORT_TO], "$csp_violation"),
+ ("crash", "application/reports+json", [CRASH_REPORT], "$browser_crash_report"),
+ ]
+ )
+ @patch("posthog.api.report.capture_batch_internal")
+ @patch("posthog.api.report.capture_internal")
+ def test_report_events_carry_the_reporting_client_ip(
+ self, _name, content_type, payload, event_name, mock_capture, mock_batch_capture
+ ):
+ mock_capture.return_value = MagicMock(raise_for_status=MagicMock())
+ mock_batch_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,
+ HTTP_X_FORWARDED_FOR="203.0.113.7, 10.0.0.1",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ if mock_capture.called:
+ assert mock_capture.call_args.kwargs["event_name"] == event_name
+ properties = mock_capture.call_args.kwargs["properties"]
+ else:
+ (event,) = mock_batch_capture.call_args.kwargs["events"]
+ assert event["event"] == event_name
+ properties = event["properties"]
+ assert properties["$ip"] == "203.0.113.7"
+
@patch("posthog.api.report.capture_internal")
def test_capture_csp_no_trailing_slash(self, mock_capture):
mock_capture.return_value = MagicMock(status_code=204)