: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(security): require the current password to change the account email (#104404)
Yasen9ff76fa561ec
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex f6bf53c6cc78..47170c98e1cd 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4605,6 +4605,11 @@ export interface UserApi {readonly is_impersonated_reason: string | null/** @nullable */readonly sensitive_session_expires_at: string | null+ /**+ * When the last re-authentication stops counting as fresh. Changing `email` after this needs a new re-authentication. Null when the session has none on record.+ * @nullable+ */+ readonly fresh_reauth_expires_at: string | nullreadonly team: TeamBasicApireadonly organization: OrganizationApireadonly organizations: readonly OrganizationBasicApi[]@@ -4716,6 +4721,11 @@ export interface PatchedUserApi {readonly is_impersonated_reason?: string | null/** @nullable */readonly sensitive_session_expires_at?: string | null+ /**+ * When the last re-authentication stops counting as fresh. Changing `email` after this needs a new re-authentication. Null when the session has none on record.+ * @nullable+ */+ readonly fresh_reauth_expires_at?: string | nullreadonly team?: TeamBasicApireadonly organization?: OrganizationApireadonly organizations?: readonly OrganizationBasicApi[]diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 7187f89df2b8..ae2f12f2da0f 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -1,8 +1,9 @@import re+import timeimport uuidimport datetimefrom datetime import timedelta-from typing import cast+from typing import Any, castfrom urllib.parse import quote, unquote, urlparseimport pytest@@ -11,6 +12,7 @@ from posthog.test.base import APIBaseTest, NonAtomicBaseTestfrom unittest import mockfrom unittest.mock import ANY, patch+from django.conf import settingsfrom django.core import mailfrom django.core.cache import cachefrom django.db import connection@@ -976,6 +978,80 @@ class TestUserAPI(APIBaseTest):)+ @parameterized.expand(+ [+ ("email", {"email": "[email protected]", "current_password": "testpassword12345"}, 403),+ ("password", {"password": "a_new_password", "current_password": "testpassword12345"}, 403),+ ("taken_email", {"email": "[email protected]"}, 403),+ ("invalid_email", {"email": "not-an-email"}, 403),+ ("same_email_in_other_case", {"email": "[email protected]"}, 200),+ ("profile_field", {"first_name": "Newname"}, 200),+ ("non_object_body", ["email", "password"], 400),+ ]+ )+ @patch("posthog.api.email_verification.send_email_verification_code")+ @patch("posthog.api.user.is_email_available", return_value=True)+ def test_token_auth_cannot_change_email_or_password(+ self, _name: str, payload: Any, expected_status: int, _mock_is_email_available, mock_send_code+ ):+ self.user.email = "[email protected]"+ self.user.save()+ User.objects.create_user("[email protected]", "pwd1234*", "Other")+ key = self.create_personal_api_key_with_scopes(["user:write"])+ self.client.logout()++ response = self.client.patch(+ "/api/users/@me/", payload, content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {key}"+ )++ assert response.status_code == expected_status, response.content+ self.user.refresh_from_db()+ assert self.user.email == "[email protected]"+ assert self.user.pending_email is None+ assert self.user.check_password(self.CONFIG_PASSWORD)+ mock_send_code.assert_not_called()++ @parameterized.expand(+ [+ ("fresh_reauth", True, False, 200),+ ("stale_reauth", True, True, 403),+ ("passwordless_fresh_reauth", False, False, 200),+ ("passwordless_stale_reauth", False, True, 403),+ ]+ )+ @patch("posthog.api.email_verification.send_email_verification_code")+ @patch("posthog.api.user.is_email_available", return_value=True)+ def test_email_change_requires_a_fresh_reauth(+ self,+ _name: str,+ has_password: bool,+ stale: bool,+ expected_status: int,+ _mock_is_email_available,+ mock_send_code,+ ):+ self.user.email = "[email protected]"+ if not has_password:+ self.user.set_unusable_password()+ self.user.save()+ self.client.force_login(self.user)+ if stale:+ session = self.client.session+ session[settings.SESSION_LAST_REAUTH_AT_KEY] = time.time() - settings.SESSION_FRESH_REAUTH_AGE - 1+ session.save()++ response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})++ assert response.status_code == expected_status, response.content+ self.user.refresh_from_db()+ if expected_status == 200:+ assert self.user.pending_email == "[email protected]"+ mock_send_code.assert_called_once()+ else:+ assert response.json()["code"] == "sensitive_action_required_reauth"+ assert self.user.pending_email is None+ mock_send_code.assert_not_called()+def test_email_change_rejected_when_new_email_is_plus_addressed(self):self.user.email = "[email protected]"self.user.save()diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 91670d7bbb79..534148d9a2ae 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -6,6 +6,7 @@ import secretsimport urllib.parsefrom base64 import b32encodefrom binascii import unhexlify+from collections.abc import Mappingfrom datetime import UTC, datetime, timedeltafrom typing import Any, NoReturn, Optional, cast@@ -134,7 +135,12 @@ from posthog.session.activity import (sync_current_session_metadata,)from posthog.session.models import Session-from posthog.session.reauth import sensitive_action_reference, step_up_required+from posthog.session.reauth import (+ fresh_reauth_expires_at,+ reauth_is_fresh,+ sensitive_action_reference,+ step_up_required,+)from posthog.tasks.email import (send_email_change_emails,send_password_changed_email,@@ -232,6 +238,12 @@ class UserSerializer(serializers.ModelSerializer):help_text="The reason the operator gave when the current impersonation session started (or was last up/downgraded). Null when not impersonating.")sensitive_session_expires_at = serializers.SerializerMethodField()+ fresh_reauth_expires_at = serializers.SerializerMethodField(+ help_text=(+ "When the last re-authentication stops counting as fresh. Changing `email` after this needs a new "+ "re-authentication. Null when the session has none on record."+ )+ )is_2fa_enabled = serializers.SerializerMethodField()has_social_auth = serializers.SerializerMethodField()has_sso_enforcement = serializers.SerializerMethodField()@@ -331,6 +343,7 @@ class UserSerializer(serializers.ModelSerializer):"is_impersonated_read_only","is_impersonated_reason","sensitive_session_expires_at",+ "fresh_reauth_expires_at","team","organization","organizations",@@ -378,6 +391,7 @@ class UserSerializer(serializers.ModelSerializer):"is_impersonated_read_only","is_impersonated_reason","sensitive_session_expires_at",+ "fresh_reauth_expires_at","team","organization","organizations",@@ -479,6 +493,16 @@ class UserSerializer(serializers.ModelSerializer):return session_expiry_time.replace(tzinfo=UTC).isoformat()+ def get_fresh_reauth_expires_at(self, instance: User) -> Optional[str]:+ if "request" not in self.context:+ return None++ expires_at = fresh_reauth_expires_at(self.context["request"].session)+ if expires_at is None:+ return None++ return datetime.fromtimestamp(expires_at, tz=UTC).isoformat()+@tracer.start_as_current_span("user_serializer.has_social_auth")def get_has_social_auth(self, instance: User) -> bool:return instance.social_auth.exists()@@ -713,11 +737,11 @@ class UserSerializer(serializers.ModelSerializer):# Fold both sides: `validate_email` hands back the stored address for an edit of the case# alone, and a legacy row can hold that address in any case.- if (- "email" in validated_data- and EmailNormalizer.normalize(validated_data["email"]) != EmailNormalizer.normalize(instance.email)- and is_email_available()- ):+ changes_email = "email" in validated_data and EmailNormalizer.normalize(+ validated_data["email"]+ ) != EmailNormalizer.normalize(instance.email)++ if changes_email and is_email_available():new_email = validated_data["email"]# Moving between two SSO-enforced domains of the same org is a domain migration, not an SSO bypass.# SSO enforcement can only be set on a verified domain, so an enforced domain is always verified.@@ -1060,6 +1084,46 @@ class UserViewSet("user_permissions": UserPermissions(cast(User, self.request.user)),}+ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ self.guard_identity_change(request)+ return super().update(request, *args, **kwargs)++ def guard_identity_change(self, request: Request) -> None:+ """Refuse an email or password change that the request cannot prove the account holder wants.++ This runs before serializer validation, because an email validation error would tell the+ caller which addresses already have an account.+ """+ # DRF types `request.data` as a mapping, but a JSON array or string body parses to a list or a+ # str. Such a body carries neither field, and the serializer rejects it with a 400.+ data = cast(Any, request.data)+ if not isinstance(data, Mapping):+ return++ email = data.get("email")+ changes_email = "email" in data and not (+ isinstance(email, str)+ and EmailNormalizer.normalize(email) == EmailNormalizer.normalize(self.get_object().email)+ )++ # The login email and the password decide who can sign in, so a leaked personal API key or+ # OAuth token must not reset either of them.+ if not isinstance(request.successful_authenticator, SessionAuthentication):+ if changes_email or "password" in data:+ raise exceptions.PermissionDenied(+ "You can only change your email or password from the PostHog app, not with an API key or token."+ )+ return++ # A session alone is not enough for the email, because the freshness window of+ # TimeSensitiveActionPermission is hours wide. The account holder re-authenticates first, which+ # for an account without a password means a passkey or an SSO round trip.+ if changes_email and not reauth_is_fresh(request.session):+ raise exceptions.PermissionDenied(+ "Confirm it's you before changing your email.",+ code="sensitive_action_required_reauth",+ )+def perform_destroy(self, user: User) -> None:report_user_deleted_account(user)super().perform_destroy(user)diff --git a/posthog/session/reauth.py b/posthog/session/reauth.pyindex 7b39196d6508..c5a51f757b34 100644--- a/posthog/session/reauth.py+++ b/posthog/session/reauth.py@@ -1,3 +1,4 @@+import timefrom typing import Optionalfrom django.conf import settings@@ -19,3 +20,20 @@ def sensitive_action_reference(session: SessionBase) -> Optional[float]:def step_up_required(session: SessionBase) -> bool:"""Whether a risk anomaly flagged this session as needing a fresh re-auth before sensitive actions."""return bool(session.get(settings.SESSION_STEP_UP_REQUIRED_KEY))+++def fresh_reauth_expires_at(session: SessionBase) -> Optional[float]:+ """End of the short window that an identity change needs, counted from the last re-auth alone.++ Session creation does not count here, unlike in `sensitive_action_reference`: a login stamps both+ keys, so a fresh login still passes, but an old session cannot.+ """+ last_reauth_at = session.get(settings.SESSION_LAST_REAUTH_AT_KEY)+ if not last_reauth_at:+ return None+ return last_reauth_at + settings.SESSION_FRESH_REAUTH_AGE+++def reauth_is_fresh(session: SessionBase) -> bool:+ expires_at = fresh_reauth_expires_at(session)+ return expires_at is not None and time.time() < expires_at and not step_up_required(session)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex edfb93a5a886..005c60a3343b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -345,6 +345,10 @@ SESSION_COOKIE_AGE = get_from_env("SESSION_COOKIE_AGE", 60 * 60 * 24 * 14, type_# For sensitive actions we have an additional permission (default 2 hour)SESSION_SENSITIVE_ACTIONS_AGE = get_from_env("SESSION_SENSITIVE_ACTIONS_AGE", 60 * 60 * 2, type_cast=int)+# Changing the login email asks for a re-auth of its own, because the 2 hour window above is wide+# enough for a stolen session cookie to take the account over (default 5 minutes)+SESSION_FRESH_REAUTH_AGE = get_from_env("SESSION_FRESH_REAUTH_AGE", 60 * 5, type_cast=int)+SESSION_COOKIE_NAME = get_from_env("SESSION_COOKIE_NAME", "sessionid")CSRF_COOKIE_NAME = "posthog_csrftoken"CSRF_COOKIE_AGE = get_from_env("CSRF_COOKIE_AGE", SESSION_COOKIE_AGE, type_cast=int)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 273039abbf4b..9be6ff77f37a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -68353,6 +68353,11 @@ export namespace Schemas {readonly is_impersonated_reason: string | null;/** @nullable */readonly sensitive_session_expires_at: string | null;+ /**+ * When the last re-authentication stops counting as fresh. Changing `email` after this needs a new re-authentication. Null when the session has none on record.+ * @nullable+ */+ readonly fresh_reauth_expires_at: string | null;readonly team: TeamBasic;readonly organization: Organization;readonly organizations: readonly OrganizationBasic[];@@ -77697,6 +77702,11 @@ export namespace Schemas {readonly is_impersonated_reason?: string | null;/** @nullable */readonly sensitive_session_expires_at?: string | null;+ /**+ * When the last re-authentication stops counting as fresh. Changing `email` after this needs a new re-authentication. Null when the session has none on record.+ * @nullable+ */+ readonly fresh_reauth_expires_at?: string | null;readonly team?: TeamBasic;readonly organization?: Organization;readonly organizations?: readonly OrganizationBasic[];