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(ci): keep the schema cache restore alive without an OIDC key (#101420)

Julian Bez6e030c302b41
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index 46958c067ea1..36726b12eaa7 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -380,6 +380,11 @@ jobs:
# Internal API auth needs a non-empty INTERNAL_API_SECRET when DEBUG/TEST are off, and
# this job boots the app prod-like. The dev value is fine for CI.
INTERNAL_API_SECRET: 'posthog123'
+ # ensure_migration_defaults seeds a first-party OAuth application that signs with
+ # RS256, which needs a key. This job does not set TEST=1, so it gets no generated
+ # one. A fake key, so the job also runs for external contributors, who cannot read
+ # secrets.
+ OIDC_RSA_PRIVATE_KEY: ${{ vars.OIDC_RSA_FAKE_PRIVATE_KEY }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
diff --git a/posthog/management/commands/ensure_migration_defaults.py b/posthog/management/commands/ensure_migration_defaults.py
index dd11ede3ead5..6f170e714bf7 100644
--- a/posthog/management/commands/ensure_migration_defaults.py
+++ b/posthog/management/commands/ensure_migration_defaults.py
@@ -9,6 +9,8 @@ from typing import Any
from django.contrib.auth.models import Group as AuthGroup
from django.core.management.base import BaseCommand
+from oauth2_provider.settings import oauth2_settings
+
from posthog.models.data_color_theme import DataColorTheme
from posthog.models.oauth import OAuthApplication
@@ -316,8 +318,31 @@ _FEATURE_FLAG_TEMPLATE: dict[str, Any] = {
class Command(BaseCommand):
help = "Ensure default data from migrations exists for schema-only restores."
+ def _seed_streamlit_oauth_app(self, created_items: list[str], skipped_items: list[str]) -> None:
+ # OAuthApplication.clean() rejects RS256 where no OIDC RSA private key is
+ # configured, and an error here would skip every seed after this one.
+ if not oauth2_settings.OIDC_RSA_PRIVATE_KEY:
+ skipped_items.append(f"OAuth app: {_STREAMLIT_OAUTH_APP_NAME} (no OIDC_RSA_PRIVATE_KEY configured)")
+ return
+
+ if OAuthApplication.objects.filter(client_id=_STREAMLIT_OAUTH_CLIENT_ID).exists():
+ return
+
+ OAuthApplication.objects.create(
+ name=_STREAMLIT_OAUTH_APP_NAME,
+ client_id=_STREAMLIT_OAUTH_CLIENT_ID,
+ client_secret=secrets.token_urlsafe(48),
+ client_type="confidential",
+ authorization_grant_type="authorization-code",
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ is_first_party=True,
+ )
+ created_items.append(f"OAuth app: {_STREAMLIT_OAUTH_APP_NAME}")
+
def handle(self, *args: Any, **options: Any) -> None:
created_items: list[str] = []
+ skipped_items: list[str] = []
for group_name in _AUTH_GROUPS:
_, created = AuthGroup.objects.get_or_create(name=group_name)
@@ -350,18 +375,7 @@ class Command(BaseCommand):
ai_pilled.save(update_fields=["is_active"])
created_items.append("Growth enrichment prompt config: ai_pilled")
- if not OAuthApplication.objects.filter(client_id=_STREAMLIT_OAUTH_CLIENT_ID).exists():
- OAuthApplication.objects.create(
- name=_STREAMLIT_OAUTH_APP_NAME,
- client_id=_STREAMLIT_OAUTH_CLIENT_ID,
- client_secret=secrets.token_urlsafe(48),
- client_type="confidential",
- authorization_grant_type="authorization-code",
- redirect_uris="https://localhost",
- algorithm="RS256",
- is_first_party=True,
- )
- created_items.append(f"OAuth app: {_STREAMLIT_OAUTH_APP_NAME}")
+ self._seed_streamlit_oauth_app(created_items, skipped_items)
for template_data in (_PRODUCT_ANALYTICS_TEMPLATE, _FEATURE_FLAG_TEMPLATE):
name = template_data["template_name"]
@@ -376,3 +390,6 @@ class Command(BaseCommand):
self.stdout.write("Created defaults:\n- " + "\n- ".join(created_items))
else:
self.stdout.write("Default migration data already present.")
+
+ if skipped_items:
+ self.stdout.write("Skipped defaults:\n- " + "\n- ".join(skipped_items))
diff --git a/posthog/management/commands/migrate.py b/posthog/management/commands/migrate.py
index f47464b23d0d..7f8ef5a8ca9e 100644
--- a/posthog/management/commands/migrate.py
+++ b/posthog/management/commands/migrate.py
@@ -25,6 +25,7 @@ from django.core.management.commands.migrate import Command as DjangoMigrateComm
from django.db import DEFAULT_DB_ALIAS
from django.db.migrations.recorder import MigrationRecorder
+from posthog.cloud_utils import is_ci
from posthog.management.migration_profiling.profiler import profile_migrations
from common.migration_utils import (
@@ -229,7 +230,8 @@ class Command(DjangoMigrateCommand):
profile_operations = options.get("profile_operations", False)
# When profiling, the assumption is a fresh-DB run — both code paths
# below assume migrations were previously applied, which fights that.
- skip_caching = production_mode or test_mode or profile_operations
+ # The cache and the orphan check serve local worktree switches, not CI.
+ skip_caching = production_mode or test_mode or profile_operations or is_ci()
skip_orphan_check = options.get("skip_orphan_check", False) or skip_caching
# Get connection for orphan check
diff --git a/posthog/management/commands/test/test_ensure_migration_defaults.py b/posthog/management/commands/test/test_ensure_migration_defaults.py
index 3d28d082d7af..75fdc593330b 100644
--- a/posthog/management/commands/test/test_ensure_migration_defaults.py
+++ b/posthog/management/commands/test/test_ensure_migration_defaults.py
@@ -1,14 +1,26 @@
import re
from collections.abc import Iterator
+from io import StringIO
from typing import Any
-from django.test import SimpleTestCase
+from unittest.mock import patch
+from django.core.management import call_command
+from django.test import SimpleTestCase, TestCase
+
+from oauth2_provider.settings import oauth2_settings
from parameterized import parameterized
from posthog.schema import InsightVizNode
-from posthog.management.commands.ensure_migration_defaults import _FEATURE_FLAG_TEMPLATE, _PRODUCT_ANALYTICS_TEMPLATE
+from posthog.management.commands.ensure_migration_defaults import (
+ _FEATURE_FLAG_TEMPLATE,
+ _PRODUCT_ANALYTICS_TEMPLATE,
+ _STREAMLIT_OAUTH_CLIENT_ID,
+)
+from posthog.models.oauth import OAuthApplication
+
+from products.dashboards.backend.models.dashboard_templates import DashboardTemplate
_PLACEHOLDER = re.compile(r"^\{([A-Z0-9_]+)\}$")
@@ -68,3 +80,20 @@ class TestSeededDashboardTemplates(SimpleTestCase):
) -> None:
declared = {variable["id"] for variable in template.get("variables", [])}
assert _placeholders(tile.get("query")) <= declared
+
+
+class TestEnsureMigrationDefaults(TestCase):
+ @parameterized.expand([("with an OIDC key", "-----FAKE KEY-----", True), ("without an OIDC key", "", False)])
+ def test_seeds_every_default_and_creates_the_oauth_app_only_when_rs256_can_sign(
+ self, _label: str, oidc_key: str, expects_oauth_app: bool
+ ) -> None:
+ OAuthApplication.objects.filter(client_id=_STREAMLIT_OAUTH_CLIENT_ID).delete()
+ template_name = _PRODUCT_ANALYTICS_TEMPLATE["template_name"]
+ DashboardTemplate.objects.filter(template_name=template_name, team__isnull=True).delete()
+
+ with patch.object(oauth2_settings, "OIDC_RSA_PRIVATE_KEY", oidc_key):
+ call_command("ensure_migration_defaults", stdout=StringIO())
+
+ assert OAuthApplication.objects.filter(client_id=_STREAMLIT_OAUTH_CLIENT_ID).exists() is expects_oauth_app
+ # Seeded after the OAuth app, so its presence proves the command ran to the end.
+ assert DashboardTemplate.objects.filter(template_name=template_name, team__isnull=True).exists()