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: add resource access control to endpoints (#62234)

Reece Jones0db1ab0ddeb5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 88e8c887f18b..0164826b4f65 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5795,9 +5795,9 @@ snapshots:
scenes-app-settings-authentication-domains--one-unverified-domain--light:
hash: v1.k794b7964.f2136f46f5946ffdd00316ec9f195c08ccae540ab2e2f0022a22631ef6d20ff6.nUefq9IWQvO8EuUAwIcjmRcN9dqhOXqr_Pi83bQ8gDk
scenes-app-settings-environment--settings-environment-access-control--dark:
- hash: v1.k794b7964.8e7139903f0757d1a146e0fdecb609897adab5e44759388e6519071de71fb3da.fn33v4OSYyLwpEedq8dy4MBX5S-X6dvnqUodLsegFyY
+ hash: v1.k794b7964.8eb727ffc92903b8783e6b9d9ead9665c4c051d5a250747e320f12cd56cbc283.s0HuvGumzXMgZkSkaKB3VXe8Qoj95m3fEIYGgdNpvdA
scenes-app-settings-environment--settings-environment-access-control--light:
- hash: v1.k794b7964.20b3ba9ad4c71ab66d2416cab2e3315d249c054b762cfa39f6c4869aead1dc1e.ICoy0vmj9nEkTU-gn1v-51B3gJK7Tc7_DFUJlZaDrbs
+ hash: v1.k794b7964.b7c88c1ee291902a35dcc2099e0f45124ba38b454d4e81a506d7e16af837c64e.gIBdXCQwFKxIMPz_5QHIbvM72jx10TdYve9NE3cfPMs
scenes-app-settings-environment--settings-environment-autocapture--dark:
hash: v1.k794b7964.9f86feacf66829a02d5c14b62d237c3abe5e96cc13f88dd9e1d32397c30d2112.i48i7eB2z6UfXa3VwFKDH0SjzebQXoZPcfON8C_SoCg
scenes-app-settings-environment--settings-environment-autocapture--light:
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts
index eec01cb07f51..ef44d841d7d3 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts
@@ -294,6 +294,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(
AccessControlResourceType.Action,
AccessControlResourceType.ActivityLog,
AccessControlResourceType.Dashboard,
+ AccessControlResourceType.Endpoint,
AccessControlResourceType.Experiment,
AccessControlResourceType.ExternalDataSource,
AccessControlResourceType.WarehouseObjects,
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 283367e31170..7442fddc9e3e 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -325,6 +325,11 @@ function SQLEditorSceneTitle(): JSX.Element | null {
AccessControlLevel.Editor
)
+ const saveAsEndpointAccessDisabledReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Endpoint,
+ AccessControlLevel.Editor
+ )
+
const secondarySaveMenuItems = useMemo(
() =>
saveAsMenuItems.secondary.map((item) => ({
@@ -342,9 +347,21 @@ function SQLEditorSceneTitle(): JSX.Element | null {
saveAsView()
},
- accessDisabledReason: item.action === 'view' ? saveAsViewAccessDisabledReason : undefined,
+ accessDisabledReason:
+ item.action === 'view'
+ ? saveAsViewAccessDisabledReason
+ : item.action === 'endpoint'
+ ? saveAsEndpointAccessDisabledReason
+ : undefined,
})),
- [saveAsEndpoint, saveAsInsight, saveAsMenuItems.secondary, saveAsView, saveAsViewAccessDisabledReason]
+ [
+ saveAsEndpoint,
+ saveAsInsight,
+ saveAsMenuItems.secondary,
+ saveAsView,
+ saveAsViewAccessDisabledReason,
+ saveAsEndpointAccessDisabledReason,
+ ]
)
const onPrimarySaveClick = (): void => {
@@ -499,7 +516,9 @@ function SQLEditorSceneTitle(): JSX.Element | null {
? [
{
label: 'Save as endpoint...',
- disabledReason: saveAsDisabledReason,
+ disabledReason:
+ saveAsDisabledReason ??
+ saveAsEndpointAccessDisabledReason,
onClick: () => saveAsEndpoint(),
},
]
@@ -558,7 +577,9 @@ function SQLEditorSceneTitle(): JSX.Element | null {
? [
{
label: 'Save as endpoint...',
- disabledReason: saveAsDisabledReason,
+ disabledReason:
+ saveAsDisabledReason ??
+ saveAsEndpointAccessDisabledReason,
onClick: () => saveAsEndpoint(),
},
]
@@ -586,7 +607,12 @@ function SQLEditorSceneTitle(): JSX.Element | null {
type="primary"
size="small"
onClick={onPrimarySaveClick}
- disabledReason={saveAsDisabledReason}
+ disabledReason={
+ saveAsDisabledReason ??
+ (saveAsMenuItems.primary.action === 'endpoint'
+ ? saveAsEndpointAccessDisabledReason
+ : undefined)
+ }
sideAction={{
icon: <IconChevronDown />,
'data-attr': 'sql-editor-save-options-button',
diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/Endpoint.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/Endpoint.tsx
index b61f301d8364..09ccf9f4fda8 100644
--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/Endpoint.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/Endpoint.tsx
@@ -12,10 +12,12 @@ import {
lemonToast,
} from '@posthog/lemon-ui'
+import { AccessControlAction } from 'lib/components/AccessControlAction'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { variablesLogic } from '~/queries/nodes/DataVisualization/Components/Variables/variablesLogic'
import { NodeKind } from '~/queries/schema/schema-general'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { endpointLogic } from 'products/endpoints/frontend/endpointLogic'
import { endpointsLogic } from 'products/endpoints/frontend/endpointsLogic'
@@ -160,9 +162,14 @@ export function Endpoint({ tabId }: EndpointProps): JSX.Element {
/>
</LemonField.Pure>
- <LemonButton type="primary" onClick={handleSubmit} icon={<IconEndpoints />} size="medium">
- {isUpdateMode ? 'Update endpoint' : 'Create endpoint'}
- </LemonButton>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton type="primary" onClick={handleSubmit} icon={<IconEndpoints />} size="medium">
+ {isUpdateMode ? 'Update endpoint' : 'Create endpoint'}
+ </LemonButton>
+ </AccessControlAction>
</div>
</div>
)
diff --git a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
index 6a82376ef11f..e040822c5575 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
@@ -17,6 +17,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { Link } from 'lib/lemon-ui/Link'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'
@@ -24,7 +25,14 @@ import { urls } from 'scenes/urls'
import { ScenePanelActionsSection } from '~/layout/scenes/SceneLayout'
import { isDataTableNode, isDataVisualizationNode, isEventsQuery, isHogQLQuery } from '~/queries/utils'
-import { ExporterFormat, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
+import {
+ AccessControlLevel,
+ AccessControlResourceType,
+ ExporterFormat,
+ InsightLogicProps,
+ InsightShortId,
+ QueryBasedInsightModel,
+} from '~/types'
import { endpointLogic } from 'products/endpoints/frontend/endpointLogic'
@@ -50,6 +58,12 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
const { canCopyToProject } = useValues(interProjectCopyLogic)
const isSavedInsight = hasDashboardItemId && !!insight?.id && !!insight?.short_id
+
+ // Creating an endpoint from an insight is a create operation, so it's gated on resource-level access.
+ const createEndpointAccessReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Endpoint,
+ AccessControlLevel.Editor
+ )
const canExport = exportContext != null && insight.short_id != null
const showCohort =
hogQL != null &&
@@ -164,11 +178,10 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
<ButtonPrimitive
onClick={openCreateFromInsightModal}
menuItem
- disabledReasons={
- !isSavedInsight
- ? { 'You must save the insight first before creating an endpoint from it': true }
- : undefined
- }
+ disabledReasons={{
+ 'You must save the insight first before creating an endpoint from it': !isSavedInsight,
+ ...(createEndpointAccessReason ? { [createEndpointAccessReason]: true } : {}),
+ }}
>
<IconEndpoints />
Create endpoint
diff --git a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
index d5d6bb534f93..028542e4caf0 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
@@ -27,6 +27,7 @@ import { SceneActivityIndicator } from 'lib/components/Scenes/SceneUpdateActivit
import { urlForSubscriptions } from 'lib/components/Subscriptions/utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
@@ -133,7 +134,10 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
const showCopyToProject = isSavedInsight && canCopyToProject
const showFileMenu = true // file ops (project tree, terraform) always available
const showEditMenu = true // duplicate always available
- const showCreateEndpoint = featureFlags[FEATURE_FLAGS.ENDPOINTS] && isSavedInsight
+ const showCreateEndpoint =
+ featureFlags[FEATURE_FLAGS.ENDPOINTS] &&
+ isSavedInsight &&
+ !getAccessControlDisabledReason(AccessControlResourceType.Endpoint, AccessControlLevel.Editor)
const showAddToNotebook = isSavedInsight
const showCreateMenu =
showCreateEndpoint ||
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index fc2bf0821002..7bb98a72c121 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -348,6 +348,9 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr
[Scene.Survey]: AccessControlResourceType.Survey,
[Scene.Surveys]: AccessControlResourceType.Survey,
+ // Endpoints
+ [Scene.EndpointsScene]: AccessControlResourceType.Endpoint,
+
// Product Tours
[Scene.ProductTour]: AccessControlResourceType.ProductTour,
[Scene.ProductTours]: AccessControlResourceType.ProductTour,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 476ad304d476..37bd75fdd452 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -283,6 +283,7 @@ export enum AccessControlResourceType {
RevenueAnalytics = 'revenue_analytics',
Survey = 'survey',
Logs = 'logs',
+ Endpoint = 'endpoint',
ProductTour = 'product_tour',
Experiment = 'experiment',
ExperimentSavedMetric = 'experiment_saved_metric',
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 12ef92872bad..af9f0bad8acc 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -59,6 +59,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = (
"action",
"customer_analytics",
"dashboard",
+ "endpoint",
"experiment",
"external_data_source",
"warehouse_objects",
@@ -292,6 +293,8 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
return "session_recording_playlist"
if name == "experimentsavedmetric":
return "experiment_saved_metric"
+ if name == "endpointversion":
+ return "endpoint"
if name == "externaldatasource":
return "external_data_source"
if name == "externaldataschema":
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.py
index 0d3aac681b82..ea8fb9f426b4 100644
--- a/products/endpoints/backend/api.py
+++ b/products/endpoints/backend/api.py
@@ -19,7 +19,8 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema_view
from loginas.utils import is_impersonated_session
from pydantic import BaseModel
from rest_framework import serializers, status, viewsets
-from rest_framework.exceptions import Throttled, ValidationError
+from rest_framework.exceptions import PermissionDenied, Throttled, ValidationError
+from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -73,6 +74,9 @@ from posthog.models.activity_logging.activity_log import (
changes_between,
log_activity,
)
+from posthog.permissions import APIScopePermission, TeamMemberAccessPermission
+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
+from posthog.rbac.user_access_control import access_level_satisfied_for_resource
from posthog.schema_migrations.upgrade import upgrade
from posthog.types import InsightQueryNode
@@ -386,7 +390,13 @@ class MaterializationPreviewRequestSerializer(serializers.Serializer):
description="Update an existing endpoint.",
),
)
-class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemViewSetMixin, viewsets.ModelViewSet):
+class EndpointViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ PydanticModelMixin,
+ TaggedItemViewSetMixin,
+ viewsets.ModelViewSet,
+):
# NOTE: Do we need to override the scopes for the "create"
scope_object = "endpoint"
# Special case for query - these are all essentially read actions
@@ -420,6 +430,38 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
def get_throttles(self):
return [EndpointBurstThrottle(), EndpointSustainedThrottle()]
+ def dangerously_get_permissions(self):
+ # `run` is the public-facing execution API. It still requires authentication, the
+ # `endpoint:read` API scope, and project membership, but intentionally skips
+ # resource-level access control (AccessControlPermission) — a restrictive resource-level
+ # default must not break execution for API consumers. Explicit per-endpoint
+ # (object-level) denials are still enforced in run() via _enforce_object_level_access.
+ if self.action == "run":
+ return [permission() for permission in (IsAuthenticated, APIScopePermission, TeamMemberAccessPermission)]
+ raise NotImplementedError()
+
+ def _get_endpoint_with_object_access(self, name: str | None) -> Endpoint:
+ """Fetch a team-scoped endpoint by name and enforce object-level access controls.
+
+ The custom retrieve/destroy/versions/materialization actions fetch endpoints directly via
+ get_object_or_404, which bypasses get_object()'s built-in check_object_permissions. Routing
+ through here restores that check so per-endpoint resource access controls (RBAC) are honored,
+ not just the resource-level defaults.
+ """
+ endpoint = get_object_or_404(Endpoint, team=self.team, name=name, deleted=False)
+ self.check_object_permissions(self.request, endpoint)
+ return endpoint
+
+ def _enforce_object_level_access(self, endpoint: Endpoint) -> None:
+ """Block execution only when the user is explicitly denied this specific endpoint via an
+ object-level access control. Unlike check_object_permissions, this ignores resource-level
+ defaults so a restrictive project default doesn't break the public execution API. Creators
+ and org admins always pass (specific_access_level_for_object returns the highest level).
+ """
+ specific_level = self.user_access_control.specific_access_level_for_object(endpoint)
+ if specific_level is not None and not access_level_satisfied_for_resource("endpoint", specific_level, "viewer"):
+ raise PermissionDenied("You do not have access to this endpoint.")
+
def _parse_version_param(self, request: Request) -> int | None:
"""Parse version number from request body or query params.
@@ -573,7 +615,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
)
def retrieve(self, request: Request, name=None, *args, **kwargs) -> Response:
"""Retrieve an endpoint, or a specific endpoint version."""
- endpoint = get_object_or_404(Endpoint.objects.all(), team=self.team, name=name, deleted=False)
+ endpoint = self._get_endpoint_with_object_access(name)
version_number = self._parse_version_param(request)
try:
@@ -877,10 +919,9 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
If version is specified, updates target that specific version.
Otherwise, the current version is used.
"""
- endpoint = get_object_or_404(Endpoint, team=self.team, name=name, deleted=False)
# Enforce object-level RBAC: a user with global editor scope can still be restricted
# from a specific endpoint via per-object access controls.
- self.check_object_permissions(request, endpoint)
+ endpoint = self._get_endpoint_with_object_access(name)
endpoint_before_update = Endpoint.objects.get(pk=endpoint.id)
upgraded_query = upgrade(request.data)
@@ -1268,7 +1309,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
def destroy(self, request: Request, name=None, *args, **kwargs) -> Response:
"""Delete an endpoint and clean up materialized query."""
- endpoint = get_object_or_404(Endpoint, team=self.team, name=name, deleted=False)
+ endpoint = self._get_endpoint_with_object_access(name)
endpoint_id = str(endpoint.id)
endpoint_name = endpoint.name
@@ -2203,6 +2244,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
def run(self, request: Request, name=None, *args, **kwargs) -> Response:
"""Execute endpoint with optional parameters."""
endpoint = get_object_or_404(Endpoint, team=self.team, name=name, is_active=True, deleted=False)
+ self._enforce_object_level_access(endpoint)
data = self.get_model(request.data, EndpointRunRequest)
# Track endpoint execution for deprecation monitoring
@@ -2512,7 +2554,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
Returns versions in descending order (latest first).
"""
- endpoint = get_object_or_404(Endpoint, team=self.team, name=name, deleted=False)
+ endpoint = self._get_endpoint_with_object_access(name)
versions_qs = endpoint.versions.all()
page = self.paginate_queryset(versions_qs)
if page is not None:
@@ -2531,7 +2573,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
Supports ?version=N query param to get status for a specific version.
"""
- endpoint = get_object_or_404(Endpoint, team=self.team, name=name, deleted=False)
+ endpoint = self._get_endpoint_with_object_access(name)
version_number = self._parse_version_param(request)
if version_number is not None:
@@ -2554,7 +2596,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
Returns the transformed query, range pair info, and aggregate re-aggregation info.
"""
- endpoint = get_object_or_404(Endpoint, team=self.team, name=name, deleted=False)
+ endpoint = self._get_endpoint_with_object_access(name)
version_number = request.validated_data.get("version")
if version_number is not None:
@@ -2708,7 +2750,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView
Supports ?version=N query param to generate spec for a specific version.
"""
- endpoint = get_object_or_404(Endpoint, team=self.team, name=name, deleted=False)
+ endpoint = self._get_endpoint_with_object_access(name)
version = None
version_number = self._parse_version_param(request)
diff --git a/products/endpoints/backend/tests/test_endpoint_access_control.py b/products/endpoints/backend/tests/test_endpoint_access_control.py
new file mode 100644
index 000000000000..3c617de2c459
--- /dev/null
+++ b/products/endpoints/backend/tests/test_endpoint_access_control.py
@@ -0,0 +1,202 @@
+import pytest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+from posthog.rbac.user_access_control import ACCESS_CONTROL_RESOURCES, model_to_resource
+
+from products.endpoints.backend.models import Endpoint, EndpointVersion
+from products.endpoints.backend.tests.conftest import create_endpoint_with_version
+
+try:
+ from ee.models.rbac.access_control import AccessControl
+except ImportError:
+ pass
+
+
+SAMPLE_QUERY = {"kind": "HogQLQuery", "query": "SELECT 1"}
+
+
+class TestEndpointResourceRegistration(SimpleTestCase):
+ def test_endpoint_is_a_controllable_resource(self):
+ self.assertIn("endpoint", ACCESS_CONTROL_RESOURCES)
+
+ def test_endpoint_model_maps_to_endpoint_resource(self):
+ self.assertEqual(model_to_resource(Endpoint()), "endpoint")
+
+ def test_endpoint_version_inherits_parent_endpoint_resource(self):
+ # Versions have no route of their own, so access control on a version resolves
+ # to the parent endpoint resource via the model_to_resource override.
+ self.assertEqual(model_to_resource(EndpointVersion()), "endpoint")
+
+
+class TestEndpointAccessControl(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ self.viewer_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.editor_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.no_access_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+
+ self.endpoint = create_endpoint_with_version(
+ name="my_endpoint",
+ team=self.team,
+ query=SAMPLE_QUERY,
+ created_by=self.user,
+ )
+
+ def _create_access_control(self, user, resource="endpoint", resource_id=None, access_level="viewer"):
+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)
+ return AccessControl.objects.create(
+ team=self.team,
+ resource=resource,
+ resource_id=resource_id,
+ access_level=access_level,
+ organization_member=membership,
+ )
+
+ def _create_project_default(self, resource="endpoint", access_level="none"):
+ return AccessControl.objects.create(
+ team=self.team,
+ resource=resource,
+ resource_id=None,
+ access_level=access_level,
+ organization_member=None,
+ role=None,
+ )
+
+ def _list_url(self) -> str:
+ return f"/api/environments/{self.team.pk}/endpoints/"
+
+ def _detail_url(self, name=None) -> str:
+ return f"/api/environments/{self.team.pk}/endpoints/{name or self.endpoint.name}/"
+
+ @parameterized.expand(
+ [
+ # (access_level, method, expected_status, patch_body)
+ ("viewer", "GET", status.HTTP_200_OK, None),
+ ("viewer", "PATCH", status.HTTP_403_FORBIDDEN, {"description": "updated"}),
+ ("viewer", "DELETE", status.HTTP_403_FORBIDDEN, None),
+ ("editor", "GET", status.HTTP_200_OK, None),
+ ("editor", "PATCH", status.HTTP_200_OK, {"description": "updated"}),
+ ("editor", "DELETE", status.HTTP_204_NO_CONTENT, None),
+ ("none", "GET", status.HTTP_403_FORBIDDEN, None),
+ ]
+ )
+ def test_access_level_matrix(self, access_level, method, expected_status, patch_body):
+ user = {"viewer": self.viewer_user, "editor": self.editor_user, "none": self.no_access_user}[access_level]
+ self._create_access_control(user, access_level=access_level)
+ self.client.force_login(user)
+
+ if method == "GET":
+ response = self.client.get(self._detail_url())
+ elif method == "PATCH":
+ response = self.client.patch(self._detail_url(), data=patch_body, format="json")
+ elif method == "DELETE":
+ response = self.client.delete(self._detail_url())
+ else:
+ raise AssertionError(f"Unsupported method {method}")
+
+ self.assertEqual(response.status_code, expected_status, getattr(response, "data", None))
+
+ def test_viewer_can_list(self):
+ self._create_access_control(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+ self.assertEqual(self.client.get(self._list_url()).status_code, status.HTTP_200_OK)
+
+ def test_project_default_none_blocks_non_creator_retrieve(self):
+ self._create_project_default(access_level="none")
+ self.client.force_login(self.viewer_user)
+ self.assertEqual(self.client.get(self._detail_url()).status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_object_level_none_blocks_specific_endpoint(self):
+ # Resource-level viewer access, but object-level "none" on this specific endpoint.
+ self._create_access_control(self.viewer_user, access_level="viewer")
+ self._create_access_control(self.viewer_user, resource_id=str(self.endpoint.id), access_level="none")
+ self.client.force_login(self.viewer_user)
+ self.assertEqual(self.client.get(self._detail_url()).status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_run_blocked_by_object_level_denial(self):
+ # run (execution) is gated by object-level access only: an explicit per-endpoint "none"
+ # blocks execution before the query runs.
+ self._create_access_control(self.viewer_user, resource_id=str(self.endpoint.id), access_level="none")
+ self.client.force_login(self.viewer_user)
+ response = self.client.get(self._detail_url() + "run/")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_run_not_blocked_by_resource_level_default(self):
+ # A restrictive resource-level default must NOT block execution — run is the public-facing
+ # data API. Without an explicit per-endpoint denial, the team member can still run it.
+ self._create_project_default(access_level="none")
+ self.client.force_login(self.viewer_user)
+ response = self.client.get(self._detail_url() + "run/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, getattr(response, "data", None))
+
+ def test_create_blocked_without_resource_editor_access(self):
+ self._create_access_control(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+ response = self.client.post(
+ self._list_url(), data={"name": "blocked_create", "query": SAMPLE_QUERY}, format="json"
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(Endpoint.objects.filter(team=self.team, name="blocked_create").exists())
+
+ def test_create_allowed_with_resource_editor_access(self):
+ self._create_access_control(self.editor_user, access_level="editor")
+ self.client.force_login(self.editor_user)
+ response = self.client.post(
+ self._list_url(), data={"name": "editor_create", "query": SAMPLE_QUERY}, format="json"
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ self.assertTrue(Endpoint.objects.filter(team=self.team, name="editor_create").exists())
+
+ def test_creator_list_filters_out_object_blocked_endpoint(self):
+ # Creator sees their own endpoint; an object-level "none" on another user's endpoint excludes it.
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ other_endpoint = create_endpoint_with_version(
+ name="other_endpoint", team=self.team, query=SAMPLE_QUERY, created_by=other_user
+ )
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="endpoint",
+ resource_id=str(other_endpoint.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ self.client.force_login(self.user)
+ response = self.client.get(self._list_url())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ names = [e["name"] for e in response.json()["results"]]
+ self.assertIn(self.endpoint.name, names)
+ self.assertNotIn(other_endpoint.name, names)
+
+ def test_object_level_grant_works_through_project_default_none(self):
+ # With the project default at "none", an object-level grant still lets the user read and
+ # edit that specific endpoint, while other endpoints stay blocked.
+ other_endpoint = create_endpoint_with_version(
+ name="other_endpoint", team=self.team, query=SAMPLE_QUERY, created_by=self.user
+ )
+ self._create_project_default(access_level="none")
+ self._create_access_control(self.viewer_user, resource_id=str(self.endpoint.id), access_level="editor")
+ self.client.force_login(self.viewer_user)
+
+ self.assertEqual(self.client.get(self._detail_url()).status_code, status.HTTP_200_OK)
+ patch_response = self.client.patch(self._detail_url(), data={"description": "granted edit"}, format="json")
+ self.assertEqual(patch_response.status_code, status.HTTP_200_OK)
+
+ # A different endpoint without an object-level grant stays blocked.
+ self.assertEqual(self.client.get(self._detail_url(other_endpoint.name)).status_code, status.HTTP_403_FORBIDDEN)
diff --git a/products/endpoints/frontend/EndpointHeader.tsx b/products/endpoints/frontend/EndpointHeader.tsx
index 7fa7748c4fbf..ef3641529b6e 100644
--- a/products/endpoints/frontend/EndpointHeader.tsx
+++ b/products/endpoints/frontend/EndpointHeader.tsx
@@ -3,14 +3,16 @@ import { useActions, useValues } from 'kea'
import { IconBug } from '@posthog/icons'
import { LemonButton, LemonLabel, LemonSwitch } from '@posthog/lemon-ui'
+import { AccessControlAction } from 'lib/components/AccessControlAction'
import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { EndpointRequest } from '~/queries/schema/schema-general'
import { isInsightVizNode } from '~/queries/utils'
-import { EndpointType, EndpointVersionType } from '~/types'
+import { AccessControlLevel, AccessControlResourceType, EndpointType, EndpointVersionType } from '~/types'
import { endpointLogic } from './endpointLogic'
import { endpointSceneLogic } from './endpointSceneLogic'
@@ -32,6 +34,13 @@ export const EndpointSceneHeader = (): JSX.Element => {
useActions(endpointSceneLogic)
const { superpowersEnabled } = useValues(superpowersLogic)
+ // SceneTitleSection takes a boolean `canEdit` rather than disabled/disabledReason, so we can't
+ // wrap it with AccessControlAction — use the same helper AccessControlAction relies on internally.
+ const editAccessDisabledReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Endpoint,
+ AccessControlLevel.Editor
+ )
+
// When viewing a non-current version, target that version for updates
const targetVersion =
viewingVersion && viewingVersion.version !== endpoint?.current_version ? viewingVersion.version : undefined
@@ -98,7 +107,7 @@ export const EndpointSceneHeader = (): JSX.Element => {
name={endpointName || endpoint?.name}
description={endpointDescription ?? viewingVersion?.description ?? endpoint?.description}
resourceType={{ type: 'endpoints' }}
- canEdit
+ canEdit={!editAccessDisabledReason}
// onNameChange={} - we explicitly disallow this
onDescriptionChange={(description) => setEndpointDescription(description)}
isLoading={endpointLoading && !endpoint}
@@ -128,21 +137,26 @@ export const EndpointSceneHeader = (): JSX.Element => {
Discard changes
</LemonButton>
)}
- <LemonButton
- type="primary"
- onClick={handleSave}
- disabledReason={
- !endpoint
- ? 'Endpoint not loaded'
- : !hasChanges
- ? 'No changes to save'
- : hasQueryChange && targetVersion
- ? 'Query can only be changed when on the latest version'
- : undefined
- }
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
>
- Update
- </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={handleSave}
+ disabledReason={
+ !endpoint
+ ? 'Endpoint not loaded'
+ : !hasChanges
+ ? 'No changes to save'
+ : hasQueryChange && targetVersion
+ ? 'Query can only be changed when on the latest version'
+ : undefined
+ }
+ >
+ Update
+ </LemonButton>
+ </AccessControlAction>
</>
}
/>
diff --git a/products/endpoints/frontend/Endpoints.tsx b/products/endpoints/frontend/Endpoints.tsx
index 342684427b13..229b4963d4d4 100644
--- a/products/endpoints/frontend/Endpoints.tsx
+++ b/products/endpoints/frontend/Endpoints.tsx
@@ -4,6 +4,7 @@ import { router } from 'kea-router'
import { IconRefresh } from '@posthog/icons'
import { LemonButton, LemonDialog } from '@posthog/lemon-ui'
+import { AccessControlAction } from 'lib/components/AccessControlAction'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { TagSelect } from 'lib/components/TagSelect'
import { More } from 'lib/lemon-ui/LemonButton/More'
@@ -18,7 +19,7 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { isHogQLQuery } from '~/queries/utils'
-import { EndpointType } from '~/types'
+import { AccessControlLevel, AccessControlResourceType, EndpointType } from '~/types'
import { humanizeQueryKind } from './common'
import { EndpointFromInsightModal } from './EndpointFromInsightModal'
@@ -169,30 +170,45 @@ export const EndpointsTable = (): JSX.Element => {
>
View usage
</LemonButton>
- <LemonButton onClick={() => handleDuplicate(record)} fullWidth>
- Duplicate endpoint
- </LemonButton>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton onClick={() => handleDuplicate(record)} fullWidth>
+ Duplicate endpoint
+ </LemonButton>
+ </AccessControlAction>
<LemonDivider />
- <LemonButton
- onClick={() => {
- handleEndpointActivation(record)
- }}
- fullWidth
- status="alt"
- data-attr="endpoint-activate"
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
>
- {record.is_active ? 'Deactivate endpoint' : 'Activate endpoint'}
- </LemonButton>
- <LemonButton
- onClick={() => {
- handleDelete(record.name)
- }}
- fullWidth
- status="danger"
+ <LemonButton
+ onClick={() => {
+ handleEndpointActivation(record)
+ }}
+ fullWidth
+ status="alt"
+ data-attr="endpoint-activate"
+ >
+ {record.is_active ? 'Deactivate endpoint' : 'Activate endpoint'}
+ </LemonButton>
+ </AccessControlAction>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
>
- Delete endpoint
- </LemonButton>
+ <LemonButton
+ onClick={() => {
+ handleDelete(record.name)
+ }}
+ fullWidth
+ status="danger"
+ >
+ Delete endpoint
+ </LemonButton>
+ </AccessControlAction>
</>
}
/>
diff --git a/products/endpoints/frontend/EndpointsScene.tsx b/products/endpoints/frontend/EndpointsScene.tsx
index a8651a0eb6a0..3ee3b55931ff 100644
--- a/products/endpoints/frontend/EndpointsScene.tsx
+++ b/products/endpoints/frontend/EndpointsScene.tsx
@@ -4,6 +4,7 @@ import { router } from 'kea-router'
import { IconPlusSmall } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
+import { AccessControlAction } from 'lib/components/AccessControlAction'
import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'
import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'
import { BigLeaguesHog } from 'lib/components/hedgehogs'
@@ -16,6 +17,7 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { Endpoints } from './Endpoints'
import { endpointsLogic } from './endpointsLogic'
@@ -70,24 +72,29 @@ export function EndpointsScene(): JSX.Element {
interaction="click"
scope={Scene.EndpointsScene}
>
- <LemonButton
- type="primary"
- to={urls.sqlEditor({ source: 'endpoint' })}
- sideAction={{
- dropdown: {
- placement: 'bottom-end',
- className: 'new-endpoint-overlay',
- actionable: true,
- overlay: <OverlayForNewEndpointMenu />,
- },
- 'data-attr': 'new-endpoint-dropdown',
- }}
- data-attr="new-endpoint-button"
- size="small"
- icon={<IconPlusSmall />}
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
>
- New
- </LemonButton>
+ <LemonButton
+ type="primary"
+ to={urls.sqlEditor({ source: 'endpoint' })}
+ sideAction={{
+ dropdown: {
+ placement: 'bottom-end',
+ className: 'new-endpoint-overlay',
+ actionable: true,
+ overlay: <OverlayForNewEndpointMenu />,
+ },
+ 'data-attr': 'new-endpoint-dropdown',
+ }}
+ data-attr="new-endpoint-button"
+ size="small"
+ icon={<IconPlusSmall />}
+ >
+ New
+ </LemonButton>
+ </AccessControlAction>
</AppShortcut>
}
/>
diff --git a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
index bed0c9f0fd7c..a8b7ee5f6042 100644
--- a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
+++ b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
@@ -13,10 +13,13 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
+import { AccessControlAction } from 'lib/components/AccessControlAction'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { MaterializationStatusModal } from 'scenes/data-warehouse/saved_queries/MaterializationStatusModal'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
import { endpointLogic } from '../endpointLogic'
import { endpointSceneLogic, MaterializationPreview } from '../endpointSceneLogic'
@@ -122,11 +125,16 @@ export function EndpointConfiguration(): JSX.Element {
Choose how fresh the returned data should be. Shorter periods serve fresher
data, but consume more compute.
</p>
- <LemonSelect
- value={effectiveDataFreshness}
- onChange={setDataFreshness}
- options={DATA_FRESHNESS_OPTIONS}
- />
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonSelect
+ value={effectiveDataFreshness}
+ onChange={setDataFreshness}
+ options={DATA_FRESHNESS_OPTIONS}
+ />
+ </AccessControlAction>
</div>
),
},
@@ -281,12 +289,17 @@ function MaterializationContent(): JSX.Element {
{canMaterialize && (
<div className="flex flex-col gap-4">
- <LemonSwitch
- label={isMaterialized ? 'Materialization enabled' : 'Enable materialization'}
- checked={isMaterialized}
- onChange={handleToggleMaterialization}
- bordered
- />
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonSwitch
+ label={isMaterialized ? 'Materialization enabled' : 'Enable materialization'}
+ checked={isMaterialized}
+ onChange={handleToggleMaterialization}
+ bordered
+ />
+ </AccessControlAction>
{hasUnsavedMaterializationChange && (
<LemonBanner type="info">
@@ -363,13 +376,20 @@ function MaterializationContent(): JSX.Element {
}
info="Your date range variables are bucketed into this interval in the stored materialized table. Smaller bucket - more precise results. Larger bucket - less granular results."
>
- <LemonSelect
- value={
- bucketOverrides[pair.column] || BUCKET_FN_TO_KEY[pair.bucket_fn] || 'day'
- }
- onChange={(value) => setBucketOverride(pair.column, value)}
- options={BUCKET_OPTIONS}
- />
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonSelect
+ value={
+ bucketOverrides[pair.column] ||
+ BUCKET_FN_TO_KEY[pair.bucket_fn] ||
+ 'day'
+ }
+ onChange={(value) => setBucketOverride(pair.column, value)}
+ options={BUCKET_OPTIONS}
+ />
+ </AccessControlAction>
</LemonField.Pure>
))}
</div>
diff --git a/products/endpoints/frontend/newEndpointMenu.tsx b/products/endpoints/frontend/newEndpointMenu.tsx
index d6dee40f22f7..4eeb72766a7a 100644
--- a/products/endpoints/frontend/newEndpointMenu.tsx
+++ b/products/endpoints/frontend/newEndpointMenu.tsx
@@ -4,8 +4,11 @@ import { router } from 'kea-router'
import { IconGraph, IconServer } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
+import { AccessControlAction } from 'lib/components/AccessControlAction'
import { urls } from 'scenes/urls'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
import { insightPickerEndpointModalLogic } from './insightPickerEndpointModalLogic'
interface EndpointTypeOption {
@@ -39,19 +42,24 @@ export function OverlayForNewEndpointMenu(): JSX.Element {
return (
<>
{options.map((option) => (
- <LemonButton
+ <AccessControlAction
key={option.name}
- icon={<option.icon />}
- onClick={option.onClick}
- data-attr={option.dataAttr}
- data-attr-endpoint-type={option.name}
- fullWidth
+ resourceType={AccessControlResourceType.Endpoint}
+ minAccessLevel={AccessControlLevel.Editor}
>
- <div className="flex flex-col text-sm py-1">
- <strong>{option.name}</strong>
- <span className="text-xs font-sans font-normal">{option.description}</span>
- </div>
- </LemonButton>
+ <LemonButton
+ icon={<option.icon />}
+ onClick={option.onClick}
+ data-attr={option.dataAttr}
+ data-attr-endpoint-type={option.name}
+ fullWidth
+ >
+ <div className="flex flex-col text-sm py-1">
+ <strong>{option.name}</strong>
+ <span className="text-xs font-sans font-normal">{option.description}</span>
+ </div>
+ </LemonButton>
+ </AccessControlAction>
))}
</>
)