:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(auth): stop scanning posthog_user on every google login (#103450)
posthog[bot]a530bb4f28f6
diff --git a/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.py b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.pyindex 5ec1fa3ac482..1c9fdd8e555d 100644--- a/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.py+++ b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.py@@ -1,5 +1,7 @@# Test cases for user-email-lookups-use-the-shared-fold rule.# ruff: noqa: F821, E501+from django.contrib.auth import get_user_model+from posthog.helpers.email_utils import EmailLookupHandlerfrom posthog.models import User@@ -25,6 +27,16 @@ def flagged_exact_match(email: str):return User.objects.filter(email=email).first()+def flagged_swappable_model_get(email: str):+ # ruleid: user-email-lookups-use-the-shared-fold+ return get_user_model().objects.get(email__iexact=email)+++def flagged_swappable_model_exact_match(email: str):+ # ruleid: user-email-lookups-use-the-shared-fold+ return get_user_model().objects.filter(email=email).first()++def ok_shared_fold_queryset(email: str):# ok: user-email-lookups-use-the-shared-foldreturn EmailLookupHandler.users_matching_email(email).exists()diff --git a/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.yaml b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.yamlindex 1151ac6d875e..ad42e56c1172 100644--- a/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.yaml+++ b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.yaml@@ -21,17 +21,22 @@ rules:severity: ERRORpatterns:- pattern-either:- - pattern: User.objects.filter(..., email__iexact=$VALUE, ...)- - pattern: User.objects.get(..., email__iexact=$VALUE, ...)- - pattern: User.objects.filter(..., email=$VALUE, ...)- - pattern: User.objects.get(..., email=$VALUE, ...)+ # `email__iexact` is flagged on any receiver. A bare `email=` is flagged only on+ # `User`, because other models carry an `email` column of their own.- pattern: $QS.filter(..., email__iexact=$VALUE, ...)- pattern: $QS.exclude(..., email__iexact=$VALUE, ...)+ - pattern: $QS.get(..., email__iexact=$VALUE, ...)+ - pattern: User.objects.filter(..., email=$VALUE, ...)+ - pattern: User.objects.get(..., email=$VALUE, ...)+ - pattern: get_user_model().objects.filter(..., email=$VALUE, ...)+ - pattern: get_user_model().objects.get(..., email=$VALUE, ...)paths:- # The paths where an address decides which account a request reaches.+ # The paths that resolve a `User` by address, where a disagreeing fold sends a+ # request to the wrong account and an unindexed fold scans the whole table.include:- /ee/api/agentic_provisioning/**/*.py- /ee/api/authentication.py+ - /ee/api/google_oauth_diagnostics.py- /ee/api/scim/**/*.py- /ee/partners/stripe/api/provisioning/**/*.py- /posthog/api/authentication.pydiff --git a/ee/api/google_oauth_diagnostics.py b/ee/api/google_oauth_diagnostics.pyindex 8f434fba029e..a2a72d90bea9 100644--- a/ee/api/google_oauth_diagnostics.py+++ b/ee/api/google_oauth_diagnostics.py@@ -21,7 +21,6 @@ from typing import Anyfrom urllib.parse import urlparsefrom django.conf import settings-from django.contrib.auth import get_user_modelimport jwtimport requests@@ -31,6 +30,7 @@ from social_django.models import UserSocialAuthfrom posthog.egress.google_workspace.transport import GoogleWorkspaceClientfrom posthog.exceptions_capture import capture_exception+from posthog.helpers.email_utils import EmailLookupHandlerUSERINFO_URL = "https://www.googleapis.com/oauth2/v3/userinfo"TOKENINFO_URL = "https://oauth2.googleapis.com/tokeninfo"@@ -263,7 +263,7 @@ def _account_properties(email: Any, sub: Any) -> Properties:UserSocialAuth.objects.filter(provider="google-oauth2", uid__in=uids).values_list("uid", flat=True))return {- "existing_user": isinstance(email, str) and get_user_model().objects.filter(email__iexact=email).exists(),+ "existing_user": isinstance(email, str) and EmailLookupHandler.users_matching_email(email).exists(),"has_google_social_auth": bool(linked_uids),"social_auth_uid_type": "sub" if sub in linked_uids else "email" if email in linked_uids else None,}diff --git a/ee/api/test/test_google_oauth_diagnostics.py b/ee/api/test/test_google_oauth_diagnostics.pyindex 3ac8afab9a8f..3c90babf6a88 100644--- a/ee/api/test/test_google_oauth_diagnostics.py+++ b/ee/api/test/test_google_oauth_diagnostics.py@@ -8,7 +8,9 @@ from typing import Anyfrom unittest.mock import patch+from django.db import connectionfrom django.test import TestCase, override_settings+from django.test.utils import CaptureQueriesContextimport jwtimport requests@@ -163,3 +165,17 @@ class TestGoogleOAuthDiagnostics(TestCase):serialized = json.dumps(event, default=str)for private in (ACCESS_TOKEN, EMAIL, SUB, profile["name"], profile["picture"]):assert private not in serialized++ def test_existing_user_check_resolves_through_the_indexed_lower_fold(self) -> None:+ with (+ patch.object(GoogleOAuth2, "user_data", return_value={"sub": SUB, "email": EMAIL}),+ patch("ee.api.google_oauth_diagnostics.posthoganalytics.capture"),+ CaptureQueriesContext(connection) as queries,+ ):+ CustomGoogleOAuth2().user_data(ACCESS_TOKEN, response=_token_response())++ # `posthog_user` has an expression index on `LOWER(email)` only, so an `UPPER` comparison+ # from `email__iexact` falls back to a sequential scan on every Google login.+ user_lookups = [q["sql"] for q in queries.captured_queries if 'FROM "posthog_user"' in q["sql"]]+ assert user_lookups+ assert not [sql for sql in user_lookups if "UPPER(" in sql]diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 88a6db367ab1..931b01350e52 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -6,7 +6,6 @@ ee/api/agentic_provisioning/test/test_region_proxy.py::TestShouldProxyTokenLookuee/api/test/test_billing.py::TestExportStreamingee/api/test/test_billing.py::TestResolveTeamLabelsee/api/test/test_billing.py::TestRewriteCsvLabels-ee/api/test/test_google_oauth_diagnostics.py::TestGoogleOAuthDiagnosticsee/api/vercel/test/test_vercel_connect.py::TestValidateNextUrlee/billing/test/test_billing_consumer.py::TestBillingConsumerUsageSpikeee/billing/test/test_billing_manager.py::TestParamSerialization