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(marketing-analytics): add access control (#125499)

Lucas Ricoybb21072a8395
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.ts
index e4539205e44b..7328229b9190 100644
--- a/common/storybook/.storybook/app-context.ts
+++ b/common/storybook/.storybook/app-context.ts
@@ -43,6 +43,7 @@ export const getStorybookAppContext = (): AppContext => ({
early_access_feature: 'manager',
external_data_source: 'manager',
web_analytics: 'manager',
+ marketing_analytics: 'manager',
activity_log: 'viewer',
customer_analytics: 'manager',
llm_analytics: 'manager',
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 80325152dbcf..978d9ba7c49a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15323,9 +15323,9 @@ snapshots:
scenes-app-settings-authentication-domains--redesigned-needs-upgrade--light:
hash: v1.k794b7964.f395a7d506b5cf5720728881ee9cfb100548e824fe4dc6cd2dbcd3781f1f7a2c._C4PfqjO_GbsDI6xtIQmmKzrMsnvWR-r7kGCnR8rZE4
scenes-app-settings-environment--settings-environment-access-control--dark:
- hash: v1.k794b7964.5d0771b46de9a55a9741a2efb7b28ccc21f62f9658dfb8946deb63efeb8c4cf8.2EXyngsVLFVhWMEoZis_fVvzRAGpR3BSDfMXn3ngBbo
+ hash: v1.k794b7964.577b5cb70184dc199b51e5c97a88023e432e14e8c3a46ca5b19da13dc98891d5.qoieSgSqwcfEFhokL46UPeVt2V3X_bfHHRMKCGp9cBo
scenes-app-settings-environment--settings-environment-access-control--light:
- hash: v1.k794b7964.fc0e0f399960a95c4b91fe86019daf99040ea87fea3224475861d28b7e831241.ekJN2R8grjTm8lFb41G00oRlNNwYLunnvlSDtGTg-So
+ hash: v1.k794b7964.d28d778058fe71865a41b467aeee6d960832a7a80c1370a3a9f17298ee46e430.coNaH1SpoX6bPkFXTN8rDgkz3U8dOkUnUGwpDKTSZfc
scenes-app-settings-environment--settings-environment-activity-logs--dark:
hash: v1.k794b7964.8575a8735ea3be3fcc292bdd55ffe856563799579b57a8ce860fd01fb14b5322.KlK2JNUssGtoCo4pnps9NRwZM0LJjp2yCkox9PilYY0
scenes-app-settings-environment--settings-environment-activity-logs--light:
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx
index 51cf830ca797..ac978697fb4c 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx
@@ -4,7 +4,7 @@ import { capitalizeFirstLetter } from 'kea-forms'
import { IconPencil } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, LemonTag, ProfilePicture, Tooltip } from '@posthog/lemon-ui'
-import { pluralizeResource } from 'lib/utils/accessControlUtils'
+import { resourceLabel } from 'lib/utils/accessControlUtils'
import { fullName } from 'lib/utils/strings'
import { APIScopeObject } from '~/types'
@@ -143,10 +143,8 @@ function AccessSummary({
<div className="flex gap-2 flex-wrap items-center">
{visibleTags.map(({ resource, level }) => (
<LemonTag key={resource} type="default">
- {resource === 'project'
- ? 'Project'
- : capitalizeFirstLetter(pluralizeResource(resource as APIScopeObject))}
- : {capitalizeFirstLetter(level)}
+ {resource === 'project' ? 'Project' : resourceLabel(resource as APIScopeObject)}:{' '}
+ {capitalizeFirstLetter(level)}
</LemonTag>
))}
{hiddenCount > 0 && <span className="text-warning text-xs">+{hiddenCount} more</span>}
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
index 852ad5d7fc15..789b7e50574d 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
@@ -19,7 +19,7 @@ import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { captureAccessControlEvent, pluralizeResource } from 'lib/utils/accessControlUtils'
+import { captureAccessControlEvent, resourceLabel } from 'lib/utils/accessControlUtils'
import { toSentenceCase } from 'lib/utils/strings'
import { userLogic } from 'scenes/userLogic'
@@ -778,12 +778,12 @@ export const accessControlsLogic = kea<accessControlsLogicType>([
)
.map((resource) => ({
key: resource as APIScopeObject,
- label: toSentenceCase(pluralizeResource(resource as APIScopeObject)),
+ label: resourceLabel(resource as APIScopeObject),
}))
: // Fallback to list of all resources while loading
resources.map((resource) => ({
key: resource,
- label: toSentenceCase(pluralizeResource(resource)),
+ label: resourceLabel(resource),
}))
return rows.sort((a, b) => a.label.localeCompare(b.label))
},
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 f69a067ceacc..3dfeacbf4ff0 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
@@ -33,6 +33,7 @@ export const RESOURCE_ROLLOUT_FLAG_REQUIREMENTS: Partial<Record<AccessControlRes
[AccessControlResourceType.Tracing]: FEATURE_FLAGS.TRACING,
[AccessControlResourceType.Tagger]: FEATURE_FLAGS.LLM_ANALYTICS_TAGS,
[AccessControlResourceType.BusinessKnowledge]: FEATURE_FLAGS.PRODUCT_BUSINESS_KNOWLEDGE,
+ [AccessControlResourceType.MarketingAnalytics]: FEATURE_FLAGS.WEB_ANALYTICS_MARKETING,
}
export function isResourceRolledOut(
@@ -196,6 +197,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(
AccessControlResourceType.Heatmap,
AccessControlResourceType.Insight,
AccessControlResourceType.LlmAnalytics,
+ AccessControlResourceType.MarketingAnalytics,
AccessControlResourceType.Evaluation,
AccessControlResourceType.McpAnalytics,
AccessControlResourceType.Tagger,
diff --git a/frontend/src/lib/utils/accessControlUtils.test.ts b/frontend/src/lib/utils/accessControlUtils.test.ts
new file mode 100644
index 000000000000..9a365807eada
--- /dev/null
+++ b/frontend/src/lib/utils/accessControlUtils.test.ts
@@ -0,0 +1,14 @@
+import { AccessControlResourceType } from '~/types'
+
+import { resourceLabel, resourceTypeToString } from './accessControlUtils'
+
+describe('accessControlUtils', () => {
+ test.each([
+ [AccessControlResourceType.FeatureFlag, 'Feature flags', 'feature flag'],
+ [AccessControlResourceType.McpAnalytics, 'MCP analytics', 'MCP analytic'],
+ [AccessControlResourceType.MarketingAnalytics, 'Marketing analytics', 'marketing analytics resource'],
+ ])('names %s as "%s" in lists and "%s" in messages', (resource, label, singular) => {
+ expect(resourceLabel(resource)).toEqual(label)
+ expect(resourceTypeToString(resource)).toEqual(singular)
+ })
+})
diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.ts
index d165084525c4..9daa4a0a1c0c 100644
--- a/frontend/src/lib/utils/accessControlUtils.ts
+++ b/frontend/src/lib/utils/accessControlUtils.ts
@@ -3,7 +3,7 @@ import posthog from 'posthog-js'
import type { LemonSelectOptionLeaf } from '@posthog/lemon-ui'
import { getAppContext } from 'lib/utils/getAppContext'
-import { toSentenceCase } from 'lib/utils/strings'
+import { capitalizeFirstLetter, toSentenceCase } from 'lib/utils/strings'
import { Scene, sceneToAccessControlResourceType } from 'scenes/sceneTypes'
import { APIScopeObject, AccessControlLevel, AccessControlResourceType, AvailableFeature } from '~/types'
@@ -109,6 +109,8 @@ export const pluralizeResource = (resource: APIScopeObject): string => {
return 'revenue analytics'
} else if (resource === AccessControlResourceType.WebAnalytics) {
return 'web analytics'
+ } else if (resource === AccessControlResourceType.MarketingAnalytics) {
+ return 'marketing analytics'
} else if (resource === AccessControlResourceType.ActivityLog) {
return 'activity logs'
} else if (resource === AccessControlResourceType.ExternalDataSource) {
@@ -147,6 +149,9 @@ export const pluralizeResource = (resource: APIScopeObject): string => {
return resource.replace(/_/g, ' ') + 's'
}
+/** Label for a resource in access control lists, e.g. "Marketing analytics". */
+export const resourceLabel = (resource: APIScopeObject): string => capitalizeFirstLetter(pluralizeResource(resource))
+
/**
* Returns the ordered list of access levels available for a given resource type.
* Different resource types have different sets of available access levels.
@@ -186,6 +191,8 @@ export const resourceTypeToString = (resourceType: AccessControlResourceType): s
return 'revenue analytics resource'
} else if (resourceType === AccessControlResourceType.WebAnalytics) {
return 'web analytics resource'
+ } else if (resourceType === AccessControlResourceType.MarketingAnalytics) {
+ return 'marketing analytics resource'
} else if (resourceType === AccessControlResourceType.ErrorTracking) {
return 'error tracking resource'
} else if (resourceType === AccessControlResourceType.ExternalDataSource) {
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestedActions.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestedActions.tsx
index dbfffd54b41a..8b93cb132ee1 100644
--- a/frontend/src/scenes/marketing-analytics/Setup/SuggestedActions.tsx
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestedActions.tsx
@@ -3,8 +3,13 @@ import { useActions, useValues } from 'kea'
import { IconCheckCircle, IconRefresh } from '@posthog/icons'
import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
import { CAPABILITY_COPY, ReadinessHeader } from './ReadinessHeader'
import { SuggestionRow } from './SuggestionRow'
@@ -55,6 +60,10 @@ export function SuggestedActions(): JSX.Element {
restoreAllDismissed,
} = useActions(setupPlanLogic)
+ const editDisabledReason =
+ useRestrictedArea({ scope: RestrictionScope.Project, minimumAccessLevel: TeamMembershipLevel.Admin }) ??
+ getAccessControlDisabledReason(AccessControlResourceType.MarketingAnalytics, AccessControlLevel.Editor)
+
const isBatchApplying = safeBatch.some((s) => applyingIds.includes(s.id))
return (
@@ -73,6 +82,7 @@ export function SuggestedActions(): JSX.Element {
type="secondary"
size="small"
loading={isBatchApplying}
+ disabledReason={editDisabledReason}
onClick={reviewSafeBatch}
// "Safe" is about what can go in one batch, not a verdict on
// the rest — say so, because the label alone reads as one.
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.test.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.test.tsx
index 1ec266416c6b..af22d04e270a 100644
--- a/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.test.tsx
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.test.tsx
@@ -75,6 +75,24 @@ describe('SuggestionRow', () => {
expect(screen.queryByText('Open settings')).toBeNull()
})
+ /** The test app context carries no access level, which the gate treats as no access.
+ * Only ops that write marketing config go through `apply_setup_ops`, so only those
+ * should lose their button; a navigation CTA has no permission of its own to check. */
+ it.each([
+ ['open_source_wizard', 'Connect', false],
+ ['create_conversion_goal', 'Review change', true],
+ ])('gates the %s CTA (%s) on edit access: %s', async (op, label, disabled) => {
+ render(
+ <SuggestionRow
+ suggestion={{ ...suggestion({ kind: 'fix_conversion_goal' }), apply: { op } } as Suggestion}
+ onReview={() => {}}
+ />
+ )
+
+ await waitFor(() => expect(screen.getByText(label)).toBeTruthy())
+ expect(screen.getByText(label).closest('button')?.getAttribute('aria-disabled') === 'true').toBe(disabled)
+ })
+
it('does not offer the section it is already rendered in', async () => {
render(
<SuggestionRow
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.tsx
index 437d10c6a10c..98172b3ce73f 100644
--- a/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.tsx
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.tsx
@@ -2,13 +2,21 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import {
SetupSection,
marketingAnalyticsLogic,
} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
import type { ApplyOp, Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
-import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+import {
+ CONFIG_WRITE_OPS,
+ setupPlanLogic,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { CAPABILITY_COPY } from './ReadinessHeader'
import { SECTION_BY_KIND, SECTION_LABEL } from './sectionRouting'
@@ -77,6 +85,9 @@ export function SuggestionRow({
isDismissed?: boolean
}): JSX.Element {
const { applyingIds } = useValues(setupPlanLogic)
+ const editDisabledReason =
+ useRestrictedArea({ scope: RestrictionScope.Project, minimumAccessLevel: TeamMembershipLevel.Admin }) ??
+ getAccessControlDisabledReason(AccessControlResourceType.MarketingAnalytics, AccessControlLevel.Editor)
const { dismissSuggestion, restoreSuggestion } = useActions(setupPlanLogic)
const { setSetupSection } = useActions(marketingAnalyticsLogic)
@@ -90,6 +101,7 @@ export function SuggestionRow({
const settlesInTab = suggestion.apply?.op === 'open_settings' && !!section
const ctaLabel = suggestion.apply && !settlesInTab ? (CTA_LABEL[suggestion.apply.op] ?? 'Review change') : null
const sectionCta = !ctaLabel && section && section !== currentSection ? section : null
+ const writesConfig = !!suggestion.apply && CONFIG_WRITE_OPS.has(suggestion.apply.op)
return (
<div className="flex items-start gap-3 py-3 px-3 border-b last:border-b-0">
@@ -129,7 +141,13 @@ export function SuggestionRow({
<div className="flex items-center gap-1 shrink-0">
{ctaLabel && (
- <LemonButton type="primary" size="small" loading={isApplying} onClick={() => onReview(suggestion)}>
+ <LemonButton
+ type="primary"
+ size="small"
+ loading={isApplying}
+ disabledReason={writesConfig ? editDisabledReason : undefined}
+ onClick={() => onReview(suggestion)}
+ >
{ctaLabel}
</LemonButton>
)}
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index f03ceb7ca4fa..dfe6d74a4140 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -423,7 +423,8 @@ export const sceneToAccessControlResourceType: Partial<
[Scene.WebAnalyticsRecap]: AccessControlResourceType.WebAnalytics,
// Marketing Analytics
- [Scene.MarketingAnalytics]: AccessControlResourceType.WebAnalytics,
+ [Scene.MarketingAnalytics]: AccessControlResourceType.MarketingAnalytics,
+ [Scene.MarketingAnalyticsSettings]: AccessControlResourceType.MarketingAnalytics,
// Metrics
[Scene.Metrics]: AccessControlResourceType.Metrics,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx
index 96793dcf542a..6f153c59208b 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx
@@ -4,7 +4,10 @@ import { useMemo } from 'react'
import { IconCheck, IconWarning, IconX } from '@posthog/icons'
import { LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
import { LemonInputSelect, LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { CURRENCY_SYMBOL_TO_NAME_MAP, IMPORTANT_CURRENCIES, OTHER_CURRENCIES } from 'lib/utils/currency'
import {
@@ -17,6 +20,7 @@ import {
VALID_NATIVE_MARKETING_SOURCES,
} from '~/queries/schema/schema-general'
import type { MarketingAnalyticsSchemaFieldTypes } from '~/queries/schema/schema-general'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { ExternalTable } from '../../logic/marketingAnalyticsLogic'
import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'
@@ -184,6 +188,9 @@ function buildColumnOptions(
export function ColumnMappingModal({ table, isOpen, onClose }: ColumnMappingModalProps): JSX.Element {
const { updateSourceMapping, testMapping } = useActions(marketingAnalyticsSettingsLogic)
+ const editDisabledReason =
+ useRestrictedArea({ scope: RestrictionScope.Project, minimumAccessLevel: TeamMembershipLevel.Admin }) ??
+ getAccessControlDisabledReason(AccessControlResourceType.MarketingAnalytics, AccessControlLevel.Editor)
const { sources_map, testMappingResults } = useValues(marketingAnalyticsSettingsLogic)
const requiredFields = Object.values(MarketingAnalyticsColumnsSchemaNames).filter(
@@ -262,9 +269,10 @@ export function ColumnMappingModal({ table, isOpen, onClose }: ColumnMappingModa
onClick={handleTestMapping}
tooltip="Test the mapping by running the adapter query"
disabledReason={
- requiredFieldsConfigured < requiredFields.length
+ editDisabledReason ??
+ (requiredFieldsConfigured < requiredFields.length
? 'Configure all required fields first'
- : undefined
+ : undefined)
}
>
{testResult?.status === 'loading' ? (
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
index 85dc629a8951..ff99e0731fb9 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
@@ -31,6 +31,22 @@ const AUDIT_AFFECTING_OPS = new Set([
'set_campaign_field_preference',
])
+/** Ops that `apply_setup_ops` writes to the marketing config, so they need edit access.
+ * Mirrors `APPLICABLE_OPS` in `products/marketing_analytics/backend/services/setup_types.py`.
+ * The other ops open a page, a wizard or a warehouse action that carries its own permissions. */
+export const CONFIG_WRITE_OPS = new Set([
+ 'add_custom_source_mapping',
+ 'remove_custom_source_mapping',
+ 'set_campaign_field_preference',
+ 'add_campaign_name_mapping',
+ 'remove_campaign_name_mapping',
+ 'create_conversion_goal',
+ 'update_conversion_goal',
+ 'delete_conversion_goal',
+ 'set_source_column_mapping',
+ 'set_customer_analytics_event',
+])
+
const teamId = window.POSTHOG_APP_CONTEXT?.current_team?.id
/** Suggestion ids are semantic and project-independent — `connect_source:google_ads`
* is the same string in every project — so an unprefixed bucket would hide a finding
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 1d91900f3494..df12ffad4f58 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -356,6 +356,7 @@ export enum AccessControlResourceType {
WarehouseTable = 'warehouse_table',
WarehouseView = 'warehouse_view',
WebAnalytics = 'web_analytics',
+ MarketingAnalytics = 'marketing_analytics',
ActivityLog = 'activity_log',
BusinessKnowledge = 'business_knowledge',
ErrorTracking = 'error_tracking',
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index bf089f18699d..3ad32307a83c 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -92,6 +92,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = (
"survey",
"ticket",
"web_analytics",
+ "marketing_analytics",
"activity_log",
"business_knowledge",
"error_tracking",
@@ -122,11 +123,6 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {
"experiment_saved_metric": "experiment",
"experiment_holdout": "experiment",
"dashboard_template": "dashboard",
- # Marketing analytics doesn't have its own RBAC resource yet — inherit from
- # web_analytics so the existing per-team controls actually gate it (matches
- # the frontend mapping in sceneTypes.ts: Scene.MarketingAnalytics ->
- # AccessControlResourceType.WebAnalytics).
- "marketing_analytics": "web_analytics",
# Vision alerts are configured via the scanner's access level rather than a
# separate resource.
"vision_alert": "replay_scanner",
@@ -220,8 +216,11 @@ def resource_to_display_name(resource: APIScopeObject) -> str:
# Product name: a proper noun, and it does not take a plural
return "Stamphog"
- # Default: replace underscores and add 's' for plural
- return f"{resource.replace('_', ' ')}s"
+ name = resource.replace("_", " ")
+ # Names such as "marketing analytics", "logs" and "metrics" are already plural
+ if name.endswith("s"):
+ return name
+ return f"{name}s"
def ordered_access_levels(resource: APIScopeObject) -> list[AccessControlLevel]:
diff --git a/products/access_control/backend/migrations/0004_backfill_marketing_analytics_access_control.py b/products/access_control/backend/migrations/0004_backfill_marketing_analytics_access_control.py
new file mode 100644
index 000000000000..dc755a750624
--- /dev/null
+++ b/products/access_control/backend/migrations/0004_backfill_marketing_analytics_access_control.py
@@ -0,0 +1,46 @@
+from django.db import migrations
+
+CHUNK_SIZE = 200
+
+
+def backfill_marketing_analytics_access_control(apps, schema_editor):
+ # Marketing analytics used to inherit its access level from web_analytics; now that it's an
+ # independent resource, mirror every resource-wide web_analytics grant onto a matching
+ # marketing_analytics row so existing permissions keep working instead of silently defaulting
+ # to editor. Rows with a resource_id are per-object grants and were never part of marketing
+ # analytics' access resolution, so they're excluded.
+ AccessControl = apps.get_model("ee", "AccessControl")
+
+ # `marketing_analytics` was already a valid resource choice while it inherited from
+ # web_analytics, so stray resource-wide rows may exist that nothing ever read. They are
+ # removed first so the result mirrors web_analytics exactly instead of keeping a stale level
+ # or making an orphan row live.
+ AccessControl.objects.filter(resource="marketing_analytics", resource_id__isnull=True).delete()
+
+ for row in AccessControl.objects.filter(resource="web_analytics", resource_id__isnull=True).iterator(
+ chunk_size=CHUNK_SIZE
+ ):
+ AccessControl.objects.create(
+ resource="marketing_analytics",
+ resource_id=None,
+ team_id=row.team_id,
+ organization_member_id=row.organization_member_id,
+ role_id=row.role_id,
+ access_level=row.access_level,
+ created_by_id=row.created_by_id,
+ )
+
+
+def reverse_func(apps, schema_editor):
+ pass
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("access_control", "0003_teamaccesscontrolconfig"),
+ ("ee", "0067_remove_scimrequestlog_identity_provider_config_and_more"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_marketing_analytics_access_control, reverse_func),
+ ]
diff --git a/products/access_control/backend/migrations/max_migration.txt b/products/access_control/backend/migrations/max_migration.txt
index d73eb2f04ec4..76b0faf73e9d 100644
--- a/products/access_control/backend/migrations/max_migration.txt
+++ b/products/access_control/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_teamaccesscontrolconfig
+0004_backfill_marketing_analytics_access_control
diff --git a/products/access_control/backend/tests/test_field_access_control.py b/products/access_control/backend/tests/test_field_access_control.py
index 079e3dabdd52..dea9fe29aba3 100644
--- a/products/access_control/backend/tests/test_field_access_control.py
+++ b/products/access_control/backend/tests/test_field_access_control.py
@@ -4,14 +4,20 @@ import pytest
from posthog.test.base import BaseTest
from django.db import models
+from django.test import SimpleTestCase
+from parameterized import parameterized
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from posthog.models.team import Team
from posthog.rbac.decorators import field_access_control
-from products.access_control.backend.facade.user_access_control import UserAccessControl, get_field_access_control_map
+from products.access_control.backend.facade.user_access_control import (
+ UserAccessControl,
+ get_field_access_control_map,
+ resource_to_display_name,
+)
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
@@ -141,3 +147,15 @@ class TestFieldAccessControlDecorator(BaseTest):
detail = exc_info.value.detail
assert "session_recording_opt_in" in detail
+
+
+class TestResourceToDisplayName(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("feature_flag", "feature flags"),
+ ("marketing_analytics", "marketing analytics"),
+ ("logs", "logs"),
+ ]
+ )
+ def test_resource_to_display_name(self, resource: Any, expected: str) -> None:
+ assert resource_to_display_name(resource) == expected
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.py
index 3b5f18f76fbd..ef673de6b8c7 100644
--- a/products/marketing_analytics/backend/api.py
+++ b/products/marketing_analytics/backend/api.py
@@ -1251,10 +1251,9 @@ class ConversionRecordingsResponseSerializer(serializers.Serializer):
class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
- # `marketing_analytics` is gated by the API scope of the same name and inherits
- # RBAC from `web_analytics` (see RESOURCE_INHERITANCE_MAP). Custom @action methods
- # below are not standard CRUD names, so each declares its own `required_scopes`;
- # actions without it stay session-only (not reachable via API key / OAuth / MCP).
+ # `marketing_analytics` is gated by the API scope and the RBAC resource of the same
+ # name. Custom @action methods below are not standard CRUD names, so each declares
+ # its own `required_scopes`; actions without it stay session-only (not reachable via API key / OAuth / MCP).
scope_object = "marketing_analytics"
serializer_class = _FallbackSerializer
permission_classes = [IsAuthenticated]
diff --git a/products/marketing_analytics/backend/hogql_queries/access_control.py b/products/marketing_analytics/backend/hogql_queries/access_control.py
new file mode 100644
index 000000000000..92a51abdcbd4
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/access_control.py
@@ -0,0 +1,18 @@
+from typing import TYPE_CHECKING
+
+from posthog.models import User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+if TYPE_CHECKING:
+ from posthog.models.team.team import Team
+
+
+class MarketingAnalyticsAccessMixin:
+ """Every marketing analytics query runner requires viewer access to the `marketing_analytics` resource."""
+
+ team: "Team"
+
+ def validate_query_runner_access(self, user: User) -> bool:
+ user_access_control = UserAccessControl(user=user, team=self.team)
+ return user_access_control.assert_access_level_for_resource("marketing_analytics", "viewer")
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index 9a875dca262e..2fab57dbd038 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -58,6 +58,7 @@ from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precomput
)
from products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_name
+from .access_control import MarketingAnalyticsAccessMixin
from .adapters.base import MarketingSourceAdapter, QueryContext
from .adapters.factory import MarketingSourceFactory
from .conversion_goal_processor import ConversionGoalProcessor, goal_sums_a_property
@@ -174,7 +175,9 @@ def _session_start_day(expr: ast.Expr) -> ast.Expr:
return ast.Call(name="toStartOfDay", args=[expr])
-class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC, Generic[ResponseType]):
+class MarketingAnalyticsBaseQueryRunner(
+ MarketingAnalyticsAccessMixin, AnalyticsQueryRunner[ResponseType], ABC, Generic[ResponseType]
+):
"""Base class for marketing analytics query runners with shared functionality."""
def __init__(self, *args, **kwargs):
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py
index c1c4e6a8fe6d..521546f7c660 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py
@@ -27,6 +27,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
from posthog.ph_client import feature_enabled_or_false
+from .access_control import MarketingAnalyticsAccessMixin
from .attribution_base import ConversionGoal
from .conversion_goal_conditions import conversion_goal_match_expr
from .marketing_analytics_config import MarketingAnalyticsConfig
@@ -35,7 +36,9 @@ from .search_conversion_query_runner import SearchConversionQueryRunner
MAX_POSTHOG_CONVERSION_GOALS = 5
-class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticsSearchQueryResponse]):
+class MarketingAnalyticsSearchQueryRunner(
+ MarketingAnalyticsAccessMixin, AnalyticsQueryRunner[MarketingAnalyticsSearchQueryResponse]
+):
query: MarketingAnalyticsSearchQuery
response: MarketingAnalyticsSearchQueryResponse
cached_response: CachedMarketingAnalyticsSearchQueryResponse
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_rbac.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_rbac.py
new file mode 100644
index 000000000000..046c12cdcd03
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_rbac.py
@@ -0,0 +1,82 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.schema import DateRange, MarketingAnalyticsAggregatedQuery, MarketingAnalyticsSearchQuery
+
+from posthog.constants import AvailableFeature
+
+from products.access_control.backend.facade.user_access_control import UserAccessControlError
+from products.access_control.backend.models.access_control import AccessControl
+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_aggregated_query_runner import (
+ MarketingAnalyticsAggregatedQueryRunner,
+)
+from products.marketing_analytics.backend.hogql_queries.marketing_search_query_runner import (
+ MarketingAnalyticsSearchQueryRunner,
+)
+
+ACCESS_CASES = [
+ ("default", None, None, True),
+ ("marketing_viewer", "marketing_analytics", "viewer", True),
+ ("marketing_none", "marketing_analytics", "none", False),
+ ("web_analytics_none", "web_analytics", "none", True),
+]
+
+RUNNERS = [
+ (
+ "aggregated",
+ lambda team: MarketingAnalyticsAggregatedQueryRunner(
+ team=team, query=MarketingAnalyticsAggregatedQuery(dateRange=DateRange(date_from="-7d"), properties=[])
+ ),
+ ),
+ (
+ "search",
+ lambda team: MarketingAnalyticsSearchQueryRunner(
+ team=team, query=MarketingAnalyticsSearchQuery(dateRange=DateRange(date_from="-7d"), sources=[])
+ ),
+ ),
+]
+
+
+class TestMarketingAnalyticsRBAC(APIBaseTest):
+ def _grant(self, resource: str | None, access_level: str | None) -> None:
+ if resource is not None:
+ AccessControl.objects.create(team=self.team, resource=resource, access_level=access_level)
+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]
+ self.organization.save()
+
+ @parameterized.expand(
+ [
+ (f"{runner_name}_{case_name}", build_runner, resource, access_level, has_access)
+ for runner_name, build_runner in RUNNERS
+ for case_name, resource, access_level, has_access in ACCESS_CASES
+ ]
+ )
+ def test_validate_query_runner_access(
+ self, _name: str, build_runner, resource: str | None, access_level: str | None, has_access: bool
+ ) -> None:
+ self._grant(resource, access_level)
+ runner = build_runner(self.team)
+
+ if has_access:
+ assert runner.validate_query_runner_access(self.user)
+ else:
+ with self.assertRaises(UserAccessControlError):
+ runner.validate_query_runner_access(self.user)
+
+ @parameterized.expand(
+ [
+ ("marketing_none", "marketing_analytics", "none", status.HTTP_403_FORBIDDEN),
+ ("marketing_viewer", "marketing_analytics", "viewer", status.HTTP_200_OK),
+ ("web_analytics_none", "web_analytics", "none", status.HTTP_200_OK),
+ ]
+ )
+ def test_viewset_follows_marketing_analytics_access(
+ self, _name: str, resource: str, access_level: str, expected_status: int
+ ) -> None:
+ self._grant(resource, access_level)
+
+ response = self.client.get(f"/api/projects/{self.team.pk}/marketing_analytics/conversion_goals")
+
+ assert response.status_code == expected_status, response.content
diff --git a/products/marketing_analytics/backend/test_api_apply_setup_ops.py b/products/marketing_analytics/backend/test_api_apply_setup_ops.py
index 66bb23cf391b..d837a0b0cc04 100644
--- a/products/marketing_analytics/backend/test_api_apply_setup_ops.py
+++ b/products/marketing_analytics/backend/test_api_apply_setup_ops.py
@@ -441,10 +441,10 @@ class TestApplySetupOpsFeatureFlag(APIBaseTest):
class TestApplySetupOpsRequiresProjectAdmin(APIBaseTest):
- """`marketing_analytics:write` resolves to `editor` (web_analytics' default level via
- RESOURCE_INHERITANCE_MAP), which every project member has. Without an explicit admin
- check this endpoint is a way around both the team PATCH gate on
- marketing_analytics_config and the admin check the sibling goal endpoints carry."""
+ """`marketing_analytics:write` resolves to `editor` (the resource's default level),
+ which every project member has. Without an explicit admin check this endpoint is a
+ way around both the team PATCH gate on marketing_analytics_config and the admin
+ check the sibling goal endpoints carry."""
def setUp(self):
super().setUp()
diff --git a/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.tsx b/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.tsx
index ee2f5a809bb4..28d3186e6f89 100644
--- a/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.tsx
+++ b/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.tsx
@@ -7,9 +7,12 @@ import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedAr
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
import type { ConversionRecommendationApi } from '../generated/api.schemas'
import { conversionGoalFormLogic } from './conversionGoalFormLogic'
import { ConversionRecommendationCard } from './ConversionRecommendationCard'
@@ -28,10 +31,9 @@ export function ConversionGoalRecommendations({
}): JSX.Element | null {
const { currentTeamId, currentTeamLoading } = useValues(teamLogic)
const { isSaving } = useValues(conversionGoalFormLogic({ projectId: currentTeamId ?? -1 }))
- const restrictedReason = useRestrictedArea({
- scope: RestrictionScope.Project,
- minimumAccessLevel: TeamMembershipLevel.Admin,
- })
+ const editDisabledReason =
+ useRestrictedArea({ scope: RestrictionScope.Project, minimumAccessLevel: TeamMembershipLevel.Admin }) ??
+ getAccessControlDisabledReason(AccessControlResourceType.MarketingAnalytics, AccessControlLevel.Editor)
const { user } = useValues(userLogic)
const { featureFlags } = useValues(featureFlagLogic)
const enabled = !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI]
@@ -136,7 +138,7 @@ export function ConversionGoalRecommendations({
onUseSuggestion={() => onUseSuggestion(recommendation)}
onDismiss={() => dismissRecommendation(recommendation)}
disabledReason={
- restrictedReason ||
+ editDisabledReason ||
(currentTeamLoading || isSaving
? 'Wait for the project settings to finish saving.'
: undefined)
@@ -243,7 +245,7 @@ export function ConversionGoalRecommendations({
type="secondary"
size="small"
loading={isAnalyzing || stateLoading}
- disabledReason={scanDisabledReason}
+ disabledReason={editDisabledReason ?? scanDisabledReason}
onClick={() => requestAnalysis(true)}
data-attr="marketing-conversion-update-recommendations"
>