: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(auth): drop session.accessed from device gate (#56584)
Raúl Negrón-Oteroa0fd625192bb
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex c7caeaba8214..032569f1744c 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -513,16 +513,17 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):with self.assertNumQueries(baseline + 11):self.dashboard_api.get_dashboard(dashboard_id, query_params={"no_items_field": "true"})+ # was baseline + 11 + 12, -1 after dropping duplicate session lookupself.dashboard_api.create_insight({"filters": filter_dict, "dashboards": [dashboard_id]})- with self.assertNumQueries(baseline + 11 + 12):+ with self.assertNumQueries(baseline + 11 + 11):self.dashboard_api.get_dashboard(dashboard_id, query_params={"no_items_field": "true"})self.dashboard_api.create_insight({"filters": filter_dict, "dashboards": [dashboard_id]})- with self.assertNumQueries(baseline + 11 + 12):+ with self.assertNumQueries(baseline + 11 + 11):self.dashboard_api.get_dashboard(dashboard_id, query_params={"no_items_field": "true"})self.dashboard_api.create_insight({"filters": filter_dict, "dashboards": [dashboard_id]})- with self.assertNumQueries(baseline + 11 + 12):+ with self.assertNumQueries(baseline + 11 + 11):self.dashboard_api.get_dashboard(dashboard_id, query_params={"no_items_field": "true"})@snapshot_postgres_queriesdiff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 37ebc0b1fa24..5c11fef9cba3 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -4,21 +4,26 @@ import uuidfrom datetime import UTC, datetime, timedeltafrom typing import cast+import pytestfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import ANY, MagicMock, patchfrom django.conf import settings+from django.contrib.auth import BACKEND_SESSION_KEYfrom django.contrib.sessions.middleware import SessionMiddlewarefrom django.core import mail+from django.core.asgi import get_asgi_applicationfrom django.core.cache import cachefrom django.http import HttpResponsefrom django.test import RequestFactory, override_settingsfrom django.utils import timezone+from asgiref.sync import sync_to_asyncfrom django_otp.oath import totpfrom django_otp.plugins.otp_static.models import StaticDevicefrom django_otp.util import random_hex+from httpx import ASGITransport, AsyncClientfrom parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.exceptions import AuthenticationFailed@@ -42,7 +47,7 @@ from posthog.helpers.user_devices import (has_valid_known_device_cookie,)from posthog.middleware import KnownLoginDeviceCookieMiddleware-from posthog.models import User+from posthog.models import FeatureFlag, Userfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organization, OrganizationMembership@@ -2378,10 +2383,88 @@ class TestKnownLoginDeviceCookieMiddleware(APIBaseTest):def test_does_not_set_known_device_cookie_for_internal_api_user(self):request = RequestFactory().get("/api/internal/hog_flows/process_due_schedules")SessionMiddleware(lambda r: HttpResponse()).process_request(request)- request.session["touched"] = True+ # Simulate a session that *looks* logged-in to prove the synthetic-user guard wins on its own+ request.session[BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend"request.__dict__["user"] = InternalAPIUser()response = KnownLoginDeviceCookieMiddleware(lambda r: HttpResponse())(request)assert response.status_code == 200assert not any(name.startswith("ph_device_") for name in response.cookies)++ def test_does_not_set_known_device_cookie_when_session_accessed_without_login(self):+ # Regression: under ASGI, posthoganalytics' middleware awaits `request.auser`, which reads+ # the session and sets `session.accessed=True` even on requests that never went through+ # `auth.login()`. The gate must rely on `BACKEND_SESSION_KEY`, not on `session.accessed`.+ request = RequestFactory().get("/api/some_endpoint")+ SessionMiddleware(lambda r: HttpResponse()).process_request(request)+ # Touch the session the way an upstream middleware would — flips `accessed` but does not log in+ request.session.get("anything")+ assert request.session.accessed is True+ assert BACKEND_SESSION_KEY not in request.session+ request.__dict__["user"] = self.user++ response = KnownLoginDeviceCookieMiddleware(lambda r: HttpResponse())(request)++ assert response.status_code == 200+ assert not any(name.startswith("ph_device_") for name in response.cookies)++[email protected]_db(transaction=True)+async def test_known_device_cookie_async_chain_with_project_secret_api_key():+ """Reproduces the production crash on the original (pre-fix) middleware: against the+ initial known-device cookie code (commit 177ab2ded11), this test fails with the exact+ prod stack trace —++ File "posthog/middleware.py", in __call__+ set_known_device_cookie(response, request.user)+ File "posthog/helpers/user_devices.py", in set_known_device_cookie+ KNOWN_DEVICE_COOKIE.format(user_id=user.id),+ AttributeError: 'ProjectSecretAPIKeyUser' object has no attribute 'id'++ Drives the real ASGI middleware chain via httpx + ASGITransport (patterned after+ posthog-python's integration_tests/django5). Sync `Client` skips the ASGI app and so+ cannot reproduce the failure — the chain depends on PosthogContextMiddleware.__acall__+ awaiting request.auser(), which goes through Django's separate `_acached_user` cache+ and re-reads the session that PostHogTokenCookieMiddleware reset mid-chain, flipping+ `accessed=True` and opening the gate against the non-User principal.+ """++ @sync_to_async+ def setup_team_and_flag():+ org = Organization.objects.create(name="Test Org")+ user = User.objects.create_user(+ email=f"test-{uuid.uuid4()}@example.com",+ first_name="Test",+ password=VALID_TEST_PASSWORD,+ )+ org.members.add(user)+ team = Team.objects.create(organization=org, name="Test Team")+ team.rotate_secret_token_and_save(user=user, is_impersonated_session=False)+ FeatureFlag.objects.create(+ team=team,+ key="rc-async-test",+ name="RC",+ active=True,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": '{"x": 1}'},+ },+ is_remote_configuration=True,+ )+ return team++ team = await setup_team_and_flag()++ asgi_app = get_asgi_application()+ # httpx ASGITransport's `app` type spec is stricter than Django's ASGIHandler signature; the+ # protocols are compatible at runtime, just disagree on dict/MutableMapping in the typing.+ async with AsyncClient(transport=ASGITransport(app=asgi_app), base_url="http://testserver") as ac: # type: ignore[arg-type]+ response = await ac.get(+ f"/api/projects/{team.id}/feature_flags/rc-async-test/remote_config",+ headers={"authorization": f"Bearer {team.secret_api_token}"},+ )++ assert response.status_code == status.HTTP_200_OK, response.text+ assert not any(name.startswith("ph_device_") for name in response.cookies)diff --git a/posthog/api/test/test_preflight.py b/posthog/api/test/test_preflight.pyindex 36f9c7041ad4..2e6128a356ff 100644--- a/posthog/api/test/test_preflight.py+++ b/posthog/api/test/test_preflight.py@@ -198,7 +198,7 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):def test_cloud_preflight_limited_db_queries(self):with self.is_cloud(True):# :IMPORTANT: This code is hit _every_ web request on cloud so avoid ever increasing db load.- with self.assertNumQueries(6): # session (2x), user, team, organization and slack instance setting.+ with self.assertNumQueries(5): # session, user, team, organization and slack instance setting.response = self.client.get("/_preflight/")assert response.status_code == status.HTTP_200_OKdiff --git a/posthog/middleware.py b/posthog/middleware.pyindex b7dd3893615a..6c49ae526214 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -11,8 +11,7 @@ from typing import Optional, castfrom urllib.parse import urlencodefrom django.conf import settings-from django.contrib.auth import logout-from django.contrib.sessions.middleware import SessionMiddleware+from django.contrib.auth import BACKEND_SESSION_KEY, logoutfrom django.core.cache import cachefrom django.core.exceptions import MiddlewareNotUsedfrom django.db import connection@@ -22,6 +21,7 @@ from django.middleware.csrf import CsrfViewMiddlewarefrom django.shortcuts import redirectfrom django.urls import resolvefrom django.utils.cache import add_never_cache_headers+from django.utils.deprecation import MiddlewareMixinimport structlogfrom django_prometheus.middleware import Metrics@@ -555,14 +555,20 @@ class CustomPrometheusMetrics(Metrics):return super().register_metric(metric_cls, name, documentation, labelnames=labelnames, **kwargs)-class PostHogTokenCookieMiddleware(SessionMiddleware):+class PostHogTokenCookieMiddleware(MiddlewareMixin):"""- Adds two secure cookies to enable auto-filling the current project token on the docs.+ Adds secure cookies that let the website auto-fill the current project token / login method on docs.++ Note: this used to subclass SessionMiddleware, which had the side effect of running a second+ SessionMiddleware.process_request mid-chain — replacing request.session with a fresh, unloaded+ SessionStore. That caused two real problems: (1) downstream gates relying on request.session.accessed+ became asymmetric across sync vs ASGI auth (Django keeps separate _cached_user / _acached_user),+ and (2) any later code that read a session key (e.g. BACKEND_SESSION_KEY) paid a redundant DB load+ against the fresh store, which N+1 query-count tests would catch. The session is already saved by+ the SessionMiddleware higher in the stack; this middleware only needs to set response cookies."""def process_response(self, request, response):- response = super().process_response(request, response)-if settings.TEST:passelif is_dev_mode():@@ -647,26 +653,33 @@ class SessionAgeMiddleware:self.get_response = get_responsedef __call__(self, request: HttpRequest):+ # Anonymous requests have no session-auth context — skipping avoids materializing a session+ # row for every public/API-key-authenticated request. Previously this ran unconditionally,+ # but the modifications were silently dropped by PostHogTokenCookieMiddleware's session+ # reset; once that reset is removed, those modifications would persist and cause spurious+ # session inserts on every anonymous request.+ if not request.user.is_authenticated:+ return self.get_response(request)+# NOTE: This should be covered by the post_login signal, but we add it here as a fallbackget_or_set_session_cookie_created_at(request=request)- if request.user.is_authenticated:- # Get session creation time- session_created_at = request.session.get(settings.SESSION_COOKIE_CREATED_AT_KEY)- if session_created_at:- # Get timeout from Redis cache first, fallback to settings- org_id = request.user.current_organization_id- session_age = None- if org_id:- session_age = cache.get(f"org_session_age:{org_id}")-- if session_age is None:- session_age = settings.SESSION_COOKIE_AGE-- current_time = time.time()- if current_time - session_created_at > session_age:- logout(request)- return redirect("/login?message=Your session has expired. Please log in again.")+ # Get session creation time+ session_created_at = request.session.get(settings.SESSION_COOKIE_CREATED_AT_KEY)+ if session_created_at:+ # Get timeout from Redis cache first, fallback to settings+ org_id = request.user.current_organization_id+ session_age = None+ if org_id:+ session_age = cache.get(f"org_session_age:{org_id}")++ if session_age is None:+ session_age = settings.SESSION_COOKIE_AGE++ current_time = time.time()+ if current_time - session_created_at > session_age:+ logout(request)+ return redirect("/login?message=Your session has expired. Please log in again.")response = self.get_response(request)return response@@ -680,7 +693,14 @@ class KnownLoginDeviceCookieMiddleware:def __call__(self, request: HttpRequest):response = self.get_response(request)- if isinstance(request.user, User) and request.session.accessed and not is_impersonated_session(request):+ # Gate on `BACKEND_SESSION_KEY` (set by `auth.login()`, removed by `auth.logout()`) rather than+ # `request.session.accessed` — the latter flips True whenever any upstream middleware reads the+ # session, which makes the gate dependent on middleware ordering and async/sync execution mode.+ if (+ isinstance(request.user, User)+ and BACKEND_SESSION_KEY in request.session+ and not is_impersonated_session(request)+ ):set_known_device_cookie(response, request.user)return responsediff --git a/posthog/session_recordings/test/test_session_recording_playlist.py b/posthog/session_recordings/test/test_session_recording_playlist.pyindex 1032d67141c9..4565b0327a8b 100644--- a/posthog/session_recordings/test/test_session_recording_playlist.py+++ b/posthog/session_recordings/test/test_session_recording_playlist.py@@ -305,13 +305,13 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):)def test_can_create_many_playlists_without_n_plus_1(self):- # one query to get started and then 14 per creation (was 13, +1 for organization query)- with self.assertNumQueries(14 * 50 + 1):+ # one query to get started and then 13 per creation (was 14, -1 after dropping duplicate session lookup)+ with self.assertNumQueries(13 * 50 + 1):for i in range(50):self._create_playlist({"name": f"test-{i}", "type": "collection"})- # 14 per creation (was 13, +1 for organization query)- with self.assertNumQueries(14 * 100):+ # 13 per creation (was 14, -1 after dropping duplicate session lookup)+ with self.assertNumQueries(13 * 100):for i in range(100):self._create_playlist({"name": f"test-{i}", "type": "collection"})