: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): mint scoped gateway tokens per run (#87269)
Brandon67fd71f82c4e
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex 4c7e3cccaa0d..1befbbd91fd2 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -20,7 +20,7 @@ from openai.types.chat import (from posthoganalytics.ai.gemini import genaifrom posthoganalytics.ai.openai import OpenAIfrom prometheus_client import Counter-from rest_framework import exceptions, response, serializers, viewsets+from rest_framework import exceptions, response, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import AuthenticationFailedfrom rest_framework.permissions import IsAuthenticated@@ -31,14 +31,28 @@ from posthog.api.wizard.utils import json_schema_to_gemini_schemafrom posthog.auth import OAuthAccessTokenAuthentication, SessionAuthenticationfrom posthog.cloud_utils import get_api_hostfrom posthog.exceptions_capture import capture_exception-from posthog.models import User+from posthog.llm.wizard_gateway_token import (+ WizardGatewayMintError,+ mint_wizard_gateway_token,+ wizard_gateway_base_url,+ wizard_gateway_configured,+ wizard_product_node,+)+from posthog.models import Team, Userfrom posthog.models.project import Projectfrom posthog.permissions import APIScopePermissionfrom posthog.rate_limit import (SetupWizardAuthenticationRateThrottle,SetupWizardCloudRunBurstRateThrottle,SetupWizardCloudRunSustainedRateThrottle,+ SetupWizardGatewayTokenRateThrottle,SetupWizardQueryRateThrottle,+ refund_wizard_mint,+ reserve_wizard_mint,+)+from posthog.storage.gateway_credential_cache import (+ GATEWAY_CREDENTIAL_REQUIRED_SCOPE as RequiredGatewayScope,+ oauth_credential_authorized,)from posthog.user_permissions import UserPermissions@@ -61,6 +75,14 @@ OPENAI_SUPPORTED_MODELS = {"o4-mini", "gpt-5-mini", "gpt-5-nano", "gpt-5"}# loop lands on. Only requests that reach creation consume it.WIZARD_CLOUD_RUN_DAILY_ATTEMPT_CAP = 15+WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL = Counter(+ "posthog_wizard_gateway_token_requests_total",+ "Wizard gateway-token mint requests, by outcome (minted/unconfigured/not_wizard_app/"+ "scope_missing/team_ambiguous/team_missing/unauthorized/program_unknown/not_rolled_out/"+ "mint_failed)",+ labelnames=["outcome"],+)+WIZARD_CLOUD_RUN_REQUESTS_TOTAL = Counter("posthog_wizard_cloud_run_requests_total","Cloud-run wizard kickoff requests, by outcome (created/unavailable/invalid/permission_denied/throttled)",@@ -159,10 +181,12 @@ class SetupWizardViewSet(viewsets.ViewSet):return []def throttled(self, request: Request, wait: float) -> NoReturn:- # 429s never reach the action body, so without this the kickoff counter is blind to- # rate-limited users and throttle pressure is invisible in dashboards.+ # A rejection from DRF's own throttle check returns before the action body, so+ # it counts here. A reservation that raises inside a body counts there instead.if self.action == "cloud_run":WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="throttled").inc()+ if self.action == "gateway_token":+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="throttled").inc()super().throttled(request, wait)@action(methods=["POST"], detail=False, url_path="initialize")@@ -385,6 +409,118 @@ class SetupWizardViewSet(viewsets.ViewSet):return Response({"data": response_data})+ @action(+ methods=["POST"],+ detail=False,+ url_path="gateway_token",+ throttle_classes=[SetupWizardGatewayTokenRateThrottle],+ )+ def gateway_token(self, request: Request) -> Response:+ """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.+ """+ if not wizard_gateway_configured():+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="unconfigured").inc()+ raise exceptions.NotFound("Wizard gateway tokens are not available.")++ authenticator = OAuthAccessTokenAuthentication()+ # authenticate() raises its own AuthenticationFailed, so the count wraps the+ # call rather than only the two checks below.+ try:+ result = authenticator.authenticate(request)+ if not result:+ raise AuthenticationFailed("Invalid access token.")+ user, _ = result+ if not user:+ raise AuthenticationFailed("Invalid access token.")+ except AuthenticationFailed:+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="invalid_token").inc()+ raise++ access_token = authenticator.access_token+ # llm_gateway:read is on every sandbox and agent token, so the scope alone+ # cannot identify the wizard.+ 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.")++ # 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.")++ 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.")+ 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)++ # 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.")++ distinct_id = str(user.distinct_id)+ 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.")++ # 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)+ 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.")+ try:+ reserved = reserve_wizard_mint(request, self)+ except exceptions.Throttled:+ # The reservation raises after check_throttles ran, so the throttled()+ # hook never sees it.+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="throttled").inc()+ raise+ try:+ minted = mint_wizard_gateway_token(obo=str(team.organization_id), user=distinct_id, product=product)+ except WizardGatewayMintError as e:+ # An ambiguous failure keeps the slot rather than risk the ceiling.+ if not e.token_may_exist:+ refund_wizard_mint(reserved)+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="mint_failed").inc()+ capture_exception(e, {"ai_product": "wizard", "team_id": team.id})+ return Response({"error": "Gateway token mint failed."}, status=status.HTTP_503_SERVICE_UNAVAILABLE)++ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="minted").inc()+ return Response(+ {+ "token": minted["token"],+ "expires_at": minted["expires_at"],+ "cap_usd": minted.get("cap_usd"),+ "gateway_url": wizard_gateway_base_url(),+ # Keeps a team breakdown beside the org-level obo attribution.+ "team_id": team.id,+ },+ status=status.HTTP_201_CREATED,+ )+@action(methods=["POST"],url_path="authenticate",diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 4f69e5335a74..61ec3b039e6a 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -1,6 +1,7 @@import jsonfrom datetime import timedelta+import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -9,12 +10,18 @@ from django.test import override_settingsfrom django.urls import reversefrom django.utils import timezone+from prometheus_client import REGISTRYfrom rest_framework import status+from rest_framework.exceptions import Throttled+from rest_framework.request import Request+from rest_framework.test import APIRequestFactoryfrom posthog.api.wizard.http import SETUP_WIZARD_CACHE_PREFIX, SETUP_WIZARD_CACHE_TIMEOUTfrom posthog.cloud_utils import get_api_host+from posthog.llm.wizard_gateway_token import WizardGatewayMintErrorfrom posthog.models import Organization, PersonalAPIKey, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.rate_limit import SetupWizardGatewayTokenRateThrottle, refund_wizard_mint, reserve_wizard_mintclass SetupWizardTests(APIBaseTest):@@ -617,3 +624,393 @@ class SetupWizardCloudRunTests(APIBaseTest):def tearDown(self):super().tearDown()cache.clear() # Clears out all DRF throttle data+++class SetupWizardGatewayTokenThrottleTests(APIBaseTest):+ def tearDown(self):+ super().tearDown()+ cache.clear()++ def test_key_ignores_a_caller_supplied_forwarded_for(self):+ from posthog.rate_limit import SetupWizardGatewayTokenRateThrottle++ throttle = SetupWizardGatewayTokenRateThrottle()+ factory = APIRequestFactory()++ first = factory.post("/api/wizard/gateway_token", HTTP_X_FORWARDED_FOR="1.2.3.4")+ second = factory.post("/api/wizard/gateway_token", HTTP_X_FORWARDED_FOR="5.6.7.8, 9.9.9.9")++ # Same untrusted origin, two different forwarded headers: the bucket+ # must not move, or the cap is bypassed by rotating the header.+ assert throttle.get_cache_key(Request(first), None) == throttle.get_cache_key(Request(second), None)++ @patch("posthog.rate_limit.OAuthAccessTokenAuthentication")+ def test_key_follows_the_authenticated_user(self, mock_authentication):+ from posthog.rate_limit import SetupWizardGatewayTokenRateThrottle++ throttle = SetupWizardGatewayTokenRateThrottle()+ factory = APIRequestFactory()+ mock_authentication.return_value.authenticate.return_value = (self.user, None)++ keyed = throttle.get_cache_key(Request(factory.post("/api/wizard/gateway_token")), None)+ mock_authentication.return_value.authenticate.return_value = None+ anonymous = throttle.get_cache_key(Request(factory.post("/api/wizard/gateway_token")), None)++ assert keyed != anonymous+++@override_settings(+ WIZARD_GATEWAY_MINT_KEY="phs_wizard_mint",+ WIZARD_GATEWAY_URL="https://ai-gateway.us.posthog.com",+ WIZARD_GATEWAY_CLIENT_IDS=["wizard-client-id"],+ WIZARD_GATEWAY_PROGRAM_IDS=["integration"],+)+class SetupWizardGatewayTokenTests(APIBaseTest):+ GATEWAY_TOKEN_URL = "/api/wizard/gateway_token"++ MINTED = {"token": "phe_test_token", "expires_at": "2026-08-22T00:00:00Z", "cap_usd": "50"}++ def tearDown(self):+ super().tearDown()+ cache.clear() # Clears out all DRF throttle data++ def _mock_oauth(self, mock_authentication, scope=None, scoped_teams=None, client_id="wizard-client-id"):+ mock_authenticator = mock_authentication.return_value+ mock_authenticator.authenticate.return_value = (self.user, None)+ mock_authenticator.access_token.scope = "llm_gateway:read" if scope is None else scope+ mock_authenticator.access_token.scoped_teams = scoped_teams if scoped_teams is not None else [self.team.id]+ mock_authenticator.access_token.application.client_id = client_id+ return mock_authenticator++ @override_settings(WIZARD_GATEWAY_MINT_KEY="")+ def test_unconfigured_is_404(self):+ response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})+ assert response.status_code == status.HTTP_404_NOT_FOUND++ @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_mints_for_scoped_oauth_token(self, mock_authentication, mock_flag, mock_mint, mock_authorized):+ self._mock_oauth(mock_authentication)++ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert response.status_code == status.HTTP_201_CREATED, response.content+ body = response.json()+ assert body["token"] == "phe_test_token"+ assert body["expires_at"] == self.MINTED["expires_at"]+ assert body["gateway_url"] == "https://ai-gateway.us.posthog.com"+ assert body["team_id"] == self.team.id+ assert mock_mint.call_args.kwargs == {+ "obo": str(self.team.organization_id),+ "user": str(self.user.distinct_id),+ "product": "wizard:integration",+ }++ @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):+ 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++ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_missing_gateway_scope_is_401(self, mock_authentication):+ # "*" must not subsume the privileged scope.+ self._mock_oauth(mock_authentication, scope="*")+ response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})+ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_token_from_another_application_is_401(self, mock_authentication, mock_authorized):+ self._mock_oauth(mock_authentication, client_id="sandbox-client-id")+ response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})+ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=False)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_revoked_project_access_is_403(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_403_FORBIDDEN++ def test_unauthenticated_request_is_rejected(self):+ # No authenticator mock: the real one must refuse a request with no+ # bearer, on a viewset whose permission_classes is empty.+ self.client.logout()+ response = self.client.post(self.GATEWAY_TOKEN_URL)+ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ def test_session_cookie_alone_is_rejected(self):+ # APIBaseTest leaves a logged-in session; it must not authorize a mint.+ response = self.client.post(self.GATEWAY_TOKEN_URL)+ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_multi_team_scope_is_400(self, mock_authentication):+ self._mock_oauth(mock_authentication, scoped_teams=[self.team.id, self.team.id + 1])+ response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ @patch(+ "posthog.api.wizard.http.mint_wizard_gateway_token",+ side_effect=WizardGatewayMintError("refused"),+ )+ @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_mint_failure_is_503(self, mock_authentication, mock_flag, mock_mint, mock_authorized):+ self._mock_oauth(mock_authentication)+ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE++ def _reserved_counter_value(self, key="refund-test-key"):+ """The live value of the reservation counter for a pinned cache key."""+ import time++ from django.core.cache import cache as django_cache++ from posthog.rate_limit import SetupWizardGatewayTokenRateThrottle++ window = int(time.time()) // SetupWizardGatewayTokenRateThrottle().duration+ return django_cache.get(f"{key}:{window}")++ @patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="refund-test-key")+ @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_failure_that_issued_no_token_returns_the_slot(+ self, mock_authentication, mock_flag, mock_authorized, mock_key+ ):+ # Nothing below the helper's unit tests covers deleting or inverting this.+ self._mock_oauth(mock_authentication)+ with patch(+ "posthog.api.wizard.http.mint_wizard_gateway_token",+ side_effect=WizardGatewayMintError("refused", token_may_exist=False),+ ):+ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE+ assert self._reserved_counter_value() == 0++ @override_settings(DEBUG=False)+ @patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="refund-test-key")+ @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_induced_failures_cannot_buy_extra_tokens(self, mock_authentication, mock_flag, mock_authorized, mock_key):+ """The counter must equal the tokens actually issued, however many failures ran.++ The refund exists so an outage does not burn a user's quota, which invites+ the mirror question: induce failures on purpose and keep the slot each time.+ That is only safe while a refund is impossible on any path that hands back a+ token, so the ceiling has to bind on issued tokens rather than on attempts.+ """+ self._mock_oauth(mock_authentication)++ with patch(+ "posthog.api.wizard.http.mint_wizard_gateway_token",+ side_effect=WizardGatewayMintError("unreachable", token_may_exist=False),+ ):+ for _ in range(20):+ failed = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert failed.status_code == status.HTTP_503_SERVICE_UNAVAILABLE++ assert self._reserved_counter_value() == 0++ with patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=self.MINTED) as mock_mint:+ for _ in range(5):+ ok = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert ok.status_code == status.HTTP_201_CREATED+ # The ceiling counts issued tokens, so the 20 refunded failures bought+ # nothing: the sixth mint is refused even though 25 requests preceded it.+ refused = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert refused.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert mock_mint.call_count == 5+ assert self._reserved_counter_value() == 6++ @patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="refund-test-key")+ @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_failure_that_may_have_issued_a_token_keeps_the_slot(+ self, mock_authentication, mock_flag, mock_authorized, mock_key+ ):+ # The paired negative: the gateway may hold this token.+ self._mock_oauth(mock_authentication)+ with patch(+ "posthog.api.wizard.http.mint_wizard_gateway_token",+ side_effect=WizardGatewayMintError("unreadable", token_may_exist=True),+ ):+ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE+ assert self._reserved_counter_value() == 1++ @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_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"}+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND+ 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_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+ 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_string_program_is_refused_not_a_500(+ self, mock_authentication, mock_flag, mock_authorized, mock_mint+ ):+ # An unhashable value raises on the set membership, inside a throttle that+ # runs before authentication.+ self._mock_oauth(mock_authentication)+ response = self.client.post(+ self.GATEWAY_TOKEN_URL,+ data=json.dumps({"program": ["integration"]}),+ content_type="application/json",+ headers={"authorization": "Bearer pha_test"},+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND+ mock_mint.assert_not_called()++ @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_a_throttled_mint_is_counted(self, mock_authentication, mock_flag, mock_mint, mock_authorized):+ self._mock_oauth(mock_authentication)+ before = _gateway_token_outcome("throttled")++ for _ in range(5):+ self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert _gateway_token_outcome("throttled") == before + 1++ def test_an_unresolvable_bearer_is_counted(self):+ before = _gateway_token_outcome("invalid_token")++ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_unknown"}+ )++ assert response.status_code == status.HTTP_401_UNAUTHORIZED+ assert _gateway_token_outcome("invalid_token") == before + 1+++def _gateway_token_outcome(outcome: str) -> float:+ """Current value of one outcome counter. An unrecorded label reads as zero."""+ return REGISTRY.get_sample_value("posthog_wizard_gateway_token_requests_total", {"outcome": outcome}) or 0.0+++class TestReserveWizardMint:+ """The ceiling is atomic and sits on the mint, not on arrival."""++ @pytest.fixture(autouse=True)+ def _settings(self):+ with override_settings(WIZARD_GATEWAY_PROGRAM_IDS=["integration"], DEBUG=False):+ yield++ def _request(self):+ factory = APIRequestFactory()+ return Request(factory.post("/api/wizard/gateway_token", {"program": "integration"}))++ def test_the_sixth_reservation_in_a_window_is_refused(self):+ from django.core.cache import cache as django_cache++ django_cache.clear()+ req = self._request()+ with patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="k"):+ for _ in range(5):+ reserve_wizard_mint(req, None)+ with pytest.raises(Throttled):+ reserve_wizard_mint(req, None)++ def test_the_reservation_returns_the_counter_it_charged(self):+ from django.core.cache import cache as django_cache++ django_cache.clear()+ req = self._request()+ with patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="k"):+ counter = reserve_wizard_mint(req, None)+ assert counter is not None+ assert counter.startswith("k:")+ assert django_cache.get(counter) == 1++ def test_a_refund_returns_the_slot_to_that_counter(self):+ from django.core.cache import cache as django_cache++ django_cache.clear()+ req = self._request()+ with patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="k"):+ counter = reserve_wizard_mint(req, None)+ refund_wizard_mint(counter)+ # The refunded slot is spendable again rather than merely not charged.+ for _ in range(5):+ reserve_wizard_mint(req, None)+ with pytest.raises(Throttled):+ reserve_wizard_mint(req, None)++ def test_a_vanished_key_is_re_established_so_its_counter_is_refundable(self):+ from django.core.cache import cache as django_cache++ django_cache.clear()+ req = self._request()+ with patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="k"):+ with patch("posthog.rate_limit.cache.incr", side_effect=ValueError("no key")):+ counter = reserve_wizard_mint(req, None)++ assert counter is not None+ assert django_cache.get(counter) == 1+ refund_wizard_mint(counter)+ assert django_cache.get(counter) == 0++ def test_a_refund_without_a_counter_is_a_no_op(self):+ refund_wizard_mint(None)++ def test_a_cache_failure_fails_open(self):+ # Load-shedding posture: the per-token cap and the wallet also bound this,+ # and a Redis blip must not turn a minted token into a 500.+ req = self._request()+ with patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", side_effect=RuntimeError("redis down")):+ reserve_wizard_mint(req, None)diff --git a/posthog/llm/test_wizard_gateway_token.py b/posthog/llm/test_wizard_gateway_token.pynew file mode 100644index 000000000000..d0aa5caae103--- /dev/null+++ b/posthog/llm/test_wizard_gateway_token.py@@ -0,0 +1,251 @@+import pytest+from unittest.mock import patch++from django.test import override_settings++import requests++from posthog.llm.wizard_gateway_token import (+ WizardGatewayMintError,+ mint_wizard_gateway_token,+ wizard_gateway_base_url,+ wizard_gateway_configured,+ wizard_product_node,+)++MINT_SETTINGS = {+ "WIZARD_GATEWAY_URL": "https://ai-gateway.us.posthog.com",+ "WIZARD_GATEWAY_MINT_KEY": "phs_wizard_secret",+ "WIZARD_GATEWAY_CLIENT_IDS": ["wizard-client-id"],+ # Not _DEFAULT_CAP_USD: equal values make the honored-setting and fell-back+ # assertions indistinguishable.+ "WIZARD_GATEWAY_TOKEN_CAP_USD": "25",+ "WIZARD_GATEWAY_TOKEN_TTL_SECONDS": 86400,+ "WIZARD_GATEWAY_PROGRAM_IDS": ["integration"],+}+++class _Response:+ def __init__(self, status_code: int, payload=None, raise_on_json=False):+ self.status_code = status_code+ self._payload = payload+ self._raise_on_json = raise_on_json+ self.text = "body"++ def json(self):+ if self._raise_on_json:+ raise ValueError("not json")+ return self._payload+++class TestMintWizardGatewayToken:+ @pytest.fixture(autouse=True)+ def _mint_settings(self):+ with override_settings(**MINT_SETTINGS):+ yield++ def test_posts_pinned_attribution_and_bearer(self):+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z", "cap_usd": "25"}+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post:+ assert mint_wizard_gateway_token(obo="org_1", user="user_1") == minted++ assert post.call_args[0][0] == "https://ai-gateway.us.posthog.com/v1/tokens"+ assert post.call_args.kwargs["json"] == {+ "cap_usd": "25.000000",+ "ttl_seconds": 86400,+ "product": "wizard",+ "obo": "org_1",+ "user": "user_1",+ }+ assert post.call_args.kwargs["headers"] == {"Authorization": "Bearer phs_wizard_secret"}+ assert post.call_args.kwargs["timeout"] > 0++ @override_settings(WIZARD_GATEWAY_URL="https://ai-gateway.us.posthog.com/v1/")+ def test_version_suffixed_setting_does_not_double_up(self):+ # The setting may carry /v1; both the mint path and the base handed to the+ # CLI must come out the same regardless.+ assert wizard_gateway_base_url() == "https://ai-gateway.us.posthog.com"+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z"}+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert post.call_args[0][0] == "https://ai-gateway.us.posthog.com/v1/tokens"++ @override_settings(WIZARD_GATEWAY_TOKEN_TTL_SECONDS=172800)+ def test_ttl_clamped_to_gateway_ceiling(self):+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z"}+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert post.call_args.kwargs["json"]["ttl_seconds"] == 86400++ @override_settings(WIZARD_GATEWAY_TOKEN_TTL_SECONDS=5)+ def test_ttl_clamped_to_a_ttl_that_outlives_a_run(self):+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z"}+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert post.call_args.kwargs["json"]["ttl_seconds"] == 3600++ @pytest.mark.parametrize(+ "response",+ [+ _Response(429),+ _Response(500),+ _Response(200, {"token": "phe_x", "expires_at": "z"}), # only 201 is a mint+ ],+ )+ def test_non_201_raises(self, response):+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=response):+ with pytest.raises(WizardGatewayMintError):+ mint_wizard_gateway_token(obo="org_1", user="user_1")++ def test_transport_failure_raises(self):+ with patch(+ "posthog.llm.wizard_gateway_token.requests.post",+ side_effect=requests.RequestException("connection reset"),+ ):+ with pytest.raises(WizardGatewayMintError):+ mint_wizard_gateway_token(obo="org_1", user="user_1")++ def test_non_json_body_raises(self):+ with patch(+ "posthog.llm.wizard_gateway_token.requests.post",+ return_value=_Response(201, raise_on_json=True),+ ):+ with pytest.raises(WizardGatewayMintError):+ mint_wizard_gateway_token(obo="org_1", user="user_1")++ @pytest.mark.parametrize(+ "payload",+ [+ {"expires_at": "2026-08-22T00:00:00Z"}, # no token+ {"token": "phe_x"}, # no expiry, so the CLI cannot refresh+ [], # not an object+ ],+ )+ def test_incomplete_payload_raises(self, payload):+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, payload)):+ with pytest.raises(WizardGatewayMintError):+ mint_wizard_gateway_token(obo="org_1", user="user_1")++ @pytest.mark.parametrize(+ "configured",+ [+ "not a number",+ "0",+ "-5",+ "20000",+ # Reaches the quantize guard: the result needs more digits than the+ # decimal context allows, so quantize raises rather than returning.+ "1e100000",+ # Parse as Decimals but are not finite, so the is_finite branch is the+ # only thing between them and the gateway.+ "NaN",+ "Infinity",+ "",+ # Positive but under a microdollar: it quantizes to 0.000000, which+ # the gateway rejects as non-positive.+ "0.0000001",+ ],+ )+ def test_out_of_contract_cap_falls_back_to_the_default(self, configured):+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z"}+ with override_settings(WIZARD_GATEWAY_TOKEN_CAP_USD=configured):+ with patch(+ "posthog.llm.wizard_gateway_token.requests.post",+ return_value=_Response(201, minted),+ ) as post:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert post.call_args.kwargs["json"]["cap_usd"] == "20.000000"++ @pytest.mark.parametrize(+ "raised,token_may_exist",+ [+ # Never reached the gateway, so nothing was issued.+ (requests.exceptions.ConnectionError("refused"), False),+ (requests.exceptions.ConnectTimeout("connect timed out"), False),+ # The request may have landed; the gateway could hold a token.+ (requests.exceptions.ReadTimeout("read timed out"), True),+ ],+ )+ def test_transport_failures_report_whether_a_token_may_exist(self, raised, token_may_exist):+ with patch("posthog.llm.wizard_gateway_token.requests.post", side_effect=raised):+ with pytest.raises(WizardGatewayMintError) as excinfo:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert excinfo.value.token_may_exist is token_may_exist++ def test_a_refusal_reports_that_no_token_exists(self):+ with patch(+ "posthog.llm.wizard_gateway_token.requests.post",+ return_value=_Response(400, {"error": "bad request"}),+ ):+ with pytest.raises(WizardGatewayMintError) as excinfo:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert excinfo.value.token_may_exist is False++ def test_an_unreadable_201_reports_that_a_token_may_exist(self):+ # The gateway said it minted; we just could not read it back. Refunding the+ # slot here would let the ceiling be exceeded by a token that is live.+ with patch(+ "posthog.llm.wizard_gateway_token.requests.post",+ return_value=_Response(201, {"not": "a token"}),+ ):+ with pytest.raises(WizardGatewayMintError) as excinfo:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert excinfo.value.token_may_exist is True++ @override_settings(WIZARD_GATEWAY_TOKEN_CAP_USD="12.5")+ def test_in_contract_cap_is_sent_as_fixed_point(self):+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z"}+ with patch(+ "posthog.llm.wizard_gateway_token.requests.post",+ return_value=_Response(201, minted),+ ) as post:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert post.call_args.kwargs["json"]["cap_usd"] == "12.500000"++ def test_secret_never_appears_in_the_error(self):+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(403)):+ with pytest.raises(WizardGatewayMintError) as raised:+ mint_wizard_gateway_token(obo="org_1", user="user_1")+ assert "phs_wizard_secret" not in str(raised.value)+++class TestWizardGatewayConfigured:+ def test_all_four_present(self):+ with override_settings(**MINT_SETTINGS):+ assert wizard_gateway_configured() is True++ @pytest.mark.parametrize(+ "missing",+ [+ "WIZARD_GATEWAY_URL",+ "WIZARD_GATEWAY_MINT_KEY",+ "WIZARD_GATEWAY_CLIENT_IDS",+ # An empty program list refuses every program, so leaving it out is an+ # unconfigured deploy, not a fleet of callers sending bad names.+ "WIZARD_GATEWAY_PROGRAM_IDS",+ ],+ )+ def test_any_missing_piece_disables(self, missing):+ blank: dict = {+ **MINT_SETTINGS,+ missing: [] if missing in ("WIZARD_GATEWAY_CLIENT_IDS", "WIZARD_GATEWAY_PROGRAM_IDS") else "",+ }+ with override_settings(**blank):+ assert wizard_gateway_configured() is False+++class TestWizardProductNode:+ @override_settings(WIZARD_GATEWAY_PROGRAM_IDS=["integration", "audit"])+ def test_a_configured_program_gets_its_own_node(self):+ assert wizard_product_node("audit") == "wizard:audit"++ @override_settings(WIZARD_GATEWAY_PROGRAM_IDS=["integration"])+ def test_an_unknown_program_is_refused(self):+ assert wizard_product_node("../../etc") is None+ assert wizard_product_node("not-a-program") is None+ assert wizard_product_node("") is None+ assert wizard_product_node(None) is None++ @override_settings(WIZARD_GATEWAY_PROGRAM_IDS=[])+ def test_no_configured_programs_refuses_every_program(self):+ assert wizard_product_node("audit") is Nonediff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pynew file mode 100644index 000000000000..7580259f0c94--- /dev/null+++ b/posthog/llm/wizard_gateway_token.py@@ -0,0 +1,199 @@+"""Mint a wizard-run scoped gateway token.++Django mints a `phe_` off the PostHog-owned wizard team's `phs_`+(WIZARD_GATEWAY_MINT_KEY) rather than sending the user's OAuth token to the+gateway. The mint pins what the caller must not control (product=wizard, obo=the+customer organization, the acting user) plus a per-run cap and an expiry, and the+debit lands on the wizard team, never the customer's wallet. Kept separate from+products/tasks' sandbox mint (ai_gateway_token.py): the wizard needs+`expires_at` back for CLI-side refresh, and an interactive mint answers one+attempt fast instead of retrying into the CLI's timeout.+"""++from decimal import Decimal, InvalidOperation+from typing import Any++from django.conf import settings++import requests+import structlog+from prometheus_client import Counter++logger = structlog.get_logger(__name__)++_MINT_TIMEOUT_SECONDS = 10++# The gateway refuses a TTL outside these bounds with a 400, so clamp locally: a+# misconfigured setting should not turn every mint into a 503.+# Far above the gateway's own 60s floor: a run's holders capture the bearer once+# and cannot re-resolve, so a token must outlive the whole run. Clamping to that+# floor would turn a misconfigured knob into mid-run 401s.+_MIN_TTL_SECONDS = 3600+_MAX_TTL_SECONDS = 86400++# The gateway 400s a cap that is non-positive, over 6dp, or above its top-up+# ceiling, so a bad knob falls back locally instead of 503ing every mint.+_DEFAULT_CAP_USD = Decimal("20")+_MAX_CAP_USD = Decimal("10000")+_CAP_QUANTUM = Decimal("0.000001")++WIZARD_PRODUCT = "wizard"+++def wizard_product_node(program: str | None) -> str | None:+ """The product node to pin for a run, or None when this is not a program+ Django knows.++ The setting is authoritative: an unrecognized program is refused rather than+ folded into a generic node. Gateway budgets match a node value exactly, so+ folding would report a new program's spend as plain wizard spend and leave the+ program 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.+ """+ # 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+ # before authentication.+ if isinstance(program, str) and program in set(settings.WIZARD_GATEWAY_PROGRAM_IDS):+ return f"{WIZARD_PRODUCT}:{program}"+ return None+++WIZARD_GATEWAY_MINTS = Counter(+ "posthog_wizard_gateway_token_mints_total",+ "Wizard gateway token mints, by outcome (ok/refused/unreachable/malformed)",+ labelnames=["outcome"],+)+++class WizardGatewayMintError(Exception):+ """The gateway refused or failed the mint; the caller answers 503.++ token_may_exist is False only when the failure proves no token was issued,+ so the caller can return the daily mint slot. It defaults True: refunding a+ slot for a token the gateway did mint would let the ceiling be exceeded.+ """++ def __init__(self, message: str, *, token_may_exist: bool = True) -> None:+ super().__init__(message)+ self.token_may_exist = token_may_exist+++def wizard_gateway_configured() -> bool:+ """Every one of the four is required; any missing piece answers 404.++ The program list is a hard requirement, not a refinement: an empty one+ refuses every program, so without it the deploy would report itself+ configured and 400 every request as though the callers were at fault.+ """+ return bool(+ settings.WIZARD_GATEWAY_MINT_KEY+ and settings.WIZARD_GATEWAY_URL+ and settings.WIZARD_GATEWAY_CLIENT_IDS+ and settings.WIZARD_GATEWAY_PROGRAM_IDS+ )+++def wizard_gateway_base_url() -> str:+ """The gateway base without the version segment. The CLI gets the same string,+ so both sides read one normalization of the setting."""+ return settings.WIZARD_GATEWAY_URL.rstrip("/").removesuffix("/v1")+++def mint_wizard_gateway_token(*, obo: str, user: str, product: str = WIZARD_PRODUCT) -> dict[str, Any]:+ """Mint one run's token; returns {token, expires_at, cap_usd}. Raises+ WizardGatewayMintError on any refusal or transport failure; the bearer never+ appears in logs or exception text.+ """+ base_url = wizard_gateway_base_url()+ body = {+ "cap_usd": _cap_usd(),+ "ttl_seconds": _ttl_seconds(),+ "product": product,+ "obo": obo,+ "user": user,+ }+ try:+ response = requests.post(+ f"{base_url}/v1/tokens",+ json=body,+ headers={"Authorization": f"Bearer {settings.WIZARD_GATEWAY_MINT_KEY}"},+ timeout=_MINT_TIMEOUT_SECONDS,+ )+ except requests.RequestException as e:+ WIZARD_GATEWAY_MINTS.labels(outcome="unreachable").inc()+ logger.warning("wizard_gateway_token: mint transport failure", error=str(e))+ # Only a failure after the request was transmitted can leave a token behind.+ # URL and schema errors raise before any byte is sent, and a connect-level+ # failure never established the session; ConnectTimeout subclasses+ # ConnectionError, while a ReadTimeout's request may have landed.+ #+ # Not a clean split: requests re-raises a body-phase read timeout as+ # ConnectionError, so that case refunds despite the request landing. The+ # token it may leave behind is never delivered, and a cap is a ceiling+ # rather than a reservation, so an unheld token spends nothing.+ never_sent = isinstance(+ e,+ (+ requests.exceptions.ConnectionError,+ requests.exceptions.URLRequired,+ requests.exceptions.MissingSchema,+ requests.exceptions.InvalidSchema,+ requests.exceptions.InvalidURL,+ ),+ )+ raise WizardGatewayMintError("gateway unreachable", token_may_exist=not never_sent) from e++ if response.status_code != 201:+ WIZARD_GATEWAY_MINTS.labels(outcome="refused").inc()+ logger.warning("wizard_gateway_token: mint refused", status=response.status_code)+ # The gateway answered and refused, so no token was issued.+ raise WizardGatewayMintError(f"mint refused with HTTP {response.status_code}", token_may_exist=False)+ try:+ minted = response.json()+ except ValueError as e:+ WIZARD_GATEWAY_MINTS.labels(outcome="malformed").inc()+ raise WizardGatewayMintError("mint response was not JSON") from e+ if not isinstance(minted, dict) or not minted.get("token") or not minted.get("expires_at"):+ WIZARD_GATEWAY_MINTS.labels(outcome="malformed").inc()+ raise WizardGatewayMintError("mint response missing token or expires_at")+ WIZARD_GATEWAY_MINTS.labels(outcome="ok").inc()+ return {+ "token": minted["token"],+ "expires_at": minted["expires_at"],+ "cap_usd": minted.get("cap_usd"),+ }+++def _ttl_seconds() -> int:+ """The requested token lifetime, clamped to the gateway's mint bounds."""+ return max(_MIN_TTL_SECONDS, min(int(settings.WIZARD_GATEWAY_TOKEN_TTL_SECONDS), _MAX_TTL_SECONDS))+++def _cap_usd() -> str:+ """The per-token cap as a fixed-point string the gateway accepts. An+ unparseable, non-positive, or over-ceiling setting falls back to the default+ rather than making every mint a 503.+ """+ raw = str(settings.WIZARD_GATEWAY_TOKEN_CAP_USD)+ try:+ cap = Decimal(raw)+ except (InvalidOperation, ValueError):+ logger.warning("wizard_gateway_token: cap_usd is not a decimal, using the default", cap=raw)+ cap = _DEFAULT_CAP_USD+ # Quantize before the range check: a positive value below a microdollar+ # rounds to 0.000000, which the gateway rejects as non-positive. Guarded+ # because quantize raises once the result needs more digits than the decimal+ # context allows, and this function's contract is to fall back, never raise.+ if cap.is_finite():+ try:+ cap = cap.quantize(_CAP_QUANTUM)+ except InvalidOperation:+ logger.warning("wizard_gateway_token: cap_usd is out of representable range, using the default", cap=raw)+ cap = _DEFAULT_CAP_USD.quantize(_CAP_QUANTUM)+ if not cap.is_finite() or cap <= 0 or cap > _MAX_CAP_USD:+ logger.warning("wizard_gateway_token: cap_usd out of range, using the default", cap=raw)+ cap = _DEFAULT_CAP_USD.quantize(_CAP_QUANTUM)+ return f"{cap:f}"diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 916810b924dd..5f2069c7da46 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -9,10 +9,12 @@ from functools import lru_cachefrom typing import TYPE_CHECKINGfrom django.conf import settings+from django.core.cache import cachefrom django.urls import resolvefrom django.utils import timezonefrom prometheus_client import Counter+from rest_framework import exceptionsfrom rest_framework.throttling import SimpleRateThrottle, UserRateThrottlefrom statshog.defaults.django import statsd@@ -22,15 +24,16 @@ if TYPE_CHECKING:from rest_framework.request import Requestfrom rest_framework.views import APIView-from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthenticationfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exception+from posthog.llm.wizard_gateway_token import wizard_product_nodefrom posthog.metrics import LABEL_PATH, LABEL_ROUTE, LABEL_TEAM_IDfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.team.team import Teamfrom posthog.models.utils import hash_key_valuefrom posthog.settings.utils import get_list-from posthog.utils import patchable+from posthog.utils import get_trusted_client_ip, patchableRATE_LIMIT_EXCEEDED_COUNTER = Counter("rate_limit_exceeded_total",@@ -1131,6 +1134,126 @@ class SetupWizardQueryRateThrottle(SimpleRateThrottle):return f"throttle_wizard_query_{sha_hash}"+class SetupWizardGatewayTokenRateThrottle(SimpleRateThrottle):+ """Derives the per-user, per-program mint bucket. `reserve_wizard_mint` counts it.++ Its own namespace, so a mint never spends the wizard query allowance.+ """++ # Assigned by SimpleRateThrottle.__init__ from the parsed rate.+ num_requests: int+ duration: int++ scope = "wizard_gateway_token"++ def get_rate(self):+ if settings.DEBUG:+ return "1000/day"+ return "5/day"++ def allow_request(self, request, view):+ """Always admit; the ceiling is the view's atomic reservation.++ A read here and a charge after the mint would sit a whole mint round trip+ apart, so parallel requests would all see the same free slot. This class+ now only derives the identity, and `reserve_wizard_mint` owns the count.+ Errors are swallowed: this is a load-shedding gate, and it must fail open.+ """+ return True++ def get_cache_key(self, request, view):+ """The per-user, per-program bucket identity. Read by the view's reservation."""+ # request.user is anonymous here: the viewset authenticates sessions only and+ # the bearer is checked in the action body, after throttling. get_ident would+ # then key on the caller-chosen X-Forwarded-For, so resolve the token and fall+ # back to the trusted proxy chain's client IP.+ ident = None+ try:+ result = OAuthAccessTokenAuthentication().authenticate(request)+ except Exception:+ # A bad bearer must not become a 500; the action rejects it a moment later.+ result = None+ if result is not None:+ user, _ = result+ if user is not None:+ ident = f"user:{user.pk}"+ if ident is None:+ ident = f"ip:{get_trusted_client_ip(request) or 'unknown'}"+ # Bucket per program, on the resolved node rather than the raw field: keying+ # on what the caller sent would hand out a fresh quota per invented name.+ try:+ program = request.data.get("program") if isinstance(request.data, dict) else None+ except Exception:+ program = None+ # One shared bucket for anything unrecognized: a per-name bucket would hand+ # out a fresh quota for every invented program, even though each is refused.+ ident = f"{ident}|{wizard_product_node(program) or 'unknown-program'}"+ # nosemgrep: python.flask.security.audit.directly-returned-format-string.directly-returned-format-string+ return f"throttle_wizard_gateway_token_{hashlib.sha256(ident.encode()).hexdigest()}"+++def reserve_wizard_mint(request, view) -> str | None:+ """Atomically consume one of this user's daily mints for this program, or raise.++ Called immediately before the mint, after every gate, so a request refused by a+ gate spends nothing, while parallel requests cannot all slip under the ceiling+ the way a read-then-charge throttle lets them. A mint that then fails keeps its+ slot unless the failure proves no token was issued; see refund_wizard_mint.++ Returns the counter it charged so the refund targets that exact key. Recomputing+ the window at refund time would decrement the next day's counter for a request+ spanning 00:00 UTC, handing out a free slot.++ Fails open on a cache error: this bounds spend that the per-token cap and the+ wallet also bound, and a Redis blip must not turn a minted token into a 500.+ """+ throttle = SetupWizardGatewayTokenRateThrottle()+ if throttle.rate is None:+ return None+ try:+ key = throttle.get_cache_key(request, view)+ if key is None:+ return None+ window = int(time.time()) // throttle.duration+ counter = f"{key}:{window}"+ cache.add(counter, 0, timeout=throttle.duration)+ try:+ count = cache.incr(counter)+ except ValueError:+ # The key vanished between add and incr, so the incr wrote nothing.+ # Persist the charge as the window's first rather than leaving it+ # implicit: the counter this returns is refundable, and a handle for a+ # charge that was never stored would debit a concurrent request's slot.+ cache.set(counter, 1, timeout=throttle.duration)+ count = 1+ except Exception as e:+ capture_exception(e)+ return None+ if count > throttle.num_requests:+ raise exceptions.Throttled(detail="This wizard program has used its daily run limit. Try again tomorrow.")+ return counter+++def refund_wizard_mint(counter: str | None) -> None:+ """Return a reserved mint slot after a failure that issued no token.++ Only for failures that prove the gateway holds nothing: refunding one it did+ mint would let a user exceed the daily ceiling. Swallows cache errors so a+ refund can never turn the 503 the caller is already answering into a 500.+ """+ if counter is None:+ return+ try:+ cache.decr(counter)+ except ValueError:+ # The window that owned the charge is gone, so there is nothing to return.+ pass+ except Exception as e:+ # A lost refund costs the user a slot until the window rolls, and looks+ # identical to a moot one; the sibling reserve reports its errors the same way.+ capture_exception(e)++class SetupWizardCloudRunOutcomeAwareThrottle(UserRateThrottle):"""Counts a user's recent wizard cloud RUNS (not requests), excluding failed and cancelled ones.diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 877735a0f496..4f02ec891b38 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1,5 +1,6 @@# Web app specific settings/middleware/apps setupimport os+import jsonfrom datetime import timedeltaimport structlog@@ -1354,6 +1355,35 @@ AI_GATEWAY_INTERNAL_TOKEN = get_from_env("AI_GATEWAY_INTERNAL_TOKEN", "")AI_GATEWAY_URL = get_from_env("AI_GATEWAY_URL", "")AI_GATEWAY_API_KEY = get_from_env("AI_GATEWAY_API_KEY", "")+# Projected into gateway_credential.json: a JSON team_id -> tier map+# ("free"/"pro"/"enterprise") for the gateway's rate-limit bucket.+# Parsed defensively rather than with type_cast=json.loads: that runs at settings+# import, so a malformed value takes every process down at boot, while the+# consumer is written to degrade to no overrides.+try:+ AI_GATEWAY_TEAM_TIER_OVERRIDES = json.loads(get_from_env("AI_GATEWAY_TEAM_TIER_OVERRIDES", "{}"))+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_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+# scope on every sandbox and agent token, so the scope alone does not identify the+# wizard. Empty refuses every mint, and blanks are filtered because a list of+# empty strings is truthy and would read as configured.+WIZARD_GATEWAY_CLIENT_IDS = [+ client_id for client_id in get_list(get_from_env("WIZARD_GATEWAY_CLIENT_IDS", "")) if client_id+]+WIZARD_GATEWAY_TOKEN_CAP_USD = get_from_env("WIZARD_GATEWAY_TOKEN_CAP_USD", "20")+# Wizard programs that may mint, each getting its own pinned product node and so+# its own per-program budget and mint quota. The list is authoritative: a program+# absent here is refused, not folded into a generic node, so listing a new program+# is required rather than optional. Mirrors the CLI's PROGRAM_REGISTRY.+WIZARD_GATEWAY_PROGRAM_IDS = get_list(get_from_env("WIZARD_GATEWAY_PROGRAM_IDS", ""))+WIZARD_GATEWAY_TOKEN_TTL_SECONDS = get_from_env("WIZARD_GATEWAY_TOKEN_TTL_SECONDS", 86400, type_cast=int)+# Sharing configuration settingsSHARING_TOKEN_GRACE_PERIOD_SECONDS = 60 * 5 # 5 minutesdiff --git a/posthog/storage/gateway_credential_cache.py b/posthog/storage/gateway_credential_cache.pyindex c4ce411a619d..a39f6e789042 100644--- a/posthog/storage/gateway_credential_cache.py+++ b/posthog/storage/gateway_credential_cache.py@@ -5,7 +5,8 @@ One blob per phs_ project secret key / pha_ OAuth token, keyed by the credentialso the secret never sits in a Redis key. Public phc_ project tokens can't dispatch.Key: cache/team_tokens_hashed/<sha256$hex>/team_metadata/gateway_credential.json- Body: {team_id, project_token, scopes, billing_mode, revoked_at, overspend_allowance_usd?}+ Body: {team_id, project_token, scopes, billing_mode, revoked_at,+ overspend_allowance_usd?, tier?}The hash matches Django's hash_key_value(token, mode="sha256") = "sha256$"+hex, which thegateway derives identically. A credential holding llm_gateway:read attributes to its team@@ -69,6 +70,13 @@ GATEWAY_CREDENTIAL_FIELDS = ["revoked_at",]+# Tier (gateway-defined, internal/auth/gateway_credential.go) feeds the+# rate-limit/shed bucket. Settings-driven rather than a Team column: a handful of+# internal teams, and a settings change lands on the hourly reprojection with no+# signal wiring.+TIER_KEY = "tier"+GATEWAY_KNOWN_TIERS = {"free", "pro", "enterprise"}+# Overspend allowance wire contract (gateway-defined, internal/auth/gateway_credential.go):# fixed-point USD string, 6dp, present only when set. Out-of-range/malformed clamps to 0 there,# so we validate at the write surfaces instead of relying on the clamp.@@ -290,9 +298,40 @@ def _policy_for_credential(if allowance is not None:policy[OVERSPEND_ALLOWANCE_KEY] = format_overspend_allowance_usd(allowance)+ # Absent means tier-unknown on the gateway, so ordinary teams' blobs stay+ # byte-identical.+ tier = _team_tier_overrides().get(str(team.id))+ if tier is not None:+ # isinstance first: an unhashable value from the JSON setting would raise on+ # the membership test, inside a projection whose failure expires every blob.+ if isinstance(tier, str) and tier in GATEWAY_KNOWN_TIERS:+ policy[TIER_KEY] = tier+ else:+ # The gateway never sees the value, so this is the only signal a typo gets.+ logger.warning("gateway_credential: unrecognized tier override, not projecting", team_id=team.id, tier=tier)+return policy+def _team_tier_overrides() -> dict[str, str]:+ """Explicit team_id (string) -> tier map for the gateway's rate-limit bucket. A+ non-mapping value degrades to no overrides rather than failing the projection.+ """+ raw = getattr(settings, "AI_GATEWAY_TEAM_TIER_OVERRIDES", {}) or {}+ if not isinstance(raw, dict):+ logger.warning("gateway_credential: tier overrides setting is not a mapping, ignoring")+ return {}+ return raw+++def oauth_credential_authorized(credential: OAuthAccessToken, team: Any) -> bool:+ """Whether an OAuth credential is still authorized for team right now: the user+ is active, a member, and still has project access. Callers outside the+ projection need it because a token's scoped_teams is frozen at consent.+ """+ return _oauth_authorization_ok(credential, team, team.id, None)++def _resolve_credential(hash_key: str) -> Credential | None:"""Reverse a cache-key hash back to its credential (Django-side reads only;the gateway never calls Django). ProjectSecretAPIKey.secure_value stores thediff --git a/posthog/storage/test/test_gateway_credential_cache.py b/posthog/storage/test/test_gateway_credential_cache.pyindex 2abb5d3f8735..d0288542a895 100644--- a/posthog/storage/test/test_gateway_credential_cache.py+++ b/posthog/storage/test/test_gateway_credential_cache.py@@ -26,7 +26,9 @@ from posthog.storage.gateway_credential_cache import (GATEWAY_CREDENTIAL_FIELDS,GATEWAY_CREDENTIAL_LAST_USED_KEY,GATEWAY_CREDENTIAL_SECRET_KEY_CACHE_TTL,+ GATEWAY_KNOWN_TIERS,OVERSPEND_ALLOWANCE_KEY,+ TIER_KEY,clear_gateway_credential,credential_hash,drain_gateway_credential_last_used,@@ -196,6 +198,48 @@ class TestGatewayCredentialWireShape(GatewayCredentialTestMixin):self.assertEqual(blob[OVERSPEND_ALLOWANCE_KEY], expected)self.assertIsInstance(blob[OVERSPEND_ALLOWANCE_KEY], str)+ def test_tier_omitted_by_default(self):+ # Absent means tier-unknown on the gateway; ordinary teams' blobs must+ # stay byte-identical to the pre-tier shape.+ credential, _ = self._make_secret_key([GATEWAY_SCOPE])+ project_gateway_credential(credential)+ blob = self._read_blob(credential_hash(credential))+ assert blob is not None+ self.assertNotIn(TIER_KEY, blob)++ def test_tier_projected_for_configured_team(self):+ credential, _ = self._make_secret_key([GATEWAY_SCOPE])+ with override_settings(+ AI_GATEWAY_TEAM_TIER_OVERRIDES={str(self.team.id): "enterprise"},+ ):+ project_gateway_credential(credential)+ blob = self._read_blob(credential_hash(credential))+ assert blob is not None+ self.assertEqual(blob[TIER_KEY], "enterprise")++ def test_unknown_tier_override_not_projected(self):+ # A typo'd tier must not reach the wire; the gateway would degrade it to+ # unknown anyway, but the blob should stay clean.+ credential, _ = self._make_secret_key([GATEWAY_SCOPE])+ with override_settings(AI_GATEWAY_TEAM_TIER_OVERRIDES={str(self.team.id): "platinum"}):+ project_gateway_credential(credential)+ blob = self._read_blob(credential_hash(credential))+ assert blob is not None+ self.assertNotIn(TIER_KEY, blob)++ def test_the_writable_tiers_are_the_gateway_vocabulary_minus_the_sentinel(self):+ # The gateway owns this vocabulary in internal/principal/tiers.go and+ # holds free/pro/enterprise/unknown. "unknown" is its sentinel for a tier+ # it could not resolve, so projecting it would assert a value rather than+ # leave the field absent; the writable set is the rest.+ #+ # Nothing can import across the repositories, so this pins the literal and+ # catches this set drifting on its own. A gateway-side change shows up as+ # gateway.auth.tier_unrecognized.total going nonzero for credential blobs,+ # but not for a tier already stamped into a live scoped-token structure,+ # which degrades to unknown with no signal.+ self.assertEqual(GATEWAY_KNOWN_TIERS, {"free", "pro", "enterprise"})+class TestOverspendAllowanceFormatting(BaseTest):@parameterized.expand(