: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
feat(wizard): management command minting the CI smoke test's gateway credential (#96854)
Brandon9ee35cb03327
diff --git a/posthog/management/commands/test/test_wizard_ci_token.py b/posthog/management/commands/test/test_wizard_ci_token.pynew file mode 100644index 000000000000..1bc622537fe5--- /dev/null+++ b/posthog/management/commands/test/test_wizard_ci_token.py@@ -0,0 +1,168 @@+from datetime import timedelta+from io import StringIO++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command+from django.core.management.base import CommandError+from django.test import override_settings+from django.utils import timezone++from posthog.management.commands.wizard_ci_token import rotate_wizard_ci_token+from posthog.models import OAuthAccessToken, OAuthApplication, Team, User++_WIZARD_CLIENT_ID = "wizard-ci-client-id"+++@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID, WIZARD_GATEWAY_CLIENT_IDS=[_WIZARD_CLIENT_ID])+class TestWizardCiTokenCommand(BaseTest):+ def _create_wizard_app(self, scopes: list[str]) -> OAuthApplication:+ return OAuthApplication.objects.create(+ client_id=_WIZARD_CLIENT_ID,+ name="PostHog Wizard",+ # The gateway attributes the app's tokens to this organization's root+ # team, so an app without one issues tokens it will refuse.+ organization=self.organization,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="http://localhost:8237/callback",+ algorithm="RS256",+ scopes=scopes,+ )++ def _run(self, *args: str) -> str:+ out = StringIO()+ call_command("wizard_ci_token", "--email", self.user.email, "--team", str(self.team.id), *args, stdout=out)+ return out.getvalue()++ def test_mints_a_long_lived_token_under_the_wizard_app(self) -> None:+ app = self._create_wizard_app(["project:read", "llm_gateway:read"])++ out = self._run("--days", "30")++ token = out.strip().splitlines()[-1]+ assert token.startswith("pha_")+ row = OAuthAccessToken.objects.get(token=token)+ assert row.application_id == app.id+ assert row.user_id == self.user.id+ assert row.scoped_teams == [self.team.id]+ # Exactly the one scope, not the app's whole ceiling: this credential+ # authenticates at the gateway on its own, for as long as it lives.+ assert row.scope.split() == ["llm_gateway:read"]+ # Not the mint helper's six hours: the smoke test runs unattended.+ assert row.expires > timezone.now() + timedelta(days=29, hours=23)+ assert row.expires <= timezone.now() + timedelta(days=30)++ def test_the_default_lifetime_is_thirty_days(self) -> None:+ self._create_wizard_app(["project:read", "llm_gateway:read"])++ out = self._run()++ row = OAuthAccessToken.objects.get(token=out.strip().splitlines()[-1])+ assert row.expires <= timezone.now() + timedelta(days=30)++ def test_re_running_revokes_the_previous_token(self) -> None:+ # Otherwise every rotation leaves another live gateway credential+ # behind with nothing naming it.+ self._create_wizard_app(["project:read", "llm_gateway:read"])+ first = self._run().strip().splitlines()[-1]++ second = self._run().strip().splitlines()[-1]++ assert not OAuthAccessToken.objects.filter(token=first).exists()+ assert OAuthAccessToken.objects.filter(token=second).exists()++ def test_a_refused_mint_leaves_the_previous_token_alive(self) -> None:+ self._create_wizard_app(["project:read", "llm_gateway:read"])+ first = self._run().strip().splitlines()[-1]++ with patch(+ "posthog.management.commands.wizard_ci_token.create_wizard_oauth_access_token_for_user",+ side_effect=RuntimeError("mint refused"),+ ):+ with pytest.raises(CommandError, match="mint refused"):+ self._run()++ assert OAuthAccessToken.objects.filter(token=first).exists()++ def test_the_lifetime_is_bounded(self) -> None:+ self._create_wizard_app(["project:read", "llm_gateway:read"])+ for days in ("0", "91"):+ with pytest.raises(CommandError, match="--days"):+ self._run("--days", days)+ assert not OAuthAccessToken.objects.exists()++ def test_refuses_a_user_outside_the_teams_organization(self) -> None:+ self._create_wizard_app(["project:read", "llm_gateway:read"])+ outsider = User.objects.create(email="[email protected]")+ out = StringIO()++ with pytest.raises(CommandError, match="not a member"):+ call_command("wizard_ci_token", "--email", outsider.email, "--team", str(self.team.id), stdout=out)+ assert not OAuthAccessToken.objects.exists()++ def test_the_rotation_is_callable_without_the_command(self) -> None:+ self._create_wizard_app(["project:read", "llm_gateway:read"])++ issued = rotate_wizard_ci_token(email=self.user.email, team_id=self.team.id, days=30)++ assert issued.token.startswith("pha_")+ assert issued.revoked == 0+ assert issued.team_id == self.team.id++ def test_refuses_a_team_the_gateway_would_not_attribute_to(self) -> None:+ # Projection resolves an OAuth credential's team from the application's+ # organization root, then fails the token closed when scoped_teams+ # disagrees, so the mismatch has to refuse rather than print a dead token.+ self._create_wizard_app(["project:read", "llm_gateway:read"])+ other = Team.objects.create(organization=self.organization, name="child")++ with pytest.raises(CommandError, match="organization root team"):+ call_command("wizard_ci_token", "--email", self.user.email, "--team", str(other.id), stdout=StringIO())+ assert not OAuthAccessToken.objects.filter(user=self.user).exists()++ def test_refuses_when_the_app_has_no_organization(self) -> None:+ OAuthApplication.objects.create(+ client_id=_WIZARD_CLIENT_ID,+ name="PostHog Wizard",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="http://localhost:8237/callback",+ algorithm="RS256",+ scopes=["project:read", "llm_gateway:read"],+ )++ with pytest.raises(CommandError, match="no single organization root team"):+ self._run()+ assert not OAuthAccessToken.objects.filter(user=self.user).exists()++ def test_refuses_when_the_app_cannot_grant_the_gateway_scope(self) -> None:+ # A token without llm_gateway:read mints nothing at the gateway, so it+ # must not be issued at all.+ self._create_wizard_app(["project:read"])++ with pytest.raises(CommandError, match="llm_gateway:read"):+ self._run()+ assert not OAuthAccessToken.objects.exists()++ @override_settings(WIZARD_GATEWAY_CLIENT_IDS=["some-other-app"])+ def test_refuses_when_the_app_is_not_a_mint_client(self) -> None:+ self._create_wizard_app(["project:read", "llm_gateway:read"])++ with pytest.raises(CommandError, match="not_wizard_app"):+ self._run()+ assert not OAuthAccessToken.objects.exists()++ @patch("posthog.temporal.oauth.wizard_identity_blocked", return_value=True)+ def test_refuses_a_blocked_identity(self, mock_blocked) -> None:+ self._create_wizard_app(["project:read", "llm_gateway:read"])++ with pytest.raises(CommandError, match="blocked"):+ self._run()+ assert not OAuthAccessToken.objects.exists()++ def test_refuses_without_a_wizard_app(self) -> None:+ with pytest.raises(CommandError, match="Wizard app not found"):+ self._run()diff --git a/posthog/management/commands/wizard_ci_token.py b/posthog/management/commands/wizard_ci_token.pynew file mode 100644index 000000000000..e2665b849078--- /dev/null+++ b/posthog/management/commands/wizard_ci_token.py@@ -0,0 +1,171 @@+"""+Mint a long-lived wizard-app OAuth token for the wizard CI smoke test.++Usage:+ python manage.py wizard_ci_token --email [email protected] --team 2+ python manage.py wizard_ci_token --email [email protected] --team 2 --days 90++The smoke test runs `wizard --ci --api-key <token>`. A personal API key (phx_)+is refused at the gateway-token mint as `invalid_token`, so CI needs a `pha_`+issued under the wizard OAuth app with `llm_gateway:read`, scoped to one team.++Two things bound it. It carries that one scope rather than the wizard app's+whole ceiling, and it expires in 30 days by default, because a credential+holding `llm_gateway:read` authenticates at the AI gateway on its own, where+none of the wizard mint's gates apply: no blocklist recheck, no rollout switch,+no program pin, no mint throttle, no per-run cap. The lifetime is the bound.++--team must be the wizard app's organization root team, which is what the+gateway attributes the app's tokens to; any other team mints a credential it+refuses. Re-running revokes the previous CI token for the same user and team,+so a rotation leaves nothing live behind it. The token is printed once, on the last+line of output, and stored nowhere else: put it straight in the CI secret.+"""++from dataclasses import dataclass+from datetime import datetime, timedelta+from typing import Any++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError+from django.db import transaction+from django.utils import timezone++import structlog++from posthog.models import OAuthAccessToken, Team, User+from posthog.scopes import resolve_ceiling++# _org_root_team_id is what projection itself resolves an OAuth credential's team+# with, so the pre-mint check reuses it rather than restating the query and+# drifting from it.+from posthog.storage.gateway_credential_cache import GATEWAY_CREDENTIAL_REQUIRED_SCOPE, _org_root_team_id+from posthog.temporal.oauth import WizardIdentityBlockedError, create_wizard_oauth_access_token_for_user, get_wizard_app++logger = structlog.get_logger(__name__)++_DEFAULT_DAYS = 30+_MAX_DAYS = 90+++class WizardCiTokenError(Exception):+ """A refusal the command renders as a CommandError."""+++@dataclass(frozen=True)+class WizardCiToken:+ token: str+ expires: datetime+ revoked: int+ email: str+ team_id: int+++def rotate_wizard_ci_token(*, email: str, team_id: int, days: int) -> WizardCiToken:+ """Mint the CI credential, then revoke the one it replaces.++ Serialized per user: two rotations that overlap would each mint and then+ delete the other's row, leaving CI with nothing live.+ """+ if days < 1 or days > _MAX_DAYS:+ raise WizardCiTokenError(f"--days must be between 1 and {_MAX_DAYS}")++ try:+ app = get_wizard_app()+ except RuntimeError as e:+ raise WizardCiTokenError(str(e)) from e+ if app.client_id not in settings.WIZARD_GATEWAY_CLIENT_IDS:+ raise WizardCiTokenError(+ f"wizard app {app.client_id} is not in WIZARD_GATEWAY_CLIENT_IDS; the mint would refuse it as not_wizard_app"+ )+ if GATEWAY_CREDENTIAL_REQUIRED_SCOPE not in (resolve_ceiling(app.ceiling_scopes) or ()):+ raise WizardCiTokenError(f"wizard app {app.client_id} cannot grant {GATEWAY_CREDENTIAL_REQUIRED_SCOPE}")++ team = Team.objects.select_related("organization").filter(id=team_id).first()+ if team is None:+ raise WizardCiTokenError(f"team {team_id} does not exist")++ # The gateway attributes an OAuth credential to its application's organization+ # root, not to scoped_teams, and then fails the token closed when the two+ # disagree. Checked here so a mismatch is a refusal rather than a printed+ # token the gateway rejects.+ attributed = _org_root_team_id(app.organization_id)+ if attributed is None:+ raise WizardCiTokenError(+ f"wizard app {app.client_id} has no single organization root team, so the gateway cannot attribute its tokens"+ )+ if attributed != team.id:+ raise WizardCiTokenError(+ f"team {team.id} is not the wizard app's organization root team ({attributed}); "+ "the gateway would refuse a token scoped to it"+ )++ user = User.objects.filter(email__iexact=email).first()+ if user is None:+ raise WizardCiTokenError(f"no user with email {email}")+ if not user.organization_memberships.filter(organization_id=team.organization_id).exists():+ raise WizardCiTokenError(f"{user.email} is not a member of team {team.id}'s organization")++ with transaction.atomic():+ # Locks this user's row for the transaction, so an overlapping rotation+ # waits rather than racing the mint against the revoke.+ User.objects.select_for_update().get(pk=user.pk)++ try:+ token = create_wizard_oauth_access_token_for_user(user, team.id, scopes=[GATEWAY_CREDENTIAL_REQUIRED_SCOPE])+ except (WizardIdentityBlockedError, RuntimeError) as e:+ raise WizardCiTokenError(str(e)) from e++ # save(), not queryset update(): the gateway's credential blob is+ # projected on post_save, which an update() does not fire, so the+ # gateway would keep serving the mint helper's six-hour expiry.+ row = OAuthAccessToken.objects.get(token=token)+ expires = timezone.now() + timedelta(days=days)+ row.expires = expires+ row.save(update_fields=["expires"])++ # After the mint, so a refusal leaves the working credential in place.+ superseded = (+ OAuthAccessToken.objects.filter(+ user=user, application=app, scoped_teams=[team.id], scope=GATEWAY_CREDENTIAL_REQUIRED_SCOPE+ )+ .exclude(expires__lte=timezone.now())+ .exclude(pk=row.pk)+ )+ revoked = superseded.count()+ superseded.delete()++ logger.info(+ "wizard_ci_token: issued",+ user_uuid=str(user.uuid),+ team_id=team.id,+ scope=GATEWAY_CREDENTIAL_REQUIRED_SCOPE,+ expires=expires.isoformat(),+ revoked_previous=revoked,+ )+ return WizardCiToken(token=token, expires=expires, revoked=revoked, email=user.email, team_id=team.id)+++class Command(BaseCommand):+ help = "Mint a long-lived wizard-app OAuth token (pha_) for the wizard CI smoke test."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--email", required=True, help="the CI bot user's email")+ parser.add_argument("--team", type=int, required=True, help="team id the token is scoped to")+ parser.add_argument("--days", type=int, default=_DEFAULT_DAYS, help=f"lifetime in days (1-{_MAX_DAYS})")++ def handle(self, *args: Any, **options: Any) -> None:+ try:+ issued = rotate_wizard_ci_token(email=options["email"], team_id=options["team"], days=options["days"])+ except WizardCiTokenError as e:+ raise CommandError(str(e)) from e++ self.stdout.write(+ self.style.SUCCESS(+ f"wizard CI token for {issued.email} on team {issued.team_id}, "+ f"scope {GATEWAY_CREDENTIAL_REQUIRED_SCOPE}, "+ f"expires {issued.expires.isoformat()}, revoked {issued.revoked} previous"+ )+ )+ self.stdout.write("Store it in the CI secret; it is not recoverable and re-running revokes it.")+ self.stdout.write(issued.token)diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 38b5d349048f..d15c1a611ec4 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -604,11 +604,13 @@ class WizardIdentityBlockedError(Exception):a transient token failure must not retry this one."""-def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:+def create_wizard_oauth_access_token_for_user(user, team_id: int, *, scopes: list[str] | None = None) -> str:"""Mint an OAuth access token under the wizard's own app for a cloud wizard run.Deliberately separate from the sandbox/agent token (`create_oauth_access_token_for_user`) so the- wizard's scopes stay independent of the agent's. Uses the wizard app's configured scope ceiling.+ wizard's scopes stay independent of the agent's. Defaults to the wizard app's+ configured scope ceiling; `scopes` narrows within it, for a credential whose+ purpose needs less than the whole ceiling.Gated here rather than only at the HTTP kickoff, which a workflow retry orresume reaches with no request in front of it.@@ -629,4 +631,11 @@ def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:if ceiling is None or len(ceiling) == 0:raise RuntimeError("Wizard app has no scope ceiling. Must be configured in the database.")- return _mint_oauth_access_token(user, team_id, app=app, scopes=sorted(ceiling))+ if scopes is None:+ return _mint_oauth_access_token(user, team_id, app=app, scopes=sorted(ceiling))+ if not scopes:+ raise RuntimeError("Refusing to mint a wizard token with no scopes.")+ outside = sorted(set(scopes) - set(ceiling))+ if outside:+ raise RuntimeError(f"Wizard app cannot grant {', '.join(outside)}.")+ return _mint_oauth_access_token(user, team_id, app=app, scopes=sorted(set(scopes)))