: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
feat: add access control to heatmaps (#69099)
Reece Jones7e1302f49a8d
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex e5b6dfaf6b77..cd9ee11f8477 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -75,6 +75,7 @@ export const getStorybookAppContext = (): AppContext => ({action: 'manager',feature_flag: 'manager',hog_flow: 'manager',+ heatmap: 'manager',dashboard: 'manager',dashboard_template: 'manager',insight: 'manager',diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 83491ecd3f80..90aed8d91cf1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6931,9 +6931,9 @@ snapshots:scenes-app-settings-authentication-domains--one-unverified-domain--light:hash: v1.k794b7964.b1ae6dbc8feb673159fcc13f4a8fd5ee856c63ad1204e839a1b55ef70d109c81.W5sqRIJDHcdkKlYg4ghfwpbKS2FmlQKF_N-1C83h9Mgscenes-app-settings-environment--settings-environment-access-control--dark:- hash: v1.k794b7964.222d107f18e152ae12812a0528d78f76540c21ec182f6d6eb92a4a65b07bd3e4.EQnX6neFEFslnBu91IL2koLBLKE59kUYQGMZ1VRtr0U+ hash: v1.k794b7964.ae02475ed52a08862e75f53a748ddb98d30a653ba6a7e6723235812b00c58c75.54z1HwOspW4NeLQfCtsLEFfg2YlLuNm6KIJBd7dhvWkscenes-app-settings-environment--settings-environment-access-control--light:- hash: v1.k794b7964.8d5f2aa041a78acbfdd0c8729d52b9489b33c68619418cad4fbd66cbfedb4dab.mVNSIO0gJ9SYgflOqcsJ0LPZOsTx6AsA32iEQFPwVCo+ hash: v1.k794b7964.8da8ddf2ff9ced44baca60ca5f4ff95395b27c0d62b5fe1fe545e38f03d3b604.51JVG37C9A9uqbeF1X_7LuAE3hUneHOglJz3wMt09PQscenes-app-settings-environment--settings-environment-autocapture--dark:hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.-ybX8d6KyxaSa-yJDVccZm2CkK8Fl8qLSbw9jGhSIx4scenes-app-settings-environment--settings-environment-autocapture--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsxindex 7643a3eeb8f3..b452d2d17fd9 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx@@ -1,6 +1,7 @@import {IconApps,IconBug,+ IconCursorClick,IconEndpoints,IconCursor,IconDashboard,@@ -66,6 +67,8 @@ export function ScopeIcon(props: { scope: APIScopeObject }): JSX.Element | nullreturn <IconDatabase />case 'feature_flag':return <IconToggle />+ case 'heatmap':+ return <IconCursorClick />case 'hog_flow':return <IconDecisionTree />case 'insight':diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex 2464504ebcf8..b708fbb241d8 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -1139,6 +1139,7 @@ export const accessControlLogic = kea<accessControlLogicType>([const resourceToRoute: Partial<Record<APIScopeObject, string>> = {warehouse_view: 'warehouse_saved_queries',early_access_feature: 'early_access_feature',+ heatmap: 'saved',replay_scanner: 'vision/scanners',}const route = resourceToRoute[resource] ?? `${resource}s`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.tsindex 8304aaf70313..6a74bd4e8ca3 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@@ -180,6 +180,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(AccessControlResourceType.ExternalDataSource,AccessControlResourceType.WarehouseObjects,AccessControlResourceType.FeatureFlag,+ AccessControlResourceType.Heatmap,AccessControlResourceType.Insight,AccessControlResourceType.LlmAnalytics,AccessControlResourceType.McpAnalytics,diff --git a/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx b/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsxindex acfd2a878378..213625d427d6 100644--- a/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx+++ b/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'import { LemonBanner, LemonButton, LemonInput, LemonLabel } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { HeatmapAdvancedSettings } from 'scenes/heatmaps/components/HeatmapAdvancedSettings'import { HeatmapRecordingFallback } from 'scenes/heatmaps/components/HeatmapRecordingFallback'import { heatmapsBrowserLogic } from 'scenes/heatmaps/components/heatmapsBrowserLogic'@@ -9,6 +10,8 @@ import { HeatmapsForbiddenURL } from 'scenes/heatmaps/components/HeatmapsForbiddimport { HeatmapsInvalidURL } from 'scenes/heatmaps/components/HeatmapsInvalidURL'import { heatmapLogic } from 'scenes/heatmaps/scenes/heatmap/heatmapLogic'+import { AccessControlLevel, AccessControlResourceType } from '~/types'+export function HeatmapHeader(): JSX.Element {const {pageUrlDraft,@@ -19,6 +22,7 @@ export function HeatmapHeader(): JSX.Element {displayUrl,displayUrlIsPattern,type,+ userAccessLevel,} = useValues(heatmapLogic)const { iframeBanner, dataUrl, isBrowserUrlAuthorized } = useValues(heatmapsBrowserLogic)const { setPageUrlDraft, applyPageUrlDraft, regenerateScreenshot, changeCaptureMethod } = useActions(heatmapLogic)@@ -41,15 +45,21 @@ export function HeatmapHeader(): JSX.Element {onPressEnter={applyPageUrlDraft}fullWidth={true}/>- <LemonButton- type="secondary"- size="small"- onClick={applyPageUrlDraft}- loading={loading}- disabledReason={disabledReason}+ <AccessControlAction+ resourceType={AccessControlResourceType.Heatmap}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel ?? undefined}>- Regenerate- </LemonButton>+ <LemonButton+ type="secondary"+ size="small"+ onClick={applyPageUrlDraft}+ loading={loading}+ disabledReason={disabledReason}+ >+ Regenerate+ </LemonButton>+ </AccessControlAction></div><div className="text-xs text-muted mt-1">The page we load in the iframe or capture as a screenshot.diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsx b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsxindex b57e7f1658a9..a27cb54d5ef9 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsx+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsx@@ -4,6 +4,7 @@ import useResizeObserver from 'use-resize-observer'import { IconCheckCircle, IconWarning } from '@posthog/icons'import { LemonBanner, LemonButton, LemonCard, LemonLabel, Spinner } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { FEATURE_FLAGS } from 'lib/constants'import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'@@ -20,7 +21,7 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { HeatmapType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, HeatmapType } from '~/types'import { HeatmapCreationStep, heatmapCreationLogic } from './heatmapCreationLogic'import { heatmapLogic } from './heatmapLogic'@@ -546,15 +547,20 @@ function ReviewStep(): JSX.Element {View heatmap</LemonButton>) : (- <LemonButton- type="primary"- onClick={() => createHeatmap(creationContext)}- loading={loading}- disabledReason={reviewBlockReason}- data-attr="save-heatmap"+ <AccessControlAction+ resourceType={AccessControlResourceType.Heatmap}+ minAccessLevel={AccessControlLevel.Editor}>- Create heatmap- </LemonButton>+ <LemonButton+ type="primary"+ onClick={() => createHeatmap(creationContext)}+ loading={loading}+ disabledReason={reviewBlockReason}+ data-attr="save-heatmap"+ >+ Create heatmap+ </LemonButton>+ </AccessControlAction>)}</div></div>diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewSceneLegacy.tsx b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewSceneLegacy.tsxindex 753ace105fe4..d2eeaa4f5ab0 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewSceneLegacy.tsx+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewSceneLegacy.tsx@@ -3,6 +3,7 @@ import { useDebouncedCallback } from 'use-debounce'import { Spinner } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'@@ -18,7 +19,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { SceneSection } from '~/layout/scenes/components/SceneSection'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { HeatmapType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, HeatmapType } from '~/types'import { heatmapLogic } from './heatmapLogic'@@ -132,24 +133,29 @@ export function HeatmapNewSceneLegacy(): JSX.Element {/><SceneDivider /><div className="flex gap-2">- <LemonButton- className="w-fit"- type="primary"- data-attr="save-heatmap"- onClick={() => createHeatmap()}- loading={false}- disabledReason={- !displayUrl- ? 'URL is required'- : !isDisplayUrlValid- ? 'Enter a valid URL'- : !!dataUrl && !isBrowserUrlAuthorized- ? 'Authorize the URL first'- : null- }+ <AccessControlAction+ resourceType={AccessControlResourceType.Heatmap}+ minAccessLevel={AccessControlLevel.Editor}>- Save- </LemonButton>+ <LemonButton+ className="w-fit"+ type="primary"+ data-attr="save-heatmap"+ onClick={() => createHeatmap()}+ loading={false}+ disabledReason={+ !displayUrl+ ? 'URL is required'+ : !isDisplayUrlValid+ ? 'Enter a valid URL'+ : !!dataUrl && !isBrowserUrlAuthorized+ ? 'Authorize the URL first'+ : null+ }+ >+ Save+ </LemonButton>+ </AccessControlAction></div></SceneContent>)diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.tsx b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.tsxindex 299142304b03..4f57c0330f9b 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.tsx+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.tsx@@ -6,6 +6,7 @@ import { IconBrowser, IconDownload } from '@posthog/icons'import { LemonTag, Spinner } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { appEditorUrl } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'import { MAX_HEATMAP_HEIGHT } from 'lib/components/heatmaps/heatmapDataLogic'@@ -15,6 +16,7 @@ import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { FilterPanel } from 'scenes/heatmaps/components/FilterPanel'import { HeatmapHeader } from 'scenes/heatmaps/components/HeatmapHeader'+import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'@@ -26,6 +28,12 @@ import { heatmapLogic } from './heatmapLogic'const HedgehogDirector = pngHoggie(directorPng)+export const scene: SceneExport<{ id: string }> = {+ component: HeatmapScene,+ logic: heatmapLogic,+ paramsToProps: ({ params: { id } }) => ({ id }),+}+export function HeatmapScene({ id }: { id: string }): JSX.Element {const logicProps = { id: id }const logic = heatmapLogic(logicProps)@@ -45,6 +53,7 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {effectiveWidth,scalePercent,isHeightCapped,+ userAccessLevel,} = useValues(logic)const {setName,@@ -106,9 +115,15 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {}}actions={<>- <LemonButton type="primary" onClick={updateHeatmap} size="small">- Save- </LemonButton>+ <AccessControlAction+ resourceType={AccessControlResourceType.Heatmap}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel ?? undefined}+ >+ <LemonButton type="primary" onClick={updateHeatmap} size="small">+ Save+ </LemonButton>+ </AccessControlAction><LemonButtononClick={exportHeatmap}data-attr="export-heatmap"diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.tsindex edd6fe8e22db..14bfdb8aa255 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts@@ -13,7 +13,8 @@ import { heatmapsBrowserLogic, isUrlPattern } from 'scenes/heatmaps/components/himport { heatmapsSceneLogic } from 'scenes/heatmaps/scenes/heatmaps/heatmapsSceneLogic'import { teamLogic } from 'scenes/teamLogic'-import { HeatmapStatus, HeatmapType } from '~/types'+import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'+import { AccessControlLevel, ActivityScope, HeatmapStatus, HeatmapType } from '~/types'import {getHeatmapScreenshotsContentRetrieveUrl,@@ -131,8 +132,10 @@ export interface heatmapLogicValues {screenshotLoaded: booleanscreenshotLoading: booleanscreenshotUrl: string | null+ sidePanelContext: SidePanelSceneContext | nullstatus: HeatmapStatustype: HeatmapType+ userAccessLevel: AccessControlLevel | nullwidth: number | null}@@ -219,6 +222,9 @@ export interface heatmapLogicActions {setType: (type: HeatmapType) => {type: HeatmapType}+ setUserAccessLevel: (level: AccessControlLevel | null) => {+ level: AccessControlLevel | null+ }setWidth: (width: number) => {width: number}@@ -317,6 +323,7 @@ export const heatmapLogic = kea<heatmapLogicType>([snapshotSavedBlockConsentModals: (value: boolean) => ({ value }),setPageUrlDraft: (value: string) => ({ value }),applyPageUrlDraft: true,+ setUserAccessLevel: (level: AccessControlLevel | null) => ({ level }),}),reducers({type: ['screenshot' as HeatmapType, { setType: (_, { type }) => type }],@@ -342,6 +349,7 @@ export const heatmapLogic = kea<heatmapLogicType>([setDisplayUrl: (_, { url }) => url ?? '',},],+ userAccessLevel: [null as AccessControlLevel | null, { setUserAccessLevel: (_, { level }) => level }],}),listeners(({ actions, values, props, cache }) => ({changeCaptureMethod: async ({ type }) => {@@ -377,6 +385,7 @@ export const heatmapLogic = kea<heatmapLogicType>([actions.snapshotSavedDisplayUrl(item.url ?? null)actions.setBlockConsentModals(item.block_consent_modals ?? false)actions.snapshotSavedBlockConsentModals(item.block_consent_modals ?? false)+ actions.setUserAccessLevel((item.user_access_level ?? null) as AccessControlLevel | null)actions.setType(item.type ?? 'screenshot')posthog.capture('in-app heatmap viewed', {heatmap_type: item.type,@@ -619,6 +628,21 @@ export const heatmapLogic = kea<heatmapLogicType>([},],}),+ selectors(({ props }) => ({+ [SIDE_PANEL_CONTEXT_KEY]: [+ () => [],+ (): SidePanelSceneContext | null => {+ return props.id && String(props.id) !== 'new'+ ? {+ activity_scope: ActivityScope.HEATMAP,+ activity_item_id: `${props.id}`,+ access_control_resource: 'heatmap',+ access_control_resource_id: `${props.id}`,+ }+ : null+ },+ ],+ })),afterMount(({ actions }) => {actions.load()}),diff --git a/frontend/src/scenes/heatmaps/scenes/heatmaps/HeatmapsScene.tsx b/frontend/src/scenes/heatmaps/scenes/heatmaps/HeatmapsScene.tsxindex 827b19c96c7b..3b1feb6d007e 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmaps/HeatmapsScene.tsx+++ b/frontend/src/scenes/heatmaps/scenes/heatmaps/HeatmapsScene.tsx@@ -3,6 +3,7 @@ import { useActions, useValues } from 'kea'import { IconPlusSmall } from '@posthog/icons'import { LemonButton, LemonInput, LemonTable, LemonTableColumn, LemonTableColumns, Link } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { MemberSelect } from 'lib/components/MemberSelect'import { Shortcut } from 'lib/components/Shortcuts/Shortcut'import { keyBinds } from 'lib/components/Shortcuts/shortcuts'@@ -18,7 +19,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 { HeatmapScreenshotType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, HeatmapScreenshotType } from '~/types'import { HEATMAPS_PER_PAGE, heatmapsSceneLogic } from './heatmapsSceneLogic'@@ -86,14 +87,20 @@ export function HeatmapsScene(): JSX.Element {<Moreoverlay={<>- <LemonButton- status="danger"- onClick={() => deleteHeatmap(row.short_id)}- fullWidth- loading={savedHeatmapsLoading}+ <AccessControlAction+ resourceType={AccessControlResourceType.Heatmap}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={row.user_access_level}>- Delete- </LemonButton>+ <LemonButton+ status="danger"+ onClick={() => deleteHeatmap(row.short_id)}+ fullWidth+ loading={savedHeatmapsLoading}+ >+ Delete+ </LemonButton>+ </AccessControlAction></>}/>@@ -119,16 +126,21 @@ export function HeatmapsScene(): JSX.Element {interaction="click"scope={Scene.Heatmaps}>- <LemonButton- type="primary"- to={urls.heatmap('new')}- data-attr="heatmaps-new-heatmap-button"- size="small"- icon={<IconPlusSmall />}- tooltip="New heatmap"+ <AccessControlAction+ resourceType={AccessControlResourceType.Heatmap}+ minAccessLevel={AccessControlLevel.Editor}>- New heatmap- </LemonButton>+ <LemonButton+ type="primary"+ to={urls.heatmap('new')}+ data-attr="heatmaps-new-heatmap-button"+ size="small"+ icon={<IconPlusSmall />}+ tooltip="New heatmap"+ >+ New heatmap+ </LemonButton>+ </AccessControlAction></Shortcut>}/>diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex a9b97ac201bc..d65e5bc7f310 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -347,6 +347,11 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.Insight]: AccessControlResourceType.Insight,[Scene.SavedInsights]: AccessControlResourceType.Insight,+ // Heatmaps+ [Scene.Heatmaps]: AccessControlResourceType.Heatmap,+ [Scene.Heatmap]: AccessControlResourceType.Heatmap,+ [Scene.HeatmapNew]: AccessControlResourceType.Heatmap,+// Notebooks[Scene.Notebook]: AccessControlResourceType.Notebook,[Scene.Notebooks]: AccessControlResourceType.Notebook,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex c47787e5ef4e..c23713448972 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -288,6 +288,7 @@ export enum AccessControlResourceType {Action = 'action',CustomerAnalytics = 'customer_analytics',FeatureFlag = 'feature_flag',+ Heatmap = 'heatmap',Insight = 'insight',Dashboard = 'dashboard',DashboardTemplate = 'dashboard_template',@@ -7698,6 +7699,7 @@ export interface HeatmapScreenshotType {exception?: stringerror?: string // Added for error responses from content endpointcreated_by?: UserBasicType | null+ user_access_level?: AccessControlLevel}export type HeatmapScreenshotContentResponse =diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex e6520dd521c9..62d6414cedad 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -69,6 +69,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = ("external_data_source","warehouse_objects","feature_flag",+ "heatmap","hog_flow","insight","llm_analytics",@@ -420,6 +421,8 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:return "export"if name == "sessionrecordingplaylist":return "session_recording_playlist"+ if name == "savedheatmap":+ return "heatmap"if name == "experimentsavedmetric":return "experiment_saved_metric"if name == "experimentholdout":diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex f6ed3b1dbccb..df939f7ac7fe 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -14,6 +14,9 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_fieldfrom prometheus_client import Counterfrom rest_framework import request, response, serializers, status, viewsets+from rest_framework.exceptions import PermissionDenied+from rest_framework.permissions import BasePermission+from rest_framework.views import APIViewfrom posthog.schema import DateRange, HogQLFilters, HogQLQueryResponse, ProductKey@@ -35,12 +38,15 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Detail, log_activity+from posthog.permissions import AccessControlPermission, is_service_authfrom posthog.rate_limit import (AIBurstRateThrottle,AISustainedRateThrottle,ClickHouseBurstRateThrottle,ClickHouseSustainedRateThrottle,)+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin+from posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.security.url_validation import is_url_allowedfrom posthog.utils import relative_date_parse_with_delta_mapping@@ -171,6 +177,41 @@ def parse_fold_summary_row(row: Any) -> dict[str, Any]:}+def anchor_url_pattern(value: str) -> str:+ """Anchor (and loosen unescaped `*`) a raw url_pattern the same way the heatmaps ClickHouse+ query does, so callers matching against it in Python (e.g. permission checks) stay consistent+ with the anchored regex `match(current_url, {url_pattern})` uses in DEFAULT_QUERY/EVENTS_QUERY."""+ validated_value = value++ # we insist on the pattern being anchored+ if not value.startswith("^"):+ validated_value = f"^{value}"+ if not value.endswith("$"):+ validated_value = f"{validated_value}$"++ # KLUDGE: we allow API callers to send something that isn't really `re2` syntax used in match()+ # KLUDGE: so if it has * but not .* then we expect at least one character to match, so we use .+ instead+ # KLUDGE: this means we don't support valid regex since we can't support matching aaaaa with a*+ # KLUDGE: but you could send a+ and it would match aaaaa+ validated_value = "".join(+ [f".+" if c == "*" and i > 0 and validated_value[i - 1] != "." else c for i, c in enumerate(validated_value)]+ )++ return validated_value+++def resolve_url_filter(url_exact: str | None, url_pattern: str | None) -> tuple[str | None, str | None]:+ """Resolve which of url_exact/url_pattern the query actually filters on when both are supplied,+ so every caller (the request serializer and the permission check) authorizes and queries the+ same value: equal values keep url_exact, differing values keep url_pattern (matching+ HeatmapsRequestSerializer.validate())."""+ if isinstance(url_exact, str) and isinstance(url_pattern, str):+ if url_exact == url_pattern:+ return url_exact, None+ return None, url_pattern+ return url_exact, url_pattern++class HeatmapsRequestSerializer(serializers.Serializer):viewport_width_min = serializers.IntegerField(required=False,@@ -295,36 +336,16 @@ class HeatmapsRequestSerializer(serializers.Serializer):def validate_url_pattern(self, value: str | None) -> str | None:if value is None:return None-- validated_value = value-- # we insist on the pattern being anchored- if not value.startswith("^"):- validated_value = f"^{value}"- if not value.endswith("$"):- validated_value = f"{validated_value}$"-- # KLUDGE: we allow API callers to send something that isn't really `re2` syntax used in match()- # KLUDGE: so if it has * but not .* then we expect at least one character to match, so we use .+ instead- # KLUDGE: this means we don't support valid regex since we can't support matching aaaaa with a*- # KLUDGE: but you could send a+ and it would match aaaaa- validated_value = "".join(- [- f".+" if c == "*" and i > 0 and validated_value[i - 1] != "." else c- for i, c in enumerate(validated_value)- ]- )-- return validated_value+ return anchor_url_pattern(value)def validate(self, values) -> dict:url_exact = values.get("url_exact", None)url_pattern = values.get("url_pattern", None)- if isinstance(url_exact, str) and isinstance(url_pattern, str):- if url_exact == url_pattern:- values.pop("url_pattern")- else:- values.pop("url_exact")+ resolved_exact, resolved_pattern = resolve_url_filter(url_exact, url_pattern)+ if resolved_exact is None and url_exact is not None:+ values.pop("url_exact")+ if resolved_pattern is None and url_pattern is not None:+ values.pop("url_pattern")if values.get("filter_test_accounts") and not isinstance(values.get("filter_test_accounts"), bool):raise serializers.ValidationError("filter_test_accounts must be a boolean")@@ -429,10 +450,80 @@ class HeatmapEventsResponseSerializer(serializers.Serializer):has_more = serializers.BooleanField(required=True)+class HeatmapAggregateQueryScopingPermission(AccessControlPermission):+ """+ `HeatmapViewSet`/`LegacyHeatmapViewSet` share `scope_object = "heatmap"` with+ `SavedHeatmapViewSet`, whose rows can carry independent object-level access grants.+ `list`/`events` have no bindable object of their own — they're arbitrary ClickHouse+ aggregate queries filtered by `url_exact`/`url_pattern` request params — so without this+ override, the base class's "has ANY specific-object grant for this resource type"+ fallback would let a viewer of ONE saved heatmap read aggregate click/event data for ANY+ url on the site.++ Scope the fallback down: a specific-object grant only satisfies this permission for a+ `url_exact` request that matches a `SavedHeatmap.data_url` (or `url`, its default) the user+ has at least the required access level on — the same value the in-app heatmap overlay always+ queries with (see heatmapDataLogic.ts). `url_pattern` requests always require resource-level+ access: the query matches the pattern against every row in the dataset, so an object grant for+ one saved heatmap can't bound what a broad pattern is allowed to read.+ """++ def has_permission(self, request, view) -> bool:+ if is_service_auth(request):+ return True++ uac = self._get_user_access_control(request, view)+ required_level = self._get_required_access_level(request, view)++ if not required_level:+ return True++ if uac.check_access_level_for_resource("heatmap", required_level=required_level):+ return True++ try:+ team = view.team+ except (ValueError, KeyError):+ return True++ # Resolve the same way HeatmapsRequestSerializer does — otherwise a caller could get+ # authorized against url_exact while the query that actually runs reads url_pattern (or+ # vice versa), authorizing one URL and querying another. `validate_url_pattern` anchors+ # the raw url_pattern *before* `validate()` compares it against url_exact, so a raw+ # url_pattern equal to url_exact no longer matches once anchored — apply the same+ # transform here, or a caller could send matching raw url_exact/url_pattern values to get+ # authorized as an exact match while the anchored pattern actually executes.+ raw_url_pattern = request.query_params.get("url_pattern")+ anchored_url_pattern = anchor_url_pattern(raw_url_pattern) if raw_url_pattern else raw_url_pattern+ url_exact, _ = resolve_url_filter(request.query_params.get("url_exact"), anchored_url_pattern)+ if not url_exact:+ # A url_pattern query matches every row whose current_url satisfies the pattern, not+ # just the granted SavedHeatmap's URL — an object grant can't bound that, so patterns+ # (and requests with no URL filter at all) require resource-level "heatmap" access.+ self.message = f"You do not have {required_level} access to this resource."+ return False++ # Prewarm rows are speculative implementation details, not user-saved authorization anchors.+ # Their creators implicitly own them, so including them would turn prewarming into aggregate-data access.+ candidates = SavedHeatmap.objects.filter(team=team, deleted=False, is_prewarm=False)+ for candidate in candidates:+ candidate_url = candidate.data_url or candidate.url+ # Match the same way the aggregate query does: url_exact ignores a trailing slash+ # (`trimRight(current_url, '/')`).+ if candidate_url.rstrip("/") == url_exact.rstrip("/") and uac.check_access_level_for_object(+ candidate, required_level=required_level+ ):+ return True++ self.message = f"You do not have {required_level} access to this resource."+ return False++class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):authentication_classes = [ExportRendererAuthentication]scope_object = "heatmap"scope_object_read_actions = ["list", "retrieve", "events"]+ permission_classes = [HeatmapAggregateQueryScopingPermission]throttle_classes = [ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle]serializer_class = HeatmapsResponseSerializer@@ -742,7 +833,7 @@ class HeatmapSnapshotMetadataSerializer(serializers.Serializer):)-class HeatmapScreenshotResponseSerializer(serializers.ModelSerializer):+class HeatmapScreenshotResponseSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)snapshots = serializers.SerializerMethodField(help_text="Per-width render metadata. Fetch the actual image bytes for a width from the content endpoint."@@ -767,6 +858,7 @@ class HeatmapScreenshotResponseSerializer(serializers.ModelSerializer):"created_at","updated_at","exception",+ "user_access_level",]read_only_fields = ["id",@@ -883,7 +975,7 @@ class HeatmapScreenshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):snapshot = min(all_snaps, key=lambda s: abs(s.width - requested_width))if not snapshot:- response_serializer = HeatmapScreenshotResponseSerializer(screenshot)+ response_serializer = HeatmapScreenshotResponseSerializer(screenshot, context=self.get_serializer_context())return _finish(response.Response(response_serializer.data, status=status.HTTP_202_ACCEPTED),"generating",@@ -896,7 +988,7 @@ class HeatmapScreenshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)return _finish(http_response, "served")elif snapshot.content_location:- response_serializer = HeatmapScreenshotResponseSerializer(screenshot)+ response_serializer = HeatmapScreenshotResponseSerializer(screenshot, context=self.get_serializer_context())return _finish(response.Response({**response_serializer.data, "error": "Content location not implemented yet"},@@ -907,7 +999,7 @@ class HeatmapScreenshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):served_width=snapshot.width,)else:- response_serializer = HeatmapScreenshotResponseSerializer(screenshot)+ response_serializer = HeatmapScreenshotResponseSerializer(screenshot, context=self.get_serializer_context())return _finish(response.Response(response_serializer.data, status=status.HTTP_202_ACCEPTED),"generating",@@ -1007,8 +1099,24 @@ class HeatmapPrewarmRequestSerializer(serializers.Serializer):return validate_page_url(value)-class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.GenericViewSet):+class HeatmapPrewarmResourceAccessPermission(BasePermission):+ message = "You do not have editor access to this resource."++ def has_permission(self, request: request.Request, view: APIView) -> bool:+ saved_heatmap_view = cast("SavedHeatmapViewSet", view)+ if saved_heatmap_view.action != "prewarm" or is_service_auth(request):+ return True++ return saved_heatmap_view.user_access_control.check_access_level_for_resource(+ "heatmap", required_level="editor"+ )+++class SavedHeatmapViewSet(+ TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDestroyModel, viewsets.GenericViewSet+):scope_object = "heatmap"+ permission_classes = [HeatmapPrewarmResourceAccessPermission]throttle_classes = [ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle]serializer_class = HeatmapScreenshotResponseSerializerqueryset = SavedHeatmap.objects.all()@@ -1082,9 +1190,12 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Glimit = max(1, min(params["limit"], 500))offset = max(0, params["offset"])count = qs.count()- results = qs[offset : offset + limit]+ # Materialize to a list (rather than passing the queryset slice through) so+ # UserAccessControlSerializerMixin recognizes it as a batch and preloads object+ # access controls once, instead of querying per-row.+ results = list(qs[offset : offset + limit])- data = HeatmapScreenshotResponseSerializer(results, many=True).data+ data = HeatmapScreenshotResponseSerializer(results, many=True, context=self.get_serializer_context()).datareturn response.Response({"results": data, "count": count}, status=status.HTTP_200_OK)@extend_schema(@@ -1179,7 +1290,8 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Gif enqueue_render:generate_heatmap_screenshot.delay(screenshot.id)- return response.Response(HeatmapScreenshotResponseSerializer(screenshot).data, status=status.HTTP_201_CREATED)+ response_serializer = HeatmapScreenshotResponseSerializer(screenshot, context=self.get_serializer_context())+ return response.Response(response_serializer.data, status=status.HTTP_201_CREATED)@extend_schema(request=HeatmapPrewarmRequestSerializer,@@ -1233,7 +1345,8 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.G):self._regenerate(obj)- return response.Response(HeatmapScreenshotResponseSerializer(obj).data, status=status.HTTP_200_OK)+ response_serializer = HeatmapScreenshotResponseSerializer(obj, context=self.get_serializer_context())+ return response.Response(response_serializer.data, status=status.HTTP_200_OK)@extend_schema(request=None,@@ -1250,7 +1363,8 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.G)self._regenerate(obj)- return response.Response(HeatmapScreenshotResponseSerializer(obj).data, status=status.HTTP_200_OK)+ response_serializer = HeatmapScreenshotResponseSerializer(obj, context=self.get_serializer_context())+ return response.Response(response_serializer.data, status=status.HTTP_200_OK)def _regenerate(self, obj: SavedHeatmap) -> None:obj.status = SavedHeatmap.Status.PROCESSING@@ -1269,6 +1383,20 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Gobj = self.get_object()old_url = obj.urlold_block_consent_modals = obj.block_consent_modals++ url_fields_changed = any(+ field in request.data and request.data[field] != getattr(obj, field) for field in ("url", "data_url")+ )+ if url_fields_changed and not self.user_access_control.check_access_level_for_resource(+ "heatmap", required_level="editor"+ ):+ # An object-level grant authorizes edits to *this* heatmap only. Letting that grant also+ # cover retargeting its url/data_url would let the grantee move which page's aggregate+ # data HeatmapAggregateQueryScopingPermission's object-grant fallback authorizes — escaping+ # the grant's intended scope. Require resource-level access to move the URL a grant is+ # anchored to.+ raise PermissionDenied("You do not have permission to change the URL of this heatmap.")+serializer = SavedHeatmapRequestSerializer(obj, data=request.data, partial=True)serializer.is_valid(raise_exception=True)updated = serializer.save()@@ -1289,4 +1417,5 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Gdetail=Detail(name=updated.name or updated.url, short_id=updated.short_id, type=updated.type),was_impersonated=is_impersonated(request),)- return response.Response(HeatmapScreenshotResponseSerializer(updated).data, status=status.HTTP_200_OK)+ response_serializer = HeatmapScreenshotResponseSerializer(updated, context=self.get_serializer_context())+ return response.Response(response_serializer.data, status=status.HTTP_200_OK)diff --git a/products/web_analytics/backend/test/test_heatmap_access_control.py b/products/web_analytics/backend/test/test_heatmap_access_control.pynew file mode 100644index 000000000000..7c4f9c8fd057--- /dev/null+++ b/products/web_analytics/backend/test/test_heatmap_access_control.py@@ -0,0 +1,438 @@+import pytest+from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.kafka_client.client import ClickhouseProducer+from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS+from posthog.models.event.util import format_clickhouse_timestamp+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.web_analytics.backend.models import SavedHeatmap+from products.web_analytics.backend.test.test_heatmaps_api import INSERT_SINGLE_HEATMAP_EVENT++try:+ from ee.models.rbac.access_control import AccessControl+except ImportError:+ pass+++class TestHeatmapResourceRegistration(SimpleTestCase):+ def test_heatmap_is_a_controllable_resource(self):+ self.assertIn("heatmap", ACCESS_CONTROL_RESOURCES)++ def test_saved_heatmap_model_maps_to_heatmap_resource(self):+ self.assertEqual(model_to_resource(SavedHeatmap()), "heatmap")+++class TestHeatmapAccessControl(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.heatmap = SavedHeatmap.objects.create(+ team=self.team,+ name="my heatmap",+ url="https://example.com",+ target_widths=[1024],+ created_by=self.user,+ status=SavedHeatmap.Status.COMPLETED,+ )++ def _create_access_control(self, user, resource="heatmap", 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="heatmap", 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}/saved/"++ def _detail_url(self, short_id=None) -> str:+ return f"/api/environments/{self.team.pk}/saved/{short_id or self.heatmap.short_id}/"++ @parameterized.expand(+ [+ # (access_level, method, expected_status, patch_body)+ ("viewer", "GET", status.HTTP_200_OK, None),+ ("viewer", "PATCH", status.HTTP_403_FORBIDDEN, {"name": "updated"}),+ ("viewer", "POST_REGENERATE", status.HTTP_403_FORBIDDEN, None),+ ("editor", "GET", status.HTTP_200_OK, None),+ ("editor", "PATCH", status.HTTP_200_OK, {"name": "updated"}),+ ("editor", "POST_REGENERATE", status.HTTP_200_OK, 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 == "POST_REGENERATE":+ response = self.client.post(self._detail_url() + "regenerate/")+ 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_heatmap(self):+ # Resource-level viewer access, but object-level "none" on this specific heatmap.+ self._create_access_control(self.viewer_user, access_level="viewer")+ self._create_access_control(self.viewer_user, resource_id=str(self.heatmap.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)++ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay")+ def test_create_blocked_without_resource_editor_access(self, mock_task):+ 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={"url": "https://example.com/blocked"}, format="json")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertFalse(SavedHeatmap.objects.filter(team=self.team, url="https://example.com/blocked").exists())+ mock_task.assert_not_called()++ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay")+ def test_create_allowed_with_resource_editor_access(self, mock_task):+ 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={"url": "https://example.com/allowed"}, format="json")+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ self.assertTrue(SavedHeatmap.objects.filter(team=self.team, url="https://example.com/allowed").exists())++ @parameterized.expand(+ [+ ("object_editor", True, status.HTTP_403_FORBIDDEN),+ ("resource_editor", False, status.HTTP_201_CREATED),+ ]+ )+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay")+ def test_prewarm_requires_resource_editor_access(+ self, _name: str, object_grant: bool, expected_status: int, mock_task: MagicMock+ ) -> None:+ self._create_project_default(access_level="none")+ self._create_access_control(+ self.editor_user,+ resource_id=str(self.heatmap.id) if object_grant else None,+ access_level="editor",+ )+ self.client.force_login(self.editor_user)+ url = f"https://example.com/prewarm-{_name}"++ response = self.client.post(self._list_url() + "prewarm/", data={"url": url}, format="json")++ self.assertEqual(response.status_code, expected_status, response.json())+ self.assertEqual(SavedHeatmap.objects.filter(team=self.team, url=url).exists(), not object_grant)+ if object_grant:+ mock_task.assert_not_called()+ else:+ mock_task.assert_called_once()++ def test_creator_list_filters_out_object_blocked_heatmap(self):+ # Creator sees their own heatmap; an object-level "none" on another user's heatmap excludes it.+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ other_heatmap = SavedHeatmap.objects.create(+ team=self.team,+ name="other heatmap",+ url="https://other.example.com",+ target_widths=[1024],+ created_by=other_user,+ status=SavedHeatmap.Status.COMPLETED,+ )+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="heatmap",+ resource_id=str(other_heatmap.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 = [h["short_id"] for h in response.json()["results"]]+ self.assertIn(self.heatmap.short_id, names)+ self.assertNotIn(other_heatmap.short_id, 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 heatmap, while other heatmaps stay blocked.+ other_heatmap = SavedHeatmap.objects.create(+ team=self.team,+ name="other heatmap",+ url="https://other.example.com",+ target_widths=[1024],+ created_by=self.user,+ status=SavedHeatmap.Status.COMPLETED,+ )+ self._create_project_default(access_level="none")+ self._create_access_control(self.viewer_user, resource_id=str(self.heatmap.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={"name": "granted edit"}, format="json")+ self.assertEqual(patch_response.status_code, status.HTTP_200_OK)++ # A different heatmap without an object-level grant stays blocked.+ self.assertEqual(+ self.client.get(self._detail_url(other_heatmap.short_id)).status_code, status.HTTP_403_FORBIDDEN+ )++ def test_object_level_editor_cannot_retarget_heatmap_url(self):+ # Regression: HeatmapAggregateQueryScopingPermission's object-grant fallback authorizes+ # aggregate queries by matching the request's url_exact against a SavedHeatmap the caller+ # has object-level access to. If an object-only editor could repoint that heatmap's+ # url/data_url, they could retarget which page's aggregate data the grant covers — an+ # object grant on one heatmap must not become a way to read data for an arbitrary URL.+ self._create_project_default(access_level="none")+ self._create_access_control(self.viewer_user, resource_id=str(self.heatmap.id), access_level="editor")+ self.client.force_login(self.viewer_user)++ retarget_response = self.client.patch(+ self._detail_url(), data={"url": "https://attacker-controlled.example.com"}, format="json"+ )+ self.assertEqual(retarget_response.status_code, status.HTTP_403_FORBIDDEN, retarget_response.json())+ self.heatmap.refresh_from_db()+ self.assertEqual(self.heatmap.url, "https://example.com")++ # Non-URL fields on the same object-level grant are unaffected.+ rename_response = self.client.patch(self._detail_url(), data={"name": "still allowed"}, format="json")+ self.assertEqual(rename_response.status_code, status.HTTP_200_OK, rename_response.json())++ def test_response_includes_user_access_level(self):+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)+ response = self.client.get(self._detail_url())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["user_access_level"], "editor")++ def test_list_response_includes_user_access_level(self):+ # The list path preloads access controls via a separate batch code path+ # (UserAccessControlSerializerMixin) from retrieve — assert it independently so a+ # regression there (e.g. a silent `None`) is caught even if retrieve still passes.+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)+ response = self.client.get(self._list_url())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ result = next(h for h in response.json()["results"] if h["short_id"] == self.heatmap.short_id)+ self.assertEqual(result["user_access_level"], "editor")+++class TestHeatmapAggregateQueryAccessControl(ClickhouseTestMixin, APIBaseTest):+ """+ Regression coverage for a privilege-escalation reported on the access-control PR: `heatmap`+ is the shared `scope_object` for both `SavedHeatmapViewSet` (persisted, object-bindable) and+ `HeatmapViewSet`/`LegacyHeatmapViewSet` (ClickHouse aggregate queries with no object to bind+ to). `AccessControlPermission`'s generic "has ANY specific-object grant for this resource+ type" fallback doesn't know the aggregate endpoints have no real object — so a viewer granted+ access to ONE saved heatmap could query aggregate click/event data for ANY url on the site.+ """++ def setUp(self):+ super().setUp()++ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()++ self.viewer_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")++ self.authorized_heatmap = SavedHeatmap.objects.create(+ team=self.team,+ name="authorized",+ url="https://example.com/authorized",+ data_url="https://example.com/authorized",+ target_widths=[1024],+ created_by=self.user,+ status=SavedHeatmap.Status.COMPLETED,+ )++ # Resource-level default is "none" — the only access this user has is the object-level+ # grant on `self.authorized_heatmap` below.+ AccessControl.objects.create(+ team=self.team, resource="heatmap", resource_id=None, access_level="none", organization_member=None+ )+ membership = OrganizationMembership.objects.get(user=self.viewer_user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="heatmap",+ resource_id=str(self.authorized_heatmap.id),+ access_level="viewer",+ organization_member=membership,+ )++ self._insert_heatmap_click(url="https://example.com/authorized")+ self._insert_heatmap_click(url="https://example.com/secret-unrelated-page")++ def _insert_heatmap_click(self, url: str) -> None:+ p = ClickhouseProducer()+ p.produce(+ topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,+ sql=INSERT_SINGLE_HEATMAP_EVENT,+ data={+ "session_id": "session1",+ "team_id": self.team.pk,+ "distinct_id": "user1",+ "timestamp": format_clickhouse_timestamp("2023-03-08T09:00:00"),+ "x": 10,+ "y": 20,+ "scale_factor": 16,+ "viewport_width": 100,+ "viewport_height": 100,+ "type": "click",+ "pointer_target_fixed": True,+ "current_url": url,+ },+ )++ def _query_aggregate(self, url_exact: str | None = None, url_pattern: str | None = None):+ self.client.force_login(self.viewer_user)+ params: dict[str, str] = {"type": "click", "date_from": "2023-03-01"}+ if url_exact is not None:+ params["url_exact"] = url_exact+ if url_pattern is not None:+ params["url_pattern"] = url_pattern+ return self.client.get(f"/api/environments/{self.team.pk}/heatmaps/", params)++ def test_object_grant_does_not_expose_aggregate_data_for_other_urls(self):+ response = self._query_aggregate(url_exact="https://example.com/secret-unrelated-page")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())++ def test_object_grant_still_allows_aggregate_data_for_the_authorized_url(self):+ # Permission-level check only: confirms the fix doesn't regress the legitimate case+ # (the point of adding object-level grants at all) by blocking the very url the user+ # was granted access to. Row counts depend on the heatmaps ClickHouse table, which is+ # exercised in test_heatmaps_api.py.+ response = self._query_aggregate(url_exact="https://example.com/authorized")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ def test_prewarm_does_not_authorize_aggregate_data(self) -> None:+ SavedHeatmap.objects.create(+ team=self.team,+ name="",+ url="https://example.com/secret-unrelated-page",+ data_url="https://example.com/secret-unrelated-page",+ target_widths=[1024],+ created_by=self.viewer_user,+ status=SavedHeatmap.Status.COMPLETED,+ is_prewarm=True,+ )++ response = self._query_aggregate(url_exact="https://example.com/secret-unrelated-page")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())++ def test_object_grant_allows_query_url_differing_only_by_trailing_slash(self):+ # The aggregate query itself ignores a trailing slash (`trimRight(current_url, '/')`);+ # the permission check must normalize the same way or a legitimately-authorized url+ # gets a spurious 403.+ response = self._query_aggregate(url_exact="https://example.com/authorized/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ @parameterized.expand(+ [+ ("matching_pattern", r"https://example\.com/authorized"),+ ("non_matching_pattern", r"https://example\.com/secret-unrelated-page"),+ ]+ )+ def test_object_grant_never_authorizes_url_pattern_queries(self, _name, url_pattern):+ # Regression: url_pattern matches every row in the dataset satisfying the pattern, so an+ # object grant for one SavedHeatmap can't bound what a broad pattern is allowed to read —+ # url_pattern must always require resource-level access, even when the pattern happens to+ # match the URL the object grant authorizes.+ response = self._query_aggregate(url_pattern=url_pattern)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())++ def test_object_grant_cannot_smuggle_unauthorized_url_via_conflicting_pattern(self):+ # Regression: when url_exact and url_pattern differ, HeatmapsRequestSerializer.validate()+ # drops url_exact and the query runs against url_pattern. The permission check must resolve+ # the same way it does, or an authorized url_exact could authorize a request that then+ # queries an unrelated, unauthorized url_pattern.+ response = self._query_aggregate(+ url_exact="https://example.com/authorized",+ url_pattern=r"https://example\.com/secret-unrelated-page",+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())++ def test_object_grant_cannot_smuggle_pattern_via_matching_raw_url_exact(self):+ # Regression: HeatmapsRequestSerializer anchors url_pattern (via validate_url_pattern)+ # before validate() compares it against url_exact, so a raw url_pattern identical to+ # url_exact no longer matches once anchored — validate() then drops url_exact and the+ # query runs against the (broad) pattern instead. A grant on a heatmap whose data_url+ # happens to look like a pattern must not let a matching raw url_exact/url_pattern pair+ # authorize as an exact match while the anchored pattern actually executes.+ broad_pattern_heatmap = SavedHeatmap.objects.create(+ team=self.team,+ name="broad pattern lookalike",+ url="https://example.com/.*",+ data_url="https://example.com/.*",+ target_widths=[1024],+ created_by=self.user,+ status=SavedHeatmap.Status.COMPLETED,+ )+ membership = OrganizationMembership.objects.get(user=self.viewer_user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="heatmap",+ resource_id=str(broad_pattern_heatmap.id),+ access_level="viewer",+ organization_member=membership,+ )+ response = self._query_aggregate(url_exact="https://example.com/.*", url_pattern="https://example.com/.*")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())++ def test_events_drilldown_does_not_expose_other_urls(self):+ self.client.force_login(self.viewer_user)+ response = self.client.get(+ f"/api/environments/{self.team.pk}/heatmaps/events/"+ "?type=click&date_from=2023-03-01"+ "&url_exact=https://example.com/secret-unrelated-page"+ '&points=[{"x":0.1,"y":320}]'+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex 4deacbd7789a..a78b6a910748 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -96,6 +96,9 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+/**+ * Mixin for serializers to add user access control fields+ */export interface HeatmapScreenshotResponseApi {readonly id: string/** Short, URL-safe identifier used as the lookup key for saved-heatmap routes. */@@ -147,6 +150,11 @@ export interface HeatmapScreenshotResponseApi {* @nullable*/readonly exception: string | null+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null}export interface HeatmapResponseItemApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 381a1f8604fa..320549983c27 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -32140,6 +32140,9 @@ export namespace Schemas {has_content: boolean;}+ /**+ * Mixin for serializers to add user access control fields+ */export interface HeatmapScreenshotResponse {readonly id: string;/** Short, URL-safe identifier used as the lookup key for saved-heatmap routes. */@@ -32191,6 +32194,11 @@ export namespace Schemas {* @nullable*/readonly exception: string | null;+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null;}export interface HeatmapsResponse {