: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(oauth): use compact whole-token scope index (#88324)
Sven Lange275463bebb00
diff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.pyindex 617e8c502cd8..35b71259392f 100644--- a/posthog/management/migration_analysis/operations.py+++ b/posthog/management/migration_analysis/operations.py@@ -720,7 +720,7 @@ Safe pattern requires:reason="RunSQL with DROP is dangerous",details={"sql": sql},)- elif "UPDATE" in sql or "DELETE" in sql:+ elif re.search(r"\b(?:UPDATE|DELETE)\b", sql):# Check for developer override for small tablesif override:return OperationRisk(diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex 4479fd2cbb9e..916ddf80ce13 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -406,6 +406,18 @@ class TestRunSQLOperations:assert risk.score == 3assert risk.level == RiskLevel.NEEDS_REVIEW+ def test_run_sql_does_not_match_keywords_inside_identifiers(self):+ op = create_mock_operation(+ migrations.RunSQL,+ sql="ALTER INDEX oauth_scope_idx SET (fastupdate = off);",+ )++ risk = self.analyzer.analyze_operation(op)++ assert risk.score == 3+ assert risk.reason == "RunSQL with ALTER may cause locks"+ assert risk.level == RiskLevel.NEEDS_REVIEW+def test_run_sql_with_concurrent_index_with_if_not_exists(self):"""Test CREATE INDEX CONCURRENTLY with IF NOT EXISTS - score 1 (SAFE)."""op = create_mock_operation(diff --git a/posthog/migrations/1317_oauthaccesstoken_scopes_gin.py b/posthog/migrations/1317_oauthaccesstoken_scopes_gin.pynew file mode 100644index 000000000000..4ae1c6958e84--- /dev/null+++ b/posthog/migrations/1317_oauthaccesstoken_scopes_gin.py@@ -0,0 +1,30 @@+# Generated by Django 5.2.17 on 2026-08-24 15:02++import django.contrib.postgres.fields+import django.contrib.postgres.indexes+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [("posthog", "1316_deprecate_organization_domain_idp_config")]++ operations = [+ SafeAddIndexConcurrently(+ model_name="oauthaccesstoken",+ index=django.contrib.postgres.indexes.GinIndex(+ models.Func(+ models.F("scope"),+ models.Value(" "),+ function="string_to_array",+ output_field=django.contrib.postgres.fields.ArrayField(base_field=models.TextField(), size=None),+ ),+ condition=models.Q(("application__isnull", False)),+ fastupdate=False,+ name="oauthaccesstoken_scopes_gin",+ ),+ ),+ ]diff --git a/posthog/migrations/1318_disable_oauth_scope_trgm_fastupdate.py b/posthog/migrations/1318_disable_oauth_scope_trgm_fastupdate.pynew file mode 100644index 000000000000..b064a0cbed9a--- /dev/null+++ b/posthog/migrations/1318_disable_oauth_scope_trgm_fastupdate.py@@ -0,0 +1,37 @@+# Generated by Django 5.2.17 on 2026-08-25 11:25++import django.contrib.postgres.indexes+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1317_oauthaccesstoken_scopes_gin"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.RunSQL(+ sql='ALTER INDEX IF EXISTS "oauthaccesstoken_scope_trgm" SET (fastupdate = off);',+ reverse_sql='ALTER INDEX IF EXISTS "oauthaccesstoken_scope_trgm" SET (fastupdate = on);',+ ),+ ],+ state_operations=[+ migrations.RemoveIndex(+ model_name="oauthaccesstoken",+ name="oauthaccesstoken_scope_trgm",+ ),+ migrations.AddIndex(+ model_name="oauthaccesstoken",+ index=django.contrib.postgres.indexes.GinIndex(+ condition=models.Q(("application__isnull", False)),+ fastupdate=False,+ fields=["scope"],+ name="oauthaccesstoken_scope_trgm",+ opclasses=["gin_trgm_ops"],+ ),+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex d481c119b0ae..fb64ff314f02 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1316_deprecate_organization_domain_idp_config+1318_disable_oauth_scope_trgm_fastupdatediff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex 6aed21731f9d..1f34c13016d7 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -511,22 +511,35 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignorereturn list(schemes) if schemes else ["https"]+def oauth_scope_tokens_expression() -> models.Func:+ return models.Func(+ models.F("scope"),+ models.Value(" "),+ function="string_to_array",+ output_field=ArrayField(models.TextField()),+ )++class OAuthAccessToken(AbstractAccessToken):class Meta(AbstractAccessToken.Meta):verbose_name = "OAuth Access Token"verbose_name_plural = "OAuth Access Tokens"swappable = "OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL"indexes = [- # The gateway credential cache scans for tokens holding a given scope via a- # whitespace-bounded regex on the space-separated `scope` text. A trigram GIN- # index lets that parameterized `~*` use an index scan; partial on- # application_id IS NOT NULL (which every such scan already filters on) keeps- # it to app tokens. See posthog/storage/gateway_credential_cache.py.+ # Pending-list merges make one token write absorb batched GIN maintenance.+ # Direct updates keep that work incremental for both scope indexes.GinIndex(fields=["scope"],name="oauthaccesstoken_scope_trgm",opclasses=["gin_trgm_ops"],condition=Q(application__isnull=False),+ fastupdate=False,+ ),+ GinIndex(+ oauth_scope_tokens_expression(),+ name="oauthaccesstoken_scopes_gin",+ condition=Q(application__isnull=False),+ fastupdate=False,),# B-tree on the plaintext `token` so equality lookups by token value resolve# via an index scan instead of a sequential scan. These lookups account for a@@ -534,6 +547,12 @@ class OAuthAccessToken(AbstractAccessToken):models.Index(fields=["token"], name="oauthaccesstoken_token_idx"),]+ @classmethod+ def with_scope(cls, scope: str) -> models.QuerySet["OAuthAccessToken"]:+ return cls.objects.alias(scope_tokens=oauth_scope_tokens_expression()).filter(+ scope_tokens__contains=[scope], application_id__isnull=False+ )+id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)user: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.pyindex fa147a0e817d..8480adcf25f5 100644--- a/posthog/models/test/test_oauth.py+++ b/posthog/models/test/test_oauth.py@@ -48,6 +48,28 @@ class TestOAuthModels(TestCase):app.refresh_from_db()self.assertEqual(app.scopes, [])+ @parameterized.expand(+ [+ ("whole_token", "openid llm_gateway:read query:read", True, True),+ ("substring", "openid llm_gateway:reader query:read", True, False),+ ("different_case", "openid LLM_GATEWAY:READ query:read", True, False),+ ("no_application", "llm_gateway:read", False, False),+ ]+ )+ def test_access_tokens_with_scope(+ self, name: str, stored_scopes: str, application_bound: bool, expected: bool+ ) -> None:+ app = self._make_app(f"Scope lookup {name}", f"scope_lookup_{name}")+ access_token = OAuthAccessToken.objects.create(+ application=app if application_bound else None,+ user=self.user,+ token=f"scope_lookup_token_{name}",+ expires=timezone.now() + timedelta(minutes=5),+ scope=stored_scopes,+ )++ self.assertEqual(OAuthAccessToken.with_scope("llm_gateway:read").filter(pk=access_token.pk).exists(), expected)+@parameterized.expand([("empty_scopes_broad", [], [], [], []),diff --git a/posthog/storage/gateway_credential_cache.py b/posthog/storage/gateway_credential_cache.pyindex 0a28a9bf2390..de04b8a550f5 100644--- a/posthog/storage/gateway_credential_cache.py+++ b/posthog/storage/gateway_credential_cache.py@@ -370,18 +370,15 @@ def refresh_all_gateway_credentials() -> int:removal. The team resolution and the per-OAuth membership/RBAC checks are memoized by team /(org, user) / (team, user) so the run does O(distinct teams/users) lookups, and .iterator()keeps the working set flat. The secret-key scopes lookup rides the projectsecretapikey_scopes_gin- index; the OAuth scope regex rides the oauthaccesstoken_scope_trgm trigram GIN index.+ index; the OAuth scope lookup rides the oauthaccesstoken_scopes_gin expression GIN index."""now = timezone.now()memo = _RefreshMemo()querysets = (ProjectSecretAPIKey.objects.select_related("team").filter(scopes__contains=[GATEWAY_CREDENTIAL_REQUIRED_SCOPE]),- OAuthAccessToken.objects.select_related("user", "application").filter(- scope__iregex=r"(^|\s)llm_gateway:read(\s|$)",- user__is_active=True,- application_id__isnull=False,- expires__gt=now,- ),+ OAuthAccessToken.with_scope(GATEWAY_CREDENTIAL_REQUIRED_SCOPE)+ .select_related("user", "application")+ .filter(user__is_active=True, expires__gt=now),)count = 0diff --git a/posthog/tasks/gateway_credential.py b/posthog/tasks/gateway_credential.pyindex 35fdabf1e650..f6cc2827399e 100644--- a/posthog/tasks/gateway_credential.py+++ b/posthog/tasks/gateway_credential.py@@ -62,8 +62,10 @@ def update_gateway_credential_cache_task(credential_kind: str, credential_id: stdef reproject_user_gateway_credentials_task(user_id: int) -> None:"""Re-project a user's OAuth credentials after a user/membership/RBAC change.Project secret keys have no user, so they're unaffected and not touched here."""- for token in OAuthAccessToken.objects.select_related("user", "application").filter(- scope__iregex=r"(^|\s)llm_gateway:read(\s|$)", user_id=user_id, application_id__isnull=False+ for token in (+ OAuthAccessToken.with_scope(GATEWAY_CREDENTIAL_REQUIRED_SCOPE)+ .select_related("user", "application")+ .filter(user_id=user_id)):project_gateway_credential(token)@@ -86,10 +88,10 @@ def reproject_team_gateway_credentials_task(team_id: int) -> None:organization_id = Team.objects.filter(pk=team_id).values_list("organization_id", flat=True).first()if organization_id is None:return- for token in OAuthAccessToken.objects.select_related("user", "application").filter(- application__organization_id=organization_id,- scope__iregex=r"(^|\s)llm_gateway:read(\s|$)",- application_id__isnull=False,+ for token in (+ OAuthAccessToken.with_scope(GATEWAY_CREDENTIAL_REQUIRED_SCOPE)+ .select_related("user", "application")+ .filter(application__organization_id=organization_id)):project_gateway_credential(token)