: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(tasks): create sandbox oauth apps during deploy bootstrap (#75926)
Alessandro Pogliaghif9fdb28ea0fd
diff --git a/bin/migrate b/bin/migrateindex 024de78e0888..03d0806e8c26 100755--- a/bin/migrate+++ b/bin/migrate@@ -226,6 +226,15 @@ if [ -n "$CLICKHOUSE_PID" ]; thenfifi+# OAuth applications task sandboxes mint their agent tokens under. Idempotent, and a no-op+# in the production regions, so it is safe to run on every deploy.+if run_scope "tasks-oauth"; then+ if [ "${DEPLOYMENT:-}" != "hobby" ]; then+ echo "Setting up task sandbox OAuth applications..."+ python manage.py setup_tasks_oauth || { echo "Error in setup_tasks_oauth, exiting."; exit 1; }+ fi+fi+# Temporal worker schedules. Skipped on hobby deploys (no Temporal cluster) and# on local dev (DEBUG=1, matching the persons-migration gate above).# Non-fatal: scheduling is reconciled idempotently on every deploy, so adiff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex 78bc024c1bc3..235a82aff6f3 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -312,6 +312,7 @@ cd /path/to/posthog-code/packages/agent && pnpm build| Temporal not reachable | Ensure Temporal is running on `127.0.0.1:7233`. Check with `temporal server start-dev` || Feature flag not enabled | Re-run `python manage.py setup_background_agents` to (re-)create the `tasks` flag at 100% rollout || Array OAuth app missing | Re-run `python manage.py setup_background_agents` |+| `PostHog AI app not found for region ...` | The PostHog AI OAuth app is missing. Run `python manage.py setup_tasks_oauth`, which creates both the Array and PostHog AI dev apps. Deploys run it from `bin/migrate`; it no-ops in the US/EU regions || GitHub token expired | Tokens from GitHub App installations expire after ~1 hour. Re-run the task to get a fresh token || "Task workflow execution blocked" | The `tasks` feature flag is not enabled for this user/org || Sandbox image build fails | Check Docker has enough disk space. Delete old images with `docker system prune` |diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex c92cd4650793..eecc09a29e92 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -16,6 +16,11 @@ POSTHOG_AI_APP_CLIENT_ID_US = "N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu"POSTHOG_AI_APP_CLIENT_ID_EU = "0Lizwa3mFSlBuEEQ8V8FMJlskUXpDuSmoEdhzxyi"POSTHOG_AI_APP_CLIENT_ID_DEV = "DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1"+# The LLM gateway authorizes by application id, so these must stay equal to+# POSTHOG_CODE_DEV_APP_ID / POSTHOG_AI_DEV_APP_ID in llm_gateway/products/config.py.+ARRAY_APP_ID_DEV = "019ebb47-c750-0000-e1ea-723a6ff112d3"+POSTHOG_AI_APP_ID_DEV = "019edb1a-cce4-0000-1f6d-682061862da9"+# Every OAuth application sandbox agent tokens are minted under. Tokens for these apps# are only ever created server-side (never via the consent flow or personal API keys),# so a request bearing one provably originates from a sandbox run.diff --git a/products/tasks/backend/management/commands/setup_tasks_oauth.py b/products/tasks/backend/management/commands/setup_tasks_oauth.pyindex c851ce26b95d..567c7800e5a1 100644--- a/products/tasks/backend/management/commands/setup_tasks_oauth.py+++ b/products/tasks/backend/management/commands/setup_tasks_oauth.py@@ -1,24 +1,35 @@-from django.conf import settings-from django.core.management.base import BaseCommand, CommandError+from django.core.management.base import BaseCommandfrom posthog.models import OAuthApplicationfrom posthog.models.oauth import OAuthApplicationAuthBrand-from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV+from posthog.temporal.oauth import (+ ARRAY_APP_CLIENT_ID_DEV,+ ARRAY_APP_ID_DEV,+ POSTHOG_AI_APP_CLIENT_ID_DEV,+ POSTHOG_AI_APP_ID_DEV,+)+from posthog.utils import get_instance_regionARRAY_REDIRECT_URIS = "http://localhost:8237/callback http://localhost:8239/callback"POSTHOG_AI_REDIRECT_URIS = "http://localhost:8000/authorize"+# Skipped rather than failed, so the unconditional call in bin/migrate is safe.+PRODUCTION_REGIONS = frozenset({"US", "EU"})+class Command(BaseCommand):- help = "Create the Array OAuth application for local cloud runs development"+ help = "Create the Array and PostHog AI OAuth applications task sandboxes mint tokens under"def handle(self, *args, **options):- if not settings.DEBUG:- raise CommandError("This command can only be run with DEBUG=1")+ region = get_instance_region()+ if region in PRODUCTION_REGIONS:+ self.stdout.write(f"Skipping dev OAuth application setup; region {region} has its own applications")+ returnself._setup_app(ARRAY_APP_CLIENT_ID_DEV,{+ "id": ARRAY_APP_ID_DEV,"name": "Array Dev App","client_type": OAuthApplication.CLIENT_PUBLIC,"authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,@@ -29,6 +40,7 @@ class Command(BaseCommand):self._setup_app(POSTHOG_AI_APP_CLIENT_ID_DEV,{+ "id": POSTHOG_AI_APP_ID_DEV,"name": "PostHog AI Dev App","client_type": OAuthApplication.CLIENT_CONFIDENTIAL,"authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,@@ -51,5 +63,14 @@ class Command(BaseCommand):)if created:self.stdout.write(self.style.SUCCESS(f"Created OAuthApplication '{app.name}' (client_id={app.client_id})"))- else:- self.stdout.write(self.style.SUCCESS(f"OAuthApplication '{app.name}' already exists"))+ return++ self.stdout.write(self.style.SUCCESS(f"OAuthApplication '{app.name}' already exists"))+ # Not repaired here: changing the pk means deleting the row, cascading to its tokens.+ if str(app.id) != defaults["id"]:+ self.stdout.write(+ self.style.WARNING(+ f" '{app.name}' has id {app.id}, expected {defaults['id']}. The LLM gateway "+ "authorizes by application id, so tokens minted under it will be rejected."+ )+ )diff --git a/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py b/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.pyindex fe701606624b..88ee73e9ebb8 100644--- a/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py+++ b/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py@@ -3,21 +3,92 @@ from io import StringIOfrom django.core.management import call_commandfrom django.test import TestCase, override_settings+from parameterized import parameterized+from posthog.models import OAuthApplicationfrom posthog.models.oauth import OAuthApplicationAuthBrand-from posthog.temporal.oauth import POSTHOG_AI_APP_CLIENT_ID_DEV+from posthog.temporal.oauth import (+ ARRAY_APP_CLIENT_ID_DEV,+ ARRAY_APP_ID_DEV,+ POSTHOG_AI_APP_CLIENT_ID_DEV,+ POSTHOG_AI_APP_ID_DEV,+)++DEV_CLIENT_IDS = [ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV]+@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="DEV")class TestSetupTasksOAuth(TestCase):- @override_settings(DEBUG=True)- def test_creates_posthog_ai_dev_oauth_app(self) -> None:+ @parameterized.expand(+ [+ (+ "array",+ ARRAY_APP_CLIENT_ID_DEV,+ ARRAY_APP_ID_DEV,+ {+ "name": "Array Dev App",+ "client_type": OAuthApplication.CLIENT_PUBLIC,+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,+ "redirect_uris": "http://localhost:8237/callback http://localhost:8239/callback",+ },+ ),+ (+ "posthog_ai",+ POSTHOG_AI_APP_CLIENT_ID_DEV,+ POSTHOG_AI_APP_ID_DEV,+ {+ "name": "PostHog AI Dev App",+ "client_type": OAuthApplication.CLIENT_CONFIDENTIAL,+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,+ "redirect_uris": "http://localhost:8000/authorize",+ "auth_brand": OAuthApplicationAuthBrand.POSTHOG.value,+ "is_verified": True,+ "is_first_party": True,+ },+ ),+ ]+ )+ def test_creates_dev_oauth_app_and_reruns_cleanly(+ self, _name: str, client_id: str, expected_id: str, expected: dict+ ) -> None:call_command("setup_tasks_oauth", stdout=StringIO())+ call_command("setup_tasks_oauth", stdout=StringIO())++ apps = OAuthApplication.objects.filter(client_id=client_id)+ assert apps.count() == 1+ app = apps.get()+ assert str(app.id) == expected_id+ for field, value in expected.items():+ assert getattr(app, field) == value, field++ @parameterized.expand(+ [+ ("us", "US", False),+ ("eu", "EU", False),+ ("hosted_dev", "DEV", True),+ ("unset_region", None, True),+ ]+ )+ def test_creates_apps_outside_production_regions_only(+ self, _name: str, region: str | None, should_create: bool+ ) -> None:+ with override_settings(CLOUD_DEPLOYMENT=region):+ call_command("setup_tasks_oauth", stdout=StringIO())++ created = OAuthApplication.objects.filter(client_id__in=DEV_CLIENT_IDS).count()+ assert created == (len(DEV_CLIENT_IDS) if should_create else 0)++ def test_warns_when_an_existing_app_has_the_wrong_id(self) -> None:+ OAuthApplication.objects.create(+ client_id=POSTHOG_AI_APP_CLIENT_ID_DEV,+ name="PostHog AI Dev App",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="http://localhost:8000/authorize",+ algorithm="RS256",+ )++ out = StringIO()+ call_command("setup_tasks_oauth", stdout=out)- app = OAuthApplication.objects.get(client_id=POSTHOG_AI_APP_CLIENT_ID_DEV)- assert app.name == "PostHog AI Dev App"- assert app.client_type == OAuthApplication.CLIENT_CONFIDENTIAL- assert app.authorization_grant_type == OAuthApplication.GRANT_AUTHORIZATION_CODE- assert app.redirect_uris == "http://localhost:8000/authorize"- assert app.auth_brand == OAuthApplicationAuthBrand.POSTHOG.value- assert app.is_verified is True- assert app.is_first_party is True+ assert f"expected {POSTHOG_AI_APP_ID_DEV}" in out.getvalue()