: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(security): report email change and identity refusal events (#106827)
Yasen71c3c23f102e
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 9af350a4d7d8..6671632f0e27 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -1097,6 +1097,73 @@ class TestUserAPI(APIBaseTest):assert self.user.pending_email is Nonemock_send_code.assert_not_called()+ @parameterized.expand(+ [+ ("email_service_available", True, True),+ ("email_service_unavailable", False, False),+ ]+ )+ @patch("posthog.api.email_verification.send_email_verification_code")+ @patch("posthog.api.user.report_user_email_change_requested")+ def test_staging_an_email_change_reports_it(+ self,+ _name: str,+ email_available: bool,+ verification_required: bool,+ mock_report,+ _mock_send_code,+ ):+ self.user.email = "[email protected]"+ self.user.save()++ with patch("posthog.api.user.is_email_available", return_value=email_available):+ response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})++ assert response.status_code == status.HTTP_200_OK, response.content+ mock_report.assert_called_once_with(self.user, verification_required=verification_required)++ @patch("posthog.api.user.is_email_available", return_value=True)+ @patch("posthog.api.user.report_user_email_change_requested")+ def test_an_unchanged_email_reports_nothing(self, mock_report, _mock_is_email_available):+ self.user.email = "[email protected]"+ self.user.save()++ response = self.client.patch("/api/users/@me/", {"email": "[email protected]", "first_name": "Newname"})++ assert response.status_code == status.HTTP_200_OK, response.content+ mock_report.assert_not_called()++ @patch("posthog.api.user.report_user_identity_change_refused")+ def test_refusing_a_token_identity_change_reports_the_reason(self, mock_report):+ self.user.email = "[email protected]"+ self.user.save()+ key = self.create_personal_api_key_with_scopes(["user:write"])+ self.client.logout()++ response = self.client.patch(+ "/api/users/@me/",+ {"email": "[email protected]"},+ content_type="application/json",+ HTTP_AUTHORIZATION=f"Bearer {key}",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ mock_report.assert_called_once_with(self.user, field="email", reason="token_auth")++ @patch("posthog.api.user.report_user_identity_change_refused")+ def test_refusing_a_stale_session_email_change_reports_the_reason(self, mock_report):+ self.user.email = "[email protected]"+ self.user.save()+ self.client.force_login(self.user)+ 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 == status.HTTP_403_FORBIDDEN, response.content+ mock_report.assert_called_once_with(self.user, field="email", reason="stale_reauth")+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 534148d9a2ae..74f2f0fb7002 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -83,6 +83,8 @@ from posthog.constants import INVITE_DAYS_VALIDITY, PERMITTED_FORUM_DOMAINS, Avafrom posthog.email import is_email_availablefrom posthog.event_usage import (report_user_deleted_account,+ report_user_email_change_requested,+ report_user_identity_change_refused,report_user_logged_in,report_user_updated,report_user_verified_email,@@ -775,6 +777,7 @@ class UserSerializer(serializers.ModelSerializer):# The code is bound to the captured address, so a concurrent email change cannot# redirect this code: once a different address is staged, the code stops verifying.email_verification_code_verifier.send_code(instance, target_email=new_email)+ report_user_email_change_requested(cast(User, instance), verification_required=True)if validated_data.get("notification_settings"):validated_data["partial_notification_settings"] = validated_data.pop("notification_settings")@@ -808,6 +811,11 @@ class UserSerializer(serializers.ModelSerializer):# Revoke other sessions after update_session_auth_hash so the current (rotated) session is kept.revoke_other_sessions_for_request(self.context["request"], instance)+ if changes_email and "email" in validated_data:+ # Without email configured the new address lands on the account directly, so the change+ # completes here rather than at verification.+ report_user_email_change_requested(instance, verification_required=False)+report_user_updated(instance, updated_attrs)return instance@@ -1110,6 +1118,11 @@ class UserViewSet(# OAuth token must not reset either of them.if not isinstance(request.successful_authenticator, SessionAuthentication):if changes_email or "password" in data:+ report_user_identity_change_refused(+ cast(User, request.user),+ field="email" if changes_email else "password",+ reason="token_auth",+ )raise exceptions.PermissionDenied("You can only change your email or password from the PostHog app, not with an API key or token.")@@ -1119,6 +1132,7 @@ class UserViewSet(# 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):+ report_user_identity_change_refused(cast(User, request.user), field="email", reason="stale_reauth")raise exceptions.PermissionDenied("Confirm it's you before changing your email.",code="sensitive_action_required_reauth",diff --git a/posthog/event_usage.py b/posthog/event_usage.pyindex 4eb0647db656..4222ac51da82 100644--- a/posthog/event_usage.py+++ b/posthog/event_usage.py@@ -154,6 +154,47 @@ def report_user_logged_in()+def report_user_email_change_requested(user: User, *, verification_required: bool) -> None:+ """Triggered when a user stages a new login email.++ `verification_required` is False on an instance without email configured, where the new address+ is written straight to the account and no code goes out.+ """+ if not user.distinct_id:+ return++ posthoganalytics.capture(+ distinct_id=user.distinct_id,+ event="user email change requested",+ properties={+ "verification_required": verification_required,+ "$set": user.get_analytics_metadata(),+ },+ groups=groups(user.current_organization, user.current_team),+ )+++def report_user_identity_change_refused(user: User, *, field: str, reason: str) -> None:+ """Triggered when the API refuses to change the login email or the password.++ `reason` is `token_auth` for a personal API key or OAuth token, or `stale_reauth` when the+ session has not re-authenticated recently enough. See `UserViewSet.guard_identity_change`.+ """+ if not user.distinct_id:+ return++ posthoganalytics.capture(+ distinct_id=user.distinct_id,+ event="user identity change refused",+ properties={+ "field": field,+ "reason": reason,+ "$set": user.get_analytics_metadata(),+ },+ groups=groups(user.current_organization, user.current_team),+ )++def report_user_updated(user: User, updated_attrs: list[str]) -> None:"""Reports a user has been updated. This includes current_team, current_organization & password.