Skip to content

: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.

fix(llma): let user:read reach /@me/spend, drop dead personal_spend scope (#59619)

Paul D'Ambra626c883f1452
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 3c442727a0b2..5c3f2f2d9869 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -93,15 +93,6 @@ export const API_SCOPES: APIScope[] = [
},
},
{ key: 'person', objectName: 'Person', objectPlural: 'persons' },
- {
- key: 'personal_spend',
- objectName: 'Personal LLM spend',
- objectPlural: 'personal LLM spend',
- disabledActions: ['write'],
- warnings: {
- read: <>This scope allows you to retrieve your own LLM spend across PostHog products.</>,
- },
- },
{ key: 'persisted_folder', objectName: 'Persisted folder', objectPlural: 'persisted folders' },
{ key: 'customer_profile_config', objectName: 'Customer profile config', objectPlural: 'customer profile configs' },
{ key: 'plugin', objectName: 'Plugin', objectPlural: 'plugins' },
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 73fa80a063e1..639f4ad1fbc7 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5369,7 +5369,6 @@ export type APIScopeObject =
| 'organization_integration'
| 'organization_member'
| 'person'
- | 'personal_spend'
| 'persisted_folder'
| 'plugin'
| 'product_tour'
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 02d4c536a0dd..4b8ce0227357 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -73,7 +73,6 @@ APIScopeObject = Literal[
"organization_integration",
"organization_member",
"person",
- "personal_spend",
"persisted_folder",
"plugin",
"product_tour",
diff --git a/products/llm_analytics/backend/api/personal_spend.py b/products/llm_analytics/backend/api/personal_spend.py
index c510793a168d..dd857cad2d7b 100644
--- a/products/llm_analytics/backend/api/personal_spend.py
+++ b/products/llm_analytics/backend/api/personal_spend.py
@@ -578,9 +578,9 @@ class PersonalSpendViewSet(viewsets.ViewSet):
(settings.LLM_ANALYTICS_INTERNAL_TEAM_ID) and are strictly scoped to the
authenticated user's email (read off the events row via person-on-events) —
callers cannot pivot to other users' data. Authorization model is "any
- authenticated PostHog user may read their own spend"; the `llm_analytics:read`
- scope on the MCP tool is decorative since no project-level scope check
- applies. Routes through `execute_with_ai_events_fallback` so reads hit the
+ authenticated PostHog user may read their own spend" via `user:read` (the
+ same scope that covers `/api/users/@me/`). Routes through
+ `execute_with_ai_events_fallback` so reads hit the
dedicated `ai_events` table when enabled, with the shared `events` table as
a fallback. Optionally filter tool / model / trace breakdowns to a single
`ai_product` via the `product` query param; `by_product` always returns
@@ -591,18 +591,16 @@ class PersonalSpendViewSet(viewsets.ViewSet):
authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
permission_classes = [permissions.IsAuthenticated, APIScopePermission]
- # Identity-scoped: the caller reads their own spend, not data nested under
- # a team or project. `scope_object = "INTERNAL"` + `dangerously_skip_scoped_team_enforcement`
- # opt out of team/org enforcement in APIScopePermission — valid here because
- # this viewset filters strictly by the authenticated user's email (see
- # `_email_filter` in `list` below). The required scope is overridden to the
- # purpose-built `personal_spend:read` — narrower than the broad `user:read`
- # cluster — and the frontend (scopes.tsx) marks its `:write` as disabled.
- scope_object = "INTERNAL"
- dangerously_skip_scoped_team_enforcement = True
-
- def dangerously_get_required_scopes(self, request: Request, view) -> list[str] | None:
- return ["personal_spend:read"]
+ # Identity-scoped (`/@me/...`): the caller reads their own spend, not data
+ # nested under a team or project. `scope_object = "user"` matches the shape
+ # of `/api/users/@me/` — APIScopePermission already exempts the `user`
+ # bucket from team/org scoping, so we don't need
+ # `dangerously_skip_scoped_team_enforcement` here. `user:read` is a clean
+ # superset of "read your own spend": anyone trusted with `user:read`
+ # already learns the more sensitive identity facts on `/api/users/@me/`,
+ # and the wildcard `*` plus OAuth identity tokens (MCP) inherit access
+ # the same way they do for every other `user`-scoped endpoint.
+ scope_object = "user"
def get_throttles(self):
return [
diff --git a/products/llm_analytics/backend/api/test/test_personal_spend.py b/products/llm_analytics/backend/api/test/test_personal_spend.py
index dd17dfe93e6f..506d5ba6f131 100644
--- a/products/llm_analytics/backend/api/test/test_personal_spend.py
+++ b/products/llm_analytics/backend/api/test/test_personal_spend.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from datetime import timedelta
+
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -12,11 +14,18 @@ from posthog.test.base import (
)
from unittest.mock import patch
+from django.conf import settings
from django.test import override_settings
+from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
+from posthog.api.oauth.test_dcr import generate_rsa_key
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
ENDPOINT = "/api/llm_analytics/@me/spend/"
@@ -371,3 +380,84 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
# Each tool drove half of the scoped spend.
assert rows["Bash"]["share_of_scoped"] == 0.5
assert rows["Read"]["share_of_scoped"] == 0.5
+
+
+@override_settings(
+ OAUTH2_PROVIDER={
+ **settings.OAUTH2_PROVIDER,
+ "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
+ }
+)
+class TestPersonalSpendNonSessionAuth(APIBaseTest):
+ """
+ Pins down what scopes the MCP and OAuth-token paths need to reach
+ `/api/llm_analytics/@me/spend/`. The endpoint is `scope_object = "user"` —
+ same bucket as `/api/users/@me/` — so the wildcard `*` (the "Full access"
+ consent option) and an explicit `user:read` both grant access. An OAuth
+ token carrying only OIDC identity scopes (`openid profile email`) without
+ any resource scope is correctly rejected: identity alone does not imply
+ permission to read account data.
+ """
+
+ def setUp(self) -> None:
+ super().setUp()
+ self._team_id_override = override_settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id)
+ self._team_id_override.enable()
+ self.addCleanup(self._team_id_override.disable)
+ self.client.logout()
+
+ def _make_pat(self, scopes: list[str]) -> str:
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="spend-test",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=scopes,
+ )
+ return raw
+
+ def _make_oauth_token(self, scope: str) -> str:
+ app = OAuthApplication.objects.create(
+ name="MCP-like client",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/cb",
+ algorithm="RS256",
+ skip_authorization=False,
+ organization=self.organization,
+ user=self.user,
+ )
+ token_value = f"pha_test_{generate_random_token_personal()[:24]}"
+ OAuthAccessToken.objects.create(
+ user=self.user,
+ application=app,
+ token=token_value,
+ expires=timezone.now() + timedelta(hours=1),
+ scope=scope,
+ )
+ return token_value
+
+ @parameterized.expand(
+ [
+ ("wildcard_pat", ["*"], status.HTTP_200_OK),
+ ("user_read_pat", ["user:read"], status.HTTP_200_OK),
+ ("unrelated_scope_pat", ["insight:read"], status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_personal_api_key_scope_matrix(self, _label: str, scopes: list[str], expected: int) -> None:
+ token = self._make_pat(scopes)
+ response = self.client.get(ENDPOINT, headers={"authorization": f"Bearer {token}"})
+ assert response.status_code == expected, response.content
+
+ @parameterized.expand(
+ [
+ ("wildcard_oauth", "*", status.HTTP_200_OK),
+ ("user_read_oauth", "user:read", status.HTTP_200_OK),
+ ("oidc_only_rejected", "openid profile email", status.HTTP_403_FORBIDDEN),
+ ("unrelated_scope_rejected", "insight:read", status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_oauth_token_scope_matrix(self, _label: str, scope: str, expected: int) -> None:
+ token = self._make_oauth_token(scope)
+ response = self.client.get(ENDPOINT, headers={"authorization": f"Bearer {token}"})
+ assert response.status_code == expected, response.content
diff --git a/products/llm_analytics/mcp/tools.yaml b/products/llm_analytics/mcp/tools.yaml
index 6d21840f4761..a027a6b813fa 100644
--- a/products/llm_analytics/mcp/tools.yaml
+++ b/products/llm_analytics/mcp/tools.yaml
@@ -406,7 +406,7 @@ tools:
operation: llm_analytics_personal_spend_list
enabled: true
scopes:
- - llm_analytics:read
+ - user:read
annotations:
readOnly: true
destructive: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 4e4b125e4b6a..93969862de0c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2942,7 +2942,7 @@
"feature": "llm_analytics",
"summary": "Get my LLM spend analysis",
"title": "Get my LLM spend analysis",
- "required_scopes": ["llm_analytics:read"],
+ "required_scopes": ["user:read"],
"new_mcp": true,
"annotations": {
"destructiveHint": false,
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 43ab767310e7..28a9592466a8 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3255,7 +3255,7 @@
"feature": "llm_analytics",
"summary": "Get my LLM spend analysis",
"title": "Get my LLM spend analysis",
- "required_scopes": ["llm_analytics:read"],
+ "required_scopes": ["user:read"],
"new_mcp": true,
"annotations": {
"destructiveHint": false,
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index bd61ce1e0a87..d4f38fde2034 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -127,8 +127,6 @@ export const OAUTH_SCOPES_SUPPORTED = [
'organization_member:write',
'person:read',
'person:write',
- 'personal_spend:read',
- 'personal_spend:write',
'persisted_folder:read',
'persisted_folder:write',
'plugin:read',