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.

chore(session): record which device signature moved on a risk detection (#81591)

Tom Piccirello9cf6a48d84ee
diff --git a/posthog/session/risk.py b/posthog/session/risk.py
index 88c84e000e4a..898808feb27f 100644
--- a/posthog/session/risk.py
+++ b/posthog/session/risk.py
@@ -2,7 +2,7 @@ from dataclasses import dataclass
from datetime import datetime
from enum import Enum, IntEnum
from math import asin, cos, radians, sin, sqrt
-from typing import Optional
+from typing import Any, Optional
from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY
@@ -132,6 +132,10 @@ def evaluate_signals(baseline: Baseline, ctx: Context, *, now: datetime) -> set[
# The independent axes a signal can observe. impossible_travel and new_country are both derived from
# a single geoip lookup on a single IP, so they corroborate each other only in appearance. Every
# RiskSignal must belong to exactly one axis or tier_for would silently cap it at MEDIUM forever.
+# Stands in for an absent user agent in telemetry, so a request that sent no header groups as its own
+# value in a breakdown instead of disappearing into null.
+MISSING_UA = "missing"
+
NETWORK_SIGNALS = frozenset({RiskSignal.IMPOSSIBLE_TRAVEL, RiskSignal.NEW_COUNTRY})
DEVICE_SIGNALS = frozenset({RiskSignal.UA_CHANGE})
@@ -333,17 +337,27 @@ def evaluate_session_risk(request: HttpRequest) -> RiskTier:
request.session.save()
if should_emit:
+ properties: dict[str, Any] = {
+ "signals": sorted(signal.value for signal in signals),
+ "tier": tier.name,
+ "enforced": enforced,
+ }
+ if RiskSignal.UA_CHANGE in signals:
+ # A session is one cookie in one browser, so the device signature should not move within
+ # it. Record which way it moved, so the volume can be attributed to a real cause — a
+ # desktop-mode toggle flipping all three components at once, a request arriving with no
+ # header — rather than guessed at. Family-level only, the same values already stored on
+ # the session row: no versions, nothing that identifies a device.
+ properties["ua_from"] = baseline.ua_signature
+ properties["ua_to"] = ctx.ua_signature or MISSING_UA
+
# Telemetry must never break the request: a capture failure here would otherwise 500 an
# otherwise-valid authenticated request from the request-phase middleware.
try:
posthoganalytics.capture(
distinct_id=str(user.distinct_id),
event="session_risk_detected",
- properties={
- "signals": sorted(signal.value for signal in signals),
- "tier": tier.name,
- "enforced": enforced,
- },
+ properties=properties,
)
except Exception:
logger.exception("session_risk telemetry capture failed")
diff --git a/posthog/session/test/test_risk_middleware.py b/posthog/session/test/test_risk_middleware.py
index 65d93501434e..25f6b54418b7 100644
--- a/posthog/session/test/test_risk_middleware.py
+++ b/posthog/session/test/test_risk_middleware.py
@@ -26,6 +26,8 @@ UA_CHANGE_CTX = Context(latitude=40.7, longitude=-74.0, country_code="US", ua_si
STABLE_CTX = Context(latitude=40.7, longitude=-74.0, country_code="US", ua_signature="chrome|mac os x|pc")
NEARBY_CTX = Context(latitude=41.0, longitude=-74.5, country_code="US", ua_signature="chrome|mac os x|pc")
NO_GEO_CTX = Context(latitude=None, longitude=None, country_code=None, ua_signature="chrome|mac os x|pc")
+# Same location as the baseline, but the request carried no user-agent header at all.
+MISSING_UA_CTX = Context(latitude=40.7, longitude=-74.0, country_code="US", ua_signature=None)
class TestEvaluateSessionRisk(BaseTest):
@@ -105,6 +107,39 @@ class TestEvaluateSessionRisk(BaseTest):
for forbidden in ("ip", "session_key", "latitude", "longitude"):
self.assertNotIn(forbidden, props)
+ @parameterized.expand(
+ [
+ ("device_changed", UA_CHANGE_CTX, "chrome|mac os x|pc", "firefox|mac os x|pc"),
+ ("no_user_agent_sent", MISSING_UA_CTX, "chrome|mac os x|pc", "missing"),
+ ]
+ )
+ def test_device_change_records_the_transition(self, _name, ctx, expected_from, expected_to):
+ # Without the transition, a spike in device changes can't be attributed to a cause, and an
+ # absent header has to be distinguishable from a real signature or it vanishes in a breakdown.
+ request = self._authed_request_with_baseline(self._make_user())
+ with (
+ patch("posthog.session.risk.current_request_context", return_value=ctx),
+ patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, False)),
+ patch("posthog.session.risk.posthoganalytics.capture") as mock_capture,
+ ):
+ evaluate_session_risk(request)
+
+ props = mock_capture.call_args.kwargs["properties"]
+ self.assertEqual(props["ua_from"], expected_from)
+ self.assertEqual(props["ua_to"], expected_to)
+
+ @patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)
+ @patch("posthog.session.risk.posthoganalytics.capture")
+ @patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, False))
+ def test_transition_omitted_when_the_device_did_not_change(self, _flags, mock_capture, _ctx):
+ request = self._authed_request_with_baseline(self._make_user())
+
+ evaluate_session_risk(request)
+
+ props = mock_capture.call_args.kwargs["properties"]
+ self.assertNotIn("ua_from", props)
+ self.assertNotIn("ua_to", props)
+
@patch("posthog.session.risk.current_request_context", return_value=UA_CHANGE_CTX)
@patch("posthog.session.risk.posthoganalytics.capture")
@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, True, False))