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(access-control): show disabled states for no-access items in UI (#69121)

Reece Jones3f8a5af90c8b
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 26615f7d65dd..a72592bd37b4 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -2816,6 +2816,11 @@ export interface FileSystemApi {
readonly created_at: string
/** @nullable */
readonly last_viewed_at: string | null
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level: string | null
}
export interface PaginatedFileSystemListApi {
@@ -2847,6 +2852,11 @@ export interface PatchedFileSystemApi {
readonly created_at?: string
/** @nullable */
readonly last_viewed_at?: string | null
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level?: string | null
}
/**
@@ -2963,6 +2973,11 @@ export interface FileSystemShortcutApi {
*/
order?: number
readonly created_at: string
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level: string | null
}
export interface PaginatedFileSystemShortcutListApi {
@@ -3001,6 +3016,11 @@ export interface PatchedFileSystemShortcutApi {
*/
order?: number
readonly created_at?: string
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level?: string | null
}
export interface FileSystemShortcutReorderApi {
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 7e7e0213f9a3..1a44f1a5c1df 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -10,6 +10,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { getEntryAccessDisabledReason, getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { withTimeout } from 'lib/utils/async'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'
@@ -1020,9 +1021,9 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
folderStates,
users,
foldersFirst: true,
- disabledReason: onlyFolders
- ? (item) => (item.type !== 'folder' ? 'Only folders can be selected' : undefined)
- : undefined,
+ disabledReason: (item) =>
+ getEntryAccessDisabledReason(item) ??
+ (onlyFolders && item.type !== 'folder' ? 'Only folders can be selected' : undefined),
})[0]
if (shortcut.type === 'folder' && shortcut.ref) {
@@ -1035,9 +1036,11 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
users,
foldersFirst: true,
searchTerm,
- disabledReason: onlyFolders
- ? (item) => (item.type !== 'folder' ? 'Only folders can be selected' : undefined)
- : undefined,
+ disabledReason: (item) =>
+ getEntryAccessDisabledReason(item) ??
+ (onlyFolders && item.type !== 'folder'
+ ? 'Only folders can be selected'
+ : undefined),
})
for (let i = 0; i < splitPath(shortcut.ref).length; i++) {
converted = converted[0]?.children || []
@@ -1096,9 +1099,9 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
users: {},
foldersFirst: false,
searchTerm,
- disabledReason: onlyFolders
- ? (item) => (item.type !== 'folder' ? 'Only folders can be selected' : undefined)
- : undefined,
+ disabledReason: (item) =>
+ getProductAccessDisabledReason(item as FileSystemImport) ??
+ (onlyFolders && item.type !== 'folder' ? 'Only folders can be selected' : undefined),
})
return function getStaticItems(searchTerm: string, onlyFolders: boolean): TreeDataItem[] {
const data: [string, FileSystemImport[]][] = [
@@ -1200,6 +1203,7 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
users,
foldersFirst: false,
searchTerm,
+ disabledReason: (item) => getProductAccessDisabledReason(item as FileSystemImport),
})
}
},
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx
index f1da6c819599..2c7b261b0aba 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx
@@ -7,6 +7,7 @@ import { Spinner } from '@posthog/lemon-ui'
import api from 'lib/api'
import { LemonTreeSelectMode, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
+import { getEntryAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'
import { PROJECT_TREE_KEY } from '~/layout/panel-layout/ProjectTree/ProjectTree'
@@ -449,9 +450,9 @@ export const projectTreeLogic = kea<projectTreeLogicType>([
checkedItems,
root: 'project://',
users,
- disabledReason: onlyFolders
- ? (item) => (item.type !== 'folder' ? 'Only folders can be selected' : undefined)
- : undefined,
+ disabledReason: (item) =>
+ getEntryAccessDisabledReason(item) ??
+ (onlyFolders && item.type !== 'folder' ? 'Only folders can be selected' : undefined),
})
return children
},
@@ -467,6 +468,7 @@ export const projectTreeLogic = kea<projectTreeLogicType>([
disableFolderSelect: true,
recent: true,
users,
+ disabledReason: (item) => getEntryAccessDisabledReason(item),
})
if (recentResultsLoading) {
results.push({
@@ -518,9 +520,9 @@ export const projectTreeLogic = kea<projectTreeLogicType>([
disableFolderSelect: true,
recent: sortMethod === 'recent',
users,
- disabledReason: onlyFolders
- ? (item) => (item.type !== 'folder' ? 'Only folders can be selected' : undefined)
- : undefined,
+ disabledReason: (item) =>
+ getEntryAccessDisabledReason(item) ??
+ (onlyFolders && item.type !== 'folder' ? 'Only folders can be selected' : undefined),
})
if (searchResultsLoading) {
results.push({
diff --git a/frontend/src/lib/components/Search/Search.tsx b/frontend/src/lib/components/Search/Search.tsx
index 79ff8011ce3e..d40ecd1e0c42 100644
--- a/frontend/src/lib/components/Search/Search.tsx
+++ b/frontend/src/lib/components/Search/Search.tsx
@@ -498,6 +498,9 @@ function SearchRoot({
const handleItemClick = useCallback(
(item: SearchItem) => {
+ if (item.disabledReason) {
+ return
+ }
if (item.id === SETTINGS_THEME_ITEM_ID) {
const record = item.record as { themeMode?: UserTheme; toggleTheme?: boolean } | undefined
if (record?.themeMode) {
@@ -884,11 +887,21 @@ function SearchResults({
return (
<div className="px-2">
<Link
- to={item.href}
- buttonProps={{
- fullWidth: true,
- }}
+ // No `to` when disabled: Link only applies its
+ // disabled state and reason tooltip without one
+ to={
+ item.disabledReason
+ ? undefined
+ : item.href
+ }
+ disabledReason={item.disabledReason}
+ buttonProps={{ fullWidth: true }}
{...props}
+ // The button-primitive styles key dimming, the
+ // not-allowed cursor, and hover suppression off this
+ aria-disabled={
+ item.disabledReason ? true : undefined
+ }
tabIndex={-1}
>
{icon}
diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsx
index 1b19bed6293d..1241b991e760 100644
--- a/frontend/src/lib/components/Search/searchLogic.tsx
+++ b/frontend/src/lib/components/Search/searchLogic.tsx
@@ -6,6 +6,7 @@ import { IconBell, IconClock, IconDownload, IconLeave, IconNotification } from '
import api from 'lib/api'
import { commandLogic } from 'lib/components/Command/commandLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { getEntryAccessDisabledReason, getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'
import { toSentenceCase } from 'lib/utils/strings'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
@@ -88,6 +89,7 @@ const fileSystemEntryToSearchItem = (
lastViewedAt: item.last_viewed_at ?? null,
itemType,
record: { ...item, iconColor: productIconColor },
+ disabledReason: getEntryAccessDisabledReason(item),
...overrides,
}
}
@@ -111,6 +113,9 @@ export interface SearchItem {
searchKeywords?: string[]
record?: Record<string, unknown>
rank?: number | null // PostgreSQL full-text search rank (from unified search API)
+ /** When set, the item is shown greyed out and non-clickable, with this reason as tooltip
+ * (e.g. the user has no access to the product or resource). */
+ disabledReason?: string
}
export interface SearchCategory {
@@ -397,6 +402,7 @@ export const searchLogic = kea<searchLogicType>([
itemType: product.iconType || product.type || null,
tags: product.tags,
lastViewedAt: product.sceneKey ? (sceneLogViewsByRef[product.sceneKey] ?? null) : null,
+ disabledReason: getProductAccessDisabledReason(product),
record: {
type: product.type || product.iconType,
iconType: product.iconType,
@@ -465,6 +471,7 @@ export const searchLogic = kea<searchLogicType>([
tags: item.tags,
searchKeywords: item.category ? categorySearchKeywords[item.category] : undefined,
lastViewedAt: item.sceneKey ? (sceneLogViewsByRef[item.sceneKey] ?? null) : null,
+ disabledReason: getProductAccessDisabledReason(item),
record: {
type: item.type || item.iconType,
iconType: item.iconType,
@@ -626,6 +633,7 @@ export const searchLogic = kea<searchLogicType>([
category: 'session_recording_playlist',
href: item.href || '#',
itemType: 'session_recording_playlist',
+ disabledReason: getEntryAccessDisabledReason(item),
record: item as unknown as Record<string, unknown>,
}
})
@@ -864,6 +872,7 @@ export const searchLogic = kea<searchLogicType>([
href,
itemType: result.type,
rank: result.rank,
+ disabledReason: getEntryAccessDisabledReason(result),
record: {
type: result.type,
...result.extra_fields,
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
index 902d420c3adf..0b41a7233946 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
@@ -351,9 +351,10 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
isContextMenuOpenForItem === item.id,
'bg-fill-button-tertiary-active': getItemActiveState(item),
'group-hover/lemon-tree-button-group:bg-fill-button-tertiary-hover cursor-pointer':
- !isEmptyFolder,
+ !isEmptyFolder && !item.disabledReason,
'hover:bg-transparent opacity-50 cursor-default':
(selectMode === 'folder-only' && !isFolder) || isEmptyFolder,
+ 'opacity-50 cursor-not-allowed': !!item.disabledReason,
'rounded-l-[var(--radius)] justify-center [&_svg]:size-4': size === 'narrow',
'group-hover/lemon-tree-button-group:pr-[30px] group-has-data-[state=open]/lemon-tree-button-group:pr-[30px] group-has-focus-within/lemon-tree-button-group:pr-[30px]':
size !== 'narrow',
@@ -369,7 +370,7 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
aria-haspopup={!!contextMenuContent}
aria-roledescription="tree item"
aria-label={ariaLabel}
- tooltip={isDragging || isEmptyFolder ? undefined : renderItemTooltip?.(item)}
+ tooltip={isDragging || isEmptyFolder ? undefined : (item.disabledReason ?? renderItemTooltip?.(item))}
tooltipPlacement="right"
>
{size === 'default' && (
diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.ts
index 9f0e49ac0ce8..9fe4f9bb99cc 100644
--- a/frontend/src/lib/utils/accessControlUtils.ts
+++ b/frontend/src/lib/utils/accessControlUtils.ts
@@ -2,6 +2,7 @@ import posthog from 'posthog-js'
import { getAppContext } from 'lib/utils/getAppContext'
import { toSentenceCase } from 'lib/utils/strings'
+import { Scene, sceneToAccessControlResourceType } from 'scenes/sceneTypes'
import { APIScopeObject, AccessControlLevel, AccessControlResourceType, AvailableFeature } from '~/types'
@@ -199,6 +200,71 @@ export const userHasAccess = (
return !getAccessControlDisabledReason(resourceType, minAccessLevel, userAccessLevel)
}
+/** Entry/search-result types mapped to the resource type gating them - identity for types that
+ * are access control resources themselves, plus the backend's RESOURCE_INHERITANCE_MAP entries
+ * for types that appear in trees and search. */
+const ENTRY_TYPE_TO_RESOURCE_TYPE: Record<string, AccessControlResourceType> = {
+ ...Object.fromEntries(Object.values(AccessControlResourceType).map((value) => [value, value])),
+ session_recording_playlist: AccessControlResourceType.SessionRecording,
+}
+
+const productHasEffectiveNoneAccess = (resourceType: AccessControlResourceType): boolean => {
+ return getAppContext()?.effective_resource_access_control?.[resourceType] === AccessControlLevel.None
+}
+
+/**
+ * Disabled reason for a product navigation item (sidebar product list, search product results)
+ * when the user's effective access to the product's resource is "none".
+ *
+ * Mirrors the scene gating in sceneLogic (which uses `effective_resource_access_control` and
+ * `sceneToAccessControlResourceType`), so items are disabled exactly when opening the target
+ * page would show "Access denied". Users with object-level grants get effective "viewer"
+ * access, so the product stays enabled for them.
+ *
+ * @param item - Navigation item with the scene key it points at (e.g. a FileSystemImport)
+ * @returns Reason to show on the disabled item, or undefined when the user has access
+ */
+export const getProductAccessDisabledReason = (item: {
+ sceneKey?: string
+ path?: string
+ displayLabel?: string
+}): string | undefined => {
+ if (!item.sceneKey) {
+ return undefined
+ }
+ const resourceType = sceneToAccessControlResourceType[item.sceneKey as Scene]
+ if (!resourceType || !productHasEffectiveNoneAccess(resourceType)) {
+ return undefined
+ }
+ return `You don't have access to ${item.displayLabel || item.path || 'this product'}`
+}
+
+/**
+ * Disabled reason for an individual item (search result, Files/Starred entry).
+ *
+ * Uses the backend-resolved access level for the underlying object, which accounts for
+ * object-level overrides - an item the user was individually granted access to stays enabled
+ * even when they have "none" access to the product. Additionally checks the product's
+ * effective access: when it is "none" the scene gate denies every item of that type,
+ * including ones the user created (object creators keep object-level access but aren't
+ * reflected in the effective map), so those must be disabled too or clicking them would
+ * still land on "Access denied".
+ *
+ * @param entry - Entry carrying the backend-resolved `user_access_level` and its type
+ * @returns Reason to show on the disabled item, or undefined when the user has access
+ */
+export const getEntryAccessDisabledReason = (entry: {
+ user_access_level?: string | null
+ type?: string | null
+}): string | undefined => {
+ const resourceType = entry.type ? ENTRY_TYPE_TO_RESOURCE_TYPE[entry.type] : undefined
+ const blockedByProduct = resourceType !== undefined && productHasEffectiveNoneAccess(resourceType)
+ if (!blockedByProduct && entry.user_access_level !== AccessControlLevel.None) {
+ return undefined
+ }
+ return `You don't have access to ${entry.type ? `this ${entry.type.replace(/_/g, ' ')}` : 'this item'}`
+}
+
/**
* Returns a tooltip message for a resource type if it has special access control behavior.
* Use this to inform users about resource-specific access control limitations or clarifications.
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 2a31411c782a..179c251c3db0 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -22449,6 +22449,10 @@
"description": "Type of object, used for icon, e.g. feature_flag, insight, etc",
"type": "string"
},
+ "user_access_level": {
+ "description": "Access level the user has for the referenced object ('none' means no access); null/absent when access controls don't apply",
+ "type": ["string", "null"]
+ },
"visualOrder": {
"description": "Order of object in tree",
"type": "number"
@@ -22662,6 +22666,10 @@
"description": "Type of object, used for icon, e.g. feature_flag, insight, etc",
"type": "string"
},
+ "user_access_level": {
+ "description": "Access level the user has for the referenced object ('none' means no access); null/absent when access controls don't apply",
+ "type": ["string", "null"]
+ },
"visualOrder": {
"description": "Order of object in tree",
"type": "number"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 846902e669fc..ebb6c9f06c0f 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3872,6 +3872,8 @@ export interface FileSystemEntry {
tags?: ('alpha' | 'beta')[]
/** Order of object in tree */
visualOrder?: number
+ /** Access level the user has for the referenced object ('none' means no access); null/absent when access controls don't apply */
+ user_access_level?: string | null
}
export type FileSystemIconType =
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 427341f01ded..cc62ed242f72 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1657,6 +1657,8 @@ export type SearchResultType = {
type: SearchableEntity
rank: number | null
extra_fields: Record<string, unknown>
+ /** Resolved access level the user has for this object ('none' means no access); null when access controls don't apply */
+ user_access_level?: AccessControlLevel | null
}
export type SearchResponse = {
diff --git a/posthog/api/file_system/access_levels.py b/posthog/api/file_system/access_levels.py
new file mode 100644
index 000000000000..d5b5bbba2bbc
--- /dev/null
+++ b/posthog/api/file_system/access_levels.py
@@ -0,0 +1,190 @@
+from collections.abc import Sequence
+from typing import Any, Optional, cast
+
+from django.apps import apps
+from django.db.models import BigIntegerField, CharField, F, QuerySet, Value
+from django.db.models.functions import Cast
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+from posthog.api.file_system.deletion import ModelRegistration, get_file_system_registration
+from posthog.rbac.user_access_control import (
+ ACCESS_CONTROL_RESOURCES,
+ RESOURCE_INHERITANCE_MAP,
+ AccessControlLevel,
+ UserAccessControl,
+)
+from posthog.scopes import APIScopeObject
+
+# (file system type, ref, created_by_id of the underlying object - None when unknown)
+FileSystemAccessEntry = tuple[str, Optional[str], Optional[int]]
+
+
+def _is_access_controlled_type(file_system_type: str) -> bool:
+ """File system types double as AccessControl resource names; only these types can resolve
+ to an access level at all (folders, SQL views, hog functions etc. have no access controls)."""
+ return file_system_type in ACCESS_CONTROL_RESOURCES or file_system_type in RESOURCE_INHERITANCE_MAP
+
+
+def _ref_translation_queryset(
+ entry_type: str, registration: ModelRegistration, refs: list[str], project_id: int
+) -> QuerySet:
+ """Queryset yielding (type, ref, pk, created_by_id) rows for one entry type, with uniform
+ column types so querysets of different models can be UNIONed into one statement."""
+ model = apps.get_model(registration.app_label, registration.model_name)
+ manager = getattr(model, registration.manager_name, model._default_manager)
+ lookup_field = registration.lookup_field
+ return (
+ manager.filter(
+ **{
+ f"{registration.team_field}__project_id": project_id,
+ f"{lookup_field}__in": refs,
+ }
+ )
+ .annotate(
+ _type=Value(entry_type, output_field=CharField()),
+ _ref=Cast(lookup_field, output_field=CharField()),
+ _pk=Cast("pk", output_field=CharField()),
+ # Cast rather than Value(None, ...): an untyped NULL lets Postgres resolve the
+ # union column as text and clash with real integer columns (see search.py)
+ _created_by_id=F("created_by_id")
+ if hasattr(model, "created_by")
+ else Cast(Value(None), output_field=BigIntegerField()),
+ )
+ .values_list("_type", "_ref", "_pk", "_created_by_id")
+ )
+
+
+def bulk_file_system_access_levels(
+ entries: Sequence[FileSystemAccessEntry],
+ user_access_control: UserAccessControl,
+ project_id: int,
+) -> dict[tuple[str, str], Optional[AccessControlLevel]]:
+ """Resolve the user's access level for the objects behind file system entries, in bulk.
+
+ Pass created_by_id=None when the caller doesn't know the underlying object's creator
+ (e.g. shortcuts) - it is then fetched alongside the ref->pk translation. Types without
+ access controls resolve to None.
+
+ AccessControl rows are keyed by the target object's pk, while some file system types
+ (insight, notebook, session_recording_playlist) use short_id as their ref, so those refs
+ are translated through the registered models - all types UNIONed into a single query.
+
+ Refs that don't resolve to an object still go through resource-level resolution rather
+ than short-circuiting to None: refs can be caller-supplied (shortcuts), and a distinct
+ value for "doesn't exist" would let members probe guessed refs to learn whether a
+ protected object exists.
+ """
+ results: dict[tuple[str, str], Optional[AccessControlLevel]] = {}
+ user_id = user_access_control.user.id
+
+ entries_by_type: dict[str, dict[str, Optional[int]]] = {}
+ for entry_type, ref, created_by_id in entries:
+ if not ref or not _is_access_controlled_type(entry_type):
+ continue
+ by_ref = entries_by_type.setdefault(entry_type, {})
+ # The same object can back several entries (e.g. an unfiled row and a user-created one)
+ # with different `created_by` values - the row marking the user as creator wins
+ if by_ref.get(ref) is None or created_by_id == user_id:
+ by_ref[ref] = created_by_id
+
+ # One UNION query across every type needing a ref->pk translation or a creator lookup
+ translation_querysets = []
+ for entry_type, creator_by_provided_ref in entries_by_type.items():
+ registration = get_file_system_registration(entry_type)
+ if not registration:
+ continue
+ needs_creator = any(created_by_id is None for created_by_id in creator_by_provided_ref.values())
+ if registration.lookup_field == "id" and not needs_creator:
+ continue
+ translation_querysets.append(
+ _ref_translation_queryset(entry_type, registration, list(creator_by_provided_ref), project_id)
+ )
+
+ # (type, ref) -> (pk, created_by_id)
+ translated: dict[tuple[str, str], tuple[str, Optional[int]]] = {}
+ if translation_querysets:
+ union_qs = translation_querysets[0]
+ if len(translation_querysets) > 1:
+ union_qs = union_qs.union(*translation_querysets[1:], all=True)
+ for row_type, ref_value, pk_value, created_by_id in union_qs:
+ translated[(row_type, str(ref_value))] = (str(pk_value), created_by_id)
+
+ for entry_type, creator_by_provided_ref in entries_by_type.items():
+ resource = cast(APIScopeObject, entry_type)
+
+ objects: list[tuple[str, Optional[int]]] = []
+ ref_by_pk: dict[str, str] = {}
+ for ref, provided_creator in creator_by_provided_ref.items():
+ row = translated.get((entry_type, ref))
+ # Unresolved refs keep the ref as a pk stand-in: it matches no AccessControl rows,
+ # so they resolve at resource level exactly like an existing object without object
+ # rows, making guessed refs indistinguishable from real-but-ungranted ones
+ pk = row[0] if row else ref
+ ref_by_pk[pk] = ref
+ objects.append((pk, provided_creator if provided_creator is not None else (row[1] if row else None)))
+
+ # Resolves from the in-memory access control preload - no queries per type
+ levels = user_access_control.bulk_object_access_levels(resource, objects)
+ for pk, level in levels.items():
+ results[(entry_type, ref_by_pk[pk])] = level
+
+ return results
+
+
+# Adds a `user_access_level` field to serializers of models that reference project objects
+# via (type, ref) - resolved in bulk, once per serialization. Deliberately no class docstring:
+# drf-spectacular inherits it (via inspect.getdoc) as the schema description of every
+# serializer that mixes this in.
+class FileSystemAccessLevelSerializerMixin(serializers.Serializer):
+ user_access_level = serializers.SerializerMethodField(
+ read_only=True,
+ help_text=(
+ "Resolved access level the user has for the object this entry references "
+ "('none' means the user can't open it). Null when access controls don't apply "
+ "to the entry type."
+ ),
+ )
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self._access_levels_by_type_ref: Optional[dict[tuple[str, str], Optional[AccessControlLevel]]] = None
+
+ def _entry_user_access_control(self) -> Optional[UserAccessControl]:
+ request = self.context.get("request")
+ if request is None or request.user.is_anonymous:
+ return None
+ view = self.context.get("view")
+ return getattr(view, "user_access_control", None)
+
+ def _compute_access_levels(
+ self, entries: Sequence[FileSystemAccessEntry], user_access_control: UserAccessControl
+ ) -> dict[tuple[str, str], Optional[AccessControlLevel]]:
+ team = self.context["get_team"]()
+ return bulk_file_system_access_levels(entries, user_access_control, team.project_id)
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_user_access_level(self, obj: Any) -> Optional[str]:
+ user_access_control = self._entry_user_access_control()
+ if user_access_control is None or not obj.ref or not _is_access_controlled_type(obj.type):
+ return None
+
+ if self._access_levels_by_type_ref is None:
+ instances = self.instance if isinstance(self.instance, list) else [self.instance]
+ entries = [
+ (instance.type, instance.ref, getattr(instance, "created_by_id", None))
+ for instance in instances
+ if instance is not None and instance.ref
+ ]
+ self._access_levels_by_type_ref = self._compute_access_levels(entries, user_access_control)
+
+ key = (obj.type, obj.ref)
+ if key not in self._access_levels_by_type_ref:
+ # Object wasn't part of the preloaded batch (e.g. freshly created) - resolve it alone
+ self._access_levels_by_type_ref.update(
+ self._compute_access_levels(
+ [(obj.type, obj.ref, getattr(obj, "created_by_id", None))], user_access_control
+ )
+ )
+ return self._access_levels_by_type_ref.get(key)
diff --git a/posthog/api/file_system/deletion.py b/posthog/api/file_system/deletion.py
index 74c87a30ad65..d58ebee69138 100644
--- a/posthog/api/file_system/deletion.py
+++ b/posthog/api/file_system/deletion.py
@@ -152,6 +152,10 @@ def is_file_system_type_registered(type_string: str) -> bool:
return type_string in _MODEL_REGISTRY
+def get_file_system_registration(type_string: str) -> ModelRegistration | None:
+ return _MODEL_REGISTRY.get(type_string)
+
+
def _resolve_user(user: Any | None) -> Any | None:
if user is not None and getattr(user, "is_authenticated", False):
return user
diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.py
index 53cede2ea742..84c81ddd4b61 100644
--- a/posthog/api/file_system/file_system.py
+++ b/posthog/api/file_system/file_system.py
@@ -14,6 +14,7 @@ from rest_framework import filters, pagination, serializers, status, viewsets
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.file_system.access_levels import FileSystemAccessLevelSerializerMixin
from posthog.api.file_system.deletion import (
HOG_FUNCTION_TYPES,
delete_file_system_object,
@@ -69,7 +70,7 @@ DELETE_PREVIEW_ENTRY_LIMIT = 200
RECENTS_SEARCH_SCAN_LIMIT = 200
-class FileSystemSerializer(serializers.ModelSerializer):
+class FileSystemSerializer(FileSystemAccessLevelSerializerMixin, serializers.ModelSerializer):
last_viewed_at = serializers.DateTimeField(read_only=True, allow_null=True)
class Meta:
@@ -85,6 +86,7 @@ class FileSystemSerializer(serializers.ModelSerializer):
"shortcut",
"created_at",
"last_viewed_at",
+ "user_access_level",
]
read_only_fields = [
"id",
@@ -92,6 +94,7 @@ class FileSystemSerializer(serializers.ModelSerializer):
"created_at",
"team_id",
"last_viewed_at",
+ "user_access_level",
]
def update(self, instance: FileSystem, validated_data: dict[str, Any]) -> FileSystem:
diff --git a/posthog/api/file_system/file_system_shortcut.py b/posthog/api/file_system/file_system_shortcut.py
index 6d7f033ff56f..6644bd37d770 100644
--- a/posthog/api/file_system/file_system_shortcut.py
+++ b/posthog/api/file_system/file_system_shortcut.py
@@ -10,13 +10,14 @@ from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.file_system.access_levels import FileSystemAccessLevelSerializerMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models import User
from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
-class FileSystemShortcutSerializer(serializers.ModelSerializer):
+class FileSystemShortcutSerializer(FileSystemAccessLevelSerializerMixin, serializers.ModelSerializer):
class Meta:
model = FileSystemShortcut
fields = [
@@ -27,10 +28,12 @@ class FileSystemShortcutSerializer(serializers.ModelSerializer):
"href",
"order",
"created_at",
+ "user_access_level",
]
read_only_fields = [
"id",
"created_at",
+ "user_access_level",
]
extra_kwargs = {
"path": {"help_text": "Display path of the shortcut in the sidebar."},
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index c4ff098793df..9a367956482d 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -7,11 +7,14 @@ from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+
from rest_framework import status
from rest_framework.test import APIRequestFactory
from posthog.api.file_system.file_system import DELETE_PREVIEW_ENTRY_LIMIT
-from posthog.models import Project, Team, User
+from posthog.models import OrganizationMembership, Project, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.file_system.file_system import FileSystem
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
@@ -1270,6 +1273,95 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):
self.assertIn("Docs/FileA", paths)
self.assertIn("Docs/FileB", paths)
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_list_annotates_resolved_user_access_level(self, mock_flag):
+ blocked_dashboard = Dashboard.objects.create(team=self.team, name="Blocked", created_by=self.other_user)
+ FileSystem.objects.create(
+ team=self.team,
+ path="Docs/Blocked",
+ depth=2,
+ type="dashboard",
+ ref=str(blocked_dashboard.pk),
+ created_by=self.other_user,
+ )
+ # Resource-level "none" doesn't exclude rows from the tree, so the annotation is
+ # what tells the UI to grey them out
+ self._create_access_control(resource="dashboard", resource_id=None, access_level="none")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ levels = {item["path"]: item["user_access_level"] for item in response.json()["results"]}
+ self.assertEqual(levels["Docs/FileA"], "manager") # creator keeps access
+ # file_b's tree row was created by someone else, but the user created the dashboard itself
+ self.assertEqual(levels["Docs/FileB"], "manager")
+ self.assertEqual(levels["Docs/Blocked"], "none")
+ self.assertIsNone(levels["Docs"]) # folders have no access controls
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_annotates_short_id_refs_via_pk_keyed_grants(self, mock_flag):
+ insight = Insight.objects.create(team=self.team, name="Granted insight", created_by=self.other_user)
+ FileSystem.objects.create(
+ team=self.team,
+ path="Docs/Granted insight",
+ depth=2,
+ type="insight",
+ ref=insight.short_id,
+ created_by=self.other_user,
+ )
+ self._create_access_control(resource="insight", resource_id=None, access_level="none")
+ membership = OrganizationMembership.objects.get(organization=self.organization, user=self.user)
+ # AccessControl rows are keyed by pk while insight file system refs are short_ids
+ self._create_access_control(
+ resource="insight",
+ resource_id=str(insight.pk),
+ access_level="viewer",
+ organization_member=membership,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ levels = {item["path"]: item["user_access_level"] for item in response.json()["results"]}
+ self.assertEqual(levels["Docs/Granted insight"], "viewer")
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_access_level_annotation_queries_do_not_scale_with_rows(self, mock_flag):
+ def create_entries(suffix: str) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name=f"D{suffix}", created_by=self.other_user)
+ insight = Insight.objects.create(team=self.team, name=f"I{suffix}", created_by=self.other_user)
+ FileSystem.objects.create(
+ team=self.team,
+ path=f"Docs/D{suffix}",
+ depth=2,
+ type="dashboard",
+ ref=str(dashboard.pk),
+ created_by=self.other_user,
+ )
+ FileSystem.objects.create(
+ team=self.team,
+ path=f"Docs/I{suffix}",
+ depth=2,
+ type="insight",
+ ref=insight.short_id,
+ created_by=self.other_user,
+ )
+
+ create_entries("1")
+ list_url = f"/api/projects/{self.team.id}/file_system/"
+ self.client.get(list_url) # warm up session-dependent queries
+
+ with CaptureQueriesContext(connection) as small_ctx:
+ self.client.get(list_url)
+
+ for i in range(2, 6):
+ create_entries(str(i))
+
+ with CaptureQueriesContext(connection) as large_ctx:
+ self.client.get(list_url)
+
+ self.assertEqual(len(small_ctx), len(large_ctx))
+
def test_created_at_filters(self):
"""
Verify we can filter by created_at greater-than and less-than.
diff --git a/posthog/api/file_system/test/test_file_system_shortcut.py b/posthog/api/file_system/test/test_file_system_shortcut.py
index b4fe8369538f..43b747c99464 100644
--- a/posthog/api/file_system/test/test_file_system_shortcut.py
+++ b/posthog/api/file_system/test/test_file_system_shortcut.py
@@ -1,5 +1,6 @@
from datetime import timedelta
+import pytest
from posthog.test.base import APIBaseTest
from django.utils import timezone
@@ -7,8 +8,14 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
+from posthog.models import User
from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
+
+from ee.models.rbac.access_control import AccessControl
+
class TestFileSystemShortcutAPI(APIBaseTest):
def test_list_shortcuts_initially_empty(self):
@@ -231,3 +238,52 @@ class TestFileSystemShortcutSurface(APIBaseTest):
format="json",
)
self.assertEqual(ok.status_code, status.HTTP_200_OK, ok.json())
+
+
+class TestFileSystemShortcutAccessLevels(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": "access_control", "name": "access_control"},
+ {"key": "role_based_access", "name": "role_based_access"},
+ ]
+ self.organization.save()
+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testpass")
+
+ def test_annotates_resolved_access_level_and_fetches_object_creator(self):
+ mine = Dashboard.objects.create(team=self.team, name="Mine", created_by=self.user)
+ theirs = Dashboard.objects.create(team=self.team, name="Theirs", created_by=self.other_user)
+ FileSystemShortcut.objects.create(
+ team=self.team, user=self.user, path="Mine", type="dashboard", ref=str(mine.pk)
+ )
+ FileSystemShortcut.objects.create(
+ team=self.team, user=self.user, path="Theirs", type="dashboard", ref=str(theirs.pk)
+ )
+ AccessControl.objects.create(team=self.team, resource="dashboard", resource_id=None, access_level="none")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/file_system_shortcut/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ levels = {item["path"]: item["user_access_level"] for item in response.json()["results"]}
+ # Shortcut rows don't store the object's creator - it is resolved from the target model,
+ # so the user's own dashboard stays accessible while the blocked one is marked "none"
+ self.assertEqual(levels, {"Mine": "manager", "Theirs": "none"})
+
+ def test_unresolved_refs_indistinguishable_from_blocked_objects(self):
+ # Shortcuts accept arbitrary refs, so a guessed ref must not reveal via its access
+ # level whether a protected object exists
+ insight = Insight.objects.create(team=self.team, name="Real", created_by=self.other_user)
+ FileSystemShortcut.objects.create(
+ team=self.team, user=self.user, path="Real", type="insight", ref=insight.short_id
+ )
+ FileSystemShortcut.objects.create(
+ team=self.team, user=self.user, path="Guessed", type="insight", ref="nonexistent"
+ )
+ AccessControl.objects.create(team=self.team, resource="insight", resource_id=None, access_level="none")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/file_system_shortcut/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ levels = {item["path"]: item["user_access_level"] for item in response.json()["results"]}
+ self.assertEqual(levels, {"Real": "none", "Guessed": "none"})
diff --git a/posthog/api/search.py b/posthog/api/search.py
index 93c571f07523..2bc4ce355a4b 100644
--- a/posthog/api/search.py
+++ b/posthog/api/search.py
@@ -1,10 +1,12 @@
import re
+from collections import defaultdict
from typing import Any, Literal, TypedDict, cast
-from django.db.models import CharField, F, Model, QuerySet, Value
+from django.db.models import BigIntegerField, CharField, F, Model, QuerySet, Value
from django.db.models.functions import Cast, JSONObject
from django.http import HttpResponse
+from drf_spectacular.utils import extend_schema
from rest_framework import serializers, viewsets
from rest_framework.request import Request
from rest_framework.response import Response
@@ -13,6 +15,7 @@ from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.helpers.full_text_search import build_rank, process_query
from posthog.models import EventDefinition, PropertyDefinition
+from posthog.rbac.user_access_control import UserAccessControl, model_to_resource
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
@@ -118,6 +121,14 @@ class SearchViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object = "INTERNAL"
serializer_class = _FallbackSerializer
+ @extend_schema(
+ parameters=[QuerySerializer],
+ description=(
+ "Full-text search across project entities. Each result includes `user_access_level`, "
+ "the requesting user's resolved access level for that object (`none` means the user "
+ "cannot open it); `null` when access controls don't apply to the entity type."
+ ),
+ )
def list(self, request: Request, **kw) -> HttpResponse:
# parse query params
query_serializer = QuerySerializer(data=self.request.query_params)
@@ -130,7 +141,13 @@ class SearchViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
include_counts = params["include_counts"]
results, counts, _ = search_entities(
- entities, query, self.project_id, self, ENTITY_MAP, include_counts=include_counts
+ entities,
+ query,
+ self.project_id,
+ self,
+ ENTITY_MAP,
+ include_counts=include_counts,
+ annotate_access_levels=self.user_access_control,
)
response_data: dict[str, Any] = {"results": results}
@@ -148,6 +165,7 @@ def search_entities(
limit: int = LIMIT,
offset: int = 0,
include_counts: bool = True,
+ annotate_access_levels: UserAccessControl | None = None,
) -> tuple[list[dict[str, Any]], dict[str, int | None] | None, int | None]:
# empty queryset to union things onto it
counts: dict[str, int | None] = dict.fromkeys(entity_map) if include_counts else {}
@@ -184,11 +202,44 @@ def search_entities(
# Apply pagination
results = cast(list[dict[str, Any]], list(qs[offset : offset + limit]))
+ if annotate_access_levels is not None:
+ _annotate_user_access_levels(results, entity_map, annotate_access_levels)
for result in results:
result.pop("_sort_name", None)
+ result.pop("_pk", None)
+ result.pop("_created_by_id", None)
return results, counts or None, total_count
+def _annotate_user_access_levels(
+ results: list[dict[str, Any]],
+ entity_map: dict[str, EntityConfig],
+ user_access_control: UserAccessControl,
+) -> None:
+ """Set `user_access_level` on each result to the user's resolved level for that object
+ ("none" means they can't open it), or None for entity types without access controls.
+
+ Resolution is keyed by `_pk`, not `result_id` — insights and notebooks use short_id as
+ their result_id while AccessControl rows are keyed by pk.
+ """
+ results_by_type: dict[str, list[dict[str, Any]]] = defaultdict(list)
+ for result in results:
+ results_by_type[result["type"]].append(result)
+
+ for entity_type, entity_results in results_by_type.items():
+ resource = model_to_resource(cast(Model, entity_map[entity_type]["klass"]))
+ if resource is None:
+ for result in entity_results:
+ result["user_access_level"] = None
+ continue
+
+ levels = user_access_control.bulk_object_access_levels(
+ resource, [(result["_pk"], result["_created_by_id"]) for result in entity_results]
+ )
+ for result in entity_results:
+ result["user_access_level"] = levels.get(result["_pk"])
+
+
def class_queryset(
view: TeamAndOrgViewSetMixin,
klass: type[Model],
@@ -200,11 +251,22 @@ def class_queryset(
):
"""Builds a queryset for the class."""
entity_type = class_to_entity_name(klass)
- values = ["type", "result_id", "extra_fields", "_sort_name"]
+ values = ["type", "result_id", "extra_fields", "_sort_name", "_pk", "_created_by_id"]
qs: QuerySet[Any] = cast(Any, klass).objects.filter(team__project_id=project_id) # filter team
qs = view.user_access_control.filter_queryset_by_access_level(qs) # filter access level
+ # Uniform columns for access level resolution — every union member must produce them
+ qs = qs.annotate(_pk=Cast("pk", CharField()))
+ if hasattr(klass, "created_by"):
+ qs = qs.annotate(_created_by_id=F("created_by_id"))
+ else:
+ # Explicitly cast rather than relying on Value(None, ...)'s output_field: Django
+ # renders untyped None values as a bare `NULL`, so if two or more such entities end
+ # up adjacent in the union, Postgres resolves their shared column as `text` and then
+ # fails to match it against a real integer `_created_by_id` column elsewhere.
+ qs = qs.annotate(_created_by_id=Cast(Value(None), output_field=BigIntegerField()))
+
# Apply entity-specific filters
if filters:
qs = qs.filter(**filters)
diff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.py
index 5a7645a90eac..c945982d4f05 100644
--- a/posthog/api/test/test_search.py
+++ b/posthog/api/test/test_search.py
@@ -7,7 +7,7 @@ from django.test.utils import CaptureQueriesContext
from posthog.api.search import ENTITY_MAP, class_queryset, search_entities
from posthog.helpers.full_text_search import build_search_vector, process_query
-from posthog.models import Team
+from posthog.models import OrganizationMembership, Team, User
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
@@ -17,6 +17,8 @@ from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from ee.models.rbac.access_control import AccessControl
+
class TestSearch(APIBaseTest):
insight_1: Insight
@@ -104,18 +106,21 @@ class TestSearch(APIBaseTest):
"type": "dashboard",
"result_id": str(self.dashboard_1.id),
"extra_fields": {"description": "", "name": "second dashboard"},
+ "user_access_level": "manager",
},
{
"rank": sorted_results[1]["rank"],
"type": "insight",
"result_id": self.insight_1.short_id,
"extra_fields": {"name": "second insight", "description": None, "query": None},
+ "user_access_level": "editor",
},
{
"rank": sorted_results[2]["rank"],
"type": "notebook",
"result_id": self.notebook_1.short_id,
"extra_fields": {"title": "second notebook", "content": None},
+ "user_access_level": "manager",
},
],
)
@@ -375,3 +380,67 @@ def test_process_query(query, expected, dbresult):
result = cursor.fetchall()
assert result[0][0] == dbresult
+
+
+class TestSearchAccessLevels(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": "access_control", "name": "access_control"},
+ {"key": "role_based_access", "name": "role_based_access"},
+ ]
+ self.organization.save()
+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testpass")
+ self.membership = OrganizationMembership.objects.get(organization=self.organization, user=self.user)
+
+ def _levels_by_result_id(self, response, entity_type: str) -> dict[str, str | None]:
+ return {
+ result["result_id"]: result["user_access_level"]
+ for result in response.json()["results"]
+ if result["type"] == entity_type
+ }
+
+ def test_blocked_resource_results_are_annotated_none(self):
+ FeatureFlag.objects.create(key="searchable-a", team=self.team, created_by=self.other_user)
+ FeatureFlag.objects.create(key="searchable-b", team=self.team, created_by=self.other_user)
+ EventDefinition.objects.create(team=self.team, name="searchable-event")
+ AccessControl.objects.create(team=self.team, resource="feature_flag", resource_id=None, access_level="none")
+
+ response = self.client.get("/api/projects/@current/search?q=searchable")
+
+ assert response.status_code == 200
+ flag_levels = self._levels_by_result_id(response, "feature_flag")
+ assert len(flag_levels) == 2
+ assert set(flag_levels.values()) == {"none"}
+ assert set(self._levels_by_result_id(response, "event_definition").values()) == {None}
+
+ def test_object_grants_resolve_by_pk_for_short_id_entities(self):
+ flag_granted = FeatureFlag.objects.create(key="searchable-a", team=self.team, created_by=self.other_user)
+ FeatureFlag.objects.create(key="searchable-b", team=self.team, created_by=self.other_user)
+ insight_granted = Insight.objects.create(name="searchable insight", team=self.team, created_by=self.other_user)
+ Insight.objects.create(name="searchable insight two", team=self.team, created_by=self.other_user)
+ for resource in ("feature_flag", "insight"):
+ AccessControl.objects.create(team=self.team, resource=resource, resource_id=None, access_level="none")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="feature_flag",
+ resource_id=str(flag_granted.pk),
+ access_level="viewer",
+ organization_member=self.membership,
+ )
+ # AccessControl rows are keyed by pk even though insight results expose short_id as result_id
+ AccessControl.objects.create(
+ team=self.team,
+ resource="insight",
+ resource_id=str(insight_granted.pk),
+ access_level="viewer",
+ organization_member=self.membership,
+ )
+
+ response = self.client.get("/api/projects/@current/search?q=searchable")
+
+ assert response.status_code == 200
+ # "none" resource access + object grants: only granted objects are returned, with resolved levels
+ assert self._levels_by_result_id(response, "feature_flag") == {str(flag_granted.pk): "viewer"}
+ assert self._levels_by_result_id(response, "insight") == {insight_granted.short_id: "viewer"}
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 7261511d0614..381a725fa82b 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -1,5 +1,6 @@
import json
from collections import defaultdict
+from collections.abc import Sequence
from dataclasses import dataclass
from enum import Enum
from functools import cached_property
@@ -646,10 +647,7 @@ class UserAccessControl:
return default_access_level(resource) if not explicit else None
# If there are access controls we pick the highest level the user has
- return max(
- access_controls,
- key=lambda access_control: ordered_access_levels(resource).index(access_control.access_level),
- ).access_level
+ return self._highest_access_level_from_rows(resource, access_controls)
def check_access_level_for_object(self, obj: Model, required_level: AccessControlLevel, explicit=False) -> bool:
"""
@@ -804,10 +802,7 @@ class UserAccessControl:
if not access_controls:
return default_access_level(resource)
- return max(
- access_controls,
- key=lambda access_control: ordered_access_levels(resource).index(access_control.access_level),
- ).access_level
+ return self._highest_access_level_from_rows(resource, access_controls)
def has_access_levels_for_resource(self, resource: APIScopeObject) -> bool:
if not self._team:
@@ -1132,27 +1127,113 @@ class UserAccessControl:
# User access level
# ------------------------------------------------------------
+ def _object_access_level_precheck(
+ self, resource: APIScopeObject, is_creator: bool, explicit: bool = False
+ ) -> tuple[bool, Optional[AccessControlLevel]]:
+ """Guard steps of object access resolution that don't need the object's own AC rows.
+
+ Returns (resolved, level): when `resolved` is True, `level` is the final answer and
+ the object's rows must not be consulted. Shared by `get_user_access_level` and
+ `bulk_object_access_levels` so the single and bulk paths cannot drift.
+ """
+ org_membership = self._organization_membership
+ if not org_membership:
+ return True, None
+
+ # Creators and org admins always have highest access
+ if is_creator or self.is_organization_admin:
+ return True, highest_access_level(resource)
+
+ if resource == "organization":
+ # Organization access is controlled via membership level only
+ if org_membership.level >= OrganizationMembership.Level.ADMIN:
+ return True, "admin"
+ return True, "member"
+
+ if not self.access_controls_supported:
+ return True, (None if explicit else default_access_level(resource))
+
+ return False, None
+
+ @staticmethod
+ def _highest_access_level_from_rows(
+ resource: APIScopeObject, access_controls: list[_AccessControl]
+ ) -> AccessControlLevel:
+ return max(
+ access_controls,
+ key=lambda access_control: ordered_access_levels(resource).index(access_control.access_level),
+ ).access_level
+
+ def _object_access_level_from_rows(
+ self, resource: APIScopeObject, object_access_controls: list[_AccessControl], explicit: bool = False
+ ) -> Optional[AccessControlLevel]:
+ """Row-based object access resolution: explicit (role/member) object rows win, then
+ resource-level rows, then default object rows, then the resource default. Shared by
+ `get_user_access_level` and `bulk_object_access_levels`.
+ """
+ explicit_rows = [
+ ac for ac in object_access_controls if ac.role_id is not None or ac.organization_member_id is not None
+ ]
+ if explicit_rows:
+ return self._highest_access_level_from_rows(resource, explicit_rows)
+
+ if self.has_access_levels_for_resource(resource):
+ access_level_for_resource = self.access_level_for_resource(resource)
+ if access_level_for_resource:
+ return access_level_for_resource
+
+ if object_access_controls:
+ return self._highest_access_level_from_rows(resource, object_access_controls)
+
+ return None if explicit else default_access_level(resource)
+
def get_user_access_level(self, obj: Model, explicit=False) -> Optional[AccessControlLevel]:
resource = model_to_resource(obj)
- specific_access_level_for_object = None
- access_level_for_resource = None
+ if not resource:
+ return None
+
+ is_creator = getattr(obj, "created_by", None) == self._user
+ resolved, level = self._object_access_level_precheck(resource, is_creator, explicit=explicit)
+ if resolved:
+ return level
+
+ object_access_controls = self._get_access_controls(
+ self._access_controls_filters_for_object(resource, str(obj.id)) # type: ignore
+ )
+ return self._object_access_level_from_rows(resource, object_access_controls, explicit=explicit)
+
+ def bulk_object_access_levels(
+ self,
+ resource: APIScopeObject,
+ objects: Sequence[tuple[str, Optional[int]]],
+ ) -> dict[str, Optional[AccessControlLevel]]:
+ """Resolve the user's access level for many objects of one resource type at once.
+
+ `objects` is a sequence of (object_pk_str, created_by_id) pairs. Semantics match
+ `get_user_access_level`, but object rows come from the bulk preload grouped in memory,
+ so no per-object queries are issued.
+ """
+ if not objects:
+ return {}
- # Check object specific access levels
- specific_access_level_for_object = self.specific_access_level_for_object(obj, explicit=explicit)
+ results: dict[str, Optional[AccessControlLevel]] = {}
+ rows_by_object_id: Optional[dict[str, list[_AccessControl]]] = None
- if specific_access_level_for_object:
- return specific_access_level_for_object
+ for object_id, created_by_id in objects:
+ is_creator = created_by_id is not None and created_by_id == self._user.id
+ resolved, level = self._object_access_level_precheck(resource, is_creator)
+ if resolved:
+ results[object_id] = level
+ continue
- # Check resource access levels
- if resource and self.has_access_levels_for_resource(resource):
- access_level_for_resource = self.access_level_for_resource(resource)
+ if rows_by_object_id is None:
+ rows_by_object_id = defaultdict(list)
+ for ac in self._get_access_controls(self._access_controls_filters_for_queryset(resource)):
+ rows_by_object_id[ac.resource_id].append(ac)
- if access_level_for_resource:
- return access_level_for_resource
+ results[object_id] = self._object_access_level_from_rows(resource, rows_by_object_id.get(object_id, []))
- # Check object general access levels
- access_level_for_object = self.access_level_for_object(obj, explicit=explicit)
- return access_level_for_object
+ return results
class UserAccessControlSerializerMixin(serializers.Serializer):
diff --git a/posthog/schema.py b/posthog/schema.py
index 075e284a8f5c..4b13eb51543c 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -1347,6 +1347,13 @@ class FileSystemEntry(BaseModel):
default=None,
description="Type of object, used for icon, e.g. feature_flag, insight, etc",
)
+ user_access_level: str | None = Field(
+ default=None,
+ description=(
+ "Access level the user has for the referenced object ('none' means no"
+ " access); null/absent when access controls don't apply"
+ ),
+ )
visualOrder: float | None = Field(default=None, description="Order of object in tree")
@@ -4743,6 +4750,13 @@ class FileSystemImport(BaseModel):
default=None,
description="Type of object, used for icon, e.g. feature_flag, insight, etc",
)
+ user_access_level: str | None = Field(
+ default=None,
+ description=(
+ "Access level the user has for the referenced object ('none' means no"
+ " access); null/absent when access controls don't apply"
+ ),
+ )
visualOrder: float | None = Field(default=None, description="Order of object in tree")
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index a959c5ef08dd..ad00073df22a 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -2329,52 +2329,47 @@
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.6
'''
- SELECT "posthog_organizationmembership"."id",
- "posthog_organizationmembership"."organization_id",
- "posthog_organizationmembership"."user_id",
- "posthog_organizationmembership"."level",
- "posthog_organizationmembership"."joined_at",
- "posthog_organizationmembership"."updated_at",
- "posthog_organizationmembership"."invited_by_id",
- "posthog_organization"."id",
- "posthog_organization"."name",
- "posthog_organization"."slug",
- "posthog_organization"."logo_media_id",
- "posthog_organization"."created_at",
- "posthog_organization"."updated_at",
- "posthog_organization"."is_active",
- "posthog_organization"."is_not_active_reason",
- "posthog_organization"."session_cookie_age",
- "posthog_organization"."is_member_join_email_enabled",
- "posthog_organization"."is_ai_data_processing_approved",
- "posthog_organization"."is_ai_training_opted_in",
- "posthog_organization"."is_ai_training_locked",
- "posthog_organization"."is_ai_training_cta_shown",
- "posthog_organization"."enforce_2fa",
- "posthog_organization"."members_can_invite",
- "posthog_organization"."members_can_create_projects",
- "posthog_organization"."members_can_use_personal_api_keys",
- "posthog_organization"."allow_publicly_shared_resources",
- "posthog_organization"."default_role_id",
- "posthog_organization"."plugins_access_level",
- "posthog_organization"."for_internal_metrics",
- "posthog_organization"."default_experiment_stats_method",
- "posthog_organization"."default_anonymize_ips",
- "posthog_organization"."is_hipaa",
- "posthog_organization"."is_pending_deletion",
- "posthog_organization"."customer_id",
- "posthog_organization"."available_product_features",
- "posthog_organization"."usage",
- "posthog_organization"."never_drop_data",
- "posthog_organization"."customer_trust_scores",
- "posthog_organization"."setup_section_2_completed",
- "posthog_organization"."personalization",
- "posthog_organization"."domain_whitelist",
- "posthog_organization"."is_platform"
- FROM "posthog_organizationmembership"
- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
- AND "posthog_organizationmembership"."user_id" = 99999)
+ SELECT "posthog_user"."id",
+ "posthog_user"."password",
+ "posthog_user"."last_login",
+ "posthog_user"."first_name",
+ "posthog_user"."last_name",
+ "posthog_user"."is_staff",
+ "posthog_user"."date_joined",
+ "posthog_user"."uuid",
+ "posthog_user"."current_organization_id",
+ "posthog_user"."current_team_id",
+ "posthog_user"."email",
+ "posthog_user"."pending_email",
+ "posthog_user"."distinct_id",
+ "posthog_user"."is_email_verified",
+ "posthog_user"."credentials_reviewed_at",
+ "posthog_user"."requested_password_reset_at",
+ "posthog_user"."requested_2fa_reset_at",
+ "posthog_user"."has_seen_product_intro_for",
+ "posthog_user"."strapi_id",
+ "posthog_user"."is_active",
+ "posthog_user"."role_at_organization",
+ "posthog_user"."theme_mode",
+ "posthog_user"."partial_notification_settings",
+ "posthog_user"."anonymize_data",
+ "posthog_user"."allow_impersonation",
+ "posthog_user"."toolbar_mode",
+ "posthog_user"."hedgehog_config",
+ "posthog_user"."allow_sidebar_suggestions",
+ "posthog_user"."shortcut_position",
+ "posthog_user"."passkeys_enabled_for_2fa",
+ "posthog_user"."hide_mcp_hints",
+ "posthog_user"."onboarding_skipped_at",
+ "posthog_user"."onboarding_skipped_reason",
+ "posthog_user"."onboarding_skipped_organization_id",
+ "posthog_user"."onboarding_delegated_to_invite_id",
+ "posthog_user"."onboarding_delegated_to_organization_id",
+ "posthog_user"."onboarding_delegation_accepted_at",
+ "posthog_user"."events_column_config",
+ "posthog_user"."email_opt_in"
+ FROM "posthog_user"
+ WHERE "posthog_user"."id" = 99999
LIMIT 21
'''
# ---
@@ -2997,47 +2992,52 @@
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.7
'''
- SELECT "posthog_user"."id",
- "posthog_user"."password",
- "posthog_user"."last_login",
- "posthog_user"."first_name",
- "posthog_user"."last_name",
- "posthog_user"."is_staff",
- "posthog_user"."date_joined",
- "posthog_user"."uuid",
- "posthog_user"."current_organization_id",
- "posthog_user"."current_team_id",
- "posthog_user"."email",
- "posthog_user"."pending_email",
- "posthog_user"."distinct_id",
- "posthog_user"."is_email_verified",
- "posthog_user"."credentials_reviewed_at",
- "posthog_user"."requested_password_reset_at",
- "posthog_user"."requested_2fa_reset_at",
- "posthog_user"."has_seen_product_intro_for",
- "posthog_user"."strapi_id",
- "posthog_user"."is_active",
- "posthog_user"."role_at_organization",
- "posthog_user"."theme_mode",
- "posthog_user"."partial_notification_settings",
- "posthog_user"."anonymize_data",
- "posthog_user"."allow_impersonation",
- "posthog_user"."toolbar_mode",
- "posthog_user"."hedgehog_config",
- "posthog_user"."allow_sidebar_suggestions",
- "posthog_user"."shortcut_position",
- "posthog_user"."passkeys_enabled_for_2fa",
- "posthog_user"."hide_mcp_hints",
- "posthog_user"."onboarding_skipped_at",
- "posthog_user"."onboarding_skipped_reason",
- "posthog_user"."onboarding_skipped_organization_id",
- "posthog_user"."onboarding_delegated_to_invite_id",
- "posthog_user"."onboarding_delegated_to_organization_id",
- "posthog_user"."onboarding_delegation_accepted_at",
- "posthog_user"."events_column_config",
- "posthog_user"."email_opt_in"
- FROM "posthog_user"
- WHERE "posthog_user"."id" = 99999
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
+ AND "posthog_organizationmembership"."user_id" = 99999)
LIMIT 21
'''
# ---
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 998070fc2893..278146aeb8b0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25138,6 +25138,11 @@ export namespace Schemas {
readonly created_at: string;
/** @nullable */
readonly last_viewed_at: string | null;
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level: string | null;
}
export interface FileSystemShortcut {
@@ -25167,6 +25172,11 @@ export namespace Schemas {
*/
order?: number;
readonly created_at: string;
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level: string | null;
}
export interface FileSystemShortcutReorder {
@@ -39906,6 +39916,11 @@ export namespace Schemas {
readonly created_at?: string;
/** @nullable */
readonly last_viewed_at?: string | null;
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level?: string | null;
}
export interface PatchedFileSystemShortcut {
@@ -39935,6 +39950,11 @@ export namespace Schemas {
*/
order?: number;
readonly created_at?: string;
+ /**
+ * Resolved access level the user has for the object this entry references ('none' means the user can't open it). Null when access controls don't apply to the entry type.
+ * @nullable
+ */
+ readonly user_access_level?: string | null;
}
export interface PatchedFolderInstructionsPublish {
@@ -70347,6 +70367,47 @@ export namespace Schemas {
force_refresh?: boolean;
};
+ export type SearchListParams = {
+ entities?: SearchListEntitiesItem[];
+ include_counts?: boolean;
+ /**
+ * @minLength 1
+ */
+ q?: string;
+ };
+
+ /**
+ * * `insight` - insight
+ * * `dashboard` - dashboard
+ * * `experiment` - experiment
+ * * `feature_flag` - feature_flag
+ * * `notebook` - notebook
+ * * `action` - action
+ * * `cohort` - cohort
+ * * `event_definition` - event_definition
+ * * `property_definition` - property_definition
+ * * `survey` - survey
+ * * `early_access_feature` - early_access_feature
+ * * `hog_flow` - hog_flow
+ */
+ export type SearchListEntitiesItem = typeof SearchListEntitiesItem[keyof typeof SearchListEntitiesItem];
+
+
+ export const SearchListEntitiesItem = {
+ Insight: 'insight',
+ Dashboard: 'dashboard',
+ Experiment: 'experiment',
+ FeatureFlag: 'feature_flag',
+ Notebook: 'notebook',
+ Action: 'action',
+ Cohort: 'cohort',
+ EventDefinition: 'event_definition',
+ PropertyDefinition: 'property_definition',
+ Survey: 'survey',
+ EarlyAccessFeature: 'early_access_feature',
+ HogFlow: 'hog_flow',
+ } as const;
+
export type SessionGroupSummariesListParams = {
/**
* Number of results to return per page.