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(rbac): flag-gated access resolution preview page (#88704)

Alex Liderb45824b50de8
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview.tsx
new file mode 100644
index 000000000000..05836676481b
--- /dev/null
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview.tsx
@@ -0,0 +1,297 @@
+import { useActions, useValues } from 'kea'
+
+import { IconExternal, IconGear } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCollapse,
+ LemonTable,
+ LemonTableColumns,
+ LemonTag,
+ Link,
+ Spinner,
+} from '@posthog/lemon-ui'
+
+import { supportLogic } from 'lib/components/Support/supportLogic'
+import { urls } from 'scenes/urls'
+
+import { objectRuleUrl } from '~/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic'
+import { humanizeAccessControlLevel } from '~/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/helpers'
+import { APIScopeObject, AccessControlLevel } from '~/types'
+
+import { describeResolutionChange } from './describeResolutionChange'
+import { ResolutionChange, resolutionPreviewLogic } from './resolutionPreviewLogic'
+
+function WhyExplainer(): JSX.Element {
+ return (
+ <LemonCollapse
+ panels={[
+ {
+ key: 'why',
+ header: 'Why are we changing this?',
+ content: (
+ <div className="flex flex-col gap-2 max-w-200">
+ <p className="mb-0">
+ We want access control to support both allowlist and denylist setups. For example:
+ </p>
+ <p className="mb-0">
+ <strong>Allowlist:</strong> your project is private (No access by default), and you
+ grant specific members or roles access above that. This already works.
+ </p>
+ <p className="mb-0">
+ <strong>Denylist:</strong> your project is open to the organization (Member by default),
+ and you want to exclude one role. Today the highest rule applies, so the only way is to
+ set the default to No access and grant access back to everyone else. Once the most
+ specific rule applies, you set No access for that one role and keep the open default.
+ </p>
+ </div>
+ ),
+ },
+ ]}
+ />
+ )
+}
+
+function urlForChangeObject(change: ResolutionChange): string | null {
+ if (change.object_id === null) {
+ return null
+ }
+ // Same link rules as the object rules table on the access control settings page
+ return objectRuleUrl({
+ resource: change.resource as APIScopeObject,
+ resource_id: change.object_id,
+ name: change.object_name ?? change.object_id,
+ short_id: change.object_short_id,
+ access_level: change.proposed.access_level as AccessControlLevel,
+ })
+}
+
+function SubjectCell({ change }: { change: ResolutionChange }): JSX.Element {
+ return (
+ <div className="flex items-center gap-2 whitespace-nowrap">
+ <span className="font-semibold max-w-60 truncate" title={change.subject.name}>
+ {change.subject.name}
+ </span>
+ <LemonTag size="small">{change.subject.type}</LemonTag>
+ </div>
+ )
+}
+
+function LevelChangeCell({ change }: { change: ResolutionChange }): JSX.Element {
+ return (
+ <div className="flex items-center gap-2 whitespace-nowrap">
+ <LemonTag>{humanizeAccessControlLevel(change.current.access_level as AccessControlLevel)}</LemonTag>
+ <span aria-hidden="true">→</span>
+ <LemonTag type={change.direction === 'gains' ? 'warning' : 'danger'}>
+ {humanizeAccessControlLevel(change.proposed.access_level as AccessControlLevel)}
+ </LemonTag>
+ </div>
+ )
+}
+
+const sharedColumns: LemonTableColumns<ResolutionChange> = [
+ {
+ title: 'Applies to',
+ key: 'subject',
+ width: 0,
+ render: (_, change) => <SubjectCell change={change} />,
+ },
+ {
+ title: 'Access',
+ key: 'change',
+ render: (_, change) => <LevelChangeCell change={change} />,
+ },
+ {
+ title: 'Why',
+ key: 'why',
+ render: (_, change) => <span className="text-muted">{describeResolutionChange(change)}</span>,
+ },
+]
+
+export function AccessResolutionPreview(): JSX.Element {
+ const { preview, previewLoading, previewForbidden } = useValues(resolutionPreviewLogic)
+ const { loadPreview } = useActions(resolutionPreviewLogic)
+ const { openSupportForm } = useActions(supportLogic)
+
+ if (previewLoading) {
+ return <Spinner className="text-lg" />
+ }
+ if (previewForbidden) {
+ return (
+ <LemonBanner type="info">
+ Only administrators can view the resolution preview. Ask an organization admin to review the changes.
+ </LemonBanner>
+ )
+ }
+ if (!preview) {
+ return (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: () => loadPreview(), 'data-attr': 'access-resolution-retry' }}
+ >
+ Couldn't load the resolution preview. Try again, and if it keeps happening contact support.
+ </LemonBanner>
+ )
+ }
+ if (preview.summary.total === 0) {
+ return (
+ <div className="flex flex-col gap-4">
+ <WhyExplainer />
+ <LemonBanner type="success">
+ No access rules resolve differently in the projects you administer. Nothing changes when the new
+ resolution takes effect.
+ </LemonBanner>
+ </div>
+ )
+ }
+
+ const projects = Array.from(
+ new Map(preview.changes.map((change) => [change.project_id, change.project_name])).entries()
+ ).sort((a, b) => a[1].localeCompare(b[1]))
+
+ const resourceColumns: LemonTableColumns<ResolutionChange> = [
+ {
+ title: 'Setting',
+ key: 'resource',
+ width: 0,
+ render: (_, change) => (
+ <span className="font-semibold capitalize whitespace-nowrap">{change.resource.replace(/_/g, ' ')}</span>
+ ),
+ },
+ ...sharedColumns,
+ {
+ key: 'actions',
+ width: 0,
+ render: () => (
+ <LemonButton
+ size="small"
+ icon={<IconGear />}
+ to={urls.settings('environment-access-control')}
+ tooltip="Edit resource access settings"
+ data-attr="access-resolution-edit-resource"
+ />
+ ),
+ },
+ ]
+ const objectColumns: LemonTableColumns<ResolutionChange> = [
+ {
+ title: 'Type',
+ key: 'type',
+ width: 0,
+ render: (_, change) => (
+ <span className="capitalize whitespace-nowrap">{change.resource.replace(/_/g, ' ')}</span>
+ ),
+ },
+ {
+ title: 'Name',
+ key: 'object',
+ width: 0,
+ render: (_, change) => {
+ const label = change.object_name ?? change.object_id
+ const url = urlForChangeObject(change)
+ return (
+ <div className="font-semibold truncate whitespace-nowrap max-w-80" title={label ?? undefined}>
+ {url ? <Link to={url}>{label}</Link> : label}
+ </div>
+ )
+ },
+ },
+ ...sharedColumns,
+ {
+ key: 'actions',
+ width: 0,
+ render: (_, change) => {
+ const url = urlForChangeObject(change)
+ return url ? (
+ <LemonButton
+ size="small"
+ icon={<IconExternal />}
+ to={url}
+ tooltip="Open"
+ data-attr="access-resolution-open-object"
+ />
+ ) : null
+ },
+ },
+ ]
+
+ return (
+ <div className="flex flex-col gap-4">
+ <WhyExplainer />
+ <div className="flex items-center gap-2">
+ {preview.summary.loses > 0 && (
+ <LemonTag type="danger" className="bg-surface-primary">
+ ▼ {preview.summary.loses} rules resolve lower
+ </LemonTag>
+ )}
+ {preview.summary.gains > 0 && (
+ <LemonTag type="warning" className="bg-surface-primary">
+ ▲ {preview.summary.gains} rules resolve higher
+ </LemonTag>
+ )}
+ </div>
+
+ {projects.map(([projectId, projectName]) => {
+ const projectChanges = preview.changes.filter((change) => change.project_id === projectId)
+ const resourceChanges = projectChanges.filter((change) => change.scope === 'resource')
+ const objectChanges = projectChanges
+ .filter((change) => change.scope === 'object')
+ .sort(
+ (a, b) =>
+ a.resource.localeCompare(b.resource) ||
+ (a.object_name ?? a.object_id ?? '').localeCompare(b.object_name ?? b.object_id ?? '')
+ )
+ return (
+ <div key={projectId} className="flex flex-col gap-2">
+ <h3 className="mb-0">{projectName}</h3>
+ {resourceChanges.length > 0 && (
+ <div>
+ <h4 className="mb-2">Resource-level access</h4>
+ <LemonTable
+ id={`access-resolution-resource-${projectId}`}
+ columns={resourceColumns}
+ dataSource={resourceChanges}
+ rowKey={(change) =>
+ `${change.resource}-${change.subject.type}-${change.subject.id}`
+ }
+ pagination={{ pageSize: 50, hideOnSinglePage: true }}
+ />
+ </div>
+ )}
+ {objectChanges.length > 0 && (
+ <div>
+ <h4 className="mb-2">Objects with their own access rules</h4>
+ <LemonTable
+ id={`access-resolution-object-${projectId}`}
+ columns={objectColumns}
+ dataSource={objectChanges}
+ rowKey={(change) =>
+ `${change.resource}-${change.object_id}-${change.subject.type}-${change.subject.id}`
+ }
+ pagination={{ pageSize: 20, hideOnSinglePage: true }}
+ />
+ </div>
+ )}
+ </div>
+ )
+ })}
+
+ <div className="flex items-center gap-2">
+ <LemonButton type="primary" disabledReason="Not available yet" data-attr="access-resolution-accept">
+ Accept the new resolution
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ onClick={() => openSupportForm({ kind: 'support' })}
+ data-attr="access-resolution-keep-current"
+ >
+ Keep current access
+ </LemonButton>
+ <span className="text-muted text-xs">
+ Contact support to keep the current access for all members. We will adjust your rules so everyone's
+ effective access stays the same.
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/describeResolutionChange.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/describeResolutionChange.ts
new file mode 100644
index 000000000000..ac0f3024fd28
--- /dev/null
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/describeResolutionChange.ts
@@ -0,0 +1,67 @@
+import { humanizeAccessControlLevel } from '~/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/helpers'
+import { AccessControlLevel } from '~/types'
+
+import { ResolutionChange, ResolutionChangeLevel } from './resolutionPreviewLogic'
+
+function scopePhrase(change: ResolutionChange, resolved: ResolutionChangeLevel): string {
+ switch (resolved.source) {
+ case 'object':
+ return change.scope === 'object' ? 'level on this object' : 'object-level rule'
+ case 'parent_object':
+ return 'rule on its source'
+ case 'resource':
+ return 'resource-level setting'
+ case 'parent_resource':
+ return 'resource-level setting of its source'
+ default:
+ return 'built-in default'
+ }
+}
+
+function describeResolved(change: ResolutionChange, resolved: ResolutionChangeLevel): string {
+ const level = humanizeAccessControlLevel(resolved.access_level as AccessControlLevel)
+ const phrase = scopePhrase(change, resolved)
+ if (resolved.source_subject === 'member') {
+ const owner = change.subject.type === 'member' ? 'their own' : `${resolved.subject_name ?? 'a member'}'s`
+ return `${owner} ${phrase} (${level})`
+ }
+ if (resolved.source_subject === 'role') {
+ const owner =
+ change.subject.type === 'role'
+ ? "the role's"
+ : resolved.subject_name
+ ? `the ${resolved.subject_name} role's`
+ : "a role's"
+ return `${owner} ${phrase} (${level})`
+ }
+ if (resolved.source === 'object' || resolved.source === 'parent_object') {
+ return `the default ${phrase} (${level})`
+ }
+ return `the ${phrase} (${level})`
+}
+
+function describeShort(change: ResolutionChange, resolved: ResolutionChangeLevel): string {
+ if (resolved.source_subject === 'member') {
+ return change.subject.type === 'member'
+ ? 'their own setting'
+ : `${resolved.subject_name ?? 'the member'}'s setting`
+ }
+ if (resolved.source_subject === 'role') {
+ return change.subject.type === 'role'
+ ? "the role's own setting"
+ : `the ${resolved.subject_name ?? ''} role's setting`
+ }
+ return `the ${scopePhrase(change, resolved)}`
+}
+
+export function describeResolutionChange(change: ResolutionChange): string {
+ // "Dana Kim holds the Engineers role." when a role's grant decides for a member today
+ const intro =
+ change.subject.type === 'member' && change.current.source_subject === 'role' && change.current.subject_name
+ ? `${change.subject.name} holds the ${change.current.subject_name} role. `
+ : ''
+ const today = describeResolved(change, change.current)
+ const proposed = describeResolved(change, change.proposed)
+ const after = describeShort(change, change.proposed)
+ return `${intro}Today ${today} applies over ${proposed}. After the change, ${after} applies.`
+}
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/resolutionPreviewLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/resolutionPreviewLogic.ts
new file mode 100644
index 000000000000..60aebca5a353
--- /dev/null
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/resolutionPreviewLogic.ts
@@ -0,0 +1,112 @@
+import { MakeLogicType, afterMount, connect, kea, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { teamLogic } from 'scenes/teamLogic'
+
+export interface ResolutionChangeSubject {
+ type: 'default' | 'role' | 'member'
+ id: string | null
+ name: string
+}
+
+/** The wire form of the backend's ResolvedAccess */
+export interface ResolutionChangeLevel {
+ access_level: string
+ source: string
+ source_subject: string | null
+ /** Name of the member or role whose row decides, when one does */
+ subject_name: string | null
+}
+
+export interface ResolutionChange {
+ subject: ResolutionChangeSubject
+ scope: 'object' | 'resource'
+ resource: string
+ project_id: number
+ project_name: string
+ object_id: string | null
+ object_name: string | null
+ object_short_id: string | null
+ current: ResolutionChangeLevel
+ proposed: ResolutionChangeLevel
+ direction: 'gains' | 'loses'
+}
+
+export interface ResolutionPreviewSummary {
+ total: number
+ gains: number
+ loses: number
+ resources: number
+ objects: number
+}
+
+export interface ResolutionPreviewResponse {
+ changes: ResolutionChange[]
+ summary: ResolutionPreviewSummary
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface resolutionPreviewLogicValues {
+ currentTeamIdStrict: number | string // teamLogic
+ preview: ResolutionPreviewResponse | null
+ previewForbidden: boolean
+ previewLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface resolutionPreviewLogicActions {
+ loadPreview: () => any
+ loadPreviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPreviewSuccess: (
+ preview: ResolutionPreviewResponse,
+ payload?: any
+ ) => {
+ preview: ResolutionPreviewResponse
+ payload?: any
+ }
+}
+
+export type resolutionPreviewLogicType = MakeLogicType<resolutionPreviewLogicValues, resolutionPreviewLogicActions>
+
+export const resolutionPreviewLogic = kea<resolutionPreviewLogicType>([
+ path([
+ 'layout',
+ 'navigation-3000',
+ 'sidepanel',
+ 'panels',
+ 'access_control',
+ 'ResolutionPreview',
+ 'resolutionPreviewLogic',
+ ]),
+ connect(() => ({ values: [teamLogic, ['currentTeamIdStrict']] })),
+ loaders(({ values }) => ({
+ preview: [
+ null as ResolutionPreviewResponse | null,
+ {
+ loadPreview: async () =>
+ await api.get<ResolutionPreviewResponse>(
+ `api/projects/${values.currentTeamIdStrict}/access_control_resolution_preview`
+ ),
+ },
+ ],
+ })),
+ reducers({
+ previewForbidden: [
+ false,
+ {
+ loadPreview: () => false,
+ loadPreviewFailure: (_, { errorObject }) => errorObject?.status === 403,
+ },
+ ],
+ }),
+ afterMount(({ actions }) => {
+ actions.loadPreview()
+ }),
+])
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
index c49c98694ad4..407f1a660715 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
@@ -108,9 +108,13 @@ export const OBJECT_RULE_RESOURCE_CONFIG: Partial<Record<APIScopeObject, ObjectR
url: (rule) => urls.dataWarehouseSource(`managed-${rule.resource_id}`),
parseUrl: (path) => /^\/data-management\/sources\/managed-([0-9a-f-]{36})(?:[/?#]|$)/.exec(path)?.[1] ?? null,
},
+ notebook: {
+ url: (rule) => (rule.short_id ? urls.notebook(rule.short_id) : null),
+ parseUrl: (path) => /^\/notebooks\/([A-Za-z0-9]+)(?:[/?#]|$)/.exec(path)?.[1] ?? null,
+ },
}
-/** A link to open the object, null for types we can't address (e.g. notebooks need a short_id). */
+/** A link to open the object, null for types without a URL or whose short_id is missing. */
export function objectRuleUrl(rule: AccessObjectRule): string | null {
return OBJECT_RULE_RESOURCE_CONFIG[rule.resource]?.url(rule) ?? null
}
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index d8d51064b145..eb15c0254ed6 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -188,6 +188,7 @@ export const FEATURE_FLAGS = {
// Feature flags used to control opt-in for different behaviors, should not be removed
ACCESS_CONTROL_DETAIL_PANEL: 'access-control-detail-panel', // owner: @a-lider #team-platform-features, gates the member and role access detail side panel
+ ACCESS_CONTROL_RESOLUTION_PREVIEW: 'access-control-resolution-preview', // owner: @a-lider #team-platform-features, gates the access resolution preview settings section and its banner
AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST: 'ai-observability-instrumentation-checklist', // owner: #team-ai-observability, gates the instrumentation checklist card and empty states
AI_OBSERVABILITY_SELF_DRIVING: 'ai-observability-daily-digest-scout', // owner: #team-ai-observability, gates the AI observability Self-driving tab
AI_TRAINING: 'ai-training', // owner: @nicowaltz #team-replay #ai-research, gates the AI training opt-out UI and API enforcement
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 60554d93f3c2..84ddef59a2d5 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -39,6 +39,7 @@ import { SessionsV2JoinModeSettings } from 'scenes/settings/environment/Sessions
import { OrganizationMCPAccess } from 'scenes/settings/organization/OrganizationMCPAccess'
import { urls } from 'scenes/urls'
+import { AccessResolutionPreview } from '~/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview'
import {
DefaultRoleSelector,
RolesAccessControls,
@@ -1933,6 +1934,25 @@ export const SETTINGS_MAP: SettingSection[] = [
},
],
},
+ {
+ level: 'organization',
+ id: 'organization-access-resolution',
+ title: 'Access resolution preview',
+ flag: 'ACCESS_CONTROL_RESOLUTION_PREVIEW',
+ // Temporary migration surface: reachable only from the access control
+ // settings banner, never from the settings navigation or search
+ hideFromNavigation: true,
+ settings: [
+ {
+ id: 'organization-access-resolution-preview',
+ title: 'Access resolution preview',
+ description:
+ 'PostHog is changing how access levels combine: the most specific rule will decide, instead of the highest one. Review what will be different for your organization before the change takes effect.',
+ component: <AccessResolutionPreview />,
+ keywords: ['access control', 'resolution', 'rbac', 'permission', 'override'],
+ },
+ ],
+ },
{
level: 'organization',
id: 'organization-security',
diff --git a/frontend/src/scenes/settings/environment/TeamAccessControl.tsx b/frontend/src/scenes/settings/environment/TeamAccessControl.tsx
index de0699fcf443..39c8eb47f340 100644
--- a/frontend/src/scenes/settings/environment/TeamAccessControl.tsx
+++ b/frontend/src/scenes/settings/environment/TeamAccessControl.tsx
@@ -1,14 +1,40 @@
import { useValues } from 'kea'
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
import { ResourcesAccessControlsV2 } from '~/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2'
+import { AvailableFeature } from '~/types'
export function TeamAccessControl(): JSX.Element {
const { currentTeam } = useValues(teamLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { isAdminOrOwner } = useValues(organizationLogic)
+ const { hasAvailableFeature } = useValues(userLogic)
return (
<div className="space-y-6">
+ {featureFlags[FEATURE_FLAGS.ACCESS_CONTROL_RESOLUTION_PREVIEW] &&
+ isAdminOrOwner &&
+ hasAvailableFeature(AvailableFeature.ACCESS_CONTROL) && (
+ <LemonBanner
+ type="warning"
+ action={{
+ children: 'Review changes',
+ to: urls.settings('organization-access-resolution'),
+ 'data-attr': 'access-resolution-banner-review',
+ }}
+ >
+ {getFeatureFlagPayload(FEATURE_FLAGS.ACCESS_CONTROL_RESOLUTION_PREVIEW)?.message ??
+ 'Access control will start using the most specific rule. Review the changes before they take effect.'}
+ </LemonBanner>
+ )}
{currentTeam?.id ? <ResourcesAccessControlsV2 projectId={`${currentTeam.id}`} /> : null}
</div>
)
diff --git a/frontend/src/scenes/settings/settingsLogic.ts b/frontend/src/scenes/settings/settingsLogic.ts
index a5c1911b3a79..5fec194b3b2d 100644
--- a/frontend/src/scenes/settings/settingsLogic.ts
+++ b/frontend/src/scenes/settings/settingsLogic.ts
@@ -488,6 +488,9 @@ export const settingsLogic = kea<settingsLogicType>([
if (section.id === 'organization-legal-documents' && !isAdminOrOwner) {
return false
}
+ if (section.id === 'organization-access-resolution' && !isAdminOrOwner) {
+ return false
+ }
return true
})
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index f4cf0a16178a..efef9e57913f 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -71,6 +71,7 @@ export type SettingSectionId =
| 'organization-oauth-apps'
| 'organization-proxy'
| 'organization-roles'
+ | 'organization-access-resolution'
| 'organization-security'
| 'organization-startup-program'
| 'organization-danger-zone'
@@ -218,6 +219,7 @@ export type SettingId =
| 'organization-oauth-apps-list'
| 'organization-proxy'
| 'organization-roles'
+ | 'organization-access-resolution-preview'
| 'organization-security'
| 'organization-mcp-access'
| 'organization-personal-api-keys'
diff --git a/posthog/test/repo_invariants/test_rbac_shadow_resolver_callers.py b/posthog/test/repo_invariants/test_rbac_shadow_resolver_callers.py
index 670d2d124b4a..80f52f7d785c 100644
--- a/posthog/test/repo_invariants/test_rbac_shadow_resolver_callers.py
+++ b/posthog/test/repo_invariants/test_rbac_shadow_resolver_callers.py
@@ -1,7 +1,12 @@
from pathlib import Path
RESOLVER_NAMES = ("resolve_most_specific_object_access", "resolve_most_specific_resource_access")
-ALLOWED = {Path("products/access_control/backend/facade/user_access_control.py")}
+ALLOWED = {
+ Path("products/access_control/backend/facade/user_access_control.py"),
+ # The read-only resolution preview compares the enforced and
+ # most-specific resolutions; it never enforces.
+ Path("products/access_control/backend/facade/resolution_preview.py"),
+}
SCANNED_ROOTS = ("posthog", "ee", "products")
diff --git a/products/access_control/backend/facade/object_names.py b/products/access_control/backend/facade/object_names.py
new file mode 100644
index 000000000000..3e01a368cc79
--- /dev/null
+++ b/products/access_control/backend/facade/object_names.py
@@ -0,0 +1,189 @@
+"""Which model backs each access-controlled resource, and how its objects are named.
+
+The registry (`resources_with_object_access_controls`) walks the registered routes, so it cannot
+drift from the code: a viewset opts in by mixing in AccessControlViewSetMixin, which stamps the
+`object_access_controls` marker this module keys on. The naming helpers build the display names
+the settings UI and the resolution preview show for object rules.
+"""
+
+from dataclasses import dataclass
+from functools import cache
+from typing import cast
+
+from django.apps import apps
+from django.core.exceptions import FieldDoesNotExist
+from django.db.models import Model
+from django.urls import URLResolver, get_resolver
+
+from posthog.exceptions_capture import capture_exception
+from posthog.scopes import INTERNAL_API_SCOPE_OBJECTS, APIScopeObject
+
+
+@dataclass(frozen=True, kw_only=True)
+class _ResourceDisplayModel:
+ app_label: str
+ model_name: str
+ name_field: str
+
+
+# Names come from universal search's ENTITY_MAP first; these entries cover resources search doesn't
+# index, so they have no ENTITY_MAP entry to borrow. Add one when a resource's objects render raw
+# ids instead of names, in the rules list or the picker; delete one when search starts indexing the
+# resource, since ENTITY_MAP is consulted first and the entry goes dead. A resource in neither place
+# and with no derivable name field is left out of the picker and falls back to the raw id.
+_MODELS_NOT_IN_ENTITY_MAP: dict[str, _ResourceDisplayModel] = {
+ "evaluation": _ResourceDisplayModel(app_label="ai_observability", model_name="evaluation", name_field="name"),
+ "warehouse_view": _ResourceDisplayModel(
+ app_label="data_modeling", model_name="datawarehousesavedquery", name_field="name"
+ ),
+ "warehouse_table": _ResourceDisplayModel(
+ app_label="warehouse_sources", model_name="datawarehousetable", name_field="name"
+ ),
+ "external_data_source": _ResourceDisplayModel(
+ app_label="warehouse_sources", model_name="externaldatasource", name_field="source_type"
+ ),
+ "session_recording": _ResourceDisplayModel(
+ app_label="posthog", model_name="sessionrecording", name_field="session_id"
+ ),
+ "ticket": _ResourceDisplayModel(app_label="conversations", model_name="ticket", name_field="ticket_number"),
+}
+
+
+@dataclass(frozen=True, kw_only=True)
+class ResolvedObjectName:
+ name: str | None
+ # Insights link by short_id rather than pk, so the frontend needs it alongside the name
+ short_id: str | None = None
+
+
+@cache
+def resources_with_object_access_controls() -> dict[APIScopeObject, frozenset[type[Model]]]:
+ """Resources that support object-level access controls, mapped to the models behind them.
+
+ A viewset opts in by mixing in AccessControlViewSetMixin, so the registered routes are the
+ source of truth and this cannot drift from the code; adding the mixin also puts the resource in
+ the settings picker. A scope served by several viewsets maps to several models. The snapshot
+ test in test_access_control.py records the resources; regenerate it with `pytest
+ --snapshot-update`.
+ """
+ found: dict[APIScopeObject, set[type[Model]]] = {}
+
+ def walk(resolver: URLResolver) -> None:
+ for pattern in resolver.url_patterns:
+ if isinstance(pattern, URLResolver):
+ walk(pattern)
+ continue
+ cls = getattr(pattern.callback, "cls", None)
+ # The marker AccessControlViewSetMixin stamps, so this facade module needs no
+ # import of the presentation class
+ if cls is None or not getattr(cls, "object_access_controls", False):
+ continue
+ scope = getattr(cls, "scope_object", None)
+ # Project-level access is its own control (the "Project access" dropdown), never an
+ # object rule; every rules endpoint filters resource="project" out as well
+ if scope and scope != "INTERNAL" and scope != "project" and scope not in INTERNAL_API_SCOPE_OBJECTS:
+ queryset = getattr(cls, "queryset", None)
+ found.setdefault(scope, set())
+ if queryset is not None:
+ found[scope].add(queryset.model)
+
+ walk(get_resolver())
+ return {scope: frozenset(models) for scope, models in found.items()}
+
+
+def model_has_field(model: type[Model], field: str) -> bool:
+ try:
+ model._meta.get_field(field)
+ return True
+ except FieldDoesNotExist:
+ return False
+
+
+@dataclass(frozen=True, kw_only=True)
+class DisplayModel:
+ """Where a resource's objects live and which field names them."""
+
+ model: type[Model]
+ name_field: str
+
+
+def display_model(resource: str) -> DisplayModel | None:
+ """Resolve a resource to its model and display field. None means the settings UI cannot work
+ with the resource's objects: search returns 400, rule writes return 400, existing rules show
+ raw ids.
+
+ A resource qualifies when its viewsets carry object-level access controls and we can name its
+ objects, tried in order: search's ENTITY_MAP (its rank-A field is the display name), the
+ supplement for resources search doesn't index, and finally a resource whose routes expose
+ exactly one model carrying a recognizable name field.
+ """
+ # Gate before the cached resolver: resource is raw request input, and caching unknown values
+ # would grow the cache by one permanent entry per distinct garbage string
+ if resource not in resources_with_object_access_controls():
+ return None
+ return _display_model_for_known_resource(resource)
+
+
+@cache
+def _display_model_for_known_resource(resource: str) -> DisplayModel | None:
+ from posthog.api.search import (
+ ENTITY_MAP, # noqa: PLC0415 — imports every searchable product model, keep it off this module's import path
+ )
+
+ model: type[Model] | None = None
+ name_field: str | None = None
+ entity = ENTITY_MAP.get(resource)
+ supplement = _MODELS_NOT_IN_ENTITY_MAP.get(resource)
+ if entity is not None:
+ model = entity["klass"]
+ name_field = next((field for field, rank in entity["search_fields"].items() if rank == "A"), None)
+ elif supplement is not None:
+ model = apps.get_model(supplement.app_label, supplement.model_name)
+ name_field = supplement.name_field
+ else:
+ models = resources_with_object_access_controls().get(cast(APIScopeObject, resource)) or frozenset()
+ if len(models) == 1:
+ model = next(iter(models))
+ name_field = next((field for field in ("name", "title", "key") if model_has_field(model, field)), None)
+
+ if model is None or name_field is None or not model_has_field(model, "team"):
+ return None
+ return DisplayModel(model=model, name_field=name_field)
+
+
+def resolve_object_names(resource: str, resource_ids: list[str], team_id: int) -> dict[str, ResolvedObjectName]:
+ """Map {resource_id -> display info} for one resource type, empty when we can't name its objects.
+
+ Queries through _base_manager so rules pointing at soft-deleted objects still resolve: those are
+ exactly the rows someone opens this page to clean up. Tenant isolation holds via team_id.
+ """
+ display = display_model(resource) if resource_ids else None
+ if display is None:
+ return {}
+ try:
+ rows = display.model._base_manager.filter(team_id=team_id, pk__in=resource_ids)
+ if resource == "insight":
+ # Insight.name is nullable and saved insights often carry only derived_name, and insight
+ # URLs address short_ids rather than the pk rules store
+ return {
+ str(pk): ResolvedObjectName(name=name or derived_name, short_id=short_id)
+ for pk, name, derived_name, short_id in rows.values_list("pk", "name", "derived_name", "short_id")
+ }
+ if resource == "ticket":
+ # A bare number doesn't read as an object; match the ticket page's own title
+ return {
+ str(pk): ResolvedObjectName(name=f"Ticket: {number}")
+ for pk, number in rows.values_list("pk", "ticket_number")
+ }
+ if model_has_field(display.model, "short_id"):
+ # Notebooks and other short_id models link by short_id, like insights
+ return {
+ str(pk): ResolvedObjectName(name=name, short_id=short_id)
+ for pk, name, short_id in rows.values_list("pk", display.name_field, "short_id")
+ }
+ return {str(pk): ResolvedObjectName(name=name) for pk, name in rows.values_list("pk", display.name_field)}
+ except Exception as e:
+ # A resource_id of the wrong shape for the model's pk, or a model that moved. The rules list
+ # falls back to raw ids, but report it: one failure usually breaks the whole resource type
+ capture_exception(e, {"resource": resource})
+ return {}
diff --git a/products/access_control/backend/facade/resolution_preview.py b/products/access_control/backend/facade/resolution_preview.py
new file mode 100644
index 000000000000..e15ef7a42fc5
--- /dev/null
+++ b/products/access_control/backend/facade/resolution_preview.py
@@ -0,0 +1,408 @@
+"""Preview of the most-specific resolution change, per rule subject.
+
+For one team, compare the enforced resolution with the most-specific resolution for every rule
+subject (the everyone-default, each named role, each named member) against every object that has
+rules and every resource that has resource-level rows. Return one change record per (subject,
+scope) pair whose level differs. Members are never enumerated: members with the same applicable
+rules resolve identically, so one subject-level record covers all of them.
+
+Read-only. Nothing here changes enforcement. The settings preview page and the divergent-org
+sweep command are the only callers.
+"""
+
+from collections.abc import Iterator
+from dataclasses import replace
+from typing import Literal, Optional, cast
+
+from django.db.models import Model
+
+from posthog.constants import AvailableFeature
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.scopes import APIScopeObject
+
+from products.access_control.backend.facade.object_names import display_model, resolve_object_names
+from products.access_control.backend.facade.subject_access_control import SubjectAccessControl
+from products.access_control.backend.facade.user_access_control import (
+ RESOURCE_FALLBACK_MAP,
+ RESOURCE_INHERITANCE_MAP,
+ RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS,
+ ResolvedAccess,
+ UserAccessControl,
+ ordered_access_levels,
+)
+from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.role import Role, RoleMembership
+
+SubjectType = Literal["default", "role", "member"]
+
+# Rows on these resources resolve the same under both ladders, or have no object model to load
+_SKIPPED_RESOURCES = frozenset({"organization", "plugin"})
+
+
+@frozen
+class SubjectRef:
+ """The rule subject a change applies to. A change applies to the members the subject reaches
+ who have no more specific rule of their own."""
+
+ type: SubjectType
+ id: Optional[str]
+ name: str
+
+
+@frozen
+class ResolutionChange:
+ subject: SubjectRef
+ scope: Literal["object", "resource"]
+ resource: str
+ object_id: Optional[str]
+ object_name: Optional[str]
+ # The object's URL key (e.g. an insight's or notebook's short id) when the model has one,
+ # so the page can link to the object
+ object_short_id: Optional[str]
+ # Both carry subject_name, so the explanation can say which role's grant applies today
+ current: ResolvedAccess
+ proposed: ResolvedAccess
+ direction: Literal["gains", "loses"]
+
+
+@frozen
+class _Subject:
+ ref: SubjectRef
+ access: SubjectAccessControl
+ member_user_id: Optional[int]
+
+
+@frozen
+class _Subjects:
+ subjects: list[_Subject]
+ role_names: dict[str, str]
+ member_names: dict[str, str]
+
+
+@frozen
+class _LoadedObject:
+ instance: Model
+ name: Optional[str]
+ short_id: Optional[str]
+
+
+def _deciding_subject_name(
+ subject: SubjectAccessControl,
+ access: ResolvedAccess,
+ role_names: dict[str, str],
+ member_names: dict[str, str],
+) -> Optional[str]:
+ """Name of the member or role whose row decided `access`.
+
+ The walks report which kind of subject decided (`source_subject`) but not which row. The
+ deciding row is re-picked from the same cached pool: the highest row of that kind in the
+ scope the walk reported.
+ """
+ if access.source_subject not in ("role", "member"):
+ return None
+ if access.source in ("object", "parent_object"):
+ if access.source_resource_id is None:
+ return None
+ filters = subject._access_controls_filters_for_object(access.source_resource, access.source_resource_id)
+ elif access.source in ("resource", "parent_resource"):
+ filters = subject._access_controls_filters_for_resource(access.source_resource)
+ else:
+ return None
+ rows = [row for row in subject._get_access_controls(filters) if subject._row_subject(row) == access.source_subject]
+ if not rows:
+ return None
+ row = subject._highest_access_from_rows(access.source_resource, rows)
+ if row.role_id is not None:
+ return role_names.get(str(row.role_id))
+ if row.organization_member_id is not None:
+ return member_names.get(str(row.organization_member_id))
+ return None
+
+
+def _enforced_object_access(subject: SubjectAccessControl, obj: Model, resource: APIScopeObject) -> ResolvedAccess:
+ """The enforced resolution of `obj` for `subject`, with provenance.
+
+ Mirrors `get_user_access_level`, which returns the level only. The preview needs the source
+ to explain each change, so it walks the same private methods. The caller already excluded
+ the precheck outcomes (creators, org admins, missing entitlement), so the row walk is the
+ whole answer.
+ """
+ rows = subject._get_access_controls(subject._access_controls_filters_for_object(resource, str(obj.pk)))
+ access = subject._object_access_level_from_rows(
+ resource, rows, fallback_parent_id=subject._fallback_parent_id(obj, resource)
+ )
+ assert access is not None # explicit=False never returns None here
+ return access
+
+
+def _subject_key(row: AccessControl) -> tuple:
+ if row.organization_member_id is not None:
+ return ("member", str(row.organization_member_id))
+ if row.role_id is not None:
+ return ("role", str(row.role_id))
+ return ("default",)
+
+
+def _build_subjects(team: Team, user_access_control: UserAccessControl, rows: list[AccessControl]) -> _Subjects:
+ """One subject per distinct rule target in `rows`, plus the everyone-default, and the
+ role and member display names keyed by id.
+
+ Org-admin members are excluded: both resolutions give them the highest level. Role ids of
+ each member subject are prefetched here, so subjects do not query per member.
+ """
+ acting_membership = user_access_control._organization_membership
+ if acting_membership is None:
+ return _Subjects(subjects=[], role_names={}, member_names={})
+
+ member_ids = {row.organization_member_id for row in rows if row.organization_member_id is not None}
+ role_ids = {row.role_id for row in rows if row.role_id is not None}
+
+ memberships = list(
+ OrganizationMembership.objects.filter(id__in=member_ids, organization_id=team.organization_id).select_related(
+ "user"
+ )
+ )
+ roles = Role.objects.filter(id__in=role_ids, organization_id=team.organization_id)
+ # Role membership is keyed by user, matching SubjectAccessControl._user_role_ids
+ role_ids_by_user: dict[int, list[str]] = {}
+ for rm in RoleMembership.objects.filter(
+ role__organization_id=team.organization_id, user_id__in=[membership.user_id for membership in memberships]
+ ):
+ role_ids_by_user.setdefault(rm.user_id, []).append(str(rm.role_id))
+
+ subjects: list[_Subject] = [
+ _Subject(
+ ref=SubjectRef(type="default", id=None, name="Everyone"),
+ access=SubjectAccessControl(user_access_control.user, team, org_membership=acting_membership),
+ member_user_id=None,
+ )
+ ]
+ for role in roles:
+ subjects.append(
+ _Subject(
+ ref=SubjectRef(type="role", id=str(role.id), name=role.name),
+ access=SubjectAccessControl(
+ user_access_control.user, team, org_membership=acting_membership, role_id=str(role.id)
+ ),
+ member_user_id=None,
+ )
+ )
+ for membership in memberships:
+ if membership.level >= OrganizationMembership.Level.ADMIN:
+ continue
+ user = membership.user
+ name = f"{user.first_name} {user.last_name}".strip() or user.email
+ member_access = SubjectAccessControl(
+ user_access_control.user, team, org_membership=acting_membership, member=membership
+ )
+ subjects.append(
+ _Subject(
+ ref=SubjectRef(type="member", id=str(membership.id), name=name),
+ access=member_access,
+ member_user_id=membership.user_id,
+ )
+ )
+
+ for subject in subjects:
+ subject_role_ids = (
+ role_ids_by_user.get(subject.member_user_id, []) if subject.member_user_id is not None else None
+ )
+ subject.access.preload_access_controls(rows, subject_role_ids=subject_role_ids)
+
+ role_names = {str(role.id): role.name for role in roles}
+ member_names = {subject.ref.id or "": subject.ref.name for subject in subjects if subject.ref.type == "member"}
+ return _Subjects(subjects=subjects, role_names=role_names, member_names=member_names)
+
+
+def _load_objects(team: Team, resource: str, object_ids: list[str]) -> dict[str, _LoadedObject]:
+ """Map {object_id -> loaded object} for one resource. Empty when the resource has no
+ display model, which also means resolution has no model class to work with."""
+ if resource == "project":
+ # Project rules point at the team itself
+ if str(team.pk) not in object_ids:
+ return {}
+ return {str(team.pk): _LoadedObject(instance=team, name=team.name, short_id=None)}
+
+ display = display_model(resource)
+ if display is None:
+ return {}
+ names = resolve_object_names(resource, object_ids, team.pk)
+ try:
+ instances = display.model._base_manager.filter(team_id=team.pk, pk__in=object_ids)
+ except Exception as e:
+ capture_exception(e, {"resource": resource})
+ return {}
+ result: dict[str, _LoadedObject] = {}
+ for obj in instances:
+ object_id = str(obj.pk)
+ name = names.get(object_id)
+ short_id = getattr(obj, "short_id", None)
+ result[object_id] = _LoadedObject(
+ instance=obj, name=name.name if name else None, short_id=str(short_id) if short_id else None
+ )
+ return result
+
+
+def build_resolution_preview(team: Team, user_access_control: UserAccessControl) -> list[ResolutionChange]:
+ """Every (subject, scope) pair on `team` whose enforced and most-specific resolutions differ."""
+ if not team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
+ return []
+
+ rows = list(AccessControl.objects.filter(team=team).exclude(resource__in=_SKIPPED_RESOURCES))
+ if not rows:
+ return []
+
+ subject_index = _build_subjects(team, user_access_control, rows)
+ changes: list[ResolutionChange] = []
+
+ def compare(
+ subject: _Subject,
+ scope: Literal["object", "resource"],
+ resource: str,
+ current: Optional[ResolvedAccess],
+ proposed: Optional[ResolvedAccess],
+ object_id: Optional[str] = None,
+ object_name: Optional[str] = None,
+ object_short_id: Optional[str] = None,
+ ) -> None:
+ if current is None or proposed is None or current.access_level == proposed.access_level:
+ return
+ order = ordered_access_levels(cast(APIScopeObject, resource))
+ direction: Literal["gains", "loses"] = (
+ "gains" if order.index(proposed.access_level) > order.index(current.access_level) else "loses"
+ )
+ changes.append(
+ ResolutionChange(
+ subject=subject.ref,
+ scope=scope,
+ resource=resource,
+ object_id=object_id,
+ object_name=object_name,
+ object_short_id=object_short_id,
+ current=replace(
+ current,
+ subject_name=_deciding_subject_name(
+ subject.access, current, subject_index.role_names, subject_index.member_names
+ ),
+ ),
+ proposed=replace(
+ proposed,
+ subject_name=_deciding_subject_name(
+ subject.access, proposed, subject_index.role_names, subject_index.member_names
+ ),
+ ),
+ direction=direction,
+ )
+ )
+
+ # Resource scope: resources that have resource-level rows. The everyone-subject cannot
+ # differ here (only default rows are visible to it, and one tier resolves the same both
+ # ways), so only named subjects with a row on the resource are compared.
+ resource_rows: dict[str, list[AccessControl]] = {}
+ for row in rows:
+ if row.resource_id is None and row.resource not in RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS:
+ resource_rows.setdefault(row.resource, []).append(row)
+ for resource, pool in resource_rows.items():
+ relevant = {_subject_key(row) for row in pool}
+ for subject in subject_index.subjects:
+ if subject.ref.type == "default" or (subject.ref.type, subject.ref.id) not in relevant:
+ continue
+ compare(
+ subject,
+ "resource",
+ resource,
+ subject.access.access_level_for_resource(cast(APIScopeObject, resource)),
+ subject.access.resolve_most_specific_resource_access(cast(APIScopeObject, resource)),
+ )
+
+ # Object scope: objects that have rules. A named subject resolves an object differently
+ # from the everyone subject only through its explicit rows: on the object itself, at the
+ # resource level, or on a parent resource the ladders consult (RESOURCE_INHERITANCE_MAP /
+ # RESOURCE_FALLBACK_MAP). Anything narrower drops real changes; anything wider repeats the
+ # everyone record once per subject.
+ object_ids_by_resource: dict[str, list[str]] = {}
+ for row in rows:
+ if row.resource_id is not None:
+ ids = object_ids_by_resource.setdefault(row.resource, [])
+ if row.resource_id not in ids:
+ ids.append(row.resource_id)
+ rows_by_resource: dict[str, list[AccessControl]] = {}
+ for row in rows:
+ rows_by_resource.setdefault(row.resource, []).append(row)
+
+ for resource, object_ids in object_ids_by_resource.items():
+ objects = _load_objects(team, resource, object_ids)
+ explicit_keys_by_object: dict[str, set[tuple]] = {}
+ resource_wide_keys: set[tuple] = set()
+ for row in rows_by_resource.get(resource, []):
+ if _subject_key(row) == ("default",):
+ continue
+ if row.resource_id is None:
+ resource_wide_keys.add(_subject_key(row))
+ else:
+ explicit_keys_by_object.setdefault(row.resource_id, set()).add(_subject_key(row))
+ scoped_resource = cast(APIScopeObject, resource)
+ for parent in {RESOURCE_INHERITANCE_MAP.get(scoped_resource), RESOURCE_FALLBACK_MAP.get(scoped_resource)} - {
+ None
+ }:
+ resource_wide_keys |= {
+ _subject_key(row)
+ for row in rows_by_resource.get(cast(str, parent), [])
+ if _subject_key(row) != ("default",)
+ }
+ for subject in subject_index.subjects:
+ key = ("default",) if subject.ref.type == "default" else (subject.ref.type, subject.ref.id)
+ # The everyone subject is always compared: the object default vs resource level
+ # case names no subject
+ subject_is_resource_wide = key == ("default",) or key in resource_wide_keys
+ for object_id in object_ids:
+ if not subject_is_resource_wide and key not in explicit_keys_by_object.get(object_id, set()):
+ continue
+ loaded = objects.get(object_id)
+ if loaded is None:
+ continue
+ obj = loaded.instance
+ if subject.member_user_id is not None and getattr(obj, "created_by_id", None) == subject.member_user_id:
+ # Creators keep the highest level under both ladders
+ continue
+ compare(
+ subject,
+ "object",
+ resource,
+ _enforced_object_access(subject.access, obj, cast(APIScopeObject, resource)),
+ subject.access.resolve_most_specific_object_access(obj),
+ object_id=object_id,
+ object_name=loaded.name,
+ object_short_id=loaded.short_id,
+ )
+
+ return changes
+
+
+def iter_resolution_changes(organization_id: Optional[str] = None) -> "Iterator[tuple[Team, list[ResolutionChange]]]":
+ """Yield (team, changes) for every team with access rules, ordered by organization.
+
+ Resolution is evaluated as one acting active member per organization; teams of
+ organizations with no active member are skipped.
+ """
+ team_ids = AccessControl.objects.values_list("team_id", flat=True).distinct()
+ teams = Team.objects.filter(id__in=team_ids).select_related("organization").order_by("organization_id")
+ if organization_id is not None:
+ teams = teams.filter(organization_id=organization_id)
+
+ acting_membership_by_org: dict[str, Optional[OrganizationMembership]] = {}
+ for team in teams.iterator():
+ org_id = str(team.organization_id)
+ if org_id not in acting_membership_by_org:
+ acting_membership_by_org[org_id] = (
+ OrganizationMembership.objects.filter(organization_id=team.organization_id, user__is_active=True)
+ .select_related("user")
+ .first()
+ )
+ membership = acting_membership_by_org[org_id]
+ if membership is None:
+ continue
+ yield team, build_resolution_preview(team, UserAccessControl(membership.user, team))
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index 1d14be4878ce..72aaac16e01e 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -277,6 +277,9 @@ class ResolvedAccess:
# (the source a table inherited from), so a display can name it. None when the rule is
# resource-wide or no rule decided.
source_resource_id: Optional[str] = None
+ # Display name of the member or role whose row decided. Enforcement never sets or reads
+ # it; the resolution preview fills it so explanations can name the deciding subject.
+ subject_name: Optional[str] = None
def model_to_resource(model: Model) -> Optional[APIScopeObject]:
diff --git a/products/access_control/backend/management/__init__.py b/products/access_control/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/access_control/backend/management/commands/__init__.py b/products/access_control/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/access_control/backend/management/commands/migrate_to_most_specific_access.py b/products/access_control/backend/management/commands/migrate_to_most_specific_access.py
new file mode 100644
index 000000000000..bab9ed9e594e
--- /dev/null
+++ b/products/access_control/backend/management/commands/migrate_to_most_specific_access.py
@@ -0,0 +1,61 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+from posthog.models.organization import Organization
+
+from products.access_control.backend.facade.resolution_preview import iter_resolution_changes
+from products.access_control.backend.models.access_control import AccessControl
+
+
+class Command(BaseCommand):
+ help = (
+ "Report readiness for most-specific access resolution across organizations that have access "
+ "rules: those that resolve differently first, then those where nothing changes, then those "
+ "that could not be evaluated (no active member to resolve as). Organizations with no rules "
+ "cannot resolve differently and are omitted. Read-only for now; migration comes later, so "
+ "--dry-run and a plain run print the same report."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--dry-run", action="store_true", help="Report only, migrate nothing")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ totals: dict[Any, dict[str, int]] = {}
+ names: dict[Any, str] = {}
+
+ for team, changes in iter_resolution_changes():
+ org_id = team.organization_id
+ names[org_id] = team.organization.name
+ counts = totals.setdefault(org_id, {"teams": 0, "changes": 0, "gains": 0, "loses": 0})
+ counts["teams"] += 1
+ counts["changes"] += len(changes)
+ counts["gains"] += sum(1 for change in changes if change.direction == "gains")
+ counts["loses"] += sum(1 for change in changes if change.direction == "loses")
+
+ divergent = {org_id: counts for org_id, counts in totals.items() if counts["changes"] > 0}
+ unchanged = {org_id: counts for org_id, counts in totals.items() if counts["changes"] == 0}
+
+ self.stdout.write(f"{len(divergent)} organizations resolve differently")
+ for org_id, counts in sorted(divergent.items(), key=lambda item: -item[1]["changes"]):
+ self.stdout.write(
+ f"{org_id}\t{names[org_id]}\tteams={counts['teams']}\t"
+ f"changes={counts['changes']}\tgains={counts['gains']}\tloses={counts['loses']}"
+ )
+
+ self.stdout.write("")
+ self.stdout.write(f"{len(unchanged)} organizations where nothing changes")
+ for org_id, counts in sorted(unchanged.items(), key=lambda item: str(item[0])):
+ self.stdout.write(f"{org_id}\t{names[org_id]}\tteams={counts['teams']}")
+
+ # Organizations with rules that yielded no evaluation: no active member to resolve as
+ unevaluated = dict(
+ Organization.objects.filter(teams__id__in=AccessControl.objects.values("team_id"))
+ .exclude(id__in=totals.keys())
+ .distinct()
+ .values_list("id", "name")
+ )
+ self.stdout.write("")
+ self.stdout.write(f"{len(unevaluated)} organizations could not be evaluated (no active member)")
+ for org_id, name in sorted(unevaluated.items(), key=lambda item: str(item[0])):
+ self.stdout.write(f"{org_id}\t{name}")
diff --git a/products/access_control/backend/management/commands/preview_most_specific_access_changes.py b/products/access_control/backend/management/commands/preview_most_specific_access_changes.py
new file mode 100644
index 000000000000..cdd82ed79ea4
--- /dev/null
+++ b/products/access_control/backend/management/commands/preview_most_specific_access_changes.py
@@ -0,0 +1,57 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+from products.access_control.backend.facade.resolution_preview import ResolutionChange, iter_resolution_changes
+
+
+class Command(BaseCommand):
+ help = (
+ "Show what changes for one organization under most-specific access resolution: "
+ "every rule that resolves differently, per project. Read-only."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("organization_id")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ detail_lines: list[str] = []
+ teams = 0
+ gains = 0
+ loses = 0
+ organization_name = ""
+
+ for team, changes in iter_resolution_changes(options["organization_id"]):
+ teams += 1
+ organization_name = team.organization.name
+ gains += sum(1 for change in changes if change.direction == "gains")
+ loses += sum(1 for change in changes if change.direction == "loses")
+ detail_lines.append(f"Project {team.pk} — {team.name}")
+ if not changes:
+ detail_lines.append(" no changes")
+ for change in changes:
+ detail_lines.append(f" {self._describe(change)}")
+
+ if teams == 0:
+ self.stdout.write("No access rules found for this organization.")
+ return
+
+ changes_total = gains + loses
+ if changes_total > 0:
+ summary = f"changes={changes_total}\tgains={gains}\tloses={loses}"
+ else:
+ summary = "no changes"
+ self.stdout.write(f"organization\t{organization_name}\tteams={teams}\t{summary}")
+ self.stdout.write("")
+ for line in detail_lines:
+ self.stdout.write(line)
+
+ def _describe(self, change: ResolutionChange) -> str:
+ if change.scope == "resource":
+ target = f"all {change.resource}s"
+ else:
+ target = f'{change.resource} "{change.object_name or change.object_id}"'
+ return (
+ f"{change.subject.type} {change.subject.name}\t{target}\t"
+ f"{change.current.access_level} -> {change.proposed.access_level} ({change.direction})"
+ )
diff --git a/products/access_control/backend/presentation/access_control.py b/products/access_control/backend/presentation/access_control.py
index 8a61f768c0e4..a44c075a91cf 100644
--- a/products/access_control/backend/presentation/access_control.py
+++ b/products/access_control/backend/presentation/access_control.py
@@ -17,6 +17,7 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, APIScopeObjectOrNotSupported
+from products.access_control.backend.facade.object_names import display_model
from products.access_control.backend.facade.subject_access_control import SubjectAccessControl
from products.access_control.backend.facade.user_access_control import (
ACCESS_CONTROL_LEVELS_RESOURCE,
@@ -46,14 +47,10 @@ def _inherited_source_display_name(obj: Model, access: ResolvedAccess) -> str |
fallback relation (that's where the walk got its id), so it is read off the object — cached
by Django, free when already loaded — never refetched by id. The name field comes from the
same registry the settings UI names objects with, so a new fallback parent needs no code here."""
- from .access_control_settings import (
- _display_model, # noqa: PLC0415 — access_control_settings imports this module; deferring breaks the cycle
- )
-
if access.source != "parent_object":
return None
parent = fallback_parent_object(obj, access.source_resource)
- display = _display_model(access.source_resource)
+ display = display_model(access.source_resource)
if parent is None or display is None:
return None
name = getattr(parent, display.name_field, None)
@@ -293,6 +290,10 @@ def upsert_access_control(
class AccessControlViewSetMixin(_GenericViewSet):
+ # The facade's route walk (object_names.resources_with_object_access_controls) keys on this
+ # marker instead of importing the class
+ object_access_controls = True
+
# Why a mixin? We want to easily add this to any existing resource, including providing easy helpers for adding access control info such
# as the current users access level to any response.
# This mixin does:
diff --git a/products/access_control/backend/presentation/access_control_settings.py b/products/access_control/backend/presentation/access_control_settings.py
index 0f6de9b82216..5ac3a400bd68 100644
--- a/products/access_control/backend/presentation/access_control_settings.py
+++ b/products/access_control/backend/presentation/access_control_settings.py
@@ -8,17 +8,12 @@ controls every product viewset mixes in stay in access_control.py.
from collections import defaultdict
from dataclasses import asdict, dataclass
-from functools import cache
from typing import TYPE_CHECKING, Any, cast
-from django.apps import apps
-from django.core.exceptions import (
- FieldDoesNotExist,
- ValidationError as DjangoValidationError,
-)
-from django.db.models import Model, Q
+from django.core.cache import cache as django_cache
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.db.models import Count, Max, Model, Q
from django.db.models.functions import Coalesce
-from django.urls import URLResolver, get_resolver
from rest_framework import exceptions
from rest_framework.decorators import action
@@ -28,12 +23,19 @@ from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from posthog.api.documentation import extend_schema
-from posthog.exceptions_capture import capture_exception
from posthog.models import PropertyDefinition
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
-from posthog.scopes import INTERNAL_API_SCOPE_OBJECTS, APIScopeObject
-
+from posthog.permissions import get_authenticator_scoped_team_ids
+from posthog.scopes import APIScopeObject
+
+from products.access_control.backend.facade.object_names import (
+ display_model,
+ model_has_field,
+ resolve_object_names,
+ resources_with_object_access_controls,
+)
+from products.access_control.backend.facade.resolution_preview import build_resolution_preview
from products.access_control.backend.facade.subject_access_control import SubjectAccessControl
from products.access_control.backend.facade.user_access_control import (
ACCESS_CONTROL_LEVELS_RESOURCE,
@@ -48,12 +50,7 @@ from products.access_control.backend.facade.user_access_control import (
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.role import Role
-from .access_control import (
- AccessControlSerializer,
- AccessControlViewSetMixin,
- ResolvedAccessSerializer,
- upsert_access_control,
-)
+from .access_control import AccessControlSerializer, ResolvedAccessSerializer, upsert_access_control
if TYPE_CHECKING:
_GenericViewSet = GenericViewSet
@@ -61,124 +58,6 @@ else:
_GenericViewSet = object
-@dataclass(frozen=True, kw_only=True)
-class _ResourceDisplayModel:
- app_label: str
- model_name: str
- name_field: str
-
-
-# Names come from universal search's ENTITY_MAP first; these entries cover resources search doesn't
-# index, so they have no ENTITY_MAP entry to borrow. Add one when a resource's objects render raw
-# ids instead of names, in the rules list or the picker; delete one when search starts indexing the
-# resource, since ENTITY_MAP is consulted first and the entry goes dead. A resource in neither place
-# and with no derivable name field is left out of the picker and falls back to the raw id.
-_MODELS_NOT_IN_ENTITY_MAP: dict[str, _ResourceDisplayModel] = {
- "evaluation": _ResourceDisplayModel(app_label="ai_observability", model_name="evaluation", name_field="name"),
- "warehouse_view": _ResourceDisplayModel(
- app_label="data_modeling", model_name="datawarehousesavedquery", name_field="name"
- ),
- "warehouse_table": _ResourceDisplayModel(
- app_label="warehouse_sources", model_name="datawarehousetable", name_field="name"
- ),
- "external_data_source": _ResourceDisplayModel(
- app_label="warehouse_sources", model_name="externaldatasource", name_field="source_type"
- ),
- "session_recording": _ResourceDisplayModel(
- app_label="posthog", model_name="sessionrecording", name_field="session_id"
- ),
- "ticket": _ResourceDisplayModel(app_label="conversations", model_name="ticket", name_field="ticket_number"),
-}
-
-
-@dataclass(frozen=True, kw_only=True)
-class _ResolvedObjectName:
- name: str | None
- # Insights link by short_id rather than pk, so the frontend needs it alongside the name
- short_id: str | None = None
-
-
-def _resolve_object_names(resource: str, resource_ids: list[str], team_id: int) -> dict[str, _ResolvedObjectName]:
- """Map {resource_id -> display info} for one resource type, empty when we can't name its objects.
-
- Queries through _base_manager so rules pointing at soft-deleted objects still resolve: those are
- exactly the rows someone opens this page to clean up. Tenant isolation holds via team_id.
- """
- display = _display_model(resource) if resource_ids else None
- if display is None:
- return {}
- try:
- rows = display.model._base_manager.filter(team_id=team_id, pk__in=resource_ids)
- if resource == "insight":
- # Insight.name is nullable and saved insights often carry only derived_name, and insight
- # URLs address short_ids rather than the pk rules store
- return {
- str(pk): _ResolvedObjectName(name=name or derived_name, short_id=short_id)
- for pk, name, derived_name, short_id in rows.values_list("pk", "name", "derived_name", "short_id")
- }
- if resource == "ticket":
- # A bare number doesn't read as an object; match the ticket page's own title
- return {
- str(pk): _ResolvedObjectName(name=f"Ticket: {number}")
- for pk, number in rows.values_list("pk", "ticket_number")
- }
- return {str(pk): _ResolvedObjectName(name=name) for pk, name in rows.values_list("pk", display.name_field)}
- except Exception as e:
- # A resource_id of the wrong shape for the model's pk, or a model that moved. The rules list
- # falls back to raw ids, but report it: one failure usually breaks the whole resource type
- capture_exception(e, {"resource": resource})
- return {}
-
-
-@cache
-def resources_with_object_access_controls() -> dict[APIScopeObject, frozenset[type[Model]]]:
- """Resources that support object-level access controls, mapped to the models behind them.
-
- A viewset opts in by mixing in AccessControlViewSetMixin, so the registered routes are the
- source of truth and this cannot drift from the code; adding the mixin also puts the resource in
- the settings picker. A scope served by several viewsets maps to several models. The snapshot
- test in test_access_control.py records the resources; regenerate it with `pytest
- --snapshot-update`.
- """
- found: dict[APIScopeObject, set[type[Model]]] = {}
-
- def walk(resolver: URLResolver) -> None:
- for pattern in resolver.url_patterns:
- if isinstance(pattern, URLResolver):
- walk(pattern)
- continue
- cls = getattr(pattern.callback, "cls", None)
- if cls is None or not issubclass(cls, AccessControlViewSetMixin):
- continue
- scope = getattr(cls, "scope_object", None)
- # Project-level access is its own control (the "Project access" dropdown), never an
- # object rule; every rules endpoint filters resource="project" out as well
- if scope and scope != "INTERNAL" and scope != "project" and scope not in INTERNAL_API_SCOPE_OBJECTS:
- queryset = getattr(cls, "queryset", None)
- found.setdefault(scope, set())
- if queryset is not None:
- found[scope].add(queryset.model)
-
- walk(get_resolver())
- return {scope: frozenset(models) for scope, models in found.items()}
-
-
-def _model_has_field(model: type[Model], field: str) -> bool:
- try:
- model._meta.get_field(field)
- return True
- except FieldDoesNotExist:
- return False
-
-
-@dataclass(frozen=True, kw_only=True)
-class _DisplayModel:
- """Where a resource's objects live and which field names them."""
-
- model: type[Model]
- name_field: str
-
-
def _project_entry(subject: SubjectAccessControl, team: Team) -> dict[str, Any]:
"""Project access is an object-level question (the team is the object), never resource-wide."""
inherited = subject.inherited_access_for_object(team)
@@ -203,50 +82,6 @@ def _resource_entry(subject: SubjectAccessControl, resource: APIScopeObject) ->
}
-def _display_model(resource: str) -> _DisplayModel | None:
- """Resolve a resource to its model and display field. None means the settings UI cannot work
- with the resource's objects: search returns 400, rule writes return 400, existing rules show
- raw ids.
-
- A resource qualifies when its viewsets carry object-level access controls and we can name its
- objects, tried in order: search's ENTITY_MAP (its rank-A field is the display name), the
- supplement for resources search doesn't index, and finally a resource whose routes expose
- exactly one model carrying a recognizable name field.
- """
- # Gate before the cached resolver: resource is raw request input, and caching unknown values
- # would grow the cache by one permanent entry per distinct garbage string
- if resource not in resources_with_object_access_controls():
- return None
- return _display_model_for_known_resource(resource)
-
-
-@cache
-def _display_model_for_known_resource(resource: str) -> _DisplayModel | None:
- from posthog.api.search import (
- ENTITY_MAP, # noqa: PLC0415 — imports every searchable product model, keep it off this module's import path
- )
-
- model: type[Model] | None = None
- name_field: str | None = None
- entity = ENTITY_MAP.get(resource)
- supplement = _MODELS_NOT_IN_ENTITY_MAP.get(resource)
- if entity is not None:
- model = entity["klass"]
- name_field = next((field for field, rank in entity["search_fields"].items() if rank == "A"), None)
- elif supplement is not None:
- model = apps.get_model(supplement.app_label, supplement.model_name)
- name_field = supplement.name_field
- else:
- models = resources_with_object_access_controls().get(cast(APIScopeObject, resource)) or frozenset()
- if len(models) == 1:
- model = next(iter(models))
- name_field = next((field for field in ("name", "title", "key") if _model_has_field(model, field)), None)
-
- if model is None or name_field is None or not _model_has_field(model, "team"):
- return None
- return _DisplayModel(model=model, name_field=name_field)
-
-
@dataclass(frozen=True, kw_only=True)
class _ObjectRuleValidationContext:
"""Duck-typed stand-in for the view in AccessControlSerializer's context, so the generic
@@ -276,6 +111,7 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
"access_control_role_objects",
"access_control_role_properties",
"access_control_object_search",
+ "access_control_resolution_preview",
]:
return ["access_control:read"]
if request.method == "PUT" and self.action == "access_control_object_rules":
@@ -283,6 +119,76 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
parent = getattr(super(), "dangerously_get_required_scopes", None)
return parent(request, view) if parent is not None else None
+ @extend_schema(exclude=True)
+ @action(methods=["GET"], detail=True, url_path="access_control_resolution_preview")
+ def access_control_resolution_preview(self, request: Request, *args, **kwargs):
+ """Every access rule in this organization that resolves differently under
+ most-specific-wins, across the projects the requester administers.
+
+ Admin only: the records describe other subjects' access. When the organization hides
+ its member list, only organization admins may read them — the records name members a
+ project admin could not otherwise see. Cached per rule set, so the answer updates the
+ moment any rule changes and repeat opens cost nothing."""
+ team = cast(Team, self.team) # type: ignore
+ user_access_control = cast(UserAccessControl, self.user_access_control) # type: ignore
+ if not user_access_control.check_can_modify_access_levels_for_object(team):
+ raise exceptions.PermissionDenied("Only administrators can view the resolution preview.")
+ if not team.organization.members_can_see_org_members and not user_access_control.is_organization_admin:
+ raise exceptions.PermissionDenied("Only organization admins can view the resolution preview.")
+
+ # Organization-wide: every project with rules that the requester administers. An org
+ # admin sees them all; a project admin sees only their own projects. A credential
+ # scoped to specific projects never reaches beyond them.
+ ruled_team_ids = set(
+ AccessControl.objects.filter(team__organization_id=team.organization_id).values_list("team_id", flat=True)
+ )
+ scoped_team_ids = get_authenticator_scoped_team_ids(request.successful_authenticator)
+ if scoped_team_ids is not None:
+ ruled_team_ids &= set(scoped_team_ids)
+ visible_teams: list[tuple[Team, UserAccessControl]] = []
+ for candidate in Team.objects.filter(organization_id=team.organization_id, id__in=ruled_team_ids).order_by(
+ "id"
+ ):
+ candidate_access = (
+ user_access_control
+ if candidate.id == team.id
+ else UserAccessControl(user_access_control.user, candidate)
+ )
+ if candidate_access.check_can_modify_access_levels_for_object(candidate):
+ visible_teams.append((candidate, candidate_access))
+
+ fingerprint = AccessControl.objects.filter(team__organization_id=team.organization_id).aggregate(
+ count=Count("id"), latest=Max("updated_at")
+ )
+ visible_ids = ",".join(str(candidate.id) for candidate, _ in visible_teams)
+ cache_key = (
+ f"access_control_resolution_preview/{team.organization_id}"
+ f"/{visible_ids}/{fingerprint['count']}/{fingerprint['latest']}"
+ )
+ cached = django_cache.get(cache_key)
+ if cached is not None:
+ return Response(cached)
+
+ changes = [
+ {**asdict(change), "project_id": candidate.id, "project_name": candidate.name}
+ for candidate, candidate_access in visible_teams
+ for change in build_resolution_preview(candidate, candidate_access)
+ ]
+ payload = {
+ "changes": changes,
+ "summary": {
+ "total": len(changes),
+ "gains": sum(1 for change in changes if change["direction"] == "gains"),
+ "loses": sum(1 for change in changes if change["direction"] == "loses"),
+ "resources": len({change["resource"] for change in changes if change["scope"] == "resource"}),
+ "objects": len(
+ {(change["resource"], change["object_id"]) for change in changes if change["scope"] == "object"}
+ ),
+ },
+ }
+ django_cache.set(cache_key, payload, timeout=300)
+ return Response(payload)
+
@extend_schema(exclude=True)
@action(methods=["GET"], detail=True, url_path="access_control_defaults")
def access_control_defaults(self, request: Request, *args, **kwargs):
@@ -327,7 +233,7 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
"available_access_levels": list(ordered_access_levels(r)),
"minimum_access_level": minimum_access_level(r),
}
- for r in sorted(r for r in resources_with_object_access_controls() if _display_model(r) is not None)
+ for r in sorted(r for r in resources_with_object_access_controls() if display_model(r) is not None)
],
}
)
@@ -499,7 +405,7 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
# rules lists show what is configured, while the picker search and the rule write are the
# surfaces that hide inaccessible objects
names_by_resource = {
- resource: _resolve_object_names(resource, ids, team.id) for resource, ids in ids_by_resource.items()
+ resource: resolve_object_names(resource, ids, team.id) for resource, ids in ids_by_resource.items()
}
results = []
@@ -610,13 +516,13 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
Works for every resource the defaults endpoint lists in object_rule_resources, with the same
display names the rules list shows. Returns pks, the identifier stored on rules and taken by
- access_control_object_rules; `?id=` also accepts an insight short_id, since insight URLs
- carry those.
+ access_control_object_rules; `?id=` also accepts a short_id for models that have one
+ (insights, notebooks), since their URLs carry those.
"""
team = cast(Team, self.team) # type: ignore
user_access_control = cast(UserAccessControl, self.user_access_control) # type: ignore
resource = request.query_params.get("resource") or ""
- display = _display_model(resource)
+ display = display_model(resource)
if display is None:
raise exceptions.ValidationError("resource does not support object access rules")
@@ -631,7 +537,7 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
# Objects mid-deletion or never saved are not sensible rule targets. Excluding rather than
# filtering keeps rows whose `deleted` is NULL, which is every row on models where the field
# was added without a default (session recordings), and legacy rows elsewhere
- if _model_has_field(display.model, "deleted"):
+ if model_has_field(display.model, "deleted"):
qs = qs.exclude(deleted=True)
# Insight-specific rather than probing for a `saved` field: only Insight has one among the
# picker resources, and a future model's field of that name could mean something else
@@ -653,7 +559,9 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
]
else:
if lookup:
- qs = qs.filter(pk=lookup)
+ # Models with a short_id (notebooks) link by it, so a pasted URL carries one
+ by_short_id = not lookup.isdigit() and model_has_field(display.model, "short_id")
+ qs = qs.filter(short_id=lookup) if by_short_id else qs.filter(pk=lookup)
elif search:
# name_field comes from _display_model's code-defined maps, never from the
# request, and search is only a value
@@ -664,7 +572,7 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
# A lookup id of the wrong shape for the model's pk matches nothing
pks = []
# One place builds display names, so the picker shows exactly what the rules list will
- names = _resolve_object_names(resource, pks, team.id)
+ names = resolve_object_names(resource, pks, team.id)
results = [{"id": pk, "name": (resolved.name if (resolved := names.get(pk)) else None) or pk} for pk in pks]
return Response({"results": results})
@@ -683,7 +591,7 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):
resource = str(request.data.get("resource") or "")
resource_id = str(request.data.get("resource_id") or "")
- display = _display_model(resource)
+ display = display_model(resource)
if display is None:
raise exceptions.ValidationError("resource does not support object access rules")
if not resource_id:
diff --git a/products/access_control/backend/tests/test_access_control.py b/products/access_control/backend/tests/test_access_control.py
index 916648aeb111..506100a4baab 100644
--- a/products/access_control/backend/tests/test_access_control.py
+++ b/products/access_control/backend/tests/test_access_control.py
@@ -19,13 +19,10 @@ from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from posthog.utils import render_template
+from products.access_control.backend.facade.object_names import display_model, resources_with_object_access_controls
from products.access_control.backend.facade.user_access_control import AccessSource
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.role import Role, RoleMembership
-from products.access_control.backend.presentation.access_control_settings import (
- _display_model,
- resources_with_object_access_controls,
-)
from products.ai_observability.backend.models.evaluations import Evaluation
from products.cohorts.backend.models.cohort import Cohort
from products.conversations.backend.models import Ticket
@@ -2265,7 +2262,7 @@ def test_resources_with_object_access_controls_snapshot(snapshot):
# snapshot above but missing here dropped out silently and needs an entry in
# _MODELS_NOT_IN_ENTITY_MAP, or has no objects worth picking.
def test_resources_served_to_the_object_rule_picker_snapshot(snapshot):
- assert sorted(r for r in resources_with_object_access_controls() if _display_model(r)) == snapshot
+ assert sorted(r for r in resources_with_object_access_controls() if display_model(r)) == snapshot
class TestAccessControlSubjectRulesEndpoints(BaseAccessControlTest):
@@ -2361,6 +2358,13 @@ class TestAccessControlSubjectRulesEndpoints(BaseAccessControlTest):
assert res.status_code == status.HTTP_200_OK, res.json()
assert [(r["id"], r["name"]) for r in res.json()["results"]] == [(str(insight.id), "Weekly signups")]
+ # Notebook URLs carry a short_id too
+ res = self.client.get(
+ f"/api/projects/@current/access_control_object_search?resource=notebook&id={notebook.short_id}"
+ )
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ assert [(r["id"], r["name"]) for r in res.json()["results"]] == [(str(notebook.id), "Q3 planning")]
+
res = self.client.get("/api/projects/@current/access_control_object_search?resource=webhook")
assert res.status_code == status.HTTP_400_BAD_REQUEST, res.json()
diff --git a/products/access_control/backend/tests/test_resolution_preview.py b/products/access_control/backend/tests/test_resolution_preview.py
new file mode 100644
index 000000000000..8a36d577cc06
--- /dev/null
+++ b/products/access_control/backend/tests/test_resolution_preview.py
@@ -0,0 +1,264 @@
+import pytest
+
+from rest_framework import status
+
+from posthog.models.organization import OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team.team import Team
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.access_control.backend.facade.resolution_preview import build_resolution_preview
+from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.tests.test_user_access_control import BaseUserAccessControlTest
+from products.dashboards.backend.models.dashboard import Dashboard
+
+
+class TestBuildResolutionPreview(BaseUserAccessControlTest):
+ def setUp(self):
+ super().setUp()
+ self.other_membership = OrganizationMembership.objects.get(user=self.other_user, organization=self.organization)
+ self.dashboard = Dashboard.objects.create(team=self.team, created_by=self.user, name="Growth KPIs")
+
+ def _changes(self):
+ return build_resolution_preview(self.team, self.user_access_control)
+
+ def test_object_default_change_is_one_everyone_record(self):
+ # The change reaches every member without a more specific rule, but it is one rule:
+ # per-member records would explode a default change into the whole project roster
+ self._create_access_control(resource="dashboard", resource_id=str(self.dashboard.id), access_level="viewer")
+ self._create_access_control(resource="dashboard", access_level="editor")
+
+ changes = self._changes()
+
+ assert len(changes) == 1
+ change = changes[0]
+ assert change.subject.type == "default"
+ assert change.scope == "object"
+ assert change.object_id == str(self.dashboard.id)
+ assert change.object_name == "Growth KPIs"
+ assert (change.current.access_level, change.current.source) == ("editor", "resource")
+ assert (change.proposed.access_level, change.proposed.source) == ("viewer", "object")
+ assert change.direction == "loses"
+
+ def test_member_override_produces_member_record_only(self):
+ # other_user holds role_b (base fixture). Today the role's grant applies; after the
+ # change their own override applies. The role itself resolves the same both ways, so
+ # only the member record is reported, not one row per role member.
+ self._create_access_control(
+ resource="dashboard",
+ resource_id=str(self.dashboard.id),
+ access_level="none",
+ organization_member=self.other_membership,
+ )
+ self._create_access_control(
+ resource="dashboard", resource_id=str(self.dashboard.id), access_level="editor", role=self.role_b
+ )
+
+ changes = self._changes()
+
+ assert len(changes) == 1
+ change = changes[0]
+ assert change.subject.type == "member"
+ assert change.subject.id == str(self.other_membership.id)
+ assert (change.current.access_level, change.proposed.access_level) == ("editor", "none")
+ assert change.proposed.source_subject == "member"
+ assert change.direction == "loses"
+
+ def test_resource_scope_member_below_role_is_one_record(self):
+ # other_user holds role_b (base fixture); their own resource-wide "none" starts applying
+ self._create_access_control(
+ resource="dashboard", access_level="none", organization_member=self.other_membership
+ )
+ self._create_access_control(resource="dashboard", access_level="editor", role=self.role_b)
+
+ changes = self._changes()
+
+ assert len(changes) == 1
+ change = changes[0]
+ assert change.scope == "resource"
+ assert change.subject.type == "member"
+ assert (change.current.access_level, change.proposed.access_level) == ("editor", "none")
+
+ def test_member_row_on_one_object_adds_no_records_for_other_objects(self):
+ # The everyone record already describes objects the member holds no rule on; a
+ # per-member copy of it would repeat the same change once per rule-holding member
+ other_dashboard = Dashboard.objects.create(team=self.team, created_by=self.user, name="Ops KPIs")
+ self._create_access_control(resource="dashboard", resource_id=str(self.dashboard.id), access_level="viewer")
+ self._create_access_control(resource="dashboard", access_level="editor")
+ self._create_access_control(
+ resource="dashboard",
+ resource_id=str(other_dashboard.id),
+ access_level="editor",
+ organization_member=self.other_membership,
+ )
+
+ changes = self._changes()
+
+ assert [(change.subject.type, change.object_id) for change in changes] == [("default", str(self.dashboard.id))]
+
+ def test_parent_resource_row_is_compared_against_child_objects(self):
+ # Resolution consults the parent resource (session_recording) for playlist objects, so
+ # a member whose only rule sits there can still resolve a playlist differently
+ from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
+
+ playlist = SessionRecordingPlaylist.objects.create(team=self.team, created_by=self.user, name="Bug hunts")
+ self._create_access_control(
+ resource="session_recording_playlist", resource_id=str(playlist.id), access_level="none"
+ )
+ self._create_access_control(
+ resource="session_recording", access_level="editor", organization_member=self.other_membership
+ )
+
+ changes = self._changes()
+
+ member_changes = [change for change in changes if change.subject.type == "member"]
+ assert [(change.scope, change.object_id) for change in member_changes] == [("object", str(playlist.id))]
+ assert (member_changes[0].current.access_level, member_changes[0].proposed.access_level) == ("editor", "none")
+
+ def test_creator_pairs_are_skipped(self):
+ # Creators keep the highest level under both ladders, so their override never applies
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.other_user)
+ self._create_access_control(
+ resource="dashboard",
+ resource_id=str(dashboard.id),
+ access_level="none",
+ organization_member=self.other_membership,
+ )
+ self._create_access_control(resource="dashboard", resource_id=str(dashboard.id), access_level="editor")
+
+ changes = self._changes()
+
+ assert [change for change in changes if change.subject.type == "member"] == []
+
+ def test_org_admin_members_are_skipped(self):
+ self._create_access_control(
+ resource="dashboard",
+ resource_id=str(self.dashboard.id),
+ access_level="none",
+ organization_member=self.other_membership,
+ )
+ self._create_access_control(resource="dashboard", resource_id=str(self.dashboard.id), access_level="editor")
+ self.other_membership.level = OrganizationMembership.Level.ADMIN
+ self.other_membership.save()
+
+ changes = self._changes()
+
+ assert [change for change in changes if change.subject.type == "member"] == []
+
+ def test_no_entitlement_returns_no_changes(self):
+ self._create_access_control(resource="dashboard", resource_id=str(self.dashboard.id), access_level="viewer")
+ self._create_access_control(resource="dashboard", access_level="editor")
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ assert self._changes() == []
+
+
+class TestResolutionPreviewAPI(BaseUserAccessControlTest):
+ def setUp(self):
+ super().setUp()
+ self.dashboard = Dashboard.objects.create(team=self.team, created_by=self.other_user, name="Growth KPIs")
+ self._create_access_control(resource="dashboard", resource_id=str(self.dashboard.id), access_level="viewer")
+ self._create_access_control(resource="dashboard", access_level="editor")
+ self.membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ self.client.force_login(self.user)
+
+ def test_requires_admin(self):
+ response = self.client.get("/api/projects/@current/access_control_resolution_preview")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_hidden_member_list_requires_org_admin(self):
+ # A project admin passes the base gate, but the org hides its member list
+ self._create_access_control(resource="project", resource_id=str(self.team.id), access_level="admin")
+ self.organization.members_can_see_org_members = False
+ self.organization.save()
+
+ response = self.client.get("/api/projects/@current/access_control_resolution_preview")
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ self.membership.level = OrganizationMembership.Level.ADMIN
+ self.membership.save()
+
+ response = self.client.get("/api/projects/@current/access_control_resolution_preview")
+ assert response.status_code == status.HTTP_200_OK
+
+ def test_returns_changes_and_summary(self):
+ self.membership.level = OrganizationMembership.Level.ADMIN
+ self.membership.save()
+
+ response = self.client.get("/api/projects/@current/access_control_resolution_preview")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ data = response.json()
+ assert data["summary"]["total"] == 1
+ assert data["summary"]["loses"] == 1
+ change = data["changes"][0]
+ assert change["subject"] == {"type": "default", "id": None, "name": "Everyone"}
+ assert change["object_name"] == "Growth KPIs"
+ assert change["project_id"] == self.team.id
+ assert change["project_name"] == self.team.name
+ assert change["current"] == {
+ "access_level": "editor",
+ "source": "resource",
+ "source_subject": "default",
+ "source_resource": "dashboard",
+ "source_resource_id": None,
+ "subject_name": None,
+ }
+ assert change["proposed"] == {
+ "access_level": "viewer",
+ "source": "object",
+ "source_subject": "default",
+ "source_resource": "dashboard",
+ "source_resource_id": str(self.dashboard.id),
+ "subject_name": None,
+ }
+
+ def test_covers_every_project_the_requester_administers(self):
+ other_team = Team.objects.create(organization=self.organization, name="Second project")
+ other_dashboard = Dashboard.objects.create(team=other_team, created_by=self.other_user, name="Other KPIs")
+ AccessControl.objects.create(
+ team=other_team, resource="dashboard", resource_id=str(other_dashboard.id), access_level="viewer"
+ )
+ AccessControl.objects.create(team=other_team, resource="dashboard", resource_id=None, access_level="editor")
+
+ # A project admin of the current team only sees this team's changes
+ self._create_access_control(resource="project", resource_id=str(self.team.id), access_level="admin")
+ response = self.client.get("/api/projects/@current/access_control_resolution_preview")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert {change["project_name"] for change in response.json()["changes"]} == {self.team.name}
+
+ # An org admin sees every project with rules
+ self.membership.level = OrganizationMembership.Level.ADMIN
+ self.membership.save()
+ response = self.client.get("/api/projects/@current/access_control_resolution_preview")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ data = response.json()
+ assert data["summary"]["total"] == 2
+ assert {change["project_name"] for change in data["changes"]} == {self.team.name, "Second project"}
+
+ def test_project_scoped_credential_stays_within_its_projects(self):
+ self.membership.level = OrganizationMembership.Level.ADMIN
+ self.membership.save()
+ other_team = Team.objects.create(organization=self.organization, name="Second project")
+ other_dashboard = Dashboard.objects.create(team=other_team, created_by=self.other_user, name="Other KPIs")
+ AccessControl.objects.create(
+ team=other_team, resource="dashboard", resource_id=str(other_dashboard.id), access_level="viewer"
+ )
+ AccessControl.objects.create(team=other_team, resource="dashboard", resource_id=None, access_level="editor")
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="scoped", user=self.user, secure_value=hash_key_value(key), scoped_teams=[self.team.id], scopes=["*"]
+ )
+ self.client.logout()
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/access_control_resolution_preview",
+ headers={"authorization": f"Bearer {key}"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert {change["project_name"] for change in response.json()["changes"]} == {self.team.name}