Skip to content

: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.

fix(auth): require a provider-verified email to link a social login (#106896)

Yasen5f85842eb063
diff --git a/ee/api/authentication.py b/ee/api/authentication.py
index 2f97da7204c3..fc8512c4b1b4 100644
--- a/ee/api/authentication.py
+++ b/ee/api/authentication.py
@@ -36,6 +36,7 @@ from posthog.cloud_utils import get_cached_instance_license
from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import EmailLookupHandler
+from posthog.helpers.sso import UNVERIFIED_SOCIAL_EMAIL_ERROR
from posthog.models.identity_provider_config import IdentityProviderConfig, has_verified_organization_domain_q
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -473,6 +474,10 @@ class CustomGoogleOAuth2(GoogleOAuth2):
try:
# Second try: Find and migrate legacy user using email as uid
social_auth = UserSocialAuth.objects.get(provider="google-oauth2", uid=email)
+ # This lookup resolves the account by email address, so the email has to be verified,
+ # the same as for `associate_by_email`.
+ if response.get("email_verified") is not True:
+ raise AuthFailed(self, UNVERIFIED_SOCIAL_EMAIL_ERROR)
# Migrate user from email to sub
social_auth.uid = sub
social_auth.save()
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.py
index a3731c6d8bfd..10661a5b1ef3 100644
--- a/ee/api/test/test_authentication.py
+++ b/ee/api/test/test_authentication.py
@@ -20,6 +20,7 @@ from django.test import RequestFactory, override_settings
from django.utils import timezone
import jwt
+import responses
from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from requests import Response
@@ -31,6 +32,7 @@ from social_django.utils import load_strategy
from posthog.api.authentication import social_identity_matches_session
from posthog.api.oidc import MultitenantOIDCAuth
from posthog.constants import AvailableFeature
+from posthog.helpers.sso import GITHUB_EMAIL_LOOKUP_ERROR, UNVERIFIED_SOCIAL_EMAIL_ERROR
from posthog.models import OrganizationMembership, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.identity_provider_config import IdentityProviderConfig
@@ -958,6 +960,164 @@ class TestEEAuthenticationAPI(APILicensedTest):
# The stranger's identity must not have been linked to the signed-in account
self.assertFalse(UserSocialAuth.objects.filter(user=self.user).exists())
+ def _complete_github_login(
+ self,
+ github_id: int,
+ emails: list[dict[str, Any]],
+ emails_status: int = 200,
+ profile_email: str | None = None,
+ login_query: str = "",
+ ) -> HttpResponse:
+ with (
+ self.settings(**GITHUB_MOCK_SETTINGS),
+ responses.RequestsMock(assert_all_requests_are_fired=False) as mock_github,
+ ):
+ mock_github.add(responses.POST, "https://github.com/login/oauth/access_token", json={"access_token": "gh"})
+ mock_github.add(
+ responses.GET,
+ "https://api.github.com/user",
+ json={"id": github_id, "login": "octo", "name": "Octo Cat", "email": profile_email},
+ )
+ mock_github.add(responses.GET, "https://api.github.com/user/emails", json=emails, status=emails_status)
+ self.client.get(f"/login/github/?{login_query}")
+ state = self.client.session["github_state"]
+ response = self.client.get(f"/complete/github/?code=2&state={state}")
+ return response
+
+ def _complete_google_login(self, email: str, email_verified: bool | None, login_query: str = "") -> HttpResponse:
+ with (
+ self.settings(**GOOGLE_MOCK_SETTINGS),
+ patch("social_core.backends.base.BaseAuth.request") as mock_request,
+ ):
+ self.client.get(f"/login/google-oauth2/?{login_query}")
+ state = self.client.session["google-oauth2_state"]
+ userinfo: dict[str, Any] = {"access_token": "123", "email": email, "sub": "google-sub-new"}
+ if email_verified is not None:
+ userinfo["email_verified"] = email_verified
+ mock_request.return_value.json.return_value = userinfo
+ return self.client.get(f"/complete/google-oauth2/?code=2&state={state}")
+
+ @parameterized.expand(
+ [
+ ("github_unverified_primary", "github", False),
+ ("google_unverified", "google-oauth2", False),
+ ("github_verified_primary", "github", True),
+ ("google_verified", "google-oauth2", True),
+ ]
+ )
+ def test_social_login_links_an_existing_account_only_by_a_provider_verified_email(
+ self, _name: str, provider: str, provider_verified: bool
+ ) -> None:
+ self.client.logout()
+ self.user.is_email_verified = False
+ self.user.save(update_fields=["is_email_verified"])
+
+ if provider == "github":
+ response = self._complete_github_login(
+ github_id=4242,
+ emails=[{"email": self.user.email, "primary": True, "verified": provider_verified}],
+ )
+ else:
+ response = self._complete_google_login(email=self.user.email, email_verified=provider_verified)
+
+ self.user.refresh_from_db()
+ is_linked = UserSocialAuth.objects.filter(user=self.user, provider=provider).exists()
+ if provider_verified:
+ self.assertEqual(self.client.session.get("_auth_user_id"), str(self.user.pk))
+ self.assertTrue(is_linked)
+ else:
+ self.assertTrue(response["Location"].startswith("/login?error_code=social_login_failure"))
+ self.assertNotIn("_auth_user_id", self.client.session)
+ self.assertFalse(is_linked)
+ self.assertTrue(self.user.check_password(cast(str, self.CONFIG_PASSWORD)))
+ self.assertFalse(self.user.is_email_verified)
+
+ @parameterized.expand(
+ [
+ ("github_unverified", "github", False, False, 200, UNVERIFIED_SOCIAL_EMAIL_ERROR),
+ ("github_public_email_lookup_fails", "github", False, True, 502, GITHUB_EMAIL_LOOKUP_ERROR),
+ ("google_unverified", "google-oauth2", False, False, 200, UNVERIFIED_SOCIAL_EMAIL_ERROR),
+ ("google_claim_missing", "google-oauth2", None, False, 200, UNVERIFIED_SOCIAL_EMAIL_ERROR),
+ ]
+ )
+ def test_social_signup_refuses_an_email_the_provider_has_not_verified(
+ self,
+ _name: str,
+ provider: str,
+ email_verified: bool | None,
+ has_public_email: bool,
+ emails_status: int,
+ expected_error: str,
+ ) -> None:
+ self.client.logout()
+ email = "[email protected]"
+
+ if provider == "github":
+ response = self._complete_github_login(
+ github_id=5151,
+ emails=[{"email": email, "primary": True, "verified": email_verified}],
+ emails_status=emails_status,
+ profile_email=email if has_public_email else None,
+ )
+ else:
+ response = self._complete_google_login(email=email, email_verified=email_verified)
+
+ location = urlparse(response["Location"])
+ self.assertEqual(location.path, "/login")
+ self.assertEqual(parse_qs(location.query)["error_detail"], [expected_error])
+ self.assertNotIn("_auth_user_id", self.client.session)
+ self.assertFalse(User.objects.filter(email=email).exists())
+ self.assertFalse(UserSocialAuth.objects.filter(provider=provider).exists())
+
+ @parameterized.expand(
+ [
+ ("github", "github", "/settings/user"),
+ ("github_account_connect_next", "github", "/account-connected/github-login?provider=github"),
+ ("google", "google-oauth2", "/settings/user"),
+ ]
+ )
+ def test_sso_reauth_with_an_unlinked_unverified_identity_grants_nothing(
+ self, _name: str, provider: str, next_url: str
+ ) -> None:
+ last_reauth_at_before = self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY]
+ login_query = urlencode({"reauth": "true", "next": next_url, "email": self.user.email})
+
+ if provider == "github":
+ response = self._complete_github_login(
+ github_id=6161,
+ emails=[{"email": self.user.email, "primary": True, "verified": False}],
+ login_query=login_query,
+ )
+ else:
+ response = self._complete_google_login(email=self.user.email, email_verified=False, login_query=login_query)
+
+ self.assertIn("error_code=social_login_failure", response["Location"])
+ self.assertEqual(self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY], last_reauth_at_before)
+ self.assertFalse(UserSocialAuth.objects.filter(user=self.user, provider=provider).exists())
+
+ def test_account_connect_path_does_not_skip_verification_when_signed_out(self) -> None:
+ self.client.logout()
+ session = self.client.session
+ session["next"] = "/account-connected/github-login?provider=github"
+ session.save()
+
+ self._complete_github_login(
+ github_id=7171, emails=[{"email": self.user.email, "primary": True, "verified": False}]
+ )
+
+ self.assertNotIn("_auth_user_id", self.client.session)
+ self.assertFalse(UserSocialAuth.objects.filter(user=self.user, provider="github").exists())
+
+ def test_already_linked_github_identity_logs_in_without_a_verified_email(self) -> None:
+ self.client.logout()
+ UserSocialAuth.objects.create(user=self.user, provider="github", uid="4242")
+
+ self._complete_github_login(
+ github_id=4242, emails=[{"email": "[email protected]", "primary": True, "verified": False}]
+ )
+
+ self.assertEqual(self.client.session.get("_auth_user_id"), str(self.user.pk))
+
def test_existing_session_remains_valid_when_sso_enforced(self):
"""Test that existing password-authenticated sessions remain valid after SSO is enforced"""
self.client.logout()
@@ -1876,7 +2036,7 @@ class TestCustomGoogleOAuth2(APILicensedTest):
# Create user with email as uid (legacy format)
social_auth = UserSocialAuth.objects.create(provider="google-oauth2", uid="[email protected]", user=self.user)
- response = {"email": "[email protected]", "sub": self.sub}
+ response = {"email": "[email protected]", "email_verified": True, "sub": self.sub}
uid = self.google_oauth.get_user_id(self.details, response)
@@ -1885,6 +2045,21 @@ class TestCustomGoogleOAuth2(APILicensedTest):
social_auth.refresh_from_db()
self.assertEqual(social_auth.uid, self.sub)
+ @parameterized.expand([("unverified", False), ("claim_missing", None)])
+ def test_get_user_id_does_not_migrate_legacy_uid_for_an_unverified_email(
+ self, _name: str, email_verified: bool | None
+ ) -> None:
+ social_auth = UserSocialAuth.objects.create(provider="google-oauth2", uid="[email protected]", user=self.user)
+ response: dict[str, Any] = {"email": "[email protected]", "sub": self.sub}
+ if email_verified is not None:
+ response["email_verified"] = email_verified
+
+ with self.assertRaises(AuthFailed):
+ self.google_oauth.get_user_id(self.details, response)
+
+ social_auth.refresh_from_db()
+ self.assertEqual(social_auth.uid, "[email protected]")
+
def test_get_user_id_new_user_uses_sub(self):
"""Test that a new user gets sub as uid."""
response = {"email": "[email protected]", "sub": self.sub}
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index edca5cf6eb21..365186f1d713 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -5,7 +5,7 @@ import time
import random
import datetime
from typing import Any, TypedDict, cast
-from urllib.parse import urlencode
+from urllib.parse import urlencode, urljoin
from uuid import uuid4
from django.conf import settings
@@ -34,13 +34,17 @@ from django_otp import login as otp_login
from django_otp.plugins.otp_static.models import StaticDevice
from drf_spectacular.utils import extend_schema
from loginas.utils import is_impersonated_session, restore_original_login
+from requests import RequestException
from rest_framework import mixins, permissions, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
+from social_core.backends.base import BaseAuth
+from social_core.backends.github import GithubOAuth2
from social_core.exceptions import AuthConnectionError, AuthFailed, AuthMissingParameter
+from social_django.models import UserSocialAuth
from social_django.strategy import DjangoStrategy
from social_django.views import auth
from two_factor.utils import default_device
@@ -58,7 +62,12 @@ from posthog.exceptions_capture import capture_exception
from posthog.geoip import get_geoip_properties
from posthog.helpers.dev_login import is_dev_login_allowed
from posthog.helpers.email_utils import EmailLookupHandler
-from posthog.helpers.sso import is_sso_reauth_begin, sso_failure_redirect_url
+from posthog.helpers.sso import (
+ GITHUB_EMAIL_LOOKUP_ERROR,
+ UNVERIFIED_SOCIAL_EMAIL_ERROR,
+ is_sso_reauth_begin,
+ sso_failure_redirect_url,
+)
from posthog.helpers.two_factor_session import (
CODE_MAX_ATTEMPTS,
LOGIN_CODE_VERIFICATION_COUNTER,
@@ -1343,6 +1352,17 @@ def _sso_reauth_request(strategy: DjangoStrategy) -> HttpRequest | None:
return request
+def _is_signed_in_github_account_link(strategy: DjangoStrategy, backend: BaseAuth) -> bool:
+ request = strategy.request
+ return (
+ bool(request)
+ and request.user.is_authenticated
+ and getattr(backend, "name", "") == "github"
+ and (strategy.session_get("next") or "").startswith("/account-connected/github-login")
+ and _sso_reauth_request(strategy) is None
+ )
+
+
def social_identity_matches_session(
strategy: DjangoStrategy,
backend: Any,
@@ -1355,10 +1375,7 @@ def social_identity_matches_session(
if not request or not request.user.is_authenticated or social is not None:
return
- is_github_account_link = getattr(backend, "name", "") == "github" and (
- strategy.session_get("next") or ""
- ).startswith("/account-connected/github-login")
- if is_github_account_link:
+ if _is_signed_in_github_account_link(strategy, backend):
return
identity_email = ((details or {}).get("email") or "").lower()
@@ -1371,6 +1388,54 @@ def social_identity_matches_session(
raise AuthFailed(backend, "reauth_user_mismatch")
+def _github_email_is_verified(backend: GithubOAuth2, access_token: str, email: str) -> bool:
+ try:
+ emails: object = backend.get_json(
+ urljoin(backend.api_url(), "user/emails"), headers={"Authorization": f"token {access_token}"}
+ )
+ except (RequestException, AuthConnectionError, ValueError) as error:
+ logger.warning("github_email_verification_lookup_failed", exc_info=True)
+ raise AuthFailed(backend, GITHUB_EMAIL_LOOKUP_ERROR) from error
+ if not isinstance(emails, list):
+ logger.warning("github_email_verification_lookup_unexpected_response")
+ raise AuthFailed(backend, GITHUB_EMAIL_LOOKUP_ERROR)
+ return any(
+ isinstance(entry, dict)
+ and entry.get("verified") is True
+ and str(entry.get("email", "")).lower() == email.lower()
+ for entry in emails
+ )
+
+
+def social_email_verified_by_provider(
+ strategy: DjangoStrategy,
+ backend: BaseAuth,
+ details: dict[str, Any] | None = None,
+ response: dict[str, Any] | None = None,
+ social: UserSocialAuth | None = None,
+ **kwargs: Any,
+) -> None:
+ # A linked identity resolves by its provider uid, and a signed-in account connect is keyed to the
+ # session. Every other flow, re-authentication included, trusts the email address.
+ if social is not None or _is_signed_in_github_account_link(strategy, backend):
+ return
+
+ response = response or {}
+ email = (details or {}).get("email") or ""
+ if isinstance(backend, GithubOAuth2):
+ # The GitHub backend picks the primary address from /user/emails without its `verified` flag,
+ # and GitHub lets an unverified address be primary.
+ is_verified = not email or _github_email_is_verified(backend, response.get("access_token", ""), email)
+ elif backend.name == "google-oauth2":
+ is_verified = response.get("email_verified") is True
+ else:
+ is_verified = response.get("email_verified") is not False
+
+ if not is_verified:
+ logger.warning("social_login_unverified_provider_email", backend=backend.name)
+ raise AuthFailed(backend, UNVERIFIED_SOCIAL_EMAIL_ERROR)
+
+
def social_reauth(
strategy: DjangoStrategy,
backend,
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index aa2099c10c06..f46a02408913 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -834,7 +834,10 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "github"})
url += f"?code=2&state={response.client.session['github_state']}"
- mock_request.return_value.json.return_value = MOCK_GITLAB_SSO_RESPONSE
+ github_emails = [{"email": MOCK_GITLAB_SSO_RESPONSE["email"], "primary": True, "verified": True}]
+ mock_request.side_effect = lambda url, *args, **kwargs: mock.Mock(
+ json=mock.Mock(return_value=github_emails if url.endswith("/user/emails") else MOCK_GITLAB_SSO_RESPONSE)
+ )
response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, status.HTTP_200_OK) # because `follow=True`
@@ -898,6 +901,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -981,6 +985,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1021,6 +1026,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1055,6 +1061,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1099,6 +1106,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1131,7 +1139,12 @@ class TestSignupAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
- mock_request.return_value.json.return_value = {"access_token": "123", "email": email, "sub": "123"}
+ mock_request.return_value.json.return_value = {
+ "access_token": "123",
+ "email": email,
+ "email_verified": True,
+ "sub": "123",
+ }
return self.client.get(url, follow=True)
@mock.patch("social_core.backends.base.BaseAuth.request")
@@ -1230,6 +1243,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1260,6 +1274,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1286,6 +1301,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1362,7 +1378,12 @@ class TestSignupAPI(APIBaseTest):
session["invite_id"] = invite_id
session.save()
url = reverse("social:complete", kwargs={"backend": "google-oauth2"}) + f"?code=2&state={state}"
- mock_request.return_value.json.return_value = {"access_token": "123", "email": email, "sub": "123"}
+ mock_request.return_value.json.return_value = {
+ "access_token": "123",
+ "email": email,
+ "email_verified": True,
+ "sub": "123",
+ }
return self.client.get(url, follow=True)
@mock.patch("social_core.backends.base.BaseAuth.request")
@@ -1411,6 +1432,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={state}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
@@ -1466,6 +1488,7 @@ class TestSignupAPI(APIBaseTest):
url = reverse("social:complete", kwargs={"backend": "google-oauth2"})
url += f"?code=2&state={response.client.session['google-oauth2_state']}"
mock_request.return_value.json.return_value = {
+ "email_verified": True,
"access_token": "123",
"email": "[email protected]",
"sub": "123",
diff --git a/posthog/helpers/sso.py b/posthog/helpers/sso.py
index c2913f55b7a2..0f18a1d91d42 100644
--- a/posthog/helpers/sso.py
+++ b/posthog/helpers/sso.py
@@ -3,6 +3,11 @@ from urllib.parse import urlencode
from django.http import HttpRequest
from django.utils.http import url_has_allowed_host_and_scheme
+UNVERIFIED_SOCIAL_EMAIL_ERROR = (
+ "Your sign-in provider hasn't verified this email address. Verify it with the provider, then sign in again."
+)
+GITHUB_EMAIL_LOOKUP_ERROR = "Couldn't check your email address with GitHub. Wait a minute, then sign in again."
+
def get_safe_next_url(next_url: str | None, request: HttpRequest) -> str | None:
"""Return next_url only when it's a safe same-origin/relative redirect target, else None.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 5c6e7a900fee..ea06701a8e0b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -309,6 +309,8 @@ SOCIAL_AUTH_PIPELINE = (
# Must stay ahead of association/provisioning so a mismatched authenticated identity is rejected first
"posthog.api.authentication.social_identity_matches_session",
"posthog.api.authentication.social_reauth",
+ # Must stay ahead of associate_by_email, which links an existing account by email with no check of its own
+ "posthog.api.authentication.social_email_verified_by_provider",
"social_core.pipeline.social_auth.associate_by_email",
"posthog.api.signup.social_create_user",
"social_core.pipeline.social_auth.associate_user",