: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(api): require staff for instance debug endpoints (#74437)
Tom Piccirelloa01438c121b9
diff --git a/frontend/src/scenes/insights/SidePanel/InsightPanelToggles.tsx b/frontend/src/scenes/insights/SidePanel/InsightPanelToggles.tsxindex 7832a87697f5..24cde2257a82 100644--- a/frontend/src/scenes/insights/SidePanel/InsightPanelToggles.tsx+++ b/frontend/src/scenes/insights/SidePanel/InsightPanelToggles.tsx@@ -27,7 +27,7 @@ export function InsightPanelToggles({ insightLogicProps }: { insightLogicProps:const { preflight } = useValues(preflightLogic)const isSavedInsight = hasDashboardItemId && !!insight?.id && !!insight?.short_id- const canShowDebugPanel = isSavedInsight && (user?.is_staff || user?.is_impersonated || !preflight?.cloud)+ const canShowDebugPanel = isSavedInsight && (user?.is_staff || user?.is_impersonated || preflight?.is_debug)const handleToggleQueryEditorPanel = (): void => {if (hasDashboardItemId && insightMode !== ItemMode.Edit) {diff --git a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsxindex c4df536e7f6c..395ecd59547e 100644--- a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx+++ b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx@@ -125,7 +125,7 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: Inconst showCohort =hogQL != null &&(isDataTableNode(query) || isDataVisualizationNode(query) || isHogQLQuery(query) || isEventsQuery(query))- const canShowDebugPanel = isSavedInsight && (user?.is_staff || user?.is_impersonated || !preflight?.cloud)+ const canShowDebugPanel = isSavedInsight && (user?.is_staff || user?.is_impersonated || preflight?.is_debug)const showMetalytics =isSavedInsight &&metalyticsInstanceId != null &&diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.pyindex 5c5f426c960f..4f62bb7470a9 100644--- a/posthog/api/debug_ch_queries.py+++ b/posthog/api/debug_ch_queries.py@@ -29,7 +29,6 @@ from posthog.clickhouse.preaggregation.experiment_metric_events_sql import (SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE,)from posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.cloud_utils import is_cloudfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Teamfrom posthog.permissions import APIScopePermission@@ -188,14 +187,22 @@ class DebugCHQueries(viewsets.ViewSet):_ALLOWED_FILTER_KEYS = frozenset({"insight_id", "experiment_id"})def _log_comment_filter(self, filter_key: str, filter_value: str) -> str:- """Build a WHERE clause filtering on a log_comment JSON field."""+ """Build a WHERE clause filtering on a log_comment JSON field, scoped to one team.++ Insight and experiment ids are sequential integers, so the log_comment match on its own+ reads any team's rows — every caller binds `team_id` alongside it.+ """if filter_key not in self._ALLOWED_FILTER_KEYS:raise ValueError(f"Invalid filter_key: {filter_key!r}")- return f"JSONExtractRaw(log_comment, '{filter_key}') = %(filter_value)s"+ return (+ f"JSONExtractRaw(log_comment, '{filter_key}') = %(filter_value)s"+ " AND JSONExtractInt(log_comment, 'team_id') = %(team_id)s"+ )- def hourly_stats(self, filter_key: str, filter_value: str):+ def hourly_stats(self, filter_key: str, filter_value: str, team_id: int):params = {"filter_value": filter_value,+ "team_id": team_id,"start_time": (datetime.now() - timedelta(days=14)).timestamp(),"not_query": "%request:_api_debug_ch_queries_%","cluster": CLICKHOUSE_CLUSTER,@@ -247,9 +254,10 @@ class DebugCHQueries(viewsets.ViewSet):for resp in response]- def stats(self, filter_key: str, filter_value: str):+ def stats(self, filter_key: str, filter_value: str, team_id: int):params = {"filter_value": filter_value,+ "team_id": team_id,"start_time": (datetime.now(UTC) - timedelta(days=14)).timestamp(),"cluster": CLICKHOUSE_CLUSTER,}@@ -285,7 +293,13 @@ class DebugCHQueries(viewsets.ViewSet):"exception_percentage": response[0][4],}- def queries(self, request: Request, filter_key: Optional[str] = None, filter_value: Optional[str] = None):+ def queries(+ self,+ request: Request,+ team_id: Optional[int] = None,+ filter_key: Optional[str] = None,+ filter_value: Optional[str] = None,+ ):params: dict = {"not_query": "%request:_api_debug_ch_queries_%","cluster": CLICKHOUSE_CLUSTER,@@ -296,6 +310,7 @@ class DebugCHQueries(viewsets.ViewSet):# nosemgrep: clickhouse-fstring-param-audit - where_clause from internal _log_comment_filterwhere_clause = self._log_comment_filter(filter_key, filter_value)params["filter_value"] = filter_value+ params["team_id"] = team_idlimit_clause = "LIMIT 10"else:where_clause = "query LIKE %(query)s AND event_time > %(start_time)s"@@ -350,7 +365,7 @@ class DebugCHQueries(viewsets.ViewSet):]def list(self, request):- if not (request.user.is_staff or DEBUG or is_impersonated_session(request) or not is_cloud()):+ if not (request.user.is_staff or DEBUG or is_impersonated_session(request)):raise exceptions.PermissionDenied("You're not allowed to see queries.")tag_queries(product=Product.INTERNAL, feature=Feature.DEBUG_QUERY)@@ -365,11 +380,18 @@ class DebugCHQueries(viewsets.ViewSet):elif experiment_id:filter_key, filter_value = "experiment_id", experiment_id- queries = self.queries(request, filter_key, filter_value)- response = {"queries": queries}+ team_id: Optional[int] = Noneif filter_key and filter_value:- response["stats"] = self.stats(filter_key, filter_value)- response["hourly_stats"] = self.hourly_stats(filter_key, filter_value)+ team = request.user.team+ if team is None:+ raise exceptions.PermissionDenied("You're not allowed to see queries.")+ team_id = team.pk++ queries = self.queries(request, team_id, filter_key, filter_value)+ response = {"queries": queries}+ if filter_key and filter_value and team_id is not None:+ response["stats"] = self.stats(filter_key, filter_value, team_id)+ response["hourly_stats"] = self.hourly_stats(filter_key, filter_value, team_id)return Response(response)def _serialize_precomputation_team(diff --git a/posthog/api/instance_status.py b/posthog/api/instance_status.pyindex 5071561d052a..2fbc3f311bb9 100644--- a/posthog/api/instance_status.py+++ b/posthog/api/instance_status.py@@ -15,7 +15,7 @@ from posthog.api.utils import actionfrom posthog.async_migrations.status import async_migrations_okfrom posthog.cloud_utils import is_cloudfrom posthog.git import get_git_commit_short-from posthog.permissions import SingleTenancyOrAdmin+from posthog.permissions import IsStaffUser, SingleTenancyOrAdminfrom posthog.storage import object_storagefrom posthog.utils import (dict_from_cursor_fetchall,@@ -214,7 +214,9 @@ class InstanceStatusViewSet(viewsets.ViewSet):})- @action(methods=["GET"], detail=False)+ # Running and recent queries carry inline filter literals from every team on the instance,+ # so this action is staff-only everywhere — self-hosted instances host multiple teams too.+ @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated, IsStaffUser])def queries(self, request: Request) -> Response:queries = {"postgres_running": self.get_postgres_running_queries()}diff --git a/posthog/api/test/test_debug_ch_queries.py b/posthog/api/test/test_debug_ch_queries.pyindex 4a29867ba2cd..931ddc24b290 100644--- a/posthog/api/test/test_debug_ch_queries.py+++ b/posthog/api/test/test_debug_ch_queries.py@@ -8,6 +8,7 @@ from rest_framework.status import HTTP_200_OK, HTTP_403_FORBIDDENfrom posthog.api.debug_ch_queries import _cache_table_statsfrom posthog.clickhouse.preaggregation.experiment_exposures_sql import SHARDED_EXPERIMENT_EXPOSURES_TABLEfrom posthog.clickhouse.preaggregation.experiment_metric_events_sql import SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE+from posthog.models import Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.settings.data_stores import CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_CLUSTER@@ -17,14 +18,13 @@ class TestDebugCHQuery(APIBaseTest):CLASS_DATA_LEVEL_SETUP = Falsedef test_denied(self):- with patch("posthog.api.debug_ch_queries.is_cloud", return_value=True):- with patch("posthog.api.debug_ch_queries.DEBUG", True):- resp = self.client.get("/api/debug_ch_queries/")- self.assertEqual(resp.status_code, HTTP_200_OK)+ with patch("posthog.api.debug_ch_queries.DEBUG", True):+ resp = self.client.get("/api/debug_ch_queries/")+ self.assertEqual(resp.status_code, HTTP_200_OK)- with patch("posthog.api.debug_ch_queries.DEBUG", False):- resp = self.client.get("/api/debug_ch_queries/")- self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN)+ with patch("posthog.api.debug_ch_queries.DEBUG", False):+ resp = self.client.get("/api/debug_ch_queries/")+ self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN)self.user.is_staff = Trueself.user.save()@@ -32,9 +32,46 @@ class TestDebugCHQuery(APIBaseTest):resp = self.client.get("/api/debug_ch_queries/")self.assertEqual(resp.status_code, HTTP_200_OK)- 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 test_non_staff_denied_off_cloud(self):+ # Self-hosted is not single-tenant: a plain member of one team must not read the executed+ # query text of every other team on the instance.+ self.assertFalse(self.user.is_staff)++ with self.is_cloud(False), patch("posthog.api.debug_ch_queries.DEBUG", False):+ resp = self.client.get("/api/debug_ch_queries/?insight_id=1")++ self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN, resp.content)++ @patch("posthog.api.debug_ch_queries.sync_execute")+ def test_filtered_queries_are_scoped_to_the_requesting_users_team(self, mock_sync_execute):+ # insight ids are sequential and the log_comment filter alone matches any team's rows,+ # so every filtered read must also bind the requester's team.+ def fake_sync_execute(sql, params):+ return [(0, 0, 0.0, 0.0, 0.0)] if "total_queries" in sql else []++ mock_sync_execute.side_effect = fake_sync_execute+ self.user.is_staff = True+ self.user.save()++ resp = self.client.get("/api/debug_ch_queries/?insight_id=1")++ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)+ self.assertTrue(mock_sync_execute.call_args_list)+ for sql, params in (call.args for call in mock_sync_execute.call_args_list):+ self.assertIn("%(team_id)s", sql)+ self.assertEqual(params["team_id"], self.team.pk)++ def test_filtered_queries_denied_when_requester_has_no_current_team(self):+ # A filtered read scopes to the requester's team; without one, refuse rather+ # than fall through to an unscoped read across every team on the instance.+ new_user = User.objects.create_user(+ email="[email protected]", password="testpass123", first_name="Staff", is_staff=True+ )+ self.client.force_login(new_user)++ resp = self.client.get("/api/debug_ch_queries/?insight_id=1")++ self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN, resp.content)def _create_pat(self, scopes: list[str]) -> str:token = generate_random_token_personal()diff --git a/posthog/api/test/test_instance_status.py b/posthog/api/test/test_instance_status.pyindex 66191ad67b28..0010c65bd173 100644--- a/posthog/api/test/test_instance_status.py+++ b/posthog/api/test/test_instance_status.py@@ -2,6 +2,7 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from parameterized import parameterizedfrom rest_framework import status@@ -13,11 +14,28 @@ class TestInstanceStatus(APIBaseTest):self.client.get("/api/instance_status/navigation").status_code,status.HTTP_200_OK,)++ self.user.is_staff = True+ self.user.save()self.assertEqual(self.client.get("/api/instance_status/queries").status_code,status.HTTP_200_OK,)+ @parameterized.expand([("non_staff", False, status.HTTP_403_FORBIDDEN), ("staff", True, status.HTTP_200_OK)])+ @patch("posthog.clickhouse.system_status.get_clickhouse_slow_log", return_value=[])+ @patch("posthog.clickhouse.system_status.get_clickhouse_running_queries", return_value=[])+ def test_queries_requires_staff_off_cloud(self, _name, is_staff, expected_status, *_mocks):+ # Running queries expose other teams' filter literals, so being logged in on a+ # self-hosted instance is not enough to read them.+ self.user.is_staff = is_staff+ self.user.save()++ with self.is_cloud(False):+ response = self.client.get("/api/instance_status/queries")++ self.assertEqual(response.status_code, expected_status, response.content)+def test_object_storage_when_disabled(self):with self.settings(OBJECT_STORAGE_ENABLED=False):response = self.client.get("/api/instance_status")