: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
feat(auth): manage active web sessions via custom session backend (#64987)
Tom Piccirello562941bb73f5
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex 5cd7c6d3d4f7..1dae95f8e30e 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -109,6 +109,7 @@ jobs:- 'posthog/hogql_queries/**'- 'posthog/settings/**'- 'posthog/kafka_client/**'+ - 'posthog/session/**'- 'posthog/schema.py'- 'posthog/schema_enums.py' # enum-only schema changes touch only this file- 'posthog/utils.py'diff --git a/ee/api/test/test_admin_oauth2_middleware.py b/ee/api/test/test_admin_oauth2_middleware.pyindex c8c4eb05ed4d..440e11a9ea63 100644--- a/ee/api/test/test_admin_oauth2_middleware.py+++ b/ee/api/test/test_admin_oauth2_middleware.py@@ -8,7 +8,6 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch-from django.contrib.sessions.backends.db import SessionStorefrom django.http import HttpResponse, HttpResponseRedirectfrom django.test import RequestFactory, override_settings@@ -18,6 +17,7 @@ from cryptography.hazmat.primitives.asymmetric import rsafrom parameterized import parameterizedfrom posthog.models import User+from posthog.session.backend import SessionStorefrom ee.middleware import AdminOAuth2Middleware, _get_email_from_id_token, admin_oauth2_callbackdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1e26a10795f5..0c7e9f6533d4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6565,9 +6565,9 @@ snapshots:scenes-app-settings-user--settings-user-notifications--light:hash: v1.k794b7964.e5c5788fd86da17b66d705e583d355fcd9083e08c571aa5c288848013f2a21be.UO4syOPC4emBEZYNpswKznQk9LQQSQ-lTz42-MODEJsscenes-app-settings-user--settings-user-profile--dark:- hash: v1.k794b7964.9cb28230c498ea58cfe66b5864c928fcc83696d9d07ba1a8cf6064fad5fe74cf.JAPRQtUYhbET7ryfHaeVHkG39W8eIluYV43XkMzxmPg+ hash: v1.k794b7964.8e074309fead3a6e5abf2b263f02d5117c0a8e3130d0ac6bddd7456942b8976c.IOEnXxWVDhORglv-Z8IDtXuO89NWwgRd9z0o3jglg0Escenes-app-settings-user--settings-user-profile--light:- hash: v1.k794b7964.4296fd73bc689c5a698fc714dd2e8f417bdccdb62b634aab1ae0f4b51a2a9e2d.He4eNIY0gBQfc7oYWJMwVSMkaM154fwFYH0CkxHoOGY+ hash: v1.k794b7964.e4738c59cb0a887733f0e1184ed95f6c1121d4957972271c62751879ed7d9905.iYs2mcf-aLhqJZPHK60Bt0lJHYdWpP21M3fC2kCoRIkscenes-app-sidepanels--side-panel-access-control--dark:hash: v1.k794b7964.62c2c16a8f2c4f944f40f081d6fde727ab499ac113130b60463202c48f742703.OPukQrf9s8yZx85qIoSBAGnwquIjb6cqCR0_2EPbfYgscenes-app-sidepanels--side-panel-access-control--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 70b2903987ac..4ab8ee996d91 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -3661,6 +3661,29 @@ export interface UserGitHubLinkStartResponseApi {connect_flow: string}+/**+ * A cookie-auth login session shown on the user's 'Web sessions' screen.+ */+export interface UserAuthSessionApi {+ /** Identifier used to revoke this login session. */+ readonly id: string+ /** When this login session last made a request (refreshed periodically). */+ readonly last_activity: string+ /** Approximate city and country derived from the IP address, if known. */+ readonly location: string+ /** Browser and operating system parsed from the user agent, e.g. 'Chrome 135 on macOS'. */+ readonly device: string+ /** How this session signed in (e.g. password, Google, SAML). */+ readonly login_method: string+ /** Whether this is the login session making the current request. */+ readonly is_current: boolean+}++export interface RevokeOtherSessionsResponseApi {+ /** Number of other login sessions that were revoked. */+ revoked_count: number+}+/*** * `later` - Later* * `other` - Other@@ -4062,3 +4085,8 @@ export type UsersIntegrationsGithubReposRetrieveParams = {*/search?: string}++export type UsersLoginSessionsListParams = {+ email?: string+ is_staff?: boolean+}diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 1fb66f272371..1b014bf883c6 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -72,8 +72,10 @@ import type {ProjectSecretApiKeysListParams,PromotedProductIntentApi,PropertyDefinitionsListParams,+ RevokeOtherSessionsResponseApi,SharingConfigurationApi,UserApi,+ UserAuthSessionApi,UserGitHubLinkStartRequestApi,UserGitHubLinkStartResponseApi,UserPushTokenItemApi,@@ -83,6 +85,7 @@ import type {UsersIntegrationsGithubReposRetrieveParams,UsersIntegrationsListParams,UsersListParams,+ UsersLoginSessionsListParams,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -3351,6 +3354,77 @@ export const usersIntegrationsGithubStartCreate = async (})}+export const getUsersLoginSessionsListUrl = (uuid: string, params?: UsersLoginSessionsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/users/${uuid}/login_sessions/?${stringifiedParams}`+ : `/api/users/${uuid}/login_sessions/`+}++/**+ * List the cookie-auth login sessions for the current user. Self-only — never another user.+ */+export const usersLoginSessionsList = async (+ uuid: string,+ params?: UsersLoginSessionsListParams,+ options?: RequestInit+): Promise<UserAuthSessionApi[]> => {+ return apiMutator<UserAuthSessionApi[]>(getUsersLoginSessionsListUrl(uuid, params), {+ ...options,+ method: 'GET',+ })+}++export const getUsersLoginSessionsDestroyUrl = (uuid: string, sessionId: string) => {+ return `/api/users/${uuid}/login_sessions/${sessionId}/`+}++/**+ * Revoke a single login session belonging to the current user. Self-only.+ *+ * Requires recent auth (TimeSensitiveActionPermission) so a stolen cookie can't weaponize+ * revocation, and is blocked while impersonating via ImpersonationBlockedPathsMiddleware.+ */+export const usersLoginSessionsDestroy = async (+ uuid: string,+ sessionId: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getUsersLoginSessionsDestroyUrl(uuid, sessionId), {+ ...options,+ method: 'DELETE',+ })+}++export const getUsersLoginSessionsRevokeOthersCreateUrl = (uuid: string) => {+ return `/api/users/${uuid}/login_sessions/revoke_others/`+}++/**+ * Revoke every login session for the current user except the one making this request. Self-only.+ *+ * Requires recent auth (TimeSensitiveActionPermission) so a stolen cookie can't weaponize the+ * "log out everywhere else" lock-out, and is blocked while impersonating.+ */+export const usersLoginSessionsRevokeOthersCreate = async (+ uuid: string,+ options?: RequestInit+): Promise<RevokeOtherSessionsResponseApi> => {+ return apiMutator<RevokeOtherSessionsResponseApi>(getUsersLoginSessionsRevokeOthersCreateUrl(uuid), {+ ...options,+ method: 'POST',+ })+}+export const getUsersOnboardingSkipCreateUrl = (uuid: string) => {return `/api/users/${uuid}/onboarding/skip/`}diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex d9a42dfb30d8..7792d9ee4faa 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -513,6 +513,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TILE_SKELETONS: 'web-analytics-tile-skeletons', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics+ WEB_SESSION_MANAGEMENT: 'web-session-management', // owner: @tom.p, gates the "Web sessions" settings UI while the backfill is rolled outWORKFLOWS_BATCH_TRIGGERS: 'workflows-batch-triggers', // owner: #team-workflowsWORKFLOWS_ENGAGEMENT_EVENTS: 'workflows-engagement-events', // owner: #team-workflowsWORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsdiff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 518d9980a1c1..62affb2c1271 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -154,6 +154,7 @@ import { AllowImpersonation } from './user/AllowImpersonation'import { ChangePassword, ChangePasswordTitle } from './user/ChangePassword'import { ConnectedApps } from './user/ConnectedApps'import { HedgehogModeSettings } from './user/HedgehogModeSettings'+import { LoginSessions } from './user/LoginSessions'import { MCPHintsSetting } from './user/MCPHintsSetting'import { OptOutCapture } from './user/OptOutCapture'import { PasskeySettings } from './user/PasskeySettings'@@ -1813,6 +1814,14 @@ export const SETTINGS_MAP: SettingSection[] = [component: <PasskeySettings />,keywords: ['webauthn', 'fido', 'biometric', 'passwordless'],},+ {+ id: 'login-sessions',+ flag: 'WEB_SESSION_MANAGEMENT',+ title: 'Web sessions',+ description: 'Devices and browsers currently signed in to your PostHog account.',+ component: <LoginSessions />,+ keywords: ['sessions', 'devices', 'logins', 'sign out', 'log out', 'security', 'revoke'],+ },],},{diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex bdfda8f89b79..76dca3ba4803 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -203,6 +203,7 @@ export type SettingId =| 'organization-security'| 'organization-personal-api-keys'| 'passkeys'+ | 'login-sessions'| 'path-cleaning'| 'person-display-name'| 'person-last-seen-at'diff --git a/frontend/src/scenes/settings/user/LoginSessions.tsx b/frontend/src/scenes/settings/user/LoginSessions.tsxnew file mode 100644index 000000000000..873edb611f0e--- /dev/null+++ b/frontend/src/scenes/settings/user/LoginSessions.tsx@@ -0,0 +1,125 @@+import { useActions, useValues } from 'kea'++import { IconLaptop, IconLeave } from '@posthog/icons'+import { LemonButton, LemonDialog, LemonTable, LemonTag } from '@posthog/lemon-ui'++import { DetectiveHog } from 'lib/components/hedgehogs'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'++import { UserAuthSessionApi } from '~/generated/core/api.schemas'++import { loginSessionsLogic } from './loginSessionsLogic'++export function LoginSessions(): JSX.Element {+ const { loginSessions, loginSessionsLoading } = useValues(loginSessionsLogic)+ const { revokeSession, revokeOtherSessions } = useActions(loginSessionsLogic)++ const hasOtherSessions = loginSessions.some((session) => !session.is_current)++ const handleRevoke = (session: UserAuthSessionApi): void => {+ LemonDialog.open({+ title: 'Log out of this device?',+ description: 'This device will be signed out of your PostHog account immediately.',+ primaryButton: {+ children: 'Log out',+ status: 'danger',+ onClick: () => revokeSession(session.id),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ const handleRevokeOthers = (): void => {+ LemonDialog.open({+ title: 'Log out everywhere else?',+ description: 'Every device except this one will be signed out of your PostHog account immediately.',+ primaryButton: {+ children: 'Log out everywhere else',+ status: 'danger',+ onClick: () => revokeOtherSessions(),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="flex justify-end">+ <LemonButton+ type="secondary"+ status="danger"+ size="small"+ loading={loginSessionsLoading}+ disabledReason={hasOtherSessions ? undefined : 'No other devices to log out'}+ onClick={handleRevokeOthers}+ >+ Log out everywhere else+ </LemonButton>+ </div>+ <LemonTable+ dataSource={loginSessions}+ loading={loginSessionsLoading}+ columns={[+ {+ title: 'Device',+ dataIndex: 'device',+ render: (_, session) => (+ <div className="flex items-center gap-2">+ <span className="font-medium">{session.device || 'Unknown device'}</span>+ {session.is_current && (+ <LemonTag type="success" size="small">+ This device+ </LemonTag>+ )}+ </div>+ ),+ },+ {+ title: 'Location',+ dataIndex: 'location',+ render: (_, session) => session.location || <span className="text-muted">Unknown</span>,+ },+ {+ title: 'Signed in with',+ dataIndex: 'login_method',+ render: (_, session) => session.login_method || <span className="text-muted">—</span>,+ },+ {+ title: 'Last active',+ dataIndex: 'last_activity',+ render: (_, session) => humanFriendlyDetailedTime(session.last_activity),+ },+ {+ title: '',+ width: 0,+ render: (_, session) =>+ session.is_current ? null : (+ <LemonButton+ icon={<IconLeave />}+ status="danger"+ size="small"+ tooltip="Log out of this device"+ disabledReason={loginSessionsLoading ? 'Working…' : undefined}+ onClick={() => handleRevoke(session)}+ />+ ),+ },+ ]}+ emptyState={+ <div className="flex items-center gap-4 py-4">+ <DetectiveHog className="w-16 h-16" />+ <div>+ <div className="flex items-center gap-2 font-semibold">+ <IconLaptop className="text-xl text-secondary" />+ No active logins found+ </div>+ <p className="text-secondary mt-1 mb-0">+ Devices signed in to your account will appear here.+ </p>+ </div>+ </div>+ }+ />+ </div>+ )+}diff --git a/frontend/src/scenes/settings/user/loginSessionsLogic.test.ts b/frontend/src/scenes/settings/user/loginSessionsLogic.test.tsnew file mode 100644index 000000000000..3ba76d676c64--- /dev/null+++ b/frontend/src/scenes/settings/user/loginSessionsLogic.test.ts@@ -0,0 +1,79 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { loginSessionsLogic } from './loginSessionsLogic'++const CURRENT_ID = '0190a1b2-0000-7000-8000-000000000001'+const OTHER_ID = '0190a1b2-0000-7000-8000-000000000002'++const SESSIONS = [+ {+ id: CURRENT_ID,+ last_activity: '2026-06-18T00:00:00Z',+ location: 'San Francisco, United States',+ device: 'Chrome 135 on macOS',+ login_method: 'password',+ is_current: true,+ },+ {+ id: OTHER_ID,+ last_activity: '2026-06-10T00:00:00Z',+ location: 'London, United Kingdom',+ device: 'Firefox 120 on Windows',+ login_method: 'Google',+ is_current: false,+ },+]++describe('loginSessionsLogic', () => {+ let logic: ReturnType<typeof loginSessionsLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/users/@me/login_sessions/': () => [200, SESSIONS],+ },+ delete: {+ '/api/users/@me/login_sessions/:id/': () => [204, null],+ },+ post: {+ '/api/users/@me/login_sessions/revoke_others/': () => [200, { revoked_count: 1 }],+ },+ })+ initKeaTests()+ logic = loginSessionsLogic()+ logic.mount()+ })++ it('loads login sessions on mount', async () => {+ await expectLogic(logic).toFinishAllListeners().toMatchValues({+ loginSessions: SESSIONS,+ })+ })++ it('removes a session from the list when revoked', async () => {+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.revokeSession(OTHER_ID)++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ loginSessions: [SESSIONS[0]],+ })+ })++ it('keeps only the current session when revoking others', async () => {+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.revokeOtherSessions()++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ loginSessions: [SESSIONS[0]],+ })+ })+})diff --git a/frontend/src/scenes/settings/user/loginSessionsLogic.ts b/frontend/src/scenes/settings/user/loginSessionsLogic.tsnew file mode 100644index 000000000000..edae7743de4e--- /dev/null+++ b/frontend/src/scenes/settings/user/loginSessionsLogic.ts@@ -0,0 +1,49 @@+import { actions, events, kea, path } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import {+ usersLoginSessionsDestroy,+ usersLoginSessionsList,+ usersLoginSessionsRevokeOthersCreate,+} from '~/generated/core/api'+import type { UserAuthSessionApi } from '~/generated/core/api.schemas'++import type { loginSessionsLogicType } from './loginSessionsLogicType'++export const loginSessionsLogic = kea<loginSessionsLogicType>([+ path(['scenes', 'settings', 'user', 'loginSessionsLogic']),++ actions({+ revokeSession: (id: string) => ({ id }),+ revokeOtherSessions: true,+ }),++ loaders(({ values }) => ({+ loginSessions: [+ [] as UserAuthSessionApi[],+ {+ loadLoginSessions: async () => {+ return await usersLoginSessionsList('@me')+ },+ revokeSession: async ({ id }) => {+ await usersLoginSessionsDestroy('@me', id)+ lemonToast.success('Logged out of that device')+ return values.loginSessions.filter((session) => session.id !== id)+ },+ revokeOtherSessions: async () => {+ const { revoked_count } = await usersLoginSessionsRevokeOthersCreate('@me')+ lemonToast.success(+ `Logged out of ${revoked_count} other ${revoked_count === 1 ? 'device' : 'devices'}`+ )+ return values.loginSessions.filter((session) => session.is_current)+ },+ },+ ],+ })),++ events(({ actions }) => ({+ afterMount: () => actions.loadLoginSessions(),+ })),+])diff --git a/posthog/admin/admins/user_admin.py b/posthog/admin/admins/user_admin.pyindex 571ff45690c2..e38605d0db30 100644--- a/posthog/admin/admins/user_admin.py+++ b/posthog/admin/admins/user_admin.py@@ -3,11 +3,9 @@ import datetimefrom django.contrib import admin, messagesfrom django.contrib.auth.admin import UserAdmin as DjangoUserAdminfrom django.contrib.auth.forms import UserChangeForm as DjangoUserChangeForm-from django.contrib.sessions.models import Sessionfrom django.core.exceptions import ValidationErrorfrom django.http import HttpResponseRedirectfrom django.urls import reverse-from django.utils import timezonefrom django.utils.html import format_htmlfrom django.utils.translation import gettext_lazy as _@@ -23,6 +21,7 @@ from posthog.api.email_verification import EmailVerifierfrom posthog.api.two_factor_reset import TwoFactorResetVerifierfrom posthog.models import Userfrom posthog.models.webauthn_credential import WebauthnCredential+from posthog.session.activity import revoke_other_sessionsfrom posthog.tasks.email import send_two_factor_reset_email@@ -254,14 +253,5 @@ class UserAdmin(DjangoUserAdmin):return super().change_view(request, object_id, form_url, extra_context)- def _user_sessions(self, user):- """Fetch user's active sessions. Uses an iterator due to large table size and lack of effective indexing."""- user_pk = str(user.pk)- sessions = Session.objects.filter(expire_date__gt=timezone.now()).only("session_data")- for s in sessions.iterator():- data = s.get_decoded()- if data.get("_auth_user_id") == user_pk:- yield s-def delete_user_sessions(self, user):- return sum(1 for s in self._user_sessions(user) if s.delete())+ return revoke_other_sessions(user, keep_session_key=None)diff --git a/posthog/admin/test_user_admin.py b/posthog/admin/test_user_admin.pynew file mode 100644index 000000000000..8f64654bfbbb--- /dev/null+++ b/posthog/admin/test_user_admin.py@@ -0,0 +1,40 @@+import uuid+from importlib import import_module++from posthog.test.base import BaseTest++from django.conf import settings+from django.contrib.admin.sites import AdminSite+from django.contrib.auth import SESSION_KEY++from posthog.admin.admins.user_admin import UserAdmin+from posthog.models import User+from posthog.session.models import Session+++class TestUserAdminSessions(BaseTest):+ def setUp(self):+ super().setUp()+ self.engine = import_module(settings.SESSION_ENGINE)+ self.admin = UserAdmin(User, AdminSite())++ def _make_user(self) -> User:+ return User.objects.create(email=f"test-{uuid.uuid4()}@example.com", distinct_id=str(uuid.uuid4()))++ def _login_session(self, user: User) -> str:+ store = self.engine.SessionStore()+ store[SESSION_KEY] = str(user.pk)+ store.create()+ return store.session_key++ def test_delete_user_sessions_revokes_all_of_the_users_sessions(self):+ user = self._make_user()+ other_user = self._make_user()+ keys = [self._login_session(user), self._login_session(user)]+ other_key = self._login_session(other_user)++ count = self.admin.delete_user_sessions(user)++ self.assertEqual(count, 2)+ self.assertFalse(Session.objects.filter(session_key__in=keys).exists())+ self.assertTrue(Session.objects.filter(session_key=other_key).exists()) # other user untoucheddiff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 592805a16315..3353a888b0a5 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -1583,8 +1583,6 @@ class TestPasskeySignupAPI(APIBaseTest):When a user signs up with a passkey, the UUID generated during passkey registrationshould become the user's actual UUID."""- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -1592,6 +1590,7 @@ class TestPasskeySignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStore# Generate a UUID that would be created during passkey registrationexpected_uuid = uuid.uuid4()@@ -1644,8 +1643,6 @@ class TestPasskeySignupAPI(APIBaseTest):"""After successful passkey signup, the session data should be cleared."""- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -1653,6 +1650,7 @@ class TestPasskeySignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStoreexpected_uuid = uuid.uuid4()@@ -1696,8 +1694,6 @@ class TestPasskeySignupAPI(APIBaseTest):# Self-created passkeys count as already-acknowledged: otherwise the user lands# on the credential review interstitial after signup and could revoke their only# login credential.- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -1705,6 +1701,7 @@ class TestPasskeySignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStoresession = SessionStore()session[WEBAUTHN_SIGNUP_EMAIL_KEY] = "[email protected]"@@ -1833,8 +1830,6 @@ class TestPasskeySignupAPI(APIBaseTest):When a password is provided, password signup should work even if passkey data exists in session.This handles the case where a user registers a passkey but then reloads the page and tries to signup with a password."""- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -1842,6 +1837,7 @@ class TestPasskeySignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStore# Create a session and set passkey data (simulating a user who registered a passkey but reloaded)session = SessionStore()@@ -1894,8 +1890,6 @@ class TestPasskeySignupAPI(APIBaseTest):When a password is provided, password signup should work even if passkey data exists in session,even when using the same email that was used for passkey registration."""- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -1903,6 +1897,7 @@ class TestPasskeySignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStorepasskey_email = "[email protected]"@@ -2865,8 +2860,6 @@ class TestInviteSignupAPI(APIBaseTest):When a password is provided for invite signup, it should work even if passkey data exists in session.This handles the case where a user registers a passkey but then reloads the page and tries to signup with a password."""- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -2874,6 +2867,7 @@ class TestInviteSignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStore# Create an inviteinvite: OrganizationInvite = OrganizationInvite.objects.create(@@ -2936,8 +2930,6 @@ class TestInviteSignupAPI(APIBaseTest):Otherwise the user lands behind the undismissable 2FA setup modal that only offers TOTP —which platform passkeys (macOS/iOS) cannot accept."""- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -2945,6 +2937,7 @@ class TestInviteSignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStoresuffix = "enforced" if org_enforce_2fa else "unenforced"target_email = f"passkey_invite_{suffix}@posthog.com"@@ -2986,8 +2979,6 @@ class TestInviteSignupAPI(APIBaseTest):# Self-created passkeys via invite signup count as already-acknowledged: otherwise# the user lands on the credential review interstitial after signup and could revoke# their only login credential.- from django.contrib.sessions.backends.db import SessionStore-from webauthn.helpers import bytes_to_base64urlfrom posthog.api.webauthn import (@@ -2995,6 +2986,7 @@ class TestInviteSignupAPI(APIBaseTest):WEBAUTHN_SIGNUP_EMAIL_KEY,WEBAUTHN_SIGNUP_USER_UUID_KEY,)+ from posthog.session.backend import SessionStoreinvite: OrganizationInvite = OrganizationInvite.objects.create(target_email="[email protected]", organization=self.organizationdiff --git a/posthog/api/test/test_user_auth_session.py b/posthog/api/test/test_user_auth_session.pynew file mode 100644index 000000000000..72624e23ce14--- /dev/null+++ b/posthog/api/test/test_user_auth_session.py@@ -0,0 +1,219 @@+import time+from datetime import timedelta+from importlib import import_module+from typing import Any, cast++from posthog.test.base import APIBaseTest++from django.conf import settings+from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY+from django.test import Client as DjangoClient+from django.urls import reverse+from django.utils import timezone++from posthog.models import User+from posthog.session.activity import session_public_id+from posthog.session.models import Session+++class TestSessionEngineActivity(APIBaseTest):+ def test_authenticated_request_attributes_session_to_user(self):+ self.client.get("/api/users/@me/")++ row = Session.objects.get(session_key=self.client.session.session_key)+ self.assertEqual(row.user_id, self.user.pk)++ def test_anonymous_request_attributes_nothing(self):+ self.client.logout()++ self.client.get("/api/users/@me/")++ self.assertFalse(Session.objects.filter(user_id=self.user.pk).exists())++ def test_logout_removes_the_session_row(self):+ self.client.get("/api/users/@me/")+ key = self.client.session.session_key+ self.assertTrue(Session.objects.filter(session_key=key).exists())++ self.client.post("/logout")++ self.assertFalse(Session.objects.filter(session_key=key).exists())+++class TestUserAuthSessionAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.engine = import_module(settings.SESSION_ENGINE)++ def _other_session(self, user: User | None = None) -> Session:+ user = user or self.user+ store = self.engine.SessionStore()+ store[SESSION_KEY] = str(user.pk)+ store[BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend"+ store.create()+ return Session.objects.get(session_key=store.session_key)++ def _revoke_url(self, session: Session) -> str:+ return f"/api/users/@me/login_sessions/{session_public_id(session.session_key)}/"++ def test_list_returns_sessions_with_current_flag(self):+ self._other_session()++ response = self.client.get("/api/users/@me/login_sessions/")++ self.assertEqual(response.status_code, 200, response.content)+ data = response.json()+ self.assertEqual(len(data), 2)+ self.assertEqual(sum(1 for s in data if s["is_current"]), 1)+ self.assertTrue(data[0]["is_current"]) # current session listed first++ def test_list_excludes_sensitive_fields(self):+ self._other_session()++ data = self.client.get("/api/users/@me/login_sessions/").json()++ for entry in data:+ self.assertNotIn("session_key", entry)+ self.assertNotIn("ip", entry)+ self.assertNotIn("user_agent", entry)++ def test_list_excludes_expired_sessions(self):+ stale = self._other_session()+ Session.objects.filter(session_key=stale.session_key).update(expire_date=timezone.now() - timedelta(days=1))++ data = self.client.get("/api/users/@me/login_sessions/").json()++ self.assertNotIn(str(session_public_id(stale.session_key)), [s["id"] for s in data])++ def test_list_only_returns_own_sessions(self):+ other_user = User.objects.create(email="[email protected]", distinct_id="other")+ self._other_session(other_user)++ data = self.client.get("/api/users/@me/login_sessions/").json()++ self.assertEqual(len(data), 1)+ self.assertTrue(data[0]["is_current"])++ def test_revoke_session_deletes_it(self):+ other = self._other_session()++ response = self.client.delete(self._revoke_url(other))++ self.assertIn(response.status_code, (200, 204), response.content)+ self.assertFalse(Session.objects.filter(session_key=other.session_key).exists())++ def test_cannot_revoke_another_users_session(self):+ other_user = User.objects.create(email="[email protected]", distinct_id="victim")+ victim = self._other_session(other_user)++ response = self.client.delete(self._revoke_url(victim))++ self.assertEqual(response.status_code, 404)+ self.assertTrue(Session.objects.filter(session_key=victim.session_key).exists())++ def test_revoke_others_keeps_current(self):+ first = self._other_session()+ second = self._other_session()++ response = self.client.post("/api/users/@me/login_sessions/revoke_others/")++ self.assertEqual(response.status_code, 200, response.content)+ self.assertEqual(response.json()["revoked_count"], 2)+ self.assertFalse(Session.objects.filter(session_key__in=[first.session_key, second.session_key]).exists())+ self.assertEqual(self.client.get("/api/users/@me/").status_code, 200) # current still works++ def test_personal_api_key_cannot_list_login_sessions(self):+ key = self.create_personal_api_key_with_scopes(["user:read"])+ self.client.logout()++ response = self.client.get("/api/users/@me/login_sessions/", HTTP_AUTHORIZATION=f"Bearer {key}")++ self.assertIn(response.status_code, (401, 403))++ def _make_session_stale(self) -> None:+ session = self.client.session+ session[settings.SESSION_COOKIE_CREATED_AT_KEY] = time.time() - settings.SESSION_SENSITIVE_ACTIONS_AGE - 100+ session.save()++ def test_revoke_requires_reauth_on_stale_session(self):+ other = self._other_session()+ self._make_session_stale()++ response = self.client.delete(self._revoke_url(other))++ self.assertEqual(response.status_code, 403)+ self.assertEqual(response.json()["code"], "sensitive_action_required_reauth")+ self.assertTrue(Session.objects.filter(session_key=other.session_key).exists())++ def test_revoke_others_requires_reauth_on_stale_session(self):+ other = self._other_session()+ self._make_session_stale()++ response = self.client.post("/api/users/@me/login_sessions/revoke_others/")++ self.assertEqual(response.status_code, 403)+ self.assertEqual(response.json()["code"], "sensitive_action_required_reauth")+ self.assertTrue(Session.objects.filter(session_key=other.session_key).exists())++ def test_listing_allowed_on_stale_session(self):+ self._other_session()+ self._make_session_stale()++ response = self.client.get("/api/users/@me/login_sessions/")++ self.assertEqual(response.status_code, 200, response.content)++ def test_actions_are_self_only_even_for_staff(self):+ self.user.is_staff = True+ self.user.save()+ victim_user = User.objects.create(email="[email protected]", distinct_id="victim-staff")+ victim = self._other_session(victim_user)++ listed = self.client.get(f"/api/users/{victim_user.uuid}/login_sessions/").json()+ self.assertNotIn(str(session_public_id(victim.session_key)), [s["id"] for s in listed])++ response = self.client.delete(+ f"/api/users/{victim_user.uuid}/login_sessions/{session_public_id(victim.session_key)}/"+ )+ self.assertEqual(response.status_code, 404)+ self.assertTrue(Session.objects.filter(session_key=victim.session_key).exists())+++class TestUserAuthSessionImpersonation(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.other_user = User.objects.create_and_join(+ self.organization, email="[email protected]", password="123456"+ )+ self.user.is_staff = True+ self.user.save()+ self.client = cast(Any, DjangoClient())+ self.client.force_login(self.user)++ def _impersonate(self):+ return self.client.post(+ reverse("loginas-user-login", kwargs={"user_id": self.other_user.id}),+ data={"read_only": "false", "reason": "test"},+ follow=True,+ )++ def test_get_list_allowed_while_impersonating(self):+ self._impersonate()++ response = self.client.get("/api/users/@me/login_sessions/")++ self.assertEqual(response.status_code, 200, response.content)++ def test_revoke_blocked_while_impersonating(self):+ self._impersonate()++ response = self.client.delete("/api/users/@me/login_sessions/00000000-0000-0000-0000-000000000000/")++ self.assertEqual(response.status_code, 403, response.content)++ def test_revoke_others_blocked_while_impersonating(self):+ self._impersonate()++ response = self.client.post("/api/users/@me/login_sessions/revoke_others/")++ self.assertEqual(response.status_code, 403, response.content)diff --git a/posthog/api/user.py b/posthog/api/user.pyindex dbddc1b34988..ddd336d4b0f7 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -30,11 +30,11 @@ from django_otp import login as otp_loginfrom django_otp.plugins.otp_static.models import StaticDevice, StaticTokenfrom django_otp.plugins.otp_totp.models import TOTPDevicefrom django_otp.util import random_hex-from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_view+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_viewfrom loginas.utils import is_impersonated_sessionfrom opentelemetry import tracefrom prometheus_client import Counter-from rest_framework import exceptions, mixins, serializers, viewsets+from rest_framework import exceptions, mixins, serializers, status, viewsetsfrom rest_framework.exceptions import NotFoundfrom rest_framework.permissions import AllowAny, IsAuthenticatedfrom rest_framework.response import Response@@ -99,6 +99,14 @@ from posthog.rate_limit import (UserAuthenticationThrottle,UserEmailVerificationThrottle,)+from posthog.session.activity import (+ list_user_sessions,+ revoke_other_sessions,+ revoke_user_auth_session,+ session_public_id,+ sync_current_session_metadata,+)+from posthog.session.models import Sessionfrom posthog.tasks.email import (send_email_change_emails,send_password_changed_email,@@ -785,6 +793,47 @@ class ScenePersonalisationSerializer(serializers.ModelSerializer):)+class UserAuthSessionSerializer(serializers.ModelSerializer):+ """A cookie-auth login session shown on the user's 'Web sessions' screen."""++ id = serializers.SerializerMethodField(help_text="Identifier used to revoke this login session.")+ last_activity = serializers.DateTimeField(+ read_only=True, help_text="When this login session last made a request (refreshed periodically)."+ )+ location = serializers.CharField(+ read_only=True, help_text="Approximate city and country derived from the IP address, if known."+ )+ device = serializers.CharField(+ source="short_user_agent",+ read_only=True,+ help_text="Browser and operating system parsed from the user agent, e.g. 'Chrome 135 on macOS'.",+ )+ login_method = serializers.CharField(+ read_only=True, help_text="How this session signed in (e.g. password, Google, SAML)."+ )+ is_current = serializers.SerializerMethodField(+ help_text="Whether this is the login session making the current request."+ )++ class Meta:+ model = Session+ fields = ["id", "last_activity", "location", "device", "login_method", "is_current"]++ @extend_schema_field({"type": "string", "format": "uuid"})+ def get_id(self, obj: Session) -> str:+ # Expose a stable, opaque id derived from the session key — never the key itself.+ return str(session_public_id(obj.session_key))++ @extend_schema_field({"type": "boolean"})+ def get_is_current(self, obj: Session) -> bool:+ request = self.context.get("request")+ return bool(request and obj.session_key == request.session.session_key)+++class RevokeOtherSessionsResponseSerializer(serializers.Serializer):+ revoked_count = serializers.IntegerField(help_text="Number of other login sessions that were revoked.")++@extend_schema(extensions={"x-product": "core"})@extend_schema_view(retrieve=extend_schema(@@ -895,6 +944,64 @@ class UserViewSet(user = self.get_object()return Response({"github_login": user.get_github_login()})+ @extend_schema(responses=UserAuthSessionSerializer(many=True))+ @action(+ methods=["GET"],+ detail=True,+ url_path="login_sessions",+ authentication_classes=[SessionAuthentication],+ permission_classes=[IsAuthenticated],+ pagination_class=None,+ )+ def login_sessions(self, request, **kwargs):+ """List the cookie-auth login sessions for the current user. Self-only — never another user."""+ user = cast(User, request.user)+ # Populate the current session's display metadata up front so it appears fully on first load+ # (the activity middleware otherwise only records it after this response is sent).+ sync_current_session_metadata(request, force=True)+ rows = list_user_sessions(user)+ current_key = request.session.session_key+ rows.sort(key=lambda row: row.session_key != current_key) # current first, stable on -last_activity+ serializer = UserAuthSessionSerializer(rows, many=True, context=self.get_serializer_context())+ return Response(serializer.data)++ @extend_schema(request=None, responses={204: OpenApiResponse(description="Login session revoked.")})+ @action(+ methods=["DELETE"],+ detail=True,+ url_path=r"login_sessions/(?P<session_id>[0-9a-f-]+)",+ authentication_classes=[SessionAuthentication],+ permission_classes=[IsAuthenticated, TimeSensitiveActionPermission],+ )+ def revoke_login_session(self, request, session_id=None, **kwargs):+ """Revoke a single login session belonging to the current user. Self-only.++ Requires recent auth (TimeSensitiveActionPermission) so a stolen cookie can't weaponize+ revocation, and is blocked while impersonating via ImpersonationBlockedPathsMiddleware.+ """+ user = cast(User, request.user)+ if not revoke_user_auth_session(user, session_id):+ raise NotFound("Login session not found.")+ return Response(status=status.HTTP_204_NO_CONTENT)++ @extend_schema(request=None, responses=RevokeOtherSessionsResponseSerializer)+ @action(+ methods=["POST"],+ detail=True,+ url_path="login_sessions/revoke_others",+ authentication_classes=[SessionAuthentication],+ permission_classes=[IsAuthenticated, TimeSensitiveActionPermission],+ )+ def revoke_other_login_sessions(self, request, **kwargs):+ """Revoke every login session for the current user except the one making this request. Self-only.++ Requires recent auth (TimeSensitiveActionPermission) so a stolen cookie can't weaponize the+ "log out everywhere else" lock-out, and is blocked while impersonating.+ """+ user = cast(User, request.user)+ revoked_count = revoke_other_sessions(user, request.session.session_key)+ return Response({"revoked_count": revoked_count})+@action(methods=["POST"], detail=False, permission_classes=[AllowAny])def verify_email(self, request, **kwargs):token = request.data["token"] if "token" in request.data else Nonediff --git a/posthog/dags/backfill_user_auth_sessions.py b/posthog/dags/backfill_user_auth_sessions.pynew file mode 100644index 000000000000..39e3ab40864e--- /dev/null+++ b/posthog/dags/backfill_user_auth_sessions.py@@ -0,0 +1,47 @@+"""Dagster job to backfill user_id/login_method onto pre-swap django_session rows.++The session store stamps user_id on every new/active session, so this only sweeps the idle+long-tail of sessions that pre-date the engine swap. It is idempotent (it touches only rows where+user_id is NULL) and batched, so it is safe to re-run and resumes where a prior run left off.+"""++import dagster+import pydantic++from posthog.dags.common import JobOwners+from posthog.session.backfill import backfill_session_user_ids+++class BackfillUserAuthSessionsConfig(dagster.Config):+ batch_size: int = pydantic.Field(default=2000, description="Sessions decoded per batch.")+ sleep_seconds: float = pydantic.Field(default=0.1, description="Seconds to sleep between batches to cap DB load.")+ dry_run: bool = pydantic.Field(default=True, description="If true, scan and report counts without writing rows.")+++def backfill_user_auth_sessions_op(+ context: dagster.OpExecutionContext,+ config: BackfillUserAuthSessionsConfig,+) -> None:+ context.log.info(f"Backfilling session user_id (dry_run={config.dry_run}, batch_size={config.batch_size})")+ stats = backfill_session_user_ids(+ batch_size=config.batch_size,+ sleep_seconds=config.sleep_seconds,+ dry_run=config.dry_run,+ )+ context.log.info(f"Scanned {stats.scanned} sessions, updated {stats.updated} (dry_run={config.dry_run})")+ context.add_output_metadata(+ {+ "scanned": dagster.MetadataValue.int(stats.scanned),+ "updated": dagster.MetadataValue.int(stats.updated),+ "dry_run": dagster.MetadataValue.bool(config.dry_run),+ }+ )+++ description="Backfill user_id/login_method onto pre-swap django_session rows (idempotent, batched).",+ tags={"owner": JobOwners.TEAM_SECURITY.value},+)+def backfill_user_auth_sessions_job():+ backfill_user_auth_sessions_op()diff --git a/posthog/dags/common/owners.py b/posthog/dags/common/owners.pyindex 4626efb095f7..b03f79a34151 100644--- a/posthog/dags/common/owners.py+++ b/posthog/dags/common/owners.py@@ -17,5 +17,6 @@ class JobOwners(str, Enum):TEAM_MANAGED_WAREHOUSE = "team-managed-warehouse"TEAM_POSTHOG_AI = "team-posthog-ai"TEAM_QUERY_PERFORMANCE = "team-query-performance"+ TEAM_SECURITY = "team-security"TEAM_WAREHOUSE_SOURCES = "team-warehouse-sources"TEAM_WEB_ANALYTICS = "team-web-analytics"diff --git a/posthog/dags/locations/analytics_platform.py b/posthog/dags/locations/analytics_platform.pyindex db0f1e788a55..60ad197a140d 100644--- a/posthog/dags/locations/analytics_platform.py+++ b/posthog/dags/locations/analytics_platform.py@@ -3,6 +3,7 @@ import dagsterfrom posthog.dags import sessions, sessions_v1_cleanupfrom posthog.dags.backfill_internal_test_users_cohort import backfill_internal_test_users_cohort_jobfrom posthog.dags.backfill_persons_on_events_mode import backfill_persons_on_events_mode_job+from posthog.dags.backfill_user_auth_sessions import backfill_user_auth_sessions_jobfrom posthog.dags.sessions import (experimental_sessions_backfill_job,experimental_sessions_v3_backfill,@@ -19,6 +20,7 @@ defs = dagster.Definitions(experimental_sessions_backfill_job,backfill_internal_test_users_cohort_job,backfill_persons_on_events_mode_job,+ backfill_user_auth_sessions_job,],loggers=loggers,resources=resources,diff --git a/posthog/dags/slack_alerts.py b/posthog/dags/slack_alerts.pyindex 92f7c54e5cfb..f51af364b470 100644--- a/posthog/dags/slack_alerts.py+++ b/posthog/dags/slack_alerts.py@@ -23,6 +23,7 @@ notification_channel_per_team = {JobOwners.TEAM_LOGS.value: "#alerts-logs-prod",JobOwners.TEAM_POSTHOG_AI.value: "#alerts-max-ai",JobOwners.TEAM_QUERY_PERFORMANCE.value: "#alerts-query-performance",+ JobOwners.TEAM_SECURITY.value: "#alerts-security",JobOwners.TEAM_WAREHOUSE_SOURCES.value: "#alerts-warehouse-sources",JobOwners.TEAM_WEB_ANALYTICS.value: "#alerts-web-analytics",}diff --git a/posthog/session/__init__.py b/posthog/session/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/session/activity.py b/posthog/session/activity.pynew file mode 100644index 000000000000..2e9add5c83a0--- /dev/null+++ b/posthog/session/activity.py@@ -0,0 +1,127 @@+import uuid+import hashlib+from typing import Optional++from django.contrib.auth import BACKEND_SESSION_KEY+from django.core.cache import cache+from django.db import transaction+from django.db.models import F+from django.http import HttpRequest+from django.utils import timezone++from loginas.utils import is_impersonated_session++from posthog.constants import AUTH_BACKEND_KEYS+from posthog.geoip import get_geoip_properties+from posthog.models import User+from posthog.session.models import Session+from posthog.utils import _is_valid_ip_address, get_ip_address, get_short_user_agent++# Fixed, arbitrary namespace for deriving a session's public id. We expose `uuid5(namespace, key)`+# rather than the session key itself so the key — which can revoke a session — is never leaked, while+# the public id stays stable and opaque (the high-entropy key can't be recovered from it).+SESSION_PUBLIC_ID_NAMESPACE = uuid.UUID("d9c8b7a6-5432-4f10-9e8d-7c6b5a4f3e2d")++# Refresh display metadata at most once per window. Throttled via cache (never via the session) so+# the write can't mark the session modified and trigger a save that resets these columns.+METADATA_SYNC_INTERVAL_SECONDS = 5 * 60+_METADATA_SYNC_CACHE_PREFIX = "auth_session_synced:"+++def session_public_id(session_key: str) -> uuid.UUID:+ return uuid.uuid5(SESSION_PUBLIC_ID_NAMESPACE, session_key)+++def _location_from_ip(ip: Optional[str]) -> Optional[str]:+ properties = get_geoip_properties(ip)+ parts = [properties.get("$geoip_city_name"), properties.get("$geoip_country_name")]+ return ", ".join(part for part in parts if part) or None+++def _login_method(request: HttpRequest) -> Optional[str]:+ backend = request.session.get(BACKEND_SESSION_KEY)+ method = AUTH_BACKEND_KEYS.get(backend) if backend else None+ return method if isinstance(method, str) else None+++def list_user_sessions(user: User) -> list[Session]:+ """The user's live login sessions, most-recently-active first.++ The row IS the session, so filtering live rows by user is the whole query — there are no stale+ or ghost rows to reconcile. Sessions never refreshed since the swap (NULL last_activity) sort last.+ """+ return list(+ Session.objects.filter(user_id=user.pk, expire_date__gt=timezone.now()).order_by(+ F("last_activity").desc(nulls_last=True)+ )+ )+++def sync_current_session_metadata(request: HttpRequest, force: bool = False) -> None:+ """Refresh display metadata (ip, UA, location, last_activity) on the current session row.++ Runs in the activity middleware on every authenticated request. Impersonation sessions are+ skipped — their row carries no `user_id` and must never surface in the impersonated user's list.+ """+ user = request.user+ if not isinstance(user, User) or not user.is_authenticated or user.pk is None:+ return+ if BACKEND_SESSION_KEY not in request.session:+ return+ session_key = request.session.session_key+ if not session_key:+ return+ if is_impersonated_session(request):+ return++ # Key the throttle by a hash of the session key, never the raw key (avoids storing it in cache keys).+ cache_key = f"{_METADATA_SYNC_CACHE_PREFIX}{hashlib.sha256(session_key.encode()).hexdigest()}"+ if not force and cache.get(cache_key):+ return++ ip = get_ip_address(request)+ fields = {+ "last_activity": timezone.now(),+ "ip": ip if _is_valid_ip_address(ip) else None,+ "short_user_agent": get_short_user_agent(request) or None,+ "location": _location_from_ip(ip),+ "login_method": _login_method(request),+ }++ # Defer the write to commit. This metadata is best-effort display data, so the write must never+ # add a query to the caller's transaction (which would break assertNumQueries assertions across+ # the suite) nor run against a transaction already broken by a handled IntegrityError. In+ # autocommit (no open transaction) on_commit runs immediately; mark the throttle only once the+ # write actually commits, so a rollback lets the next request retry.+ def _write() -> None:+ Session.objects.filter(session_key=session_key).update(**fields)+ cache.set(cache_key, True, timeout=METADATA_SYNC_INTERVAL_SECONDS)++ transaction.on_commit(_write)+++def revoke_other_sessions(user: User, keep_session_key: Optional[str]) -> int:+ """Revoke every login session for `user` except `keep_session_key`. Returns the count revoked."""+ queryset = Session.objects.filter(user_id=user.pk)+ if keep_session_key:+ queryset = queryset.exclude(session_key=keep_session_key)+ count, _ = queryset.delete()+ return count+++def revoke_user_auth_session(user: User, public_id: str) -> bool:+ """Revoke a single login session owned by `user`, identified by its public id. Self-only.++ Returns False if the id is malformed or doesn't match one of the user's sessions.+ """+ try:+ target = uuid.UUID(str(public_id))+ except (ValueError, AttributeError, TypeError):+ return False+ # The public id is a one-way derivation of the key, so match by recomputing over the user's own+ # (small) set of sessions rather than querying it directly.+ for session_key in Session.objects.filter(user_id=user.pk).values_list("session_key", flat=True):+ if session_public_id(session_key) == target:+ Session.objects.filter(user_id=user.pk, session_key=session_key).delete()+ return True+ return Falsediff --git a/posthog/session/apps.py b/posthog/session/apps.pynew file mode 100644index 000000000000..9549f07af294--- /dev/null+++ b/posthog/session/apps.py@@ -0,0 +1,10 @@+from django.apps import AppConfig+++class PostHogSessionConfig(AppConfig):+ name = "posthog.session"+ label = "posthog_session"+ verbose_name = "Sessions"++ def ready(self) -> None:+ import posthog.session.signals # noqa: F401, PLC0415 — registers the post_delete session cleanupdiff --git a/posthog/session/backend.py b/posthog/session/backend.pynew file mode 100644index 000000000000..2153c452f685--- /dev/null+++ b/posthog/session/backend.py@@ -0,0 +1,104 @@+from typing import TYPE_CHECKING, Any, cast++from django.contrib.auth import SESSION_KEY+from django.contrib.sessions.backends.base import CreateError, UpdateError+from django.contrib.sessions.backends.db import SessionStore as DBStore+from django.db import DatabaseError, IntegrityError, router, transaction+from django.utils import timezone++from asgiref.sync import sync_to_async+from loginas.settings import USER_SESSION_FLAG++if TYPE_CHECKING:+ from posthog.session.models import Session++# Columns the session machinery owns and may write on save. The remaining columns (ip,+# short_user_agent, location, last_activity beyond creation) are written by the activity middleware+# and must not be reset to NULL by a routine session save.+_SESSION_OWNED_FIELDS = ["session_data", "expire_date", "user_id"]+++def _auth_user_id(data: dict[str, Any]) -> int | None:+ if USER_SESSION_FLAG in data:+ # Impersonation (loginas): never attribute the session to the impersonated user.+ return None+ try:+ return int(data[SESSION_KEY])+ except (KeyError, TypeError, ValueError):+ return None+++class SessionStore(DBStore):+ """Database session store that keeps `user_id` on the session row in sync with `_auth_user_id`.++ The only behavioural change from Django's `db` store is that `user_id` is stamped on every save+ and that updates touch only the session-owned columns, leaving middleware-written display+ metadata intact.+ """++ @classmethod+ def get_model_class(cls):+ from posthog.session.models import Session++ return Session++ 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)+ # Only persisted on INSERT (see `save`); for existing rows the middleware owns last_activity.+ obj.last_activity = timezone.now()+ return obj++ def save(self, must_create: bool = False) -> None:+ if self.session_key is None:+ return self.create()+ data = self._get_session(no_load=must_create) # type: ignore[attr-defined] # private SessionBase method, not in django-stubs+ obj = self.create_model_instance(data)+ using = router.db_for_write(self.model, instance=obj)+ try:+ with transaction.atomic(using=using):+ self._persist(obj, must_create, using)+ except IntegrityError:+ if must_create:+ raise CreateError+ raise+ except DatabaseError:+ if not must_create:+ raise UpdateError+ raise++ async def acreate_model_instance(self, data: dict[str, Any]) -> "Session":+ obj = cast("Session", await super().acreate_model_instance(data))+ obj.user_id = _auth_user_id(data)+ obj.last_activity = timezone.now()+ return obj++ async def asave(self, must_create: bool = False) -> None:+ if self.session_key is None:+ return await self.acreate()+ data = await self._aget_session(no_load=must_create) # type: ignore[attr-defined] # private SessionBase method, not in django-stubs+ obj = await self.acreate_model_instance(data)+ using = router.db_for_write(self.model, instance=obj)++ @sync_to_async+ def run() -> None:+ with transaction.atomic(using=using):+ self._persist(obj, must_create, using)++ try:+ await run()+ except IntegrityError:+ if must_create:+ raise CreateError+ raise+ except DatabaseError:+ if not must_create:+ raise UpdateError+ raise++ def _persist(self, obj: "Session", must_create: bool, using: str) -> None:+ # On UPDATE, touch only the session-owned columns so middleware-written metadata survives.+ if must_create:+ obj.save(force_insert=True, using=using)+ else:+ obj.save(force_update=True, using=using, update_fields=_SESSION_OWNED_FIELDS)diff --git a/posthog/session/backfill.py b/posthog/session/backfill.pynew file mode 100644index 000000000000..a9a25eda58e5--- /dev/null+++ b/posthog/session/backfill.py@@ -0,0 +1,78 @@+import time+from dataclasses import dataclass++from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY+from django.utils import timezone++import structlog+from loginas import settings as la_settings++from posthog.constants import AUTH_BACKEND_KEYS+from posthog.models import User+from posthog.session.models import Session++logger = structlog.get_logger(__name__)+++@dataclass+class BackfillStats:+ scanned: int = 0+ updated: int = 0+++def _populate(session: Session) -> bool:+ """Set user_id (and metadata) on the session from its decoded data. Returns False to skip it."""+ data = session.get_decoded()+ user_id = data.get(SESSION_KEY)+ if not user_id:+ return False+ # Never attribute impersonation sessions — they must not appear in the impersonated user's list.+ if la_settings.USER_SESSION_FLAG in data:+ return False++ session.user_id = int(user_id)+ backend = data.get(BACKEND_SESSION_KEY)+ method = AUTH_BACKEND_KEYS.get(backend) if backend else None+ session.login_method = method if isinstance(method, str) else None+ return True+++def _flush(batch: list[Session], dry_run: bool) -> int:+ # Drop sessions whose user no longer exists so we never attribute a row to a deleted account.+ valid_user_ids = set(User.objects.filter(id__in={s.user_id for s in batch}).values_list("id", flat=True))+ rows = [session for session in batch if session.user_id in valid_user_ids]+ if not rows or dry_run:+ return len(rows)+ # Only freshly-attributed rows reach here (the query excludes rows that already have a user_id).+ Session.objects.bulk_update(rows, ["user_id", "login_method"], batch_size=len(rows))+ return len(rows)+++def backfill_session_user_ids(+ *, batch_size: int = 2000, sleep_seconds: float = 0.1, dry_run: bool = False+) -> BackfillStats:+ """Backfill user_id (and login_method) onto existing django_session rows. Idempotent and batched."""+ stats = BackfillStats()+ batch: list[Session] = []++ # Only live sessions still missing user_id: the store already attributes new/active sessions, so+ # this targets the pre-swap idle long-tail and makes re-runs no-ops instead of rewriting rows.+ # iterator() uses a server-side cursor so we never load the whole table.+ sessions = Session.objects.filter(expire_date__gt=timezone.now(), user_id__isnull=True).only(+ "session_key", "session_data"+ )+ for session in sessions.iterator(chunk_size=batch_size):+ stats.scanned += 1+ if _populate(session):+ batch.append(session)+ if len(batch) >= batch_size:+ stats.updated += _flush(batch, dry_run)+ batch = []+ if sleep_seconds:+ time.sleep(sleep_seconds)++ if batch:+ stats.updated += _flush(batch, dry_run)++ logger.info("backfill_user_auth_sessions_done", scanned=stats.scanned, updated=stats.updated, dry_run=dry_run)+ return statsdiff --git a/posthog/session/middleware.py b/posthog/session/middleware.pynew file mode 100644index 000000000000..98459b424316--- /dev/null+++ b/posthog/session/middleware.py@@ -0,0 +1,20 @@+from django.contrib.auth import BACKEND_SESSION_KEY+from django.http import HttpRequest++from posthog.models import User+from posthog.session.activity import sync_current_session_metadata+++class UserAuthSessionActivityMiddleware:+ """Refreshes display metadata on the current login session's row (see posthog.session.activity)."""++ def __init__(self, get_response):+ self.get_response = get_response++ def __call__(self, request: HttpRequest):+ response = self.get_response(request)+ # Same gate as KnownLoginDeviceCookieMiddleware: only session-authenticated requests. The+ # helper itself skips impersonation.+ if isinstance(request.user, User) and BACKEND_SESSION_KEY in request.session:+ sync_current_session_metadata(request)+ return responsediff --git a/posthog/session/migrations/0001_initial.py b/posthog/session/migrations/0001_initial.pynew file mode 100644index 000000000000..5927e4da438e--- /dev/null+++ b/posthog/session/migrations/0001_initial.py@@ -0,0 +1,65 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ initial = True++ dependencies = []++ operations = [+ migrations.SeparateDatabaseAndState(+ # State: Django learns about the model. Database: adopt the existing `django_session`+ # table — create it only on a fresh DB, otherwise just add the new columns. This makes+ # the engine swap log nobody out (existing session rows are preserved as-is).+ state_operations=[+ migrations.CreateModel(+ name="Session",+ fields=[+ (+ "session_key",+ models.CharField(+ max_length=40, primary_key=True, serialize=False, verbose_name="session key"+ ),+ ),+ ("session_data", models.TextField(verbose_name="session data")),+ ("expire_date", models.DateTimeField(db_index=True, verbose_name="expire date")),+ ("user_id", models.BigIntegerField(null=True)),+ ("last_activity", models.DateTimeField(null=True)),+ ("ip", models.GenericIPAddressField(null=True)),+ ("short_user_agent", models.CharField(max_length=255, null=True)),+ ("location", models.CharField(max_length=255, null=True)),+ ("login_method", models.CharField(max_length=64, null=True)),+ ],+ options={"db_table": "django_session"},+ ),+ ],+ database_operations=[+ migrations.RunSQL(+ sql="""+ CREATE TABLE IF NOT EXISTS django_session (+ session_key varchar(40) NOT NULL PRIMARY KEY,+ session_data text NOT NULL,+ expire_date timestamptz NOT NULL+ );+ DO $$+ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_indexes+ WHERE tablename = 'django_session' AND indexdef LIKE '%(expire_date)%'+ ) THEN+ CREATE INDEX django_session_expire_date_idx ON django_session (expire_date);+ END IF;+ END+ $$;+ ALTER TABLE django_session ADD COLUMN IF NOT EXISTS user_id bigint NULL;+ ALTER TABLE django_session ADD COLUMN IF NOT EXISTS last_activity timestamptz NULL;+ ALTER TABLE django_session ADD COLUMN IF NOT EXISTS ip inet NULL;+ ALTER TABLE django_session ADD COLUMN IF NOT EXISTS short_user_agent varchar(255) NULL;+ ALTER TABLE django_session ADD COLUMN IF NOT EXISTS location varchar(255) NULL;+ ALTER TABLE django_session ADD COLUMN IF NOT EXISTS login_method varchar(64) NULL;+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ ],+ ),+ ]diff --git a/posthog/session/migrations/0002_session_user_id_index.py b/posthog/session/migrations/0002_session_user_id_index.pynew file mode 100644index 000000000000..2317d8cdb682--- /dev/null+++ b/posthog/session/migrations/0002_session_user_id_index.py@@ -0,0 +1,19 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ # Concurrent index builds cannot run inside a transaction. Built concurrently (and in its own+ # migration, per PostHog policy) so adopting the existing, every-request-written django_session+ # table never takes a blocking lock on a large table.+ atomic = False++ dependencies = [("posthog_session", "0001_initial")]++ operations = [+ SafeAddIndexConcurrently(+ model_name="session",+ index=models.Index(fields=["user_id"], name="django_session_user_id_idx"),+ ),+ ]diff --git a/posthog/session/migrations/__init__.py b/posthog/session/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/session/migrations/max_migration.txt b/posthog/session/migrations/max_migration.txtnew file mode 100644index 000000000000..5a77612bbff4--- /dev/null+++ b/posthog/session/migrations/max_migration.txt@@ -0,0 +1 @@+0002_session_user_id_indexdiff --git a/posthog/session/models.py b/posthog/session/models.pynew file mode 100644index 000000000000..8ba04c6fc0ad--- /dev/null+++ b/posthog/session/models.py@@ -0,0 +1,38 @@+from django.contrib.sessions.base_session import AbstractBaseSession+from django.db import models+++class Session(AbstractBaseSession):+ """The application's session model, stored on the `django_session` table.++ Subclasses Django's `AbstractBaseSession` and is wired in via `SESSION_ENGINE`+ (`posthog.session.backend`). Beyond the base columns (`session_key`, `session_data`,+ `expire_date`) it adds a queryable `user_id` plus best-effort display metadata so a user can+ see where they're logged in and revoke a session remotely.++ `user_id` is stamped by the store from the session's `_auth_user_id` on every save, so it stays+ in sync with the authenticated user with no separate index table. Impersonation sessions are+ never attributed to the impersonated user (the store leaves `user_id` NULL for them).++ Reusing the existing `django_session` table — rather than a new one — is deliberate: swapping the+ engine then logs nobody out, since existing cookies decode unchanged.+ """++ # Plain BigIntegerField, not a ForeignKey to posthog_user: avoids a per-write FK constraint+ # check against the user table on this every-request-written table (performance).+ user_id = models.BigIntegerField(null=True)+ last_activity = models.DateTimeField(null=True)+ ip = models.GenericIPAddressField(null=True)+ short_user_agent = models.CharField(max_length=255, null=True)+ location = models.CharField(max_length=255, null=True)+ login_method = models.CharField(max_length=64, null=True)++ class Meta:+ db_table = "django_session"+ indexes = [models.Index(fields=["user_id"], name="django_session_user_id_idx")]++ @classmethod+ def get_session_store_class(cls):+ from posthog.session.backend import SessionStore++ return SessionStorediff --git a/posthog/session/signals.py b/posthog/session/signals.pynew file mode 100644index 000000000000..fc48d5aa20f9--- /dev/null+++ b/posthog/session/signals.py@@ -0,0 +1,15 @@+from django.db.models.signals import post_delete+from django.dispatch import receiver++from posthog.models.user import User+from posthog.session.models import Session+++@receiver(post_delete, sender=User)+def delete_sessions_on_user_deletion(sender: type[User], instance: User, **kwargs: object) -> None:+ """Purge a deleted user's login session rows.++ `Session.user_id` is a plain BigIntegerField (no FK), so there is no cascade — without this the+ deleted user's ip / location / user-agent would linger on the row until the session expires.+ """+ Session.objects.filter(user_id=instance.pk).delete()diff --git a/posthog/session/test/__init__.py b/posthog/session/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/session/test/test_activity.py b/posthog/session/test/test_activity.pynew file mode 100644index 000000000000..16bb72f21d7b--- /dev/null+++ b/posthog/session/test/test_activity.py@@ -0,0 +1,186 @@+import uuid+from datetime import timedelta+from importlib import import_module++from posthog.test.base import BaseTest++from django.conf import settings+from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY+from django.core.cache import cache+from django.test import RequestFactory+from django.utils import timezone++from loginas import settings as la_settings++from posthog.models import User+from posthog.session.activity import (+ list_user_sessions,+ revoke_other_sessions,+ revoke_user_auth_session,+ session_public_id,+ sync_current_session_metadata,+)+from posthog.session.models import Session+++class TestSessionActivity(BaseTest):+ def setUp(self):+ super().setUp()+ self.engine = import_module(settings.SESSION_ENGINE)+ cache.clear()++ def _make_user(self) -> User:+ return User.objects.create(email=f"test-{uuid.uuid4()}@example.com", distinct_id=str(uuid.uuid4()))++ def _login_session(self, user: User) -> str:+ store = self.engine.SessionStore()+ store[SESSION_KEY] = str(user.pk)+ store[BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend"+ store.create()+ return store.session_key++ def _request(self, user: User, session_key: str):+ request = RequestFactory().get("/")+ request.user = user+ request.session = self.engine.SessionStore(session_key=session_key)+ return request++ def test_public_id_is_stable_and_opaque(self):+ key = "some-session-key"+ self.assertEqual(session_public_id(key), session_public_id(key))+ self.assertNotEqual(session_public_id(key), session_public_id("other-key"))+ self.assertNotIn(key, str(session_public_id(key)))++ def test_list_returns_only_the_users_live_sessions(self):+ user = self._make_user()+ other_user = self._make_user()+ key = self._login_session(user)+ self._login_session(other_user)++ sessions = list_user_sessions(user)++ self.assertEqual([s.session_key for s in sessions], [key])++ def test_list_excludes_expired_sessions(self):+ user = self._make_user()+ key = self._login_session(user)+ Session.objects.filter(session_key=key).update(expire_date=timezone.now() - timedelta(days=1))++ self.assertEqual(list_user_sessions(user), [])++ def test_list_sorts_null_last_activity_last(self):+ # A backfilled session (never refreshed since the swap) has NULL last_activity and must sort+ # below sessions with real activity, not above them.+ user = self._make_user()+ active = self._login_session(user)+ idle = self._login_session(user)+ Session.objects.filter(session_key=idle).update(last_activity=None)+ Session.objects.filter(session_key=active).update(last_activity=timezone.now())++ ordered = [s.session_key for s in list_user_sessions(user)]++ self.assertLess(ordered.index(active), ordered.index(idle))++ def test_revoke_other_sessions_keeps_current(self):+ user = self._make_user()+ current = self._login_session(user)+ other = self._login_session(user)++ count = revoke_other_sessions(user, keep_session_key=current)++ self.assertEqual(count, 1)+ self.assertTrue(Session.objects.filter(session_key=current).exists())+ self.assertFalse(Session.objects.filter(session_key=other).exists())++ def test_revoke_other_sessions_does_not_touch_other_users(self):+ user = self._make_user()+ other_user = self._make_user()+ current = self._login_session(user)+ victim = self._login_session(other_user)++ revoke_other_sessions(user, keep_session_key=current)++ self.assertTrue(Session.objects.filter(session_key=victim).exists())++ def test_revoke_user_auth_session_deletes_by_public_id(self):+ user = self._make_user()+ key = self._login_session(user)++ self.assertTrue(revoke_user_auth_session(user, str(session_public_id(key))))+ self.assertFalse(Session.objects.filter(session_key=key).exists())++ def test_revoke_user_auth_session_will_not_revoke_another_users_session(self):+ user = self._make_user()+ other_user = self._make_user()+ victim_key = self._login_session(other_user)++ self.assertFalse(revoke_user_auth_session(user, str(session_public_id(victim_key))))+ self.assertTrue(Session.objects.filter(session_key=victim_key).exists())++ def test_revoke_user_auth_session_returns_false_for_invalid_id(self):+ user = self._make_user()+ self.assertFalse(revoke_user_auth_session(user, "not-a-uuid"))+ self.assertFalse(revoke_user_auth_session(user, str(uuid.uuid4())))++ def test_sync_metadata_populates_current_session(self):+ user = self._make_user()+ key = self._login_session(user)+ request = self._request(user, key)++ with self.captureOnCommitCallbacks(execute=True):+ sync_current_session_metadata(request, force=True)++ row = Session.objects.get(session_key=key)+ self.assertIsNotNone(row.last_activity)+ self.assertEqual(row.login_method, "password")++ def test_sync_metadata_is_throttled(self):+ user = self._make_user()+ key = self._login_session(user)+ request = self._request(user, key)++ with self.captureOnCommitCallbacks(execute=True):+ sync_current_session_metadata(request) # first write sets the throttle cache key+ marker = timezone.now() - timedelta(hours=1)+ Session.objects.filter(session_key=key).update(last_activity=marker)++ sync_current_session_metadata(request) # throttled — must not overwrite++ self.assertEqual(Session.objects.get(session_key=key).last_activity, marker)++ def test_sync_metadata_skips_impersonation(self):+ user = self._make_user()+ key = self._login_session(user)+ request = self._request(user, key)+ request.session[la_settings.USER_SESSION_FLAG] = "signed-original-user-pk"++ sync_current_session_metadata(request, force=True)++ self.assertIsNone(Session.objects.get(session_key=key).short_user_agent)++ def test_sync_metadata_is_deferred_to_commit(self):+ # The write is deferred to transaction.on_commit so it never adds a query inside the caller's+ # transaction (which would break assertNumQueries across the suite) or run against a+ # transaction already broken by a handled IntegrityError.+ user = self._make_user()+ key = self._login_session(user)+ request = self._request(user, key)++ request.session.get(BACKEND_SESSION_KEY) # warm the session cache (auth middleware loads it first)++ # The write adds no query to the caller's transaction — it's deferred to on_commit. Otherwise+ # every assertNumQueries assertion in the suite sees +1, and a transaction already broken by a+ # handled IntegrityError raises when the write runs.+ with self.assertNumQueries(0):+ sync_current_session_metadata(request, force=True)++ def test_user_deletion_purges_their_sessions(self):+ # user_id is a plain BigIntegerField (no FK cascade), so a deleted user's rows — and their+ # ip / location / user-agent — would otherwise linger until the session expires.+ user = self._make_user()+ key = self._login_session(user)+ self.assertTrue(Session.objects.filter(session_key=key).exists())++ user.delete()++ self.assertFalse(Session.objects.filter(session_key=key).exists())diff --git a/posthog/session/test/test_backend.py b/posthog/session/test/test_backend.pynew file mode 100644index 000000000000..f4a5ec1affae--- /dev/null+++ b/posthog/session/test/test_backend.py@@ -0,0 +1,154 @@+import uuid+from importlib import import_module++from posthog.test.base import BaseTest, NonAtomicBaseTest++from django.conf import settings+from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY+from django.contrib.sessions.backends.base import UpdateError++from asgiref.sync import async_to_sync+from loginas import settings as la_settings++from posthog.models import User+from posthog.session.models import Session+++class TestSessionStore(BaseTest):+ def setUp(self):+ super().setUp()+ self.engine = import_module(settings.SESSION_ENGINE)++ def _make_user(self) -> User:+ return User.objects.create(email=f"test-{uuid.uuid4()}@example.com", distinct_id=str(uuid.uuid4()))++ def _store(self):+ return self.engine.SessionStore()++ def test_stamps_user_id_from_auth_user_id_on_create(self):+ user = self._make_user()+ store = self._store()+ store[SESSION_KEY] = str(user.pk)+ store[BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend"+ store.create()++ row = Session.objects.get(session_key=store.session_key)+ self.assertEqual(row.user_id, user.pk)+ self.assertIsNotNone(row.last_activity)++ def test_anonymous_session_has_no_user_id(self):+ store = self._store()+ store["unrelated"] = "value"+ store.create()++ self.assertIsNone(Session.objects.get(session_key=store.session_key).user_id)++ def test_impersonation_session_is_not_attributed_to_the_user(self):+ user = self._make_user()+ store = self._store()+ store[SESSION_KEY] = str(user.pk)+ store[la_settings.USER_SESSION_FLAG] = "signed-original-user-pk"+ store.create()++ self.assertIsNone(Session.objects.get(session_key=store.session_key).user_id)++ def test_stamps_user_id_on_subsequent_save(self):+ # A session created anonymously then logged in (no cycle) must gain its user_id on save.+ user = self._make_user()+ store = self._store()+ store.create()+ store[SESSION_KEY] = str(user.pk)+ store.save()++ self.assertEqual(Session.objects.get(session_key=store.session_key).user_id, user.pk)++ def test_save_does_not_clobber_middleware_written_metadata(self):+ # The store must update only session-owned columns, leaving display metadata intact.+ user = self._make_user()+ store = self._store()+ store[SESSION_KEY] = str(user.pk)+ store.create()+ Session.objects.filter(session_key=store.session_key).update(+ short_user_agent="Chrome 135 on macOS", location="San Francisco, United States"+ )++ store["something"] = "changed"+ store.save()++ row = Session.objects.get(session_key=store.session_key)+ self.assertEqual(row.short_user_agent, "Chrome 135 on macOS")+ self.assertEqual(row.location, "San Francisco, United States")+ self.assertEqual(row.user_id, user.pk)++ def test_save_raises_update_error_when_row_is_gone(self):+ # signup.py relies on this: a save that updates zero rows must raise UpdateError, not pass.+ store = self._store()+ store["x"] = 1+ store.create()+ Session.objects.filter(session_key=store.session_key).delete()++ store["y"] = 2+ with self.assertRaises(UpdateError):+ store.save(must_create=False)+++class TestSessionStoreAsync(NonAtomicBaseTest):+ """The async store path (asave/acreate_model_instance) must match the sync path: stamp user_id,+ skip impersonation, and leave middleware-written metadata intact. NonAtomicBaseTest so the async+ DB writes (run via sync_to_async) are committed and visible to the assertions.+ """++ def setUp(self):+ super().setUp()+ self.engine = import_module(settings.SESSION_ENGINE)++ def _make_user(self) -> User:+ return User.objects.create(email=f"test-{uuid.uuid4()}@example.com", distinct_id=str(uuid.uuid4()))++ def _store(self):+ return self.engine.SessionStore()++ def test_asave_stamps_user_id(self):+ user = self._make_user()+ store = self._store()+ store[SESSION_KEY] = str(user.pk)+ store[BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend"+ async_to_sync(store.acreate)() # async INSERT path → asave(must_create=True)++ self.assertEqual(Session.objects.get(session_key=store.session_key).user_id, user.pk)++ def test_asave_does_not_attribute_impersonation(self):+ user = self._make_user()+ store = self._store()+ store[SESSION_KEY] = str(user.pk)+ store[la_settings.USER_SESSION_FLAG] = "signed-original-user-pk"+ async_to_sync(store.acreate)()++ self.assertIsNone(Session.objects.get(session_key=store.session_key).user_id)++ def test_asave_does_not_clobber_metadata(self):+ user = self._make_user()+ store = self._store()+ store[SESSION_KEY] = str(user.pk)+ async_to_sync(store.acreate)()+ Session.objects.filter(session_key=store.session_key).update(+ short_user_agent="Chrome 135 on macOS", location="San Francisco, United States"+ )++ store["something"] = "changed"+ async_to_sync(store.asave)()++ row = Session.objects.get(session_key=store.session_key)+ self.assertEqual(row.short_user_agent, "Chrome 135 on macOS")+ self.assertEqual(row.location, "San Francisco, United States")+ self.assertEqual(row.user_id, user.pk)++ def test_asave_raises_update_error_when_row_is_gone(self):+ store = self._store()+ store["x"] = 1+ async_to_sync(store.acreate)()+ Session.objects.filter(session_key=store.session_key).delete()++ store["y"] = 2+ with self.assertRaises(UpdateError):+ async_to_sync(store.asave)()diff --git a/posthog/session/test/test_backfill.py b/posthog/session/test/test_backfill.pynew file mode 100644index 000000000000..94271232a358--- /dev/null+++ b/posthog/session/test/test_backfill.py@@ -0,0 +1,123 @@+import uuid+from datetime import timedelta+from importlib import import_module++from posthog.test.base import BaseTest++from django.conf import settings+from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY+from django.utils import timezone++from dagster import build_op_context+from loginas import settings as la_settings++from posthog.dags.backfill_user_auth_sessions import backfill_user_auth_sessions_op+from posthog.models import User+from posthog.session.backfill import backfill_session_user_ids+from posthog.session.models import Session+++class _BackfillTestBase(BaseTest):+ def setUp(self):+ super().setUp()+ self.engine = import_module(settings.SESSION_ENGINE)++ def _make_user(self) -> User:+ return User.objects.create(email=f"test-{uuid.uuid4()}@example.com", distinct_id=str(uuid.uuid4()))++ def _legacy_session(self, user: User | None = None, impersonated: bool = False, anonymous: bool = False) -> str:+ """A session row as it would look before the swap: authenticated data but no stamped user_id."""+ store = self.engine.SessionStore()+ if not anonymous:+ store[SESSION_KEY] = str((user or self._make_user()).pk)+ store[BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend"+ if impersonated:+ store[la_settings.USER_SESSION_FLAG] = "signed-original-user-pk"+ store["filler"] = "x" # ensure an anonymous session still has data to persist+ store.create()+ Session.objects.filter(session_key=store.session_key).update(user_id=None, login_method=None)+ return store.session_key+++class TestBackfillSessionUserIds(_BackfillTestBase):+ def test_backfills_user_id_and_metadata(self):+ user = self._make_user()+ key = self._legacy_session(user)++ stats = backfill_session_user_ids(dry_run=False)++ row = Session.objects.get(session_key=key)+ self.assertEqual(row.user_id, user.pk)+ self.assertEqual(row.login_method, "password")+ self.assertEqual(stats.updated, 1)++ def test_skips_anonymous_sessions(self):+ key = self._legacy_session(anonymous=True)++ stats = backfill_session_user_ids(dry_run=False)++ self.assertIsNone(Session.objects.get(session_key=key).user_id)+ self.assertEqual(stats.updated, 0)++ def test_skips_impersonation_sessions(self):+ user = self._make_user()+ key = self._legacy_session(user, impersonated=True)++ backfill_session_user_ids(dry_run=False)++ self.assertIsNone(Session.objects.get(session_key=key).user_id)++ def test_dry_run_writes_nothing_but_reports_count(self):+ user = self._make_user()+ key = self._legacy_session(user)++ stats = backfill_session_user_ids(dry_run=True)++ self.assertIsNone(Session.objects.get(session_key=key).user_id)+ self.assertEqual(stats.updated, 1)++ def test_second_run_is_a_noop(self):+ user = self._make_user()+ key = self._legacy_session(user)++ backfill_session_user_ids(dry_run=False) # first run attributes the session+ stats = backfill_session_user_ids(dry_run=False) # already attributed → nothing to do++ self.assertEqual(stats.updated, 0)+ self.assertEqual(Session.objects.get(session_key=key).user_id, user.pk)++ def test_skips_deleted_user(self):+ user = self._make_user()+ key = self._legacy_session(user)+ user.delete()++ backfill_session_user_ids(dry_run=False)++ self.assertIsNone(Session.objects.get(session_key=key).user_id)++ def test_ignores_expired_sessions(self):+ user = self._make_user()+ key = self._legacy_session(user)+ Session.objects.filter(session_key=key).update(expire_date=timezone.now() - timedelta(days=1))++ backfill_session_user_ids(dry_run=False)++ self.assertIsNone(Session.objects.get(session_key=key).user_id)+++class TestBackfillUserAuthSessionsOp(_BackfillTestBase):+ def test_op_backfills_when_not_dry_run(self):+ user = self._make_user()+ key = self._legacy_session(user)++ backfill_user_auth_sessions_op(build_op_context(op_config={"dry_run": False}))++ self.assertEqual(Session.objects.get(session_key=key).user_id, user.pk)++ def test_op_defaults_to_dry_run(self):+ user = self._make_user()+ key = self._legacy_session(user)++ backfill_user_auth_sessions_op(build_op_context())++ self.assertIsNone(Session.objects.get(session_key=key).user_id)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex fe7b39f33ef6..16978164a7fb 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -106,7 +106,9 @@ INSTALLED_APPS = ["django.contrib.admin.apps.SimpleAdminConfig","django.contrib.auth","django.contrib.contenttypes",- "django.contrib.sessions",+ # Replaces django.contrib.sessions: a custom session model on the same django_session table+ # (see posthog/session). SessionMiddleware still works without the contrib app installed.+ "posthog.session","django.contrib.messages","django.contrib.postgres","django.contrib.staticfiles",@@ -167,6 +169,7 @@ MIDDLEWARE = ["posthog.middleware.SocialAuthExceptionMiddleware","posthog.middleware.SessionAgeMiddleware","posthog.middleware.KnownLoginDeviceCookieMiddleware",+ "posthog.session.middleware.UserAuthSessionActivityMiddleware","posthog.middleware.ActivityLoggingMiddleware","posthog.middleware.user_logging_context_middleware","django_otp.middleware.OTPMiddleware",@@ -293,6 +296,7 @@ SOCIAL_AUTH_GITLAB_API_URL: str = os.getenv("SOCIAL_AUTH_GITLAB_API_URL", "httpsLICENSE_SECRET_KEY = os.getenv("LICENSE_SECRET_KEY", "license-so-secret")# Cookie age in seconds (default 2 weeks) - these are the standard defaults for Django but having it here to be explicit+SESSION_ENGINE = "posthog.session.backend"SESSION_COOKIE_AGE = get_from_env("SESSION_COOKIE_AGE", 60 * 60 * 24 * 14, type_cast=int)# For sensitive actions we have an additional permission (default 2 hour)diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 7d203ddabd43..1e4210aeea9e 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -178,7 +178,7 @@ def kill_stale_queued_task_runs() -> None:@shared_task(ignore_result=True)@skip_team_scope_auditdef clear_expired_sessions() -> None:- from django.contrib.sessions.models import Session+ from posthog.session.models import Sessiondeleted_count, _ = Session.objects.filter(expire_date__lt=timezone.now()).delete()diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 970f5bd91af6..a1889d72dc70 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -51,6 +51,7 @@ post_delete:posthog.models.product_intent.product_intent._invalidate_product_intpost_delete:posthog.models.remote_config.product_tour_deletedpost_delete:posthog.models.remote_config.site_function_changedpost_delete:posthog.models.team.team.delete_team_in_cache_on_delete+post_delete:posthog.session.signals.delete_sessions_on_user_deletionpost_delete:posthog.storage.gateway_credential_signal_handlers._reproject_on_access_control_changepost_delete:posthog.storage.gateway_credential_signal_handlers._reproject_on_membership_deletepost_delete:posthog.storage.gateway_credential_signal_handlers._reproject_on_role_membership_changediff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.pyindex 90a2bfe34d62..a398f1034f1a 100644--- a/posthog/test/test_oauth_impersonation.py+++ b/posthog/test/test_oauth_impersonation.py@@ -8,7 +8,6 @@ from unittest.mock import patchfrom django.conf import settingsfrom django.contrib.auth import logout-from django.contrib.sessions.backends.db import SessionStorefrom django.core.signing import TimestampSignerfrom django.http import HttpRequestfrom django.test import RequestFactory@@ -21,6 +20,7 @@ from posthog.api.oauth.views import _impersonation_ai_processing_block, _impersofrom posthog.middleware import IMPERSONATION_READ_ONLY_SESSION_KEYfrom posthog.models import OAuthApplication, Organization, OrganizationMembership, Team, Userfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken+from posthog.session.backend import SessionStoreclass TestImpersonationOAuthRevocation(BaseTest):diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 5982177028b6..b480cae2ae4f 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -714,9 +714,10 @@ class TestTicketAPI(APIBaseTest):# Query count should be constant regardless of number of tickets# Includes: session, user, org, team, permissions, feature flag permission org lookup,# count query, tickets query, persons query (batch), distinct_ids prefetch,- # tagged_items prefetch+ # tagged_items prefetch, and the session-activity metadata write (deferred to on_commit,+ # which this test class patches to run synchronously)# Note: message stats are denormalized, no subqueries needed- with self.assertNumQueries(13):+ with self.assertNumQueries(14):response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/")self.assertEqual(response.status_code, status.HTTP_200_OK)# Should have original ticket + 10 new tickets = 11 totaldiff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 36f75c8c3509..204443cd82c0 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -723,6 +723,15 @@ tools:users-list:operation: users_listenabled: false+ users-login-sessions-destroy:+ operation: users_login_sessions_destroy+ enabled: false+ users-login-sessions-list:+ operation: users_login_sessions_list+ enabled: false+ users-login-sessions-revoke-others-create:+ operation: users_login_sessions_revoke_others_create+ enabled: falseusers-onboarding-skip-create:operation: users_onboarding_skip_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5e573fa22315..c4645992cbb2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45392,6 +45392,11 @@ export namespace Schemas {stale: number;}+ export interface RevokeOtherSessionsResponse {+ /** Number of other login sessions that were revoked. */+ revoked_count: number;+ }+export interface RoleLookupResponse {/** Matching reference, or null if none exists. */reference: RoleExternalReference | null;@@ -50122,6 +50127,24 @@ export namespace Schemas {error?: UpsertWizardSessionRequestError;}+ /**+ * A cookie-auth login session shown on the user's 'Web sessions' screen.+ */+ export interface UserAuthSession {+ /** Identifier used to revoke this login session. */+ readonly id: string;+ /** When this login session last made a request (refreshed periodically). */+ readonly last_activity: string;+ /** Approximate city and country derived from the IP address, if known. */+ readonly location: string;+ /** Browser and operating system parsed from the user agent, e.g. 'Chrome 135 on macOS'. */+ readonly device: string;+ /** How this session signed in (e.g. password, Google, SAML). */+ readonly login_method: string;+ /** Whether this is the login session making the current request. */+ readonly is_current: boolean;+ }+/*** The release condition to evaluate*/@@ -63582,5 +63605,10 @@ export namespace Schemas {search?: string;};+ export type UsersLoginSessionsListParams = {+ email?: string;+ is_staff?: boolean;+ };+}