: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
fix(session): require cross-axis corroboration before ending a session (#76109)
Tom Piccirello3955226277d0
diff --git a/posthog/api/test/test_user_auth_session.py b/posthog/api/test/test_user_auth_session.pyindex 3e5905aeeda7..e0359a276971 100644--- a/posthog/api/test/test_user_auth_session.py+++ b/posthog/api/test/test_user_auth_session.py@@ -256,10 +256,11 @@ class TestUserAuthSessionAPI(APIBaseTest):return_value={"latitude": 35.6, "longitude": 139.7, "country_code": "JP"},)def test_high_risk_request_redirects_and_flushes_through_middleware_stack(self, _geoip, _flags):- # End-to-end through the real middleware stack: a seeded NYC baseline plus a Tokyo geo on this- # request is impossible travel (HIGH); with session-end on, SessionRiskMiddleware flushes the- # session server-side and redirects. Only the geoip DB and flag service (true boundaries) are- # mocked — evaluate_session_risk, current_request_context, and evaluate_signals run for real.+ # End-to-end through the real middleware stack: a seeded NYC/Chrome baseline against a Tokyo geo+ # and a Firefox UA on this request trips both axes (HIGH), the way a replayed cookie would. With+ # session-end on, SessionRiskMiddleware flushes the session server-side and redirects. Only the+ # geoip DB and flag service (true boundaries) are mocked — evaluate_session_risk,+ # current_request_context, and evaluate_signals run for real.key = self.client.session.session_keySession.objects.filter(session_key=key).update(latitude=40.7,@@ -269,7 +270,12 @@ class TestUserAuthSessionAPI(APIBaseTest):baseline_at=timezone.now() - timedelta(minutes=30),)- response = self.client.get("/api/users/@me/")+ response = self.client.get(+ "/api/users/@me/",+ headers={+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/119.0"+ },+ )self.assertEqual(response.status_code, 302)self.assertEqual(response.headers["Location"], "/login?reason=session_risk")diff --git a/posthog/geoip.py b/posthog/geoip.pyindex 64d142113586..389f7f262b3f 100644--- a/posthog/geoip.py+++ b/posthog/geoip.py@@ -1,4 +1,6 @@import ipaddress+from dataclasses import dataclass+from functools import lru_cachefrom typing import Optional, TypedDictfrom django.contrib.gis.geoip2 import GeoIP2@@ -31,6 +33,11 @@ VALID_GEOIP_PROPERTIES = [# GeoIP2 returns the city name as 'city', but we want to map it to 'city_name'GEOIP_KEY_MAPPING = {"city": "city_name"}+# Distinct addresses whose location we keep per process. A MaxMind lookup costs ~75us even with the+# database in memory, and the risk middleware does one per authenticated request, so the working set+# of active client addresses is worth holding onto. Each entry is a few hundred bytes.+GEOIP_LOCATION_CACHE_SIZE = 4096+def get_geoip_properties(ip_address: Optional[str]) -> dict[str, str]:"""@@ -83,23 +90,51 @@ def _is_non_public_ip(ip_address: str) -> bool:)+@dataclass(frozen=True, kw_only=True)+class CachedLocation:+ """One memoized geoip result. Keyword-only because latitude and longitude share a type and would+ otherwise be swappable at the call site."""++ latitude: Optional[float]+ longitude: Optional[float]+ country_code: Optional[str]+++@lru_cache(maxsize=GEOIP_LOCATION_CACHE_SIZE)+def _lookup_location(ip_address: str) -> CachedLocation:+ """Cached lookup behind get_geoip_location, which runs on every authenticated request.++ The database is opened once at import and never written, so the mapping from address to location+ cannot change under a running process — a deploy shipping a new database restarts it. Frozen, so a+ cached entry can't be mutated through one caller and observed by the next. lru_cache doesn't store+ exceptions, so a failed lookup is retried rather than pinned for the life of the process.+ """+ assert geoip is not None # caller checks; keeps the cached path free of the None branch+ city = geoip.city(ip_address)+ latitude = city.get("latitude")+ longitude = city.get("longitude")+ country_code = city.get("country_code")+ return CachedLocation(+ latitude=float(latitude) if isinstance(latitude, int | float) else None,+ longitude=float(longitude) if isinstance(longitude, int | float) else None,+ country_code=country_code if isinstance(country_code, str) else None,+ )++def get_geoip_location(ip_address: Optional[str]) -> GeoLocation:"""Latitude/longitude/country_code for risk scoring. Unlike get_geoip_properties this keeps floats."""if not ip_address or not geoip or _is_non_public_ip(ip_address):return {}try:- city = geoip.city(ip_address)+ location = _lookup_location(ip_address)except Exception:logger.exception("geoIP location error")return {}out: GeoLocation = {}- latitude = city.get("latitude")- if isinstance(latitude, int | float):- out["latitude"] = float(latitude)- longitude = city.get("longitude")- if isinstance(longitude, int | float):- out["longitude"] = float(longitude)- country_code = city.get("country_code")- if isinstance(country_code, str):- out["country_code"] = country_code+ if location.latitude is not None:+ out["latitude"] = location.latitude+ if location.longitude is not None:+ out["longitude"] = location.longitude+ if location.country_code is not None:+ out["country_code"] = location.country_codereturn outdiff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex 7a7f929b5393..ecc1af9c5abc 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -897,10 +897,6 @@ def post_login(sender, user, request: HttpRequest, **kwargs):# fresh password/2FA/SSO login satisfies TimeSensitiveActionPermission.request.session[settings.SESSION_LAST_REAUTH_AT_KEY] = time.time()request.session.pop(settings.SESSION_STEP_UP_REQUIRED_KEY, None)- # Clear the risk-telemetry dedup markers so the first anomaly after this (re)login re-emits instead- # of being suppressed by the pre-login signature. Pairs with the baseline reset below.- request.session.pop(settings.SESSION_RISK_LAST_SIG_KEY, None)- request.session.pop(settings.SESSION_RISK_LAST_EMIT_AT_KEY, None)# Defensive risk-baseline reset: login() rotates the session key, so the new row's risk columns# are already NULL and this is normally a no-op. It guarantees a clean baseline after a high-tierdiff --git a/posthog/session/backend.py b/posthog/session/backend.pyindex 2153c452f685..21155d91686a 100644--- a/posthog/session/backend.py+++ b/posthog/session/backend.py@@ -42,6 +42,10 @@ class SessionStore(DBStore):return Session+ # Row this store loaded for the current request, or None when it never loaded one. Risk scoring+ # reads the baseline columns off it instead of issuing a second SELECT for a row already fetched.+ loaded_row: "Session | None" = None+def create_model_instance(self, data: dict[str, Any]) -> "Session":obj = cast("Session", super().create_model_instance(data))obj.user_id = _auth_user_id(data)@@ -49,6 +53,12 @@ class SessionStore(DBStore):obj.last_activity = timezone.now()return obj+ def _get_session_from_db(self) -> "Session | None":+ # Private DBStore method, not declared in django-stubs — same gap as `save` works around below.+ obj = cast("Session | None", super()._get_session_from_db()) # type: ignore[misc]+ self.loaded_row = obj+ return obj+def save(self, must_create: bool = False) -> None:if self.session_key is None:return self.create()diff --git a/posthog/session/risk.py b/posthog/session/risk.pyindex 9e3e0202a886..88c84e000e4a 100644--- a/posthog/session/risk.py+++ b/posthog/session/risk.py@@ -7,6 +7,7 @@ from typing import Optionalfrom django.conf import settingsfrom django.contrib.auth import BACKEND_SESSION_KEYfrom django.contrib.sessions.backends.base import SessionBase+from django.core.cache import cachefrom django.http import HttpRequestfrom django.utils import timezone@@ -16,11 +17,24 @@ from loginas.utils import is_impersonated_sessionfrom posthog.geoip import get_geoip_locationfrom posthog.models import User+from posthog.session.activity import session_public_idfrom posthog.session.models import Sessionfrom posthog.utils import get_trusted_client_iplogger = structlog.get_logger(__name__)+# Per-process circuit breaker for the dedup cache: how many consecutive failures still emit (and log)+# before we assume a real outage and stay quiet rather than emitting once per request.+#+# The count is deliberately approximate. Separate workers are separate processes and so hold separate+# counters, which is the intent — each one throttles its own logging. Within a process, `+= 1` is a+# read-modify-write and two threads can lose an increment between them, while the `= 0` reset is a+# single store and can't tear. A lost increment can only make the breaker trip later, never sooner,+# because the count rises solely on real failures — so the worst case is a few extra events during an+# outage, which is the direction we'd rather err in anyway.+_CACHE_FAILURE_EMIT_LIMIT = 10+_consecutive_cache_failures = 0+class RiskSignal(str, Enum):IMPOSSIBLE_TRAVEL = "impossible_travel"@@ -85,7 +99,10 @@ def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:def evaluate_signals(baseline: Baseline, ctx: Context, *, now: datetime) -> set[RiskSignal]:signals: set[RiskSignal] = set()- if baseline.ua_signature and ctx.ua_signature and baseline.ua_signature != ctx.ua_signature:+ # A *missing* user agent counts as a change, not as "nothing to compare". Session-cookie auth is+ # browser traffic and browsers always send the header, so its absence is itself anomalous — and+ # treating it as neutral would let a caller drop the header to avoid tripping the device axis.+ if baseline.ua_signature and baseline.ua_signature != ctx.ua_signature:signals.add(RiskSignal.UA_CHANGE)if baseline.country_code and ctx.country_code and baseline.country_code != ctx.country_code:@@ -112,12 +129,32 @@ def evaluate_signals(baseline: Baseline, ctx: Context, *, now: datetime) -> set[return signals-def tier_for(signals: set[RiskSignal]) -> RiskTier:- if RiskSignal.IMPOSSIBLE_TRAVEL in signals or len(signals) >= 2:+# 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.+NETWORK_SIGNALS = frozenset({RiskSignal.IMPOSSIBLE_TRAVEL, RiskSignal.NEW_COUNTRY})+DEVICE_SIGNALS = frozenset({RiskSignal.UA_CHANGE})+++def tier_for(signals: set[RiskSignal], *, device_comparable: bool) -> RiskTier:+ """HIGH ends the session, so it wants corroboration across both axes: the request came from an+ unexpected network *and* an unexpected device. VPN, relay and carrier-NAT egress moves the apparent+ location on its own, so network signals alone — however many — only warrant a step-up re-auth.++ `device_comparable` is False when the baseline holds no user agent to compare against. Then the+ device axis can't clear or confirm anything, so a network anomaly escalates on its own rather than+ leaving the session permanently un-escalatable.++ Note the device axis reads a client-supplied header, so it can only ever be evidence, never proof:+ a caller that replays the recorded user agent will not trip it. See the PR for the residual risk.+ """+ if not signals:+ return RiskTier.NONE+ network = bool(signals & NETWORK_SIGNALS)+ device = bool(signals & DEVICE_SIGNALS)+ if network and (device or not device_comparable):return RiskTier.HIGH- if signals:- return RiskTier.MEDIUM- return RiskTier.NONE+ return RiskTier.MEDIUM@dataclass@@ -152,7 +189,19 @@ def risk_flags(user: User) -> RiskFlags:)-def _baseline_for_session(session_key: str) -> Optional[Baseline]:+def _baseline_for_session(session: SessionBase, session_key: str) -> Optional[Baseline]:+ # The session store already fetched this row to read session_data, so reuse it rather than issue a+ # second SELECT for the same row on the same request — this runs on every authenticated request.+ # Falls back to a query for stores that expose no loaded row (another engine, or a new session).+ loaded = getattr(session, "loaded_row", None)+ if loaded is not None:+ return Baseline(+ latitude=loaded.latitude,+ longitude=loaded.longitude,+ country_code=loaded.country_code,+ ua_signature=loaded.ua_signature,+ baseline_at=loaded.baseline_at,+ )row = (Session.objects.filter(session_key=session_key).values("latitude", "longitude", "country_code", "ua_signature", "baseline_at")@@ -194,24 +243,32 @@ def _risk_signature(tier: RiskTier, signals: set[RiskSignal]) -> str:return f"{tier.name}:{','.join(sorted(signal.value for signal in signals))}"-def _should_emit_risk(session: SessionBase, tier: RiskTier, signals: set[RiskSignal], *, now: datetime) -> bool:- """Dedup gate. A flagged session is re-scored on every request; without this it would emit- telemetry and re-assert step-up every time, inflating counts and hammering the session store.+def _should_emit_risk(session_key: str, tier: RiskTier, signals: set[RiskSignal]) -> bool:+ """Dedup gate. A flagged session is re-scored on every request, so without this one persistent+ anomaly emits telemetry on every request and buries itself in repeats.- Returns True (and records the signature + timestamp on the session) only when the anomaly's- signature differs from the last emitted one or the re-emit cooldown has elapsed, so a persistent- anomaly surfaces once per window instead of once per request. Never touches the baseline, so- detection integrity is unaffected: the request is still scored the same next time.+ The marker lives in the shared cache rather than on the session: parallel requests each hold their+ own copy of the session and would all read a marker there as unset before any of them wrote it,+ so a burst would emit once per request anyway. `cache.add` is atomic, so exactly one request in a+ burst wins and the rest stay quiet until the entry expires. Keyed by the session's derived public+ id so a live session key never reaches the cache. Never touches the baseline, so detection is+ unaffected: the request is still scored the same next time."""- signature = _risk_signature(tier, signals)- last_signature = session.get(settings.SESSION_RISK_LAST_SIG_KEY)- last_emit_at = session.get(settings.SESSION_RISK_LAST_EMIT_AT_KEY) or 0.0- now_epoch = now.timestamp()- if signature == last_signature and (now_epoch - last_emit_at) < settings.RISK_REEMIT_COOLDOWN_S:+ global _consecutive_cache_failures+ key = f"session_risk_emit:{session_public_id(session_key)}:{_risk_signature(tier, signals)}"+ try:+ allowed = bool(cache.add(key, 1, timeout=int(settings.RISK_REEMIT_COOLDOWN_S)))+ except Exception:+ # Fail open at first, since duplicates beat missing events, but only briefly: with the gate+ # gone every request on every flagged session would emit an event and a traceback, which is+ # the storm the gate exists to prevent. Past the limit, go quiet until the cache recovers.+ _consecutive_cache_failures += 1+ if _consecutive_cache_failures <= _CACHE_FAILURE_EMIT_LIMIT:+ logger.exception("session_risk dedup cache unavailable")+ return Truereturn False- session[settings.SESSION_RISK_LAST_SIG_KEY] = signature- session[settings.SESSION_RISK_LAST_EMIT_AT_KEY] = now_epoch- return True+ _consecutive_cache_failures = 0+ return alloweddef evaluate_session_risk(request: HttpRequest) -> RiskTier:@@ -236,14 +293,14 @@ def evaluate_session_risk(request: HttpRequest) -> RiskTier:if not flags.detection:return RiskTier.NONE- baseline = _baseline_for_session(session_key)+ baseline = _baseline_for_session(request.session, session_key)if baseline is None:return RiskTier.NONEctx = current_request_context(request)now = timezone.now()signals = evaluate_signals(baseline, ctx, now=now)- tier = tier_for(signals)+ tier = tier_for(signals, device_comparable=baseline.ua_signature is not None)if tier == RiskTier.NONE:# Low-risk request: roll the known-good baseline forward (or establish it when NULL). A# suspicious request never reaches here, so it can't poison the reference it's scored against.@@ -263,7 +320,7 @@ def evaluate_session_risk(request: HttpRequest) -> RiskTier:enforced = True# `effective` is computed above and returned regardless, so session-end is never suppressed.- should_emit = _should_emit_risk(request.session, tier, signals, now=now)+ should_emit = _should_emit_risk(session_key, tier, signals)# Enforcement is independent of the telemetry dedup: apply step-up whenever it is needed and not# already set, even when the identical anomaly's telemetry is being deduped. Otherwise enabling@@ -271,11 +328,8 @@ def evaluate_session_risk(request: HttpRequest) -> RiskTier:set_step_up = needs_step_up and not request.session.get(settings.SESSION_STEP_UP_REQUIRED_KEY)if set_step_up:request.session[settings.SESSION_STEP_UP_REQUIRED_KEY] = True-- # Persist the step-up flag and/or the dedup markers _should_emit_risk just wrote, now rather than- # relying on SessionMiddleware, which skips save() on a 5xx response — otherwise a server error- # here would drop the step-up requirement.- if should_emit or set_step_up:+ # Persist now rather than relying on SessionMiddleware, which skips save() on a 5xx response —+ # otherwise a server error here would drop the step-up requirement.request.session.save()if should_emit:diff --git a/posthog/session/test/test_risk.py b/posthog/session/test/test_risk.pyindex cd2618edeeac..db485707aeab 100644--- a/posthog/session/test/test_risk.py+++ b/posthog/session/test/test_risk.py@@ -7,7 +7,11 @@ from unittest.mock import patchfrom django.test import RequestFactory, SimpleTestCasefrom django.test.utils import override_settings+from parameterized import parameterized+from posthog.session.risk import (+ DEVICE_SIGNALS,+ NETWORK_SIGNALS,Baseline,Context,RiskSignal,@@ -72,14 +76,13 @@ class TestSignalsAndTiers(BaseTest):base.update(kw)return Context(**base)- def test_impossible_travel_fires_high(self):+ def test_impossible_travel_fires(self):b = self._baseline()# Tokyo, 10 minutes laterctx = self._ctx(latitude=35.6, longitude=139.7, country_code="JP")now = self.BASELINE_TIME + timedelta(minutes=10)signals = evaluate_signals(b, ctx, now=now)self.assertIn(RiskSignal.IMPOSSIBLE_TRAVEL, signals)- self.assertEqual(tier_for(signals), RiskTier.HIGH)def test_short_hop_not_impossible(self):b = self._baseline()@@ -105,16 +108,57 @@ class TestSignalsAndTiers(BaseTest):signals = evaluate_signals(b, ctx, now=self.BASELINE_TIME + timedelta(minutes=10))self.assertNotIn(RiskSignal.IMPOSSIBLE_TRAVEL, signals)- def test_ua_change_alone_is_medium(self):+ def test_ua_change_fires_alone(self):b = self._baseline()ctx = self._ctx(ua_signature="firefox|mac os x|pc")signals = evaluate_signals(b, ctx, now=self.BASELINE_TIME + timedelta(minutes=10))self.assertEqual(signals, {RiskSignal.UA_CHANGE})- self.assertEqual(tier_for(signals), RiskTier.MEDIUM)- def test_two_mediums_escalate_to_high(self):- signals = {RiskSignal.UA_CHANGE, RiskSignal.NEW_COUNTRY}- self.assertEqual(tier_for(signals), RiskTier.HIGH)+ @parameterized.expand(+ [+ ("no_signals", set(), RiskTier.NONE),+ ("ua_change_alone", {RiskSignal.UA_CHANGE}, RiskTier.MEDIUM),+ ("new_country_alone", {RiskSignal.NEW_COUNTRY}, RiskTier.MEDIUM),+ ("impossible_travel_alone", {RiskSignal.IMPOSSIBLE_TRAVEL}, RiskTier.MEDIUM),+ ("both_geo_signals", {RiskSignal.IMPOSSIBLE_TRAVEL, RiskSignal.NEW_COUNTRY}, RiskTier.MEDIUM),+ ("new_country_and_ua", {RiskSignal.NEW_COUNTRY, RiskSignal.UA_CHANGE}, RiskTier.HIGH),+ ("impossible_travel_and_ua", {RiskSignal.IMPOSSIBLE_TRAVEL, RiskSignal.UA_CHANGE}, RiskTier.HIGH),+ (+ "all_three",+ {RiskSignal.IMPOSSIBLE_TRAVEL, RiskSignal.NEW_COUNTRY, RiskSignal.UA_CHANGE},+ RiskTier.HIGH,+ ),+ ]+ )+ def test_tier_requires_cross_axis_corroboration(self, _name, signals, expected):+ # HIGH ends the session, so it takes a network anomaly *and* a device anomaly. Counting any+ # two signals as corroboration over-escalates: impossible_travel and new_country both come+ # from one geoip lookup on one IP, so together they are a single observation, not two.+ self.assertEqual(tier_for(signals, device_comparable=True), expected)++ @parameterized.expand(+ [+ ("network_alone", {RiskSignal.IMPOSSIBLE_TRAVEL}, RiskTier.HIGH),+ ("both_geo_signals", {RiskSignal.IMPOSSIBLE_TRAVEL, RiskSignal.NEW_COUNTRY}, RiskTier.HIGH),+ ("no_signals", set(), RiskTier.NONE),+ ]+ )+ def test_network_signal_escalates_when_device_cannot_be_compared(self, _name, signals, expected):+ # With no recorded user agent the device axis can neither confirm nor clear the request, so a+ # network anomaly has to escalate on its own — otherwise such a session could never reach HIGH.+ self.assertEqual(tier_for(signals, device_comparable=False), expected)++ def test_every_signal_belongs_to_exactly_one_axis(self):+ # A new RiskSignal in neither axis would silently cap at MEDIUM forever, and one in both would+ # let a single observation corroborate itself.+ self.assertEqual(NETWORK_SIGNALS | DEVICE_SIGNALS, set(RiskSignal))+ self.assertEqual(NETWORK_SIGNALS & DEVICE_SIGNALS, set())++ def test_missing_user_agent_counts_as_a_device_change(self):+ # Dropping the header must not be a way to keep the device axis quiet.+ b = self._baseline()+ signals = evaluate_signals(b, self._ctx(ua_signature=None), now=self.BASELINE_TIME + timedelta(minutes=10))+ self.assertIn(RiskSignal.UA_CHANGE, signals)def test_null_baseline_no_signals(self):b = Baseline(latitude=None, longitude=None, country_code=None, ua_signature=None, baseline_at=None)diff --git a/posthog/session/test/test_risk_middleware.py b/posthog/session/test/test_risk_middleware.pyindex 56054ac28b04..65d93501434e 100644--- a/posthog/session/test/test_risk_middleware.py+++ b/posthog/session/test/test_risk_middleware.py@@ -17,9 +17,11 @@ from parameterized import parameterizedfrom posthog.models import Userfrom posthog.session.middleware import SessionRiskMiddlewarefrom posthog.session.models import Session-from posthog.session.risk import Context, RiskFlags, RiskTier, evaluate_session_risk+from posthog.session.risk import Context, RiskFlags, RiskTier, _baseline_for_session, evaluate_session_riskIMPOSSIBLE_TRAVEL_CTX = Context(latitude=35.6, longitude=139.7, country_code="JP", ua_signature="chrome|mac os x|pc")+# Network anomaly *and* device anomaly — the cross-axis pair that reaches HIGH.+HIGH_RISK_CTX = Context(latitude=35.6, longitude=139.7, country_code="JP", ua_signature="firefox|mac os x|pc")UA_CHANGE_CTX = Context(latitude=40.7, longitude=-74.0, country_code="US", ua_signature="firefox|mac os x|pc")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")@@ -71,7 +73,7 @@ class TestEvaluateSessionRisk(BaseTest):self.assertNotIn("step_up_required", request.session)mock_capture.assert_not_called()- @patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)+ @patch("posthog.session.risk.current_request_context", return_value=HIGH_RISK_CTX)@patch("posthog.session.risk.posthoganalytics.capture")@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, False))def test_report_only_does_not_set_flag_or_end(self, _flags, mock_capture, _ctx):@@ -128,7 +130,7 @@ class TestEvaluateSessionRisk(BaseTest):reloaded = self.engine.SessionStore(session_key=request.session.session_key)self.assertTrue(reloaded.get("step_up_required"))- @patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)+ @patch("posthog.session.risk.current_request_context", return_value=HIGH_RISK_CTX)@patch("posthog.session.risk.posthoganalytics.capture")@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, True))def test_high_effective_only_when_session_end_on(self, _flags, mock_capture, _ctx):@@ -138,6 +140,19 @@ class TestEvaluateSessionRisk(BaseTest):self.assertTrue(mock_capture.call_args.kwargs["properties"]["enforced"])@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, True, True))+ def test_network_only_anomaly_never_ends_the_session(self, _flags, mock_capture, _ctx):+ # Relay, VPN and carrier-NAT egress move the apparent location on their own, so a network-only+ # anomaly must stop at a step-up re-auth even with session-end enabled — it must never log the+ # user out on geo alone.+ request = self._authed_request_with_baseline(self._make_user())++ self.assertEqual(evaluate_session_risk(request), RiskTier.NONE)+ self.assertTrue(request.session.get("step_up_required"))+ self.assertEqual(mock_capture.call_args.kwargs["properties"]["tier"], RiskTier.MEDIUM.name)++ @patch("posthog.session.risk.current_request_context", return_value=HIGH_RISK_CTX)@patch("posthog.session.risk.posthoganalytics.capture", side_effect=RuntimeError("telemetry down"))@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, True))def test_telemetry_failure_does_not_break_evaluation(self, _flags, _capture, _ctx):@@ -146,7 +161,7 @@ class TestEvaluateSessionRisk(BaseTest):self.assertEqual(evaluate_session_risk(request), RiskTier.HIGH)- @patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)+ @patch("posthog.session.risk.current_request_context", return_value=HIGH_RISK_CTX)@patch("posthog.session.risk.posthoganalytics.capture")@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, True, False))def test_high_degrades_to_step_up_when_session_end_off(self, _flags, mock_capture, _ctx):@@ -170,19 +185,53 @@ class TestEvaluateSessionRisk(BaseTest):evaluate_session_risk(request)self.assertEqual(mock_capture.call_count, expected_calls)+ def test_baseline_reuses_the_row_the_session_store_loaded(self):+ # Loading the session already fetches this row, and scoring runs on every authenticated+ # request, so reading the baseline must not cost a second SELECT for the same row.+ key = self._login_session(self._make_user())+ self._seed_baseline(key)+ store = self.engine.SessionStore(session_key=key)+ store.load()++ with self.assertNumQueries(0):+ baseline = _baseline_for_session(store, key)++ assert baseline is not None+ self.assertEqual(baseline.country_code, "US")++ @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))+ def test_concurrent_requests_emit_once(self, _flags, mock_capture, _ctx):+ # Parallel requests each hold their own copy of the session, so dedup state kept there is read+ # before any of them writes and every one emits. The marker has to be shared for a burst of+ # requests to count as one detection.+ user = self._make_user()+ key = self._login_session(user)+ self._seed_baseline(key)+ first, second = self._request(user, key), self._request(user, key)+ # Materialize both session copies before either evaluates — that is what makes them concurrent+ # rather than sequential.+ first.session.get(SESSION_KEY), second.session.get(SESSION_KEY)++ evaluate_session_risk(first)+ evaluate_session_risk(second)++ mock_capture.assert_called_once()+@patch("posthog.session.risk.posthoganalytics.capture")@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, True, True))def test_new_signature_re_emits_within_cooldown(self, _flags, mock_capture):- # An escalation to a different anomaly (MEDIUM ua_change -> HIGH impossible travel) is a new- # incident and must re-emit even inside the cooldown window.+ # An escalation to a different anomaly (MEDIUM ua_change -> HIGH cross-axis) is a new incident+ # and must re-emit even inside the cooldown window.request = self._authed_request_with_baseline(self._make_user())with patch("posthog.session.risk.current_request_context", return_value=UA_CHANGE_CTX):evaluate_session_risk(request)- with patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX):+ with patch("posthog.session.risk.current_request_context", return_value=HIGH_RISK_CTX):evaluate_session_risk(request)self.assertEqual(mock_capture.call_count, 2)- @patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)+ @patch("posthog.session.risk.current_request_context", return_value=HIGH_RISK_CTX)@patch("posthog.session.risk.posthoganalytics.capture")@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, True))def test_dedup_suppresses_telemetry_not_session_end(self, _flags, mock_capture, _ctx):@@ -284,12 +333,13 @@ class TestEvaluateSessionRisk(BaseTest):self.assertEqual(row.latitude, 40.7) # still NYC, not poisoned to Tokyoself.assertEqual(row.country_code, "US")- @patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)+ @patch("posthog.session.risk.current_request_context", return_value=HIGH_RISK_CTX)@patch("posthog.session.risk.posthoganalytics.capture")@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, True))def test_attacker_cannot_erase_detection_over_repeated_requests(self, _flags, _capture, _ctx):- # Because the baseline is never poisoned, a replayed stolen cookie keeps tripping HIGH rather- # than self-erasing after the first hit.+ # A replayed stolen cookie arrives from the attacker's own machine and network, so it trips+ # both axes. Because the baseline is never poisoned, it keeps tripping HIGH on every request+ # rather than self-erasing after the first hit.request = self._authed_request_with_baseline(self._make_user())self.assertEqual(evaluate_session_risk(request), RiskTier.HIGH)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 69a5b2a8645d..0e1e70e71df9 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -361,11 +361,6 @@ GROWTH_ENRICHMENT_INTERNAL_TEAM_ID = get_from_env("GROWTH_ENRICHMENT_INTERNAL_TE# one source of truth, like SESSION_COOKIE_CREATED_AT_KEY above.SESSION_STEP_UP_REQUIRED_KEY = get_from_env("SESSION_STEP_UP_REQUIRED_KEY", "step_up_required")SESSION_LAST_REAUTH_AT_KEY = get_from_env("SESSION_LAST_REAUTH_AT_KEY", "last_reauth_at")-# Dedup state for risk telemetry/enforcement: the last-emitted anomaly signature and when. A flagged-# session is re-scored every request, but we only re-emit/re-enforce on a new signature or after the-# cooldown, so one persistent anomaly can't fire on every request. Cleared on (re)login by post_login.-SESSION_RISK_LAST_SIG_KEY = get_from_env("SESSION_RISK_LAST_SIG_KEY", "risk_last_sig")-SESSION_RISK_LAST_EMIT_AT_KEY = get_from_env("SESSION_RISK_LAST_EMIT_AT_KEY", "risk_last_emit_at")# Impossible-travel risk thresholds (see posthog/session/risk.py). Tunable without a code change.RISK_DISTANCE_FLOOR_KM = get_from_env("RISK_DISTANCE_FLOOR_KM", 500.0, type_cast=float)diff --git a/posthog/test/test_geoip.py b/posthog/test/test_geoip.pyindex e3cdd7ac451f..07285f9d2372 100644--- a/posthog/test/test_geoip.py+++ b/posthog/test/test_geoip.py@@ -3,10 +3,16 @@ from unittest.mock import patchfrom parameterized import parameterized-from posthog.geoip import get_geoip_location+from posthog.geoip import _lookup_location, get_geoip_locationclass TestGeoipLocation(BaseTest):+ def setUp(self):+ super().setUp()+ # Lookups are memoized per process, so results would otherwise leak across tests that mock+ # different responses for the same address.+ _lookup_location.cache_clear()+def test_returns_empty_for_local_ip(self):self.assertEqual(get_geoip_location("127.0.0.1"), {})@@ -31,3 +37,25 @@ class TestGeoipLocation(BaseTest):mock_geoip.city.return_value = {"latitude": 40.7, "longitude": -74.0, "country_code": "US", "city": "NYC"}result = get_geoip_location("8.8.8.8")self.assertEqual(result, {"latitude": 40.7, "longitude": -74.0, "country_code": "US"})++ @patch("posthog.geoip.geoip")+ def test_repeat_lookups_hit_the_database_once(self, mock_geoip):+ # This runs on every authenticated request and a lookup costs ~75us, so a repeated address+ # must not reach the database again.+ mock_geoip.city.return_value = {"latitude": 40.7, "longitude": -74.0, "country_code": "US"}++ for _ in range(3):+ get_geoip_location("8.8.8.8")++ mock_geoip.city.assert_called_once()++ @patch("posthog.geoip.geoip")+ def test_callers_cannot_corrupt_a_cached_entry(self, mock_geoip):+ # Callers own the dict they get back; mutating it must not reach the next caller.+ mock_geoip.city.return_value = {"latitude": 40.7, "longitude": -74.0, "country_code": "US"}++ first = get_geoip_location("8.8.8.8")+ first["country_code"] = "XX"+ first["latitude"] = 0.0++ self.assertEqual(get_geoip_location("8.8.8.8"), {"latitude": 40.7, "longitude": -74.0, "country_code": "US"})