:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): stop billing reads reporting a valid token as invalid (#101351)
posthog[bot]2f1002ee3933
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex 925ad769cee3..93ce020a1812 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -1513,6 +1513,29 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(mock_get_usage_data.call_args[0][1]["team_ids"], f"[{other_team.pk}]")+ @parameterized.expand(+ [+ ("list", "/api/billing/", "ee.billing.billing_manager.BillingManager.get_billing"),+ ("usage", "/api/billing/usage/", "ee.billing.billing_manager.BillingManager.get_usage_data"),+ ]+ )+ def test_a_billing_read_without_a_current_project_is_denied_rather_than_unauthenticated(+ self, _name: str, path: str, billing_call: str+ ):+ headers = self._oauth_token_headers(["billing:read"])+ self.user.current_team = None+ self.user.save()++ with patch(billing_call) as mock_billing_call:+ response = self.client.get(+ path, {"start_date": "2025-01-01"}, HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"]+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "permission_denied")+ self.assertIn("your account has none", response.json()["detail"])+ mock_billing_call.assert_not_called()+@patch("ee.billing.billing_manager.BillingManager.get_usage_data")def test_get_usage_rejects_other_org_team_ids_for_project_scoped_billing_read(self, mock_get_usage_data):other_org = self.create_organization_with_features([])diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 97aec90346f3..639b3cf63ceb 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -9,7 +9,7 @@ from django.db.models import Modelimport posthoganalyticsfrom loginas.utils import is_impersonated_session-from rest_framework.exceptions import AuthenticationFailed, NotFound, PermissionDenied+from rest_framework.exceptions import NotFound, PermissionDeniedfrom rest_framework.permissions import SAFE_METHODS, BasePermission, IsAdminUserfrom rest_framework.request import Requestfrom rest_framework.views import APIView@@ -1115,7 +1115,13 @@ class AccessControlPermission(ScopeBasePermission):if hasattr(view, "param_derived_from_user_current_team"):if view.param_derived_from_user_current_team in ("team_id", "project_id"):if request.user.current_team_id is None:- raise AuthenticationFailed("This endpoint requires a current project to be set on your account.")+ # Not `AuthenticationFailed`: the credential is valid, the account state is+ # not. A 401 here tells a token caller to replace a key that was never the+ # problem, and clients act on it by refreshing the token and retrying.+ raise PermissionDenied(+ "This endpoint reads the project that is set on your account, and your "+ "account has none. Open PostHog, select a project, then try again."+ )uac = self._get_user_access_control(request, view)scope_object = self._get_scope_object(request, view)diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex 44735d59ff0f..1a8561685976 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -62,6 +62,16 @@ function clampActorsLimit(value: unknown): number {return Math.min(Math.max(Math.trunc(value), 1), ACTORS_MAX_LIMIT)}+/** The `detail` string from a drf-exceptions-hog error body, when the body carries one. */+function parseErrorDetail(errorText: string): string | undefined {+ try {+ const detail = JSON.parse(errorText)?.detail+ return typeof detail === 'string' && detail ? detail : undefined+ } catch {+ return undefined+ }+}+function clampActorsOffset(value: unknown): number {if (typeof value !== 'number' || !Number.isFinite(value)) {return 0@@ -433,6 +443,29 @@ export class ApiClient {})}+ /**+ * PostHog also answers 401 when the token is valid but the account state is not, so the+ * bare sentinel told those callers to reconnect a credential that was never the problem.+ * It stays at the front of the message because the re-auth path matches on it, and the+ * server's reason and the status now ride along.+ */+ private buildUnauthorizedError(+ response: Response,+ errorText: string,+ url: string,+ method: string+ ): PostHogApiError {+ const detail = parseErrorDetail(errorText)+ return new PostHogApiError({+ status: response.status,+ statusText: response.statusText,+ body: errorText,+ url,+ method,+ message: detail ? `${ErrorCode.INVALID_API_KEY}: ${detail}` : ErrorCode.INVALID_API_KEY,+ })+ }+private buildApiError(response: Response, errorText: string, url: string, method: string): Error {if (response.status === 404) {const experimentNotFound = this.buildExperimentNotFoundError(response, errorText, url, method)@@ -442,7 +475,7 @@ export class ApiClient {}if (response.status === 401) {- return new Error(ErrorCode.INVALID_API_KEY)+ return this.buildUnauthorizedError(response, errorText, url, method)}if (response.status === 429) {diff --git a/services/mcp/tests/unit/unauthorized-error-detail.test.ts b/services/mcp/tests/unit/unauthorized-error-detail.test.tsnew file mode 100644index 000000000000..b07d4432173e--- /dev/null+++ b/services/mcp/tests/unit/unauthorized-error-detail.test.ts@@ -0,0 +1,69 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { ApiClient } from '@/api/client'+import { classifyAuthFailure } from '@/lib/auth-errors'+import { ErrorCode, PostHogApiError } from '@/lib/errors'++vi.mock('@/lib/posthog', () => ({+ getPostHogClient: () => ({ captureException: vi.fn() }),+}))++// PostHog answers 401 for account state as well as for a bad credential. The client used to+// collapse every 401 to the bare `INVALID_API_KEY` sentinel, so a caller holding a valid,+// freshly issued token was told to replace it, and the server's own reason never arrived.+describe('401 handling', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.spyOn(console, 'error').mockImplementation(() => {})+ })++ afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ })++ const stub401 = (body: string): void => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(body, { status: 401 })))+ }++ const requestError = async (): Promise<unknown> =>+ await new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })+ .request({ method: 'GET', path: '/api/billing/' })+ .then(+ () => undefined,+ (error: unknown) => error+ )++ it('carries the server reason and the status alongside the sentinel', async () => {+ stub401(+ JSON.stringify({+ type: 'authentication_error',+ code: 'permission_denied',+ detail: 'This endpoint reads the project that is set on your account, and your account has none.',+ })+ )++ const error = await requestError()++ expect(error).toBeInstanceOf(PostHogApiError)+ expect((error as PostHogApiError).status).toBe(401)+ expect((error as Error).message).toContain('your account has none')+ })++ it('still reads as an invalid credential, so the re-auth path keeps firing', async () => {+ stub401(JSON.stringify({ detail: 'Invalid access token.' }))++ const error = await requestError()++ expect((error as Error).message).toContain(ErrorCode.INVALID_API_KEY)+ expect(classifyAuthFailure(error).reason).toBe('invalid_api_key')+ })++ it('falls back to the bare sentinel when the body carries no reason', async () => {+ stub401('')++ const error = await requestError()++ expect((error as Error).message).toBe(ErrorCode.INVALID_API_KEY)+ })+})