: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): refuse mints with a 403 and a reason instead of a 404 (#96840)
Brandone5a065523fbd
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex 9a778e82af20..7ff6a1a00e14 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -9,6 +9,7 @@ from django.conf import settingsfrom django.core.cache import cachefrom django.utils.crypto import get_random_string+import structlogimport posthoganalyticsfrom drf_spectacular.utils import extend_schemafrom google.genai.types import GenerateContentConfig, Schema@@ -22,7 +23,7 @@ from posthoganalytics.ai.openai import OpenAIfrom prometheus_client import Counterfrom rest_framework import exceptions, response, serializers, status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import AuthenticationFailed+from rest_framework.exceptions import AuthenticationFailed, ErrorDetailfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -60,6 +61,8 @@ from posthog.user_permissions import UserPermissionsfrom products.tasks.backend.facade import api as tasks_facade+logger = structlog.get_logger(__name__)+SETUP_WIZARD_CACHE_PREFIX = "setup-wizard:v1:"SETUP_WIZARD_CACHE_TIMEOUT = 600SETUP_WIZARD_DEFAULT_MODEL = "gpt-5-mini"@@ -117,6 +120,35 @@ def _organization_ids_for_query(team_ids: list[int]) -> list[str]:]+def _refuse_mint(+ outcome: str,+ exc: exceptions.APIException,+ *,+ program: object,+ product_node: str | None,+ user: User | None = None,+ team: Team | None = None,+) -> NoReturn:+ """Count and raise one mint refusal, so no exit can skip the counter.++ The outcome rides as the body's `code`: the exception handler renders every+ APIException as {type, code, detail, attr}, so a dict detail would be+ flattened and a separate key dropped. The CLI shows `detail` and reports `code`.+ """+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome=outcome).inc()+ detail = ErrorDetail(_detail_text(exc), code=outcome)+ # The handler reads a ValidationError's codes as a list, every other class's as a string.+ exc.detail = [detail] if isinstance(exc, exceptions.ValidationError) else detail+ raise exc+++def _detail_text(exc: exceptions.APIException) -> str:+ detail = exc.detail+ if isinstance(detail, list):+ return str(detail[0]) if detail else str(exc.default_detail)+ return str(detail)++class SetupWizardSerializer(serializers.Serializer):hash = serializers.CharField()@@ -458,13 +490,34 @@ class SetupWizardViewSet(viewsets.ViewSet):"""Mint a scoped gateway token for a wizard run.The CLI uses the returned phe_ (pinned product=wizard / obo=<customer org>,- capped, expiring) as its gateway bearer and re-calls near expiry. It treats- a 404 as "stay on the legacy gateway", so rollout is controlled here rather- than by a CLI release. Every other failure fails the run.+ capped, expiring) as its gateway bearer and re-calls near expiry. There is+ no other gateway: every refusal ends the run, with the body's `detail`+ shown to the user and its `code` naming the outcome."""+ # Resolved above the first gate so every refusal names the program.+ body = request.data if isinstance(request.data, dict) else {}+ program = body.get("program")+ product = wizard_product_node(program)+ # Only a literal true: any other truthy shape keeps the 404 a fallback needs.+ reads_reason = body.get("reads_refusal_reason") is True++ def refuse(outcome: str, exc: exceptions.APIException, *, user: User | None = None) -> NoReturn:+ _refuse_mint(outcome, exc, program=program, product_node=product, user=user, team=team)++ def refuse_absent_gateway(outcome: str, message: str, *, user: User | None = None) -> NoReturn:+ """Refuse one of the three outcomes the CLI's legacy fallback absorbed.++ A build that still falls back needs the 404 to reach the legacy+ gateway, which carries its own retirement message; it renders a 403+ as revoked project access instead. Only a client that says it reads+ the reason gets one. Drop this once those builds are gone.+ """+ exc = exceptions.PermissionDenied(message) if reads_reason else exceptions.NotFound(message)+ refuse(outcome, exc, user=user)++ team: Team | None = Noneif not wizard_gateway_configured():- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="unconfigured").inc()- raise exceptions.NotFound("Wizard gateway tokens are not available.")+ refuse_absent_gateway("unconfigured", "The PostHog AI gateway is not configured on this instance.")authenticator = OAuthAccessTokenAuthentication()# authenticate() raises its own AuthenticationFailed, so the count wraps the@@ -476,9 +529,8 @@ class SetupWizardViewSet(viewsets.ViewSet):user, _ = resultif not user:raise AuthenticationFailed("Invalid access token.")- except AuthenticationFailed:- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="invalid_token").inc()- raise+ except AuthenticationFailed as e:+ refuse("invalid_token", e)access_token = authenticator.access_token# llm_gateway:read is on every sandbox and agent token, so the scope alone@@ -486,30 +538,32 @@ class SetupWizardViewSet(viewsets.ViewSet):application = getattr(access_token, "application", None)client_id = getattr(application, "client_id", None)if not client_id or client_id not in settings.WIZARD_GATEWAY_CLIENT_IDS:- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="not_wizard_app").inc()- raise AuthenticationFailed("Access token was not issued to the wizard.")+ refuse("not_wizard_app", AuthenticationFailed("Access token was not issued to the wizard."), user=user)# The token's own scope text: the `scopes` property filters through# OAUTH2_PROVIDER["SCOPES"], where a narrowing would silently drop the scope.if RequiredGatewayScope not in (access_token.scope or "").split():- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="scope_missing").inc()- raise AuthenticationFailed("Access token lacks the gateway scope.")+ refuse("scope_missing", AuthenticationFailed("Access token lacks the gateway scope."), user=user)scoped_team_ids = access_token.scoped_teams or []if len(scoped_team_ids) != 1:- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="team_ambiguous").inc()- raise exceptions.ValidationError("Access token must be scoped to exactly one team.")+ refuse(+ "team_ambiguous",+ exceptions.ValidationError("Access token must be scoped to exactly one team."),+ user=user,+ )team = Team.objects.select_related("organization").filter(id=scoped_team_ids[0]).first()if team is None:- # Deliberately 403: a 404 would read as "not rolled out" and downgrade- # the run to legacy, but a vanished team is an authorization failure.- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="team_missing").inc()- raise exceptions.PermissionDenied(ERROR_PROJECT_NOT_FOUND)+ # 403: a vanished team is an authorization failure, not a missing route.+ refuse("team_missing", exceptions.PermissionDenied(ERROR_PROJECT_NOT_FOUND), user=user)# scoped_teams is frozen at consent, so re-check what it cannot see.if not oauth_credential_authorized(access_token, team):- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="unauthorized").inc()- raise exceptions.PermissionDenied("Access token is no longer authorized for this project.")+ refuse(+ "unauthorized",+ exceptions.PermissionDenied("Access token is no longer authorized for this project."),+ user=user,+ )distinct_id = str(user.distinct_id)if wizard_identity_blocked(@@ -520,29 +574,37 @@ class SetupWizardViewSet(viewsets.ViewSet):team_ids=[team.id],surface="gateway_token",):- # 403 and not 404, ahead of the rollout gate: the CLI reads 404 as "stay- # on legacy", moving a banned run onto the looser surface.- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="blocked").inc()- raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)+ # Ahead of the rollout gate, so a ban reads as a ban whatever the flag says.+ refuse("blocked", exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL), user=user)- if not posthoganalytics.feature_enabled(- "wizard-gateway-v2",- distinct_id,- groups={"organization": str(team.organization_id), "project": str(team.id)},- group_properties={"organization": {"id": str(team.organization_id)}},- only_evaluate_locally=False,- send_feature_flag_events=False,- ):- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="not_rolled_out").inc()- raise exceptions.NotFound("Wizard gateway tokens are not rolled out for this organization.")+ # A kill switch, not a rollout gate: only a literal False refuses. With the+ # legacy product off there is no second path, so reading an outage as "not+ # rolled out" turns a flag-service blip into a global wizard outage.+ try:+ rolled_out = posthoganalytics.feature_enabled(+ "wizard-gateway-v2",+ distinct_id,+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ except Exception as e:+ logger.warning("wizard_gateway_token: rollout flag unavailable, minting", error=str(e))+ rolled_out = None+ else:+ if rolled_out is None:+ logger.warning("wizard_gateway_token: rollout flag returned no verdict, minting")+ if rolled_out is False:+ refuse_absent_gateway(+ "not_rolled_out", "Wizard gateway tokens are switched off for this organization.", user=user+ )- # Refusing keeps every pinned node one that carries a budget.- product = wizard_product_node(request.data.get("program") if isinstance(request.data, dict) else None)+ # A closed set: refusing keeps every pinned node one that carries a budget.if product is None:- # 404 and not 400: the CLI falls back only on 404, so an unlisted- # program keeps running on legacy instead of dying. It still cannot mint.- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="program_unknown").inc()- raise exceptions.NotFound("Unrecognized wizard program.")+ refuse_absent_gateway(+ "program_unknown", "Unrecognized wizard program. Upgrade with: npx @posthog/wizard@latest", user=user+ )override = wizard_limit_override(distinct_id=distinct_id,email=user.email,@@ -551,11 +613,10 @@ class SetupWizardViewSet(viewsets.ViewSet):)try:reserved = reserve_wizard_mint(request, self, limit=override.mints_per_day)- except exceptions.Throttled:+ except exceptions.Throttled as e:# The reservation raises after check_throttles ran, so the throttled()# hook never sees it.- WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="throttled").inc()- raise+ refuse("throttled", e, user=user)try:minted = mint_wizard_gateway_token(obo=str(team.organization_id), user=distinct_id, product=product, cap_usd=override.cap_usddiff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 0f616ee94a52..5a1af0d0e525 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -13,7 +13,7 @@ from django.utils import timezonefrom prometheus_client import REGISTRYfrom rest_framework import status-from rest_framework.exceptions import Throttled+from rest_framework.exceptions import AuthenticationFailed, Throttledfrom rest_framework.request import Requestfrom rest_framework.test import APIRequestFactory@@ -772,9 +772,22 @@ class SetupWizardGatewayTokenTests(APIBaseTest):return mock_authenticator@override_settings(WIZARD_GATEWAY_MINT_KEY="")- def test_unconfigured_is_404(self):+ def test_unconfigured_is_403_with_a_reason(self):+ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"reads_refusal_reason": True}, headers={"authorization": "Bearer pha_test"}+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert response.json()["code"] == "unconfigured"+ assert response.json()["detail"] == "The PostHog AI gateway is not configured on this instance."++ @override_settings(WIZARD_GATEWAY_MINT_KEY="")+ def test_a_client_that_still_falls_back_keeps_its_404(self):+ # The 404 is what sends a still-falling-back build to the legacy message.response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})- assert response.status_code == status.HTTP_404_NOT_FOUND++ assert response.status_code == status.HTTP_404_NOT_FOUND, response.content+ assert response.json()["code"] == "unconfigured"@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)@@ -803,17 +816,75 @@ class SetupWizardGatewayTokenTests(APIBaseTest):@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=False)@patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")- def test_flag_off_is_404(self, mock_authentication, mock_flag, mock_authorized):+ def test_flag_off_is_403_with_a_reason(self, mock_authentication, mock_flag, mock_authorized):self._mock_oauth(mock_authentication)- response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})- assert response.status_code == status.HTTP_404_NOT_FOUND+ response = self.client.post(+ self.GATEWAY_TOKEN_URL,+ {"program": "integration", "reads_refusal_reason": True},+ headers={"authorization": "Bearer pha_test"},+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert response.json()["code"] == "not_rolled_out"++ legacy = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert legacy.status_code == status.HTTP_404_NOT_FOUND, legacy.content++ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled")+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_a_rollout_flag_outage_mints(self, mock_authentication, mock_flag, mock_mint, mock_authorized):+ # An outage is not a False, and must not end every wizard run.+ self._mock_oauth(mock_authentication)++ for outage in ({"return_value": None}, {"side_effect": RuntimeError("flags down")}):+ mock_flag.reset_mock(return_value=True, side_effect=True)+ mock_flag.configure_mock(**outage)+ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert response.status_code == status.HTTP_201_CREATED, (outage, response.content)++ assert mock_mint.call_count == 2++ @override_settings(DEBUG=False)+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_every_refusal_names_its_outcome_as_the_code(+ self, mock_authentication, mock_flag, mock_mint, mock_authorized+ ):+ self._mock_oauth(mock_authentication, scoped_teams=[self.team.id, self.team.id + 1])+ ambiguous = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert (ambiguous.status_code, ambiguous.json()["code"]) == (status.HTTP_400_BAD_REQUEST, "team_ambiguous")++ self._mock_oauth(mock_authentication)+ for _ in range(5):+ self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ throttled = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert (throttled.status_code, throttled.json()["code"]) == (status.HTTP_429_TOO_MANY_REQUESTS, "throttled")++ mock_authentication.return_value.authenticate.side_effect = AuthenticationFailed("Invalid access token.")+ invalid = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert (invalid.status_code, invalid.json()["code"]) == (status.HTTP_401_UNAUTHORIZED, "invalid_token")@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)@patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)@patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")def test_blocked_identity_is_403_and_never_mints(self, mock_authentication, mock_flag, mock_mint, mock_authorized):- # 403 rather than 404, which the CLI reads as "stay on legacy".self._mock_oauth(mock_authentication)self.mock_blocklist.return_value = True@@ -830,8 +901,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):@patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=False)@patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")def test_a_ban_outranks_the_rollout_gate(self, mock_authentication, mock_flag, mock_mint, mock_authorized):- # Not-rolled-out answers 404 and downgrades to legacy, so the ban has to- # land first whatever the rollout says.+ # A banned account reads "blocked", not "switched off", whatever the flag says.self._mock_oauth(mock_authentication)self.mock_blocklist.return_value = True@@ -1098,9 +1168,33 @@ class SetupWizardGatewayTokenTests(APIBaseTest):def test_unlisted_program_is_refused(self, mock_authentication, mock_flag, mock_authorized, mock_mint):self._mock_oauth(mock_authentication)response = self.client.post(- self.GATEWAY_TOKEN_URL, {"program": "invented"}, headers={"authorization": "Bearer pha_test"}+ self.GATEWAY_TOKEN_URL,+ {"program": "invented", "reads_refusal_reason": True},+ headers={"authorization": "Bearer pha_test"},)- assert response.status_code == status.HTTP_404_NOT_FOUND+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert response.json()["code"] == "program_unknown"+ assert "npx @posthog/wizard@latest" in response.json()["detail"]+ mock_mint.assert_not_called()++ @patch("posthog.api.wizard.http.mint_wizard_gateway_token")+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_a_non_boolean_capability_keeps_the_compatible_status(+ self, mock_authentication, mock_flag, mock_authorized, mock_mint+ ):+ self._mock_oauth(mock_authentication)+ claimed: object+ for claimed in ("false", "true", 1, [], {"a": 1}):+ with self.subTest(claimed=claimed):+ response = self.client.post(+ self.GATEWAY_TOKEN_URL,+ data=json.dumps({"reads_refusal_reason": claimed}),+ content_type="application/json",+ headers={"authorization": "Bearer pha_test"},+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.contentmock_mint.assert_not_called()@patch("posthog.api.wizard.http.mint_wizard_gateway_token")@@ -1109,8 +1203,11 @@ class SetupWizardGatewayTokenTests(APIBaseTest):@patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")def test_missing_program_is_refused(self, mock_authentication, mock_flag, mock_authorized, mock_mint):self._mock_oauth(mock_authentication)- response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})- assert response.status_code == status.HTTP_404_NOT_FOUND+ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"reads_refusal_reason": True}, headers={"authorization": "Bearer pha_test"}+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert response.json()["code"] == "program_unknown"mock_mint.assert_not_called()@patch("posthog.api.wizard.http.mint_wizard_gateway_token")@@ -1125,11 +1222,11 @@ class SetupWizardGatewayTokenTests(APIBaseTest):self._mock_oauth(mock_authentication)response = self.client.post(self.GATEWAY_TOKEN_URL,- data=json.dumps({"program": ["integration"]}),+ data=json.dumps({"program": ["integration"], "reads_refusal_reason": True}),content_type="application/json",headers={"authorization": "Bearer pha_test"},)- assert response.status_code == status.HTTP_404_NOT_FOUND+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.contentmock_mint.assert_not_called()@override_settings(DEBUG=False)diff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pyindex fd0292ae1750..40cc1cbec8d8 100644--- a/posthog/llm/wizard_gateway_token.py+++ b/posthog/llm/wizard_gateway_token.py@@ -130,10 +130,9 @@ def wizard_product_node(program: str | None) -> str | None:folded into a generic node. Gateway budgets match a node value exactly, sofolding would report a new program's spend as plain wizard spend and leave theprogram itself with no budget of its own, and the drift would be silent.- A refusal is visible in the mint outcome counter, and the endpoint answers it- with a 404, the one status the CLI falls back on: a program this deploy has- not been told about keeps running on the legacy gateway rather than having- its run killed, while still being unable to mint.+ A refusal ends the run with an upgrade message and shows in the mint outcome+ counter as `program_unknown`; a new program is registered in the CLI, this+ setting, and a budget row."""# isinstance first: the value is caller JSON, and an unhashable one (a list# or object) raises on the set membership below, inside a throttle that runs@@ -164,7 +163,8 @@ class WizardGatewayMintError(Exception):def wizard_gateway_configured() -> bool:- """Every one of the four is required; any missing piece answers 404.+ """Every one of the four is required; any missing piece refuses every mint+ as `unconfigured`.The program list is a hard requirement, not a refinement: an empty onerefuses every program, so without it the deploy would report itselfdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex ecd782285f28..1cdd5ea8f50d 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1220,8 +1220,8 @@ try:except ValueError:AI_GATEWAY_TEAM_TIER_OVERRIDES = {}-# Wizard gateway-token mint. WIZARD_GATEWAY_MINT_KEY unset disables the endpoint-# (404), which the CLI treats as "stay on the legacy gateway".+# Wizard gateway-token mint. Any of the four unset refuses every mint as+# `unconfigured`, which ends the wizard run: there is no other gateway.WIZARD_GATEWAY_URL = get_from_env("WIZARD_GATEWAY_URL", "")WIZARD_GATEWAY_MINT_KEY = get_from_env("WIZARD_GATEWAY_MINT_KEY", "")# OAuth application client ids allowed to mint: llm_gateway:read is an internal