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.

feat(api): Allow PAT access to debug_ch_queries slowest_queries (#60055)

Juraj Majerike2433932c47c
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 5c3f2f2d9869..ea99c3623441 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -107,6 +107,7 @@ export const API_SCOPES: APIScope[] = [
},
{ key: 'property_definition', objectName: 'Property definition', objectPlural: 'property definitions' },
{ key: 'query', objectName: 'Query', objectPlural: 'queries', disabledActions: ['write'] },
+ // `query_performance` is omitted — see `INTERNAL_API_SCOPE_OBJECTS` in posthog/scopes.py.
{ key: 'replay_scanner', objectName: 'Replay scanner', objectPlural: 'replay scanners' },
{ key: 'revenue_analytics', objectName: 'Revenue analytics', objectPlural: 'revenue analytics' },
{ key: 'session_recording', objectName: 'Session recording', objectPlural: 'session recordings' },
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 05d6d455df4b..40e90a56fcfc 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5379,6 +5379,7 @@ export type APIScopeObject =
| 'project'
| 'property_definition'
| 'query'
+ | 'query_performance'
| 'replay_scanner'
| 'revenue_analytics'
| 'session_recording'
diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.py
index 679c49259f2d..8d23917f0e2c 100644
--- a/posthog/api/debug_ch_queries.py
+++ b/posthog/api/debug_ch_queries.py
@@ -7,19 +7,23 @@ from typing import Optional
from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
+from drf_spectacular.utils import extend_schema
from loginas.utils import is_impersonated_session
from rest_framework import exceptions, viewsets
from rest_framework.decorators import action
+from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.hogql.query import execute_hogql_query
+from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.cloud_utils import is_cloud
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
+from posthog.permissions import APIScopePermission
from posthog.settings.base_variables import DEBUG
from posthog.settings.data_stores import CLICKHOUSE_CLUSTER
@@ -28,11 +32,21 @@ from products.experiments.backend.models.team_experiments_config import TeamExpe
logger = logging.getLogger(__name__)
+@extend_schema(exclude=True)
class DebugCHQueries(viewsets.ViewSet):
"""
List recent CH queries initiated by this user.
"""
+ # `INTERNAL` (not `"query_performance"`) so a staff user's full-access (`*`) PAT
+ # cannot satisfy the scope check via the wildcard short-circuit in
+ # `APIScopePermission.has_permission`. The action below pins the explicit
+ # `query_performance:read` requirement, which only programmatically-minted PATs hold.
+ scope_object = "INTERNAL"
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication]
+ required_scopes: Optional[list[str]] = None
+
def _get_path(self, query: str) -> Optional[str]:
try:
return re.findall(r"request:([a-zA-Z0-9-_@]+)", query)[0].replace("_", "/")
@@ -344,7 +358,7 @@ class DebugCHQueries(viewsets.ViewSet):
logger.warning("Failed to fetch org ARR from billing tables, skipping", exc_info=True)
return {}
- @action(detail=False, methods=["GET"], url_path="slowest_queries")
+ @action(detail=False, methods=["GET"], url_path="slowest_queries", required_scopes=["query_performance:read"])
def slowest_queries(self, request):
if not request.user.is_staff:
raise exceptions.PermissionDenied("Only staff users can view slowest queries.")
diff --git a/posthog/api/test/test_debug_ch_queries.py b/posthog/api/test/test_debug_ch_queries.py
index 71333fa3638f..95f56f900b7b 100644
--- a/posthog/api/test/test_debug_ch_queries.py
+++ b/posthog/api/test/test_debug_ch_queries.py
@@ -3,6 +3,9 @@ from unittest.mock import patch
from rest_framework.status import HTTP_200_OK, HTTP_403_FORBIDDEN
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
class TestDebugCHQuery(APIBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@@ -26,3 +29,65 @@ class TestDebugCHQuery(APIBaseTest):
with patch("posthog.api.debug_ch_queries.is_cloud", return_value=False):
resp = self.client.get("/api/debug_ch_queries/")
self.assertEqual(resp.status_code, HTTP_200_OK)
+
+ def _create_pat(self, scopes: list[str]) -> str:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="test",
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ )
+ return token
+
+ def test_slowest_queries_pat_requires_scope_and_staff(self):
+ # Without the query_performance scope, even a staff user is rejected.
+ self.user.is_staff = True
+ self.user.save()
+ token = self._create_pat(scopes=["experiment:read"])
+ self.client.logout()
+
+ resp = self.client.get(
+ "/api/debug_ch_queries/slowest_queries/?hours=1",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN)
+
+ def test_slowest_queries_wildcard_pat_rejected(self):
+ # A full-access (`*`) PAT must NOT satisfy the query_performance:read requirement —
+ # this scope is INTERNAL and only programmatically-minted tokens carry it explicitly.
+ self.user.is_staff = True
+ self.user.save()
+ token = self._create_pat(scopes=["*"])
+ self.client.logout()
+
+ resp = self.client.get(
+ "/api/debug_ch_queries/slowest_queries/?hours=1",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN, resp.content)
+
+ def test_slowest_queries_pat_with_scope_but_non_staff_rejected(self):
+ # Scope grants the PAT past the scope check; is_staff still gates the action.
+ self.assertFalse(self.user.is_staff)
+ token = self._create_pat(scopes=["query_performance:read"])
+ self.client.logout()
+
+ resp = self.client.get(
+ "/api/debug_ch_queries/slowest_queries/?hours=1",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN)
+
+ @patch("posthog.api.debug_ch_queries.sync_execute", return_value=[])
+ def test_slowest_queries_pat_with_scope_and_staff_allowed(self, _mock_execute):
+ self.user.is_staff = True
+ self.user.save()
+ token = self._create_pat(scopes=["query_performance:read"])
+ self.client.logout()
+
+ resp = self.client.get(
+ "/api/debug_ch_queries/slowest_queries/?hours=1",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)
diff --git a/posthog/scopes.py b/posthog/scopes.py
index dd0bc1876c1b..52fa99a9a976 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -79,6 +79,7 @@ APIScopeObject = Literal[
"project",
"property_definition",
"query", # Covers query and events endpoints
+ "query_performance",
"replay_scanner",
"revenue_analytics",
"session_recording",
@@ -120,7 +121,7 @@ API_SCOPE_ACTIONS: tuple[APIScopeActions, ...] = get_args(APIScopeActions)
# Scope objects minted programmatically only — never via the OAuth consent flow,
# the personal-API-key UI, the CLI authorize page, or RBAC. Filtered out of
# `get_scope_descriptions()` and rejected by every user-facing scope validator.
-INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"clickhouse_test_cluster_perf"})
+INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"clickhouse_test_cluster_perf", "query_performance"})
# Scope objects available via personal API keys but never advertised through
# OAuth metadata. Used for alpha / not-yet-public products where a user can