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.

refactor(file-system): consolidate access resolution for tree mutations (#74433)

Tom Piccirelloea7304fe8142
diff --git a/posthog/api/file_system/access_levels.py b/posthog/api/file_system/access_levels.py
index ba24789e04ad..76a11df276a6 100644
--- a/posthog/api/file_system/access_levels.py
+++ b/posthog/api/file_system/access_levels.py
@@ -1,33 +1,66 @@
import logging
-from collections.abc import Sequence
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
from typing import Any, Optional, cast
from django.apps import apps
from django.core.cache import cache
+from django.core.exceptions import ValidationError as DjangoValidationError
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.api.file_system.deletion import (
+ ModelRegistration,
+ get_file_system_registration,
+ get_non_pk_keyed_file_system_types,
+ is_pk_keyed_file_system_type,
+)
+from posthog.models import Team
from posthog.rbac.user_access_control import (
ACCESS_CONTROL_RESOURCES,
RESOURCE_INHERITANCE_MAP,
AccessControlLevel,
UserAccessControl,
+ access_level_satisfied_for_resource,
)
from posthog.scopes import APIScopeObject
+from posthog.settings import EE_AVAILABLE
logger = logging.getLogger(__name__)
-# (file system type, ref, created_by_id of the underlying object - None when unknown)
-FileSystemAccessEntry = tuple[str, Optional[str], Optional[int]]
+
+@dataclass(frozen=True, kw_only=True)
+class FileSystemAccessEntry:
+ """One entry to resolve an access level for.
+
+ Keyword-only because `created_by_id` and `team_id` are both ints: positionally they can be
+ transposed without any type error, and getting that wrong resolves the entry against the
+ wrong team.
+
+ `created_by_id` is the creator of the backing object, never of the tree row that points at
+ it, and is None when the caller doesn't know it (it is then read during ref translation).
+ `team_id` is the tree row's own team, which is not necessarily the request's team.
+ """
+
+ entry_type: str
+ ref: Optional[str]
+ created_by_id: Optional[int]
+ team_id: int
+
# A ref (short_id) maps to exactly one immutable pk for the life of the object, so the
# translation is safe to cache across requests. Caching it keeps the multi-model UNION off
# the high-traffic list endpoint on every page load - the query that translates short_id refs
# to pks otherwise runs per request and adds DB pool load under contention.
+#
+# Keyed by project rather than by team, because a team segment would only repeat the project
+# one. `TeamManager.create` gives a team the id of its project, creating the project with that
+# id when the caller doesn't supply one, and `Project.objects.create_with_team` allocates a
+# single id for the pair. No code path attaches a team to an existing project, so a project
+# never holds two teams whose refs could collide under one key.
_REF_PK_CACHE_PREFIX = "fs_ref_pk:v1"
_REF_PK_CACHE_TTL = 60 * 60
@@ -63,11 +96,35 @@ def _is_access_controlled_type(file_system_type: str) -> bool:
return file_system_type in ACCESS_CONTROL_RESOURCES or file_system_type in RESOURCE_INHERITANCE_MAP
+def _coerce_refs_for_lookup(model: Any, lookup_field: str, refs: list[str]) -> list[Any]:
+ """Refs the lookup field can actually hold, dropping the ones it rejects.
+
+ `ref` is a plain CharField on the tree row and is caller-supplied when a row is created, so
+ it can hold a value the target field can't. Passing one into the query raises rather than
+ matching nothing: an integer pk raises ValueError on "oops", a UUID pk raises ValidationError.
+ Dropped refs then resolve at resource level like any other ref with no matching object, which
+ is the same fail-safe unresolvable refs already get.
+ """
+ field = model._meta.get_field(lookup_field)
+ coerced: list[Any] = []
+ for ref in refs:
+ try:
+ coerced.append(field.to_python(ref))
+ except (DjangoValidationError, ValueError, TypeError):
+ continue
+ return coerced
+
+
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."""
+ """Queryset yielding (type, ref, pk, team_id, created_by_id) rows for one entry type, with
+ uniform column types so querysets of different models can be UNIONed into one statement.
+
+ Stays project-wide rather than filtering to one team: short_id uniqueness is enforced per
+ team, not per project, so the same ref can legitimately resolve to a different real object
+ in every team - the caller keys results by the returned team_id so those don't collide.
+ """
model = apps.get_model(registration.app_label, registration.model_name)
manager = getattr(model, registration.manager_name, model._default_manager)
lookup_field = registration.lookup_field
@@ -75,28 +132,44 @@ def _ref_translation_queryset(
manager.filter(
**{
f"{registration.team_field}__project_id": project_id,
- f"{lookup_field}__in": refs,
+ f"{lookup_field}__in": _coerce_refs_for_lookup(model, lookup_field, refs),
}
)
.annotate(
_type=Value(entry_type, output_field=CharField()),
_ref=Cast(lookup_field, output_field=CharField()),
_pk=Cast("pk", output_field=CharField()),
+ _team_id=F(f"{registration.team_field}_id"),
# 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")
+ .values_list("_type", "_ref", "_pk", "_team_id", "_created_by_id")
)
+def _user_access_controls_by_team(
+ user_access_control: UserAccessControl, team_ids: Iterable[int]
+) -> dict[int, UserAccessControl]:
+ """A UserAccessControl scoped to each of the given teams.
+
+ The file system tree intentionally lists rows from every environment in the project (see
+ `_scope_by_project_and_environment`), so resolving access has to run against each row's own
+ team - a `UserAccessControl` only ever answers for the single team it was built with, and
+ silently falls back to `default_access_level` (typically "editor") for objects outside it.
+ The caller's own instance serves its own team, and the rest are memoized on it, so the
+ filter pass and the serializer pass of one request share them.
+ """
+ return user_access_control.for_team_ids(team_ids)
+
+
def bulk_file_system_access_levels(
entries: Sequence[FileSystemAccessEntry],
user_access_control: UserAccessControl,
project_id: int,
-) -> dict[tuple[str, str], Optional[AccessControlLevel]]:
+) -> dict[tuple[str, str, int], 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
@@ -113,69 +186,103 @@ def bulk_file_system_access_levels(
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.
+
+ Final resolution runs per entry's own team_id (see `_user_access_controls_by_team`), and
+ results are keyed by (type, ref, team_id), not just (type, ref): `ref` is caller-supplied
+ when a tree row is created, so nothing stops the same (type, ref) pair from appearing under
+ two different teams in one batch - e.g. a row planted in the caller's own team pointing at
+ another team's object. Collapsing those into one (type, ref) entry would let whichever
+ team's level was resolved last silently override the other's.
+
+ Translated rows are keyed the same way, by the team the matched object actually belongs to,
+ rather than by whichever group triggered the lookup. The pk cache above is keyed by project
+ instead, which is the same thing while a project and its team share an id.
"""
- results: dict[tuple[str, str], Optional[AccessControlLevel]] = {}
+ results: dict[tuple[str, str, int], 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):
+ entries_by_type_team: dict[tuple[str, int], dict[str, Optional[int]]] = {}
+ for entry in entries:
+ if not entry.ref or not _is_access_controlled_type(entry.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
-
- # (type, ref) -> (pk, created_by_id)
- translated: dict[tuple[str, str], tuple[str, Optional[int]]] = {}
-
- # One UNION query across every type needing a ref->pk translation or a creator lookup
- translation_querysets = []
- cacheable_query_types: set[str] = set() # non-id-keyed types we query, to backfill the pk cache
- for entry_type, creator_by_provided_ref in entries_by_type.items():
+ by_ref = entries_by_type_team.setdefault((entry.entry_type, entry.team_id), {})
+ if by_ref.get(entry.ref) is None or entry.created_by_id == user_id:
+ by_ref[entry.ref] = entry.created_by_id
+
+ # (type, ref, team_id) -> (pk, created_by_id)
+ translated: dict[tuple[str, str, int], tuple[str, Optional[int]]] = {}
+
+ # Refs still needing a DB lookup, merged across every team's group into one set per type -
+ # so a ref two teams' objects happen to share (see the docstring above) is queried once, not
+ # once per team. The query itself stays project-wide; every matching row, whichever team it
+ # actually belongs to, is captured below and keyed by its own team_id, not by whichever
+ # team's group triggered the lookup.
+ refs_needing_query_by_type: dict[str, set[str]] = {}
+ registrations_by_type: dict[str, ModelRegistration] = {}
+ cacheable_types: set[str] = set() # types safe to backfill the pk cache
+ for (entry_type, team_id), creator_by_provided_ref in entries_by_type_team.items():
registration = get_file_system_registration(entry_type)
if not registration:
continue
+ registrations_by_type[entry_type] = registration
needs_creator = any(created_by_id is None for created_by_id in creator_by_provided_ref.values())
- id_keyed = registration.lookup_field == "id"
- if id_keyed and not needs_creator:
+ pk_keyed = is_pk_keyed_file_system_type(registration)
+ if pk_keyed and not needs_creator:
continue
refs = list(creator_by_provided_ref)
# When we only need the ref->pk translation (not a fresh creator lookup), serve it from
# the cache and only query the refs still missing - a warm cache takes the UNION off the
# request entirely. Creator lookups always hit the DB so they never read stale creators.
- if not id_keyed and not needs_creator:
+ if not pk_keyed and not needs_creator:
cached_pks = _get_cached_ref_pks(project_id, entry_type, refs)
for ref, pk in cached_pks.items():
- translated[(entry_type, ref)] = (pk, None)
+ translated[(entry_type, ref, team_id)] = (pk, None)
refs = [ref for ref in refs if ref not in cached_pks]
if not refs:
continue
- if not id_keyed:
- cacheable_query_types.add(entry_type)
- translation_querysets.append(_ref_translation_queryset(entry_type, registration, refs, project_id))
+ if not pk_keyed:
+ cacheable_types.add(entry_type)
+ refs_needing_query_by_type.setdefault(entry_type, set()).update(refs)
+
+ translation_querysets = [
+ _ref_translation_queryset(entry_type, registrations_by_type[entry_type], list(refs), project_id)
+ for entry_type, refs in refs_needing_query_by_type.items()
+ ]
if translation_querysets:
union_qs = translation_querysets[0]
if len(translation_querysets) > 1:
union_qs = union_qs.union(*translation_querysets[1:], all=True)
pk_cache_updates: dict[tuple[str, str], str] = {}
- for row_type, ref_value, pk_value, created_by_id in union_qs:
+ for row_type, ref_value, pk_value, row_team_id, created_by_id in union_qs:
ref_str, pk_str = str(ref_value), str(pk_value)
- translated[(row_type, ref_str)] = (pk_str, created_by_id)
- if row_type in cacheable_query_types:
+ translated[(row_type, ref_str, row_team_id)] = (pk_str, created_by_id)
+ if row_type in cacheable_types:
pk_cache_updates[(row_type, ref_str)] = pk_str
_set_cached_ref_pks(project_id, pk_cache_updates)
- for entry_type, creator_by_provided_ref in entries_by_type.items():
+ access_controls_by_team = _user_access_controls_by_team(
+ user_access_control, {team_id for _entry_type, team_id in entries_by_type_team}
+ )
+
+ for (entry_type, team_id), creator_by_provided_ref in entries_by_type_team.items():
resource = cast(APIScopeObject, entry_type)
+ if not access_controls_by_team[team_id].has_project_access:
+ # Denied the whole environment, so nothing in it resolves. Without this the object
+ # rules below fall back to the resource default (editor for most types) for an
+ # environment that has no rules of its own, granting exactly what was denied.
+ for ref in creator_by_provided_ref:
+ results[(entry_type, ref, team_id)] = None
+ continue
+
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))
+ row = translated.get((entry_type, ref, team_id))
# 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
@@ -183,14 +290,116 @@ def bulk_file_system_access_levels(
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)
+ # Resolved against the entry's own team - resolves from that team's in-memory access
+ # control preload, no extra query beyond the one bulk fetch per distinct team
+ levels = access_controls_by_team[team_id].bulk_object_access_levels(resource, objects)
for pk, level in levels.items():
- results[(entry_type, ref_by_pk[pk])] = level
+ results[(entry_type, ref_by_pk[pk], team_id)] = level
return results
+def entries_missing_access_level(
+ entries: Sequence[tuple[str, str, int]],
+ user_access_control: UserAccessControl,
+ project_id: int,
+ required_level: AccessControlLevel,
+) -> list[tuple[str, str]]:
+ """The (type, ref) pairs whose backing object the user can't act on at `required_level`.
+
+ `entries` is (type, ref, team_id) - team_id is the tree row's own team, since the tree can
+ list rows from sibling environments and resolution has to run against the object's real team.
+
+ Types without access controls resolve to no level and are never reported as missing - the
+ file system can only enforce what the object's own resource model defines.
+
+ Creator status is always resolved from the backing object rather than from the file system
+ row, so a row someone filed against an object they don't own can't confer the owner's access.
+ """
+ controlled = [
+ (entry_type, ref, team_id)
+ for entry_type, ref, team_id in entries
+ if ref and _is_access_controlled_type(entry_type)
+ ]
+ if not controlled:
+ return []
+
+ levels = bulk_file_system_access_levels(
+ [
+ FileSystemAccessEntry(entry_type=entry_type, ref=ref, created_by_id=None, team_id=team_id)
+ for entry_type, ref, team_id in controlled
+ ],
+ user_access_control,
+ project_id,
+ )
+ return [
+ (entry_type, ref)
+ for entry_type, ref, team_id in controlled
+ if (level := levels.get((entry_type, ref, team_id))) is None
+ or not access_level_satisfied_for_resource(cast(APIScopeObject, entry_type), level, required_level)
+ ]
+
+
+def denied_short_id_refs(user_access_control: UserAccessControl, project_id: int) -> dict[tuple[str, int], list[str]]:
+ """Refs denied by a 'none' grant, for the file system types not keyed by primary key.
+
+ AccessControl rows always store the object's pk in `resource_id`, so for types whose file
+ system `ref` is a short_id the grant has to be translated into refs before it can be matched
+ against the tree. The tree lists rows from every environment in the project, so a grant has
+ to be checked - and its matching ref translated - against the team it was actually made in:
+ keyed by (type, team_id) so the caller can exclude a denied ref only within its own team,
+ not project-wide.
+
+ Costs one `Team` query per request plus one access-control preload per environment; the
+ per-team instances are memoized on `user_access_control`, so the serializer's own resolution
+ pass later in the same request reuses them rather than repeating either.
+ """
+ # Mirrors the early returns in `filter_and_annotate_file_system_queryset`, which discards
+ # this result in exactly these cases: these users see everything, and without the
+ # entitlement stale rules in the DB must be ignored rather than enforced.
+ if user_access_control.user.is_staff or user_access_control.is_organization_admin:
+ return {}
+ if not EE_AVAILABLE or not user_access_control.access_controls_supported:
+ return {}
+
+ resources = [
+ entry_type for entry_type in get_non_pk_keyed_file_system_types() if _is_access_controlled_type(entry_type)
+ ]
+ if not resources:
+ return {}
+
+ team_ids = Team.objects.filter(project_id=project_id).values_list("id", flat=True)
+ access_controls_by_team = _user_access_controls_by_team(user_access_control, team_ids)
+
+ denied_refs: dict[tuple[str, int], list[str]] = {}
+ for team_id, team_uac in access_controls_by_team.items():
+ denied_pks = team_uac.none_denied_object_ids(cast(Sequence[APIScopeObject], resources))
+ for entry_type, pks in denied_pks.items():
+ registration = get_file_system_registration(entry_type)
+ if registration is None:
+ continue
+ model = apps.get_model(registration.app_label, registration.model_name)
+ # Grants are stored as strings, so coerce through the model's own pk field rather
+ # than assuming a shape - these types include both integer and UUID primary keys,
+ # and a value the pk field rejects would make the query raise.
+ pk_field = model._meta.pk
+ valid_pks = []
+ for pk in pks:
+ try:
+ valid_pks.append(pk_field.to_python(pk))
+ except (DjangoValidationError, ValueError, TypeError):
+ continue
+ if not valid_pks:
+ continue
+ manager = getattr(model, registration.manager_name, model._default_manager)
+ refs = manager.filter(**{f"{registration.team_field}_id": team_id, "pk__in": valid_pks}).values_list(
+ registration.lookup_field, flat=True
+ )
+ if refs:
+ denied_refs[(entry_type, team_id)] = [str(ref) for ref in refs]
+ return denied_refs
+
+
# 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
@@ -207,7 +416,7 @@ class FileSystemAccessLevelSerializerMixin(serializers.Serializer):
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
+ self._access_levels_by_type_ref: Optional[dict[tuple[str, str, int], Optional[AccessControlLevel]]] = None
def _entry_user_access_control(self) -> Optional[UserAccessControl]:
request = self.context.get("request")
@@ -218,7 +427,7 @@ class FileSystemAccessLevelSerializerMixin(serializers.Serializer):
def _compute_access_levels(
self, entries: Sequence[FileSystemAccessEntry], user_access_control: UserAccessControl
- ) -> dict[tuple[str, str], Optional[AccessControlLevel]]:
+ ) -> dict[tuple[str, str, int], Optional[AccessControlLevel]]:
team = self.context["get_team"]()
return bulk_file_system_access_levels(entries, user_access_control, team.project_id)
@@ -231,18 +440,34 @@ class FileSystemAccessLevelSerializerMixin(serializers.Serializer):
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))
+ FileSystemAccessEntry(
+ entry_type=instance.type,
+ ref=instance.ref,
+ created_by_id=getattr(instance, "created_by_id", None),
+ team_id=instance.team_id,
+ )
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)
+ # Keyed by team_id too: `ref` is caller-supplied, so the same (type, ref) pair could
+ # otherwise collapse two different teams' objects onto one resolved level - see
+ # bulk_file_system_access_levels.
+ key = (obj.type, obj.ref, obj.team_id)
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
+ [
+ FileSystemAccessEntry(
+ entry_type=obj.type,
+ ref=obj.ref,
+ created_by_id=getattr(obj, "created_by_id", None),
+ team_id=obj.team_id,
+ )
+ ],
+ 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 d58ebee69138..22756bd413ec 100644
--- a/posthog/api/file_system/deletion.py
+++ b/posthog/api/file_system/deletion.py
@@ -6,7 +6,10 @@ from dataclasses import dataclass
from typing import Any, Literal
from django.apps import apps
-from django.core.exceptions import ObjectDoesNotExist
+from django.core.exceptions import (
+ ObjectDoesNotExist,
+ ValidationError as DjangoValidationError,
+)
from posthog.models.file_system.file_system import FileSystem, join_path, split_path
from posthog.models.signals import mute_selected_signals
@@ -156,6 +159,22 @@ def get_file_system_registration(type_string: str) -> ModelRegistration | None:
return _MODEL_REGISTRY.get(type_string)
+def is_pk_keyed_file_system_type(registration: ModelRegistration) -> bool:
+ """Whether a type's file system `ref` holds its object's primary key.
+
+ Compares against the model's own pk name rather than the literal "id", because Django lets a
+ model name its primary key any column: a registration whose lookup field is that column is
+ pk-keyed even when it isn't called "id".
+ """
+ model = apps.get_model(registration.app_label, registration.model_name)
+ return registration.lookup_field == model._meta.pk.name
+
+
+def get_non_pk_keyed_file_system_types() -> list[str]:
+ """Registered types whose file system `ref` is something other than the object's primary key."""
+ return [type_string for type_string, reg in _MODEL_REGISTRY.items() if not is_pk_keyed_file_system_type(reg)]
+
+
def _resolve_user(user: Any | None) -> Any | None:
if user is not None and getattr(user, "is_authenticated", False):
return user
@@ -176,8 +195,11 @@ def _get_object(
*,
ref: str,
team_id: int | None,
+ for_update: bool = False,
) -> Any:
queryset = _get_queryset(registration)
+ if for_update:
+ queryset = queryset.select_for_update()
filters: dict[str, Any] = {registration.lookup_field: ref, f"{registration.team_field}_id": team_id}
return queryset.get(**filters)
@@ -289,7 +311,10 @@ def delete_file_system_object(
try:
instance = _get_object(registration, ref=ref, team_id=entry.team_id)
- except ObjectDoesNotExist:
+ except (ObjectDoesNotExist, DjangoValidationError, ValueError, TypeError):
+ # A ref the lookup field can't hold (`FileSystem.ref` is a plain CharField, set by the
+ # caller when the row is created) is the same situation as one that resolves to nothing:
+ # the row references no object, so drop the row itself.
logger.warning("File system entry for type '%s' with ref '%s' has no backing object.", type_string, ref)
entry.delete()
return DeletionResult(
@@ -342,6 +367,37 @@ def delete_file_system_object(
)
+def get_restorable_object(type_string: str, ref: str, *, team_id: int | None) -> Any | None:
+ """Resolve the object an `undo_delete` would restore, or None when there is nothing to restore.
+
+ Returns None for unregistered types, types that can't be restored, refs with no backing object,
+ and objects that aren't currently soft-deleted. Callers must treat every None the same way:
+ a per-case outcome would let a caller probe which refs exist.
+ """
+ registration = _MODEL_REGISTRY.get(type_string)
+ if registration is None:
+ return None
+
+ capabilities = _introspect_model_capabilities(registration)
+ if not capabilities.has_soft_delete or not capabilities.can_restore:
+ return None
+
+ try:
+ instance = _get_object(registration, ref=ref, team_id=team_id)
+ except (ObjectDoesNotExist, DjangoValidationError, ValueError, TypeError):
+ # `ref` is caller-supplied and every model's lookup field rejects a different shape: an
+ # integer pk raises ValueError on "oops", a UUID pk raises ValidationError. Those are all
+ # the same answer as a missing object, and must return it identically so a caller can't
+ # tell a malformed ref from one that resolves to something they aren't allowed to see.
+ return None
+
+ assert capabilities.soft_delete_field is not None
+ if not getattr(instance, capabilities.soft_delete_field, False):
+ return None
+
+ return instance
+
+
def undo_delete(
*,
type_string: str,
@@ -374,15 +430,25 @@ def undo_delete(
team_id = getattr(team, "id", None)
try:
- instance = _get_object(registration, ref=ref, team_id=team_id)
+ instance = _get_object(registration, ref=ref, team_id=team_id, for_update=True)
except ObjectDoesNotExist as exc:
raise ValueError(f"Unable to restore {type_string} with ref '{ref}'") from exc
+ # Re-check the soft-delete flag here rather than trusting the caller's earlier check
+ # (get_restorable_object): that check and this restore run as separate queries, so a
+ # concurrent change to this object in between must not be silently overwritten by an
+ # unconditional restore - e.g. reviving a feature flag someone deliberately disabled in the
+ # gap between the check and this call. The row is locked for the rest of the caller's
+ # transaction, because reading it unlocked would leave the same gap between this check and
+ # the save below that the check exists to close.
+ assert capabilities.soft_delete_field is not None
+ if not getattr(instance, capabilities.soft_delete_field):
+ raise ValueError(f"{type_string} with ref '{ref}' is not currently deleted")
+
pre_hook = _PRE_RESTORE_HOOKS.get(type_string)
if pre_hook:
pre_hook(context, instance)
- assert capabilities.soft_delete_field is not None
setattr(instance, capabilities.soft_delete_field, False)
if restore_path and hasattr(instance, "_create_in_folder"):
diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.py
index ece7791a5bd2..bcc17a1a9854 100644
--- a/posthog/api/file_system/file_system.py
+++ b/posthog/api/file_system/file_system.py
@@ -1,7 +1,10 @@
import re
import shlex
+import logging
import builtins
-from typing import Any, cast
+from functools import cached_property
+from typing import Any, Optional, cast
+from uuid import UUID
from django.db import transaction
from django.db.models import Case, F, IntegerField, Q, QuerySet, Value, When
@@ -9,13 +12,19 @@ from django.db.models.functions import Concat, Lower
from drf_spectacular.utils import extend_schema
from rest_framework import filters, pagination, serializers, status, viewsets
+from rest_framework.exceptions import PermissionDenied
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.access_levels import (
+ FileSystemAccessLevelSerializerMixin,
+ denied_short_id_refs,
+ entries_missing_access_level,
+)
from posthog.api.file_system.deletion import (
HOG_FUNCTION_TYPES,
delete_file_system_object,
+ get_restorable_object,
is_file_system_type_registered,
undo_delete as undo_delete_object,
)
@@ -37,10 +46,17 @@ from posthog.models.file_system.file_system_view_log import get_recent_file_syst
from posthog.models.file_system.unfiled_file_saver import save_unfiled_files
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.settings import EE_AVAILABLE
from posthog.utils import str_to_bool
+logger = logging.getLogger(__name__)
+
DELETE_PREVIEW_ENTRY_LIMIT = 200
+# One message for every reason a restore is refused (missing, already live, or off-limits), so the
+# endpoint can't be used to learn which refs exist.
+UNDO_DELETE_REFUSED = "Couldn't restore this. It may already be restored, or you may not have access to it."
+
# Search-within-Recents scans this many of the user's most-recent views, then the text filter trims
# them to a page. Bounds the hydration key set so the query stays cheap on heavy view-log histories.
RECENTS_SEARCH_SCAN_LIMIT = 200
@@ -200,6 +216,62 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"undo_delete",
]
+ @cached_property
+ def _denied_short_id_refs(self) -> dict[tuple[str, int], builtins.list[str]]:
+ if not self.user_access_control:
+ return {}
+ return denied_short_id_refs(self.user_access_control, self.team.project_id)
+
+ @cached_property
+ def _accessible_team_ids(self) -> Optional[set[int]]:
+ """Environments in this project the user may see, or None when nothing needs filtering.
+
+ The tree deliberately spans every environment in the project, but project-level access is
+ configured per environment and a user can be denied one outright. Resource and object
+ rules don't express that: an environment with no rules of its own falls back to the
+ resource default, so a denied environment's rows would otherwise list and resolve as
+ editable. Mirrors the carve-outs in `filter_and_annotate_file_system_queryset`, which
+ already lets staff and org admins past every other check here.
+ """
+ user_access_control = self.user_access_control
+ if not user_access_control:
+ return None
+ if self.request.user.is_staff or user_access_control.is_organization_admin:
+ return None
+ if not EE_AVAILABLE or not user_access_control.access_controls_supported:
+ return None
+
+ team_ids = Team.objects.filter(project_id=self.team.project_id).values_list("id", flat=True)
+ return {
+ team_id
+ for team_id, team_access in user_access_control.for_team_ids(team_ids).items()
+ if team_access.has_project_access
+ }
+
+ def _filter_by_access_control(self, queryset: QuerySet) -> QuerySet:
+ if not self.user_access_control:
+ return queryset
+ accessible_team_ids = self._accessible_team_ids
+ if accessible_team_ids is not None:
+ queryset = queryset.filter(team_id__in=accessible_team_ids)
+ return self.user_access_control.filter_and_annotate_file_system_queryset(
+ queryset, extra_denied_refs=self._denied_short_id_refs
+ )
+
+ def _ensure_can_delete_objects(self, objects: builtins.list[tuple[str, str, int]]) -> None:
+ """Require editor access on every backing object the delete would reach.
+
+ The tree row itself has no access controls, so without this a delete routed through the
+ file system would bypass the level the object's own resource model requires. `objects` is
+ (type, ref, team_id) - team_id is each row's own team, since the tree can list rows from
+ sibling environments and the check has to run against the object's real team.
+ """
+ if not objects or not self.user_access_control:
+ return
+ denied = entries_missing_access_level(objects, self.user_access_control, self.team.project_id, "editor")
+ if denied:
+ raise PermissionDenied("You need editor access to delete this. Ask a project admin to grant it.")
+
def _basename_regex(self, value: str) -> str:
return rf"(^|(?<!\\)/)([^/]|\\.)*{re.escape(value)}([^/]|\\.)*$"
@@ -383,8 +455,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if search_param:
queryset = self._apply_search_to_queryset(queryset, search_param, basename_only=search_name_only)
- if self.user_access_control:
- queryset = self.user_access_control.filter_and_annotate_file_system_queryset(queryset)
+ queryset = self._filter_by_access_control(queryset)
if ref_param:
queryset = queryset.filter(ref=ref_param)
@@ -459,8 +530,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
search_param = request.query_params.get("search")
base_queryset = FileSystem.objects.filter(surface_q(self.file_system_surface), team_id=self.team.id)
- if self.user_access_control:
- base_queryset = self.user_access_control.filter_and_annotate_file_system_queryset(base_queryset)
+ base_queryset = self._filter_by_access_control(base_queryset)
if search_param:
base_queryset = self._apply_search_to_queryset(
base_queryset, search_param, basename_only=str_to_bool(request.query_params.get("search_name_only"))
@@ -491,7 +561,17 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
}
)
- def _ensure_can_delete(self, entry: FileSystem) -> None:
+ def _ensure_can_delete(self, entry: FileSystem) -> dict[UUID, bool]:
+ """Decide, and authorize, which of `entry`'s leaf rows carry the delete through to their
+ backing object - and lock that decision so a concurrent request can't change it before
+ `_delete_file_system_entry` acts on it (see the locking note below).
+
+ Returns a `{row_id: reaches_backing_object}` map that `destroy()` passes straight into
+ `_delete_file_system_entry`, so the actual delete reuses this locked decision instead of
+ recomputing an unlocked count of its own - two independent unlocked counts would let a
+ second concurrent delete of a sibling row change the answer in between, deleting the
+ backing object without ever having been through the editor check above.
+ """
stack: list[FileSystem] = [entry]
seen: set[str] = set()
entries_to_check: list[FileSystem] = []
@@ -509,37 +589,85 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if current.type == "folder":
descendants = FileSystem.objects.filter(path__startswith=f"{current.path}/")
descendants = self._scope_by_project_and_environment(descendants)
- if self.user_access_control:
- descendants = self.user_access_control.filter_and_annotate_file_system_queryset(descendants)
+ descendants = self._filter_by_access_control(descendants)
stack.extend(descendants)
continue
entries_to_check.append(current)
if not entries_to_check:
- return None
-
- ids_to_remove = [entry.id for entry in entries_to_check]
-
+ return {}
+
+ ids_to_remove = {entry.id for entry in entries_to_check}
+
+ # Several leaf rows can share one (team, type, ref) - that's the "last reference" case
+ # this whole check exists for - and a folder cascade can span several distinct objects.
+ # Group first so each distinct object is locked and counted exactly once, however many
+ # rows in this batch reference it.
+ # A ref-less row references no object, so it has no siblings to share a count with. It is
+ # keyed by its own id rather than pooled with every other ref-less row of its type, which
+ # would treat unrelated rows as references to one object.
+ entries_by_group: dict[tuple[int, str, Optional[str], str], list[FileSystem]] = {}
for current in entries_to_check:
- remaining = (
- FileSystem.objects.filter(team=current.team, type=current.type, ref=current.ref, shortcut=False)
- .exclude(id__in=ids_to_remove)
- .count()
- )
-
- if not is_file_system_type_registered(current.type):
+ group_key = (current.team_id, current.type, current.ref, "" if current.ref else str(current.id))
+ entries_by_group.setdefault(group_key, []).append(current)
+
+ objects_to_delete: builtins.list[tuple[str, str, int]] = []
+ reaches_backing_object: dict[UUID, bool] = {}
+
+ # Sorted so concurrent requests whose cascades overlap on more than one object always
+ # acquire the per-object locks in the same order - locking in traversal order (DFS over
+ # an unordered queryset) could have two such requests lock the same two objects in
+ # opposite order and deadlock, same failure mode `.order_by("id")` below prevents within
+ # one object's sibling set.
+ for (team_id, file_type, ref, _row_key), group in sorted(
+ entries_by_group.items(), key=lambda kv: (kv[0][0], kv[0][1], kv[0][2] or "", kv[0][3])
+ ):
+ if ref is None:
+ # No ref means no shared backing object, so there is no sibling set to count and
+ # nothing for a concurrent delete to race us to. Locking on (team, type, NULL)
+ # would instead row-lock every ref-less row of this type in the team for the rest
+ # of the transaction, serializing unrelated deletes behind this one.
+ remaining = 0
+ else:
+ # Lock every row referencing this object (not just the ones outside ids_to_remove)
+ # so a concurrent request deleting a sibling row locks the same row set in the
+ # same order and blocks on it, rather than each request locking a different subset
+ # and deadlocking against the other.
+ sibling_ids = {
+ row.id
+ for row in FileSystem.objects.select_for_update()
+ .filter(team_id=team_id, type=file_type, ref=ref, shortcut=False)
+ .order_by("id")
+ }
+ remaining = len(sibling_ids - ids_to_remove)
+ # When several rows in this batch reference the same object, only one of them may
+ # actually carry the deletion through - otherwise every row in the group would call
+ # delete_file_system_object independently, running its hooks and activity logging
+ # once per row instead of once for the object.
+ for current in group:
+ reaches_backing_object[current.id] = False
+ reaches_backing_object[group[0].id] = remaining == 0
+
+ if not is_file_system_type_registered(file_type):
continue
- if remaining == 0 and not current.ref:
+ if remaining == 0 and not ref:
# A registered-type row with no ref is a data-integrity error we refuse to delete.
- raise serializers.ValidationError(
- {"detail": f"Cannot delete type '{current.type}' without a reference."}
- )
+ raise serializers.ValidationError({"detail": f"Cannot delete type '{file_type}' without a reference."})
- return None
+ # Only the last row referencing an object carries the deletion through to the object
+ # itself; removing one of several rows leaves it untouched.
+ if remaining == 0 and ref:
+ objects_to_delete.append((file_type, ref, team_id))
- def _delete_file_system_entry(self, entry: FileSystem) -> builtins.list[dict[str, Any]]:
+ self._ensure_can_delete_objects(objects_to_delete)
+
+ return reaches_backing_object
+
+ def _delete_file_system_entry(
+ self, entry: FileSystem, reaches_backing_object: dict[UUID, bool]
+ ) -> builtins.list[dict[str, Any]]:
deleted_objects: list[dict[str, Any]] = []
if entry.shortcut:
@@ -549,23 +677,19 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if entry.type == "folder":
descendants = FileSystem.objects.filter(path__startswith=f"{entry.path}/")
descendants = self._scope_by_project_and_environment(descendants)
- if self.user_access_control:
- descendants = self.user_access_control.filter_and_annotate_file_system_queryset(descendants)
+ descendants = self._filter_by_access_control(descendants)
for child in descendants.order_by("depth", "path"):
- deleted_objects.extend(self._delete_file_system_entry(child))
+ deleted_objects.extend(self._delete_file_system_entry(child, reaches_backing_object))
entry.delete()
return deleted_objects
- remaining = (
- FileSystem.objects.filter(team=entry.team, type=entry.type, ref=entry.ref, shortcut=False)
- .exclude(id=entry.id)
- .count()
- )
-
if not is_file_system_type_registered(entry.type):
raise serializers.ValidationError({"detail": f"Cannot delete resources with type '{entry.type}'."})
- if remaining > 0:
+ # Reuses the locked decision from _ensure_can_delete rather than recounting - a row this
+ # method discovers on its own (e.g. created after that pass ran) defaults to "leave the
+ # backing object alone", the same safe outcome an unauthorized delete would get.
+ if not reaches_backing_object.get(entry.id, False):
entry.delete()
return deleted_objects
@@ -600,8 +724,8 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
deleted_objects: list[dict[str, Any]]
with transaction.atomic():
- self._ensure_can_delete(instance)
- deleted_objects = self._delete_file_system_entry(instance)
+ reaches_backing_object = self._ensure_can_delete(instance)
+ deleted_objects = self._delete_file_system_entry(instance, reaches_backing_object)
if instance.type == "folder":
leftovers = self._scope_by_project(FileSystem.objects.filter(path__startswith=f"{original_path}/"))
@@ -620,11 +744,15 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer = UndoDeleteRequestSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
- items = serializer.validated_data["items"]
+ # Each restore locks its target row and holds it to the end of the transaction, so two
+ # requests naming the same objects in opposite order would each hold one and block on the
+ # other. Sorting means every request takes those locks in the same order instead.
+ items = sorted(serializer.validated_data["items"], key=lambda item: (item["type"], item["ref"]))
undo_results: list[dict[str, str]] = []
with transaction.atomic():
for item in items:
+ self._ensure_can_restore(item["type"], item["ref"])
try:
restored_instance = undo_delete_object(
type_string=item["type"],
@@ -636,17 +764,26 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
organization=getattr(self, "organization", None),
)
except ValueError:
- import logging
-
- logging.exception(
+ logger.exception(
"Exception during undo_delete_object (type=%s, ref=%s)", item.get("type"), item.get("ref")
)
- raise serializers.ValidationError({"detail": "An internal error occurred during undo delete."})
+ raise serializers.ValidationError({"detail": UNDO_DELETE_REFUSED})
self._restore_file_system_path(restored_instance, item)
undo_results.append({"type": item["type"], "ref": item["ref"]})
return Response({"undone": undo_results}, status=status.HTTP_200_OK)
+ def _ensure_can_restore(self, type_string: str, ref: str) -> None:
+ """`undo_delete` takes a caller-supplied (type, ref) rather than a tree row, so neither
+ the tree's visibility filter nor `get_object` has run by the time we get here."""
+ instance = get_restorable_object(type_string, ref, team_id=self.team.id)
+ allowed = instance is not None and (
+ not self.user_access_control
+ or self.user_access_control.check_access_level_for_object(instance, required_level="editor")
+ )
+ if not allowed:
+ raise serializers.ValidationError({"detail": UNDO_DELETE_REFUSED})
+
@action(methods=["GET"], detail=False)
def unfiled(self, request: Request, *args: Any, **kwargs: Any) -> Response:
query_serializer = UnfiledFilesQuerySerializer(data=request.query_params)
@@ -659,7 +796,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if self.user_access_control:
# nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get (IDs from prior team-scoped query)
qs = FileSystem.objects.filter(id__in=[f.id for f in files])
- qs = self.user_access_control.filter_and_annotate_file_system_queryset(qs)
+ qs = self._filter_by_access_control(qs)
file_count = qs.count()
else:
file_count = len(files)
@@ -688,8 +825,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
with transaction.atomic():
qs = FileSystem.objects.filter(path__startswith=f"{instance.path}/")
qs = self._scope_by_project_and_environment(qs)
- if self.user_access_control:
- qs = self.user_access_control.filter_and_annotate_file_system_queryset(qs)
+ qs = self._filter_by_access_control(qs)
for file in qs:
file.path = new_path + file.path[len(instance.path) :]
file.depth = len(split_path(file.path))
@@ -738,8 +874,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
with transaction.atomic():
qs = FileSystem.objects.filter(path__startswith=f"{instance.path}/")
qs = self._scope_by_project_and_environment(qs)
- if self.user_access_control:
- qs = self.user_access_control.filter_and_annotate_file_system_queryset(qs)
+ qs = self._filter_by_access_control(qs)
for file in qs:
file.pk = None # This removes the id
@@ -782,8 +917,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
qs = FileSystem.objects.filter(path__startswith=f"{instance.path}/").order_by("depth", "path")
qs = self._scope_by_project_and_environment(qs)
- if self.user_access_control:
- qs = self.user_access_control.filter_and_annotate_file_system_queryset(qs)
+ qs = self._filter_by_access_control(qs)
total_count = qs.count()
preview_entries = list(qs[:DELETE_PREVIEW_ENTRY_LIMIT])
@@ -855,8 +989,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
qs = FileSystem.objects.filter(path__startswith=f"{path_param}/").order_by("depth", "path")
qs = self._scope_by_project_and_environment(qs)
- if self.user_access_control:
- qs = self.user_access_control.filter_and_annotate_file_system_queryset(qs)
+ qs = self._filter_by_access_control(qs)
total_count = qs.count()
preview_entries = list(qs[:DELETE_PREVIEW_ENTRY_LIMIT])
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index da49d1065ab1..122ac9d271f3 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -11,9 +11,11 @@ from django.core.cache import cache
from django.db import connection
from django.test.utils import CaptureQueriesContext
+from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIRequestFactory
+from posthog.api.file_system.deletion import undo_delete
from posthog.api.file_system.file_system import DELETE_PREVIEW_ENTRY_LIMIT
from posthog.models import OrganizationMembership, Project, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -1150,12 +1152,14 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):
created_by=self.user,
)
- def _create_access_control(self, resource, resource_id, access_level, organization_member=None, role=None):
+ def _create_access_control(
+ self, resource, resource_id, access_level, organization_member=None, role=None, team=None
+ ):
"""
- Helper to create an AccessControl row. Ensures 'team' is set.
+ Helper to create an AccessControl row. Defaults to self.team.
"""
return AccessControl.objects.create(
- team=self.team,
+ team=team or self.team,
resource=resource,
resource_id=resource_id,
access_level=access_level,
@@ -1163,6 +1167,11 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):
role=role,
)
+ # A second environment in the same project. The tree lists rows from every environment, so
+ # access resolution has to hold across that boundary, not just within self.team.
+ def _create_sibling_team(self) -> Team:
+ return Team.objects.create(project=self.project, organization=self.organization, name="Env-2")
+
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_list_excludes_items_with_none_access(self, mock_flag):
self._create_access_control(resource="dashboard", resource_id=self.file_b.ref, access_level="none")
@@ -1404,6 +1413,284 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):
# The warm request skips the short_id->pk translation query the cold request had to run
self.assertLess(len(warm_ctx), len(cold_ctx))
+ def _grant_to_user(
+ self, resource: str, resource_id: str, access_level: str, team: Team | None = None
+ ) -> AccessControl:
+ membership = OrganizationMembership.objects.get(organization=self.organization, user=self.user)
+ return self._create_access_control(
+ resource=resource,
+ resource_id=resource_id,
+ access_level=access_level,
+ organization_member=membership,
+ team=team,
+ )
+
+ # Replaces the auto-filed tree rows for an object with a single entry, because deleting an
+ # entry only reaches the backing object once it is the last row referencing it.
+ def _sole_entry_for(self, *, file_type: str, ref: str, path: str, team: Team | None = None) -> FileSystem:
+ team = team or self.team
+ FileSystem.objects.filter(team=team, type=file_type, ref=ref).delete()
+ return FileSystem.objects.create(
+ team=team,
+ path=path,
+ depth=len(path.split("/")),
+ type=file_type,
+ ref=ref,
+ created_by=self.other_user,
+ )
+
+ @parameterized.expand([("the_entry_itself",), ("an_ancestor_folder",)])
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_destroy_requires_editor_access_to_the_backing_object(self, target, mock_flag):
+ dashboard = Dashboard.objects.create(team=self.team, name="Viewer only", created_by=self.other_user)
+ entry = self._sole_entry_for(file_type="dashboard", ref=str(dashboard.pk), path="Docs/Viewer only")
+ self._grant_to_user("dashboard", str(dashboard.pk), "viewer")
+
+ delete_id = entry.id if target == "the_entry_itself" else self.folder.id
+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{delete_id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ dashboard.refresh_from_db()
+ self.assertFalse(dashboard.deleted)
+ self.assertTrue(FileSystem.objects.filter(pk=entry.pk).exists())
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_none_access_hides_entries_whose_ref_is_a_short_id(self, mock_flag):
+ insight = Insight.objects.create(team=self.team, name="Denied insight", created_by=self.other_user)
+ entry = self._sole_entry_for(file_type="insight", ref=insight.short_id, path="Docs/Denied insight")
+ # AccessControl rows are always keyed by pk, while insight entries reference the short_id
+ self._create_access_control(resource="insight", resource_id=str(insight.pk), access_level="none")
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/file_system/")
+ self.assertEqual(list_response.status_code, status.HTTP_200_OK, list_response.content)
+ paths = {item["path"] for item in list_response.json()["results"]}
+ self.assertNotIn("Docs/Denied insight", paths)
+
+ delete_response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")
+ self.assertEqual(delete_response.status_code, status.HTTP_404_NOT_FOUND, delete_response.content)
+
+ def test_undo_delete_refuses_an_object_that_is_not_deleted(self):
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="paused-flag",
+ name="Paused flag",
+ active=False,
+ created_by=self.other_user,
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/file_system/undo_delete/",
+ {"items": [{"type": "feature_flag", "ref": str(flag.pk)}]},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ flag.refresh_from_db()
+ self.assertFalse(flag.active)
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_undo_delete_requires_editor_access_to_the_backing_object(self, mock_flag):
+ dashboard = Dashboard.objects.create(
+ team=self.team, name="Deleted dashboard", created_by=self.other_user, deleted=True
+ )
+ self._grant_to_user("dashboard", str(dashboard.pk), "viewer")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/file_system/undo_delete/",
+ {"items": [{"type": "dashboard", "ref": str(dashboard.pk)}]},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ dashboard.refresh_from_db()
+ self.assertTrue(dashboard.deleted)
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_destroy_requires_editor_access_in_the_objects_own_environment(self, mock_flag):
+ team2 = self._create_sibling_team()
+ dashboard = Dashboard.objects.create(team=team2, name="Sibling env, viewer only", created_by=self.other_user)
+ entry = self._sole_entry_for(
+ file_type="dashboard", ref=str(dashboard.pk), path="Docs/Sibling env viewer", team=team2
+ )
+ self._grant_to_user("dashboard", str(dashboard.pk), "viewer", team=team2)
+
+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ dashboard.refresh_from_db()
+ self.assertFalse(dashboard.deleted)
+ self.assertTrue(FileSystem.objects.filter(pk=entry.pk).exists())
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_none_access_hides_short_id_entries_from_a_sibling_environment(self, mock_flag):
+ team2 = self._create_sibling_team()
+ insight = Insight.objects.create(team=team2, name="Sibling env, denied", created_by=self.other_user)
+ entry = self._sole_entry_for(
+ file_type="insight", ref=insight.short_id, path="Docs/Sibling env denied", team=team2
+ )
+ # AccessControl rows are always keyed by pk, while insight entries reference the short_id
+ self._create_access_control(resource="insight", resource_id=str(insight.pk), access_level="none", team=team2)
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/file_system/")
+ self.assertEqual(list_response.status_code, status.HTTP_200_OK, list_response.content)
+ paths = {item["path"] for item in list_response.json()["results"]}
+ self.assertNotIn("Docs/Sibling env denied", paths)
+
+ delete_response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")
+ self.assertEqual(delete_response.status_code, status.HTTP_404_NOT_FOUND, delete_response.content)
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_destroy_does_not_collapse_access_levels_across_teams_sharing_a_ref(self, mock_flag):
+ team2 = self._create_sibling_team()
+ dashboard = Dashboard.objects.create(team=team2, name="Victim", created_by=self.other_user)
+ self._grant_to_user("dashboard", str(dashboard.pk), "viewer", team=team2)
+ self._sole_entry_for(file_type="dashboard", ref=str(dashboard.pk), path="Shared/Victim", team=team2)
+ # Planted in the requester's own team, pointing at the victim's object via a caller-supplied ref
+ FileSystem.objects.create(
+ team=self.team,
+ path="Shared/Planted",
+ depth=2,
+ type="dashboard",
+ ref=str(dashboard.pk),
+ created_by=self.user,
+ )
+ folder = FileSystem.objects.create(team=self.team, path="Shared", depth=1, type="folder", created_by=self.user)
+
+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{folder.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ dashboard.refresh_from_db()
+ self.assertFalse(dashboard.deleted)
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_destroy_does_not_translate_a_short_id_through_another_teams_object(self, mock_flag):
+ team2 = self._create_sibling_team()
+ victim_notebook = Notebook.objects.create(team=team2, short_id="colliding-id", created_by=self.other_user)
+ self._grant_to_user("notebook", str(victim_notebook.pk), "viewer", team=team2)
+ victim_entry = self._sole_entry_for(
+ file_type="notebook", ref=victim_notebook.short_id, path="Docs/Victim notebook", team=team2
+ )
+ # Planted in the requester's own team: same short_id, but self.user is its creator here
+ Notebook.objects.create(team=self.team, short_id="colliding-id", created_by=self.user)
+
+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{victim_entry.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ victim_notebook.refresh_from_db()
+ self.assertFalse(victim_notebook.deleted)
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_destroy_locks_and_deletes_a_shared_reference_once_per_object(self, mock_flag):
+ dashboard = Dashboard.objects.create(team=self.team, name="Shared twice", created_by=self.other_user)
+ FileSystem.objects.filter(team=self.team, type="dashboard", ref=str(dashboard.pk)).delete()
+ FileSystem.objects.create(
+ team=self.team, path="Shared/A", depth=2, type="dashboard", ref=str(dashboard.pk), created_by=self.user
+ )
+ FileSystem.objects.create(
+ team=self.team, path="Shared/B", depth=2, type="dashboard", ref=str(dashboard.pk), created_by=self.user
+ )
+ folder = FileSystem.objects.create(team=self.team, path="Shared", depth=1, type="folder", created_by=self.user)
+
+ with CaptureQueriesContext(connection) as ctx:
+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{folder.id}/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ dashboard.refresh_from_db()
+ self.assertTrue(dashboard.deleted)
+
+ deleted = response.json()["deleted"]
+ dashboard_deletions = [
+ item for item in deleted if item["type"] == "dashboard" and item["ref"] == str(dashboard.pk)
+ ]
+ self.assertEqual(len(dashboard_deletions), 1, deleted)
+
+ lock_queries = [q for q in ctx.captured_queries if "FOR UPDATE" in q["sql"]]
+ self.assertEqual(len(lock_queries), 1, lock_queries)
+
+ def test_undo_delete_function_refuses_to_restore_a_live_object(self):
+ flag = FeatureFlag.objects.create(
+ team=self.team, key="live-flag", name="Live flag", created_by=self.other_user, deleted=False
+ )
+
+ with self.assertRaises(ValueError):
+ undo_delete(type_string="feature_flag", ref=str(flag.pk), user=self.user, team=self.team)
+
+ flag.refresh_from_db()
+ self.assertFalse(flag.deleted)
+
+ @parameterized.expand([("integer_pk", "dashboard"), ("uuid_pk", "hog_function/destination")])
+ def test_undo_delete_refuses_a_ref_the_lookup_field_rejects(self, _name, file_type):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/file_system/undo_delete/",
+ {"items": [{"type": file_type, "ref": "not-a-valid-ref"}]},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_a_ref_the_lookup_field_rejects_does_not_break_list_or_delete(self, mock_flag):
+ # created_by=None is what an unfiled row looks like, and it's what forces the creator
+ # lookup that pushes the raw ref into the query on the list path
+ entry = FileSystem.objects.create(
+ team=self.team,
+ path="Docs/Broken ref",
+ depth=2,
+ type="dashboard",
+ ref="not-a-number",
+ created_by=None,
+ )
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/file_system/")
+ self.assertEqual(list_response.status_code, status.HTTP_200_OK, list_response.content)
+
+ delete_response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")
+ self.assertEqual(delete_response.status_code, status.HTTP_200_OK, delete_response.content)
+ self.assertFalse(FileSystem.objects.filter(pk=entry.pk).exists())
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_environment_denied_at_project_level_is_neither_listed_nor_deletable(self, mock_flag):
+ team2 = self._create_sibling_team()
+ membership = OrganizationMembership.objects.get(organization=self.organization, user=self.user)
+ self._create_access_control(
+ resource="project",
+ resource_id=str(team2.id),
+ access_level="none",
+ organization_member=membership,
+ team=team2,
+ )
+ dashboard = Dashboard.objects.create(team=team2, name="Denied env", created_by=self.other_user)
+ entry = self._sole_entry_for(file_type="dashboard", ref=str(dashboard.pk), path="Docs/Denied env", team=team2)
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/file_system/")
+ self.assertEqual(list_response.status_code, status.HTTP_200_OK, list_response.content)
+ paths = {item["path"] for item in list_response.json()["results"]}
+ self.assertNotIn("Docs/Denied env", paths)
+
+ delete_response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")
+ self.assertEqual(delete_response.status_code, status.HTTP_404_NOT_FOUND, delete_response.content)
+ dashboard.refresh_from_db()
+ self.assertFalse(dashboard.deleted)
+
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_list_queries_do_not_scale_with_environment_count(self, mock_flag):
+ insight = Insight.objects.create(team=self.team, name="Denied insight", created_by=self.other_user)
+ self._create_access_control(resource="insight", resource_id=str(insight.pk), access_level="none")
+
+ with CaptureQueriesContext(connection) as one_environment:
+ self.client.get(f"/api/projects/{self.team.id}/file_system/")
+
+ added_environments = 3
+ for _ in range(added_environments):
+ self._create_sibling_team()
+
+ with CaptureQueriesContext(connection) as several_environments:
+ self.client.get(f"/api/projects/{self.team.id}/file_system/")
+
+ extra = len(several_environments.captured_queries) - len(one_environment.captured_queries)
+ # Each added environment costs one access-control preload. Anything beyond that means an
+ # environment is being resolved more than once per request.
+ self.assertLessEqual(extra, added_environments * 2, several_environments.captured_queries)
+
def test_created_at_filters(self):
"""
Verify we can filter by created_at greater-than and less-than.
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index defe6caf8820..7bef040b2804 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -1,6 +1,6 @@
import json
from collections import defaultdict
-from collections.abc import Sequence
+from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
from enum import Enum
from functools import cache, cached_property
@@ -517,6 +517,7 @@ class UserAccessControl:
self._user = user
self._team = team
self._cache: dict[str, list[AccessControl]] = {}
+ self._sibling_team_access_controls: dict[int, UserAccessControl] = {}
if not organization_id and team:
organization_id = str(team.organization_id)
@@ -532,6 +533,43 @@ class UserAccessControl:
self.__dict__.pop("blocked_resources", None)
self.__dict__.pop("_organization_membership", None)
self.__dict__.pop("_user_role_ids", None)
+ # Dropped rather than cleared through: each sibling carries its own preloaded rows, and
+ # some were primed from the caches being cleared here
+ self._sibling_team_access_controls = {}
+
+ def for_team_ids(self, team_ids: Iterable[int]) -> dict[int, "UserAccessControl"]:
+ """This user's access control for each of the given teams, memoized on this instance.
+
+ An instance only ever answers for the single team it was built with, and preloads that
+ team's rows on first use. Resolving objects across several teams therefore needs one
+ instance per team, and a request can reach that more than once (the file system tree
+ spans every environment in a project and resolves access on both its filter and its
+ serializer pass). Memoizing means the second pass reuses the first pass's instances,
+ including their preloaded rows, instead of rebuilding and re-querying them.
+ """
+ by_team: dict[int, UserAccessControl] = {}
+ missing: set[int] = set()
+ for team_id in team_ids:
+ if self._team is not None and team_id == self._team.id:
+ by_team[team_id] = self
+ elif team_id in self._sibling_team_access_controls:
+ by_team[team_id] = self._sibling_team_access_controls[team_id]
+ else:
+ missing.add(team_id)
+
+ if missing:
+ for team in Team.objects.filter(id__in=missing):
+ sibling = UserAccessControl(self._user, team=team)
+ if sibling._organization_id == self._organization_id:
+ # Org membership and role ids don't vary by team, so seed them from this
+ # instance rather than letting each sibling re-query them. Written straight
+ # into __dict__ because that is where cached_property stores its value.
+ sibling.__dict__["_organization_membership"] = self._organization_membership
+ sibling.__dict__["_user_role_ids"] = self._user_role_ids
+ self._sibling_team_access_controls[team.id] = sibling
+ by_team[team.id] = sibling
+
+ return by_team
@cached_property
def _organization_membership(self) -> Optional[OrganizationMembership]:
@@ -587,6 +625,13 @@ class UserAccessControl:
(a userless build fails closed), so forwarding just the access control isn't enough."""
return self._user
+ @property
+ def team(self) -> Optional[Team]:
+ """The team this instance's checks are scoped to. Callers resolving access for objects
+ that may live outside this team (e.g. a cross-environment listing) need it to tell
+ whether they can reuse this instance or must build one scoped to the object's own team."""
+ return self._team
+
@property
def rbac_supported(self) -> bool:
if not self._organization:
@@ -1220,6 +1265,20 @@ class UserAccessControl:
level = self.access_level_for_resource(resource)
return bool(level and level != NO_ACCESS_LEVEL)
+ @cached_property
+ def has_project_access(self) -> bool:
+ """Whether the user has any access to this instance's own team at the project level.
+
+ Resource and object rules only answer what the user may do with a kind of thing inside a
+ team, and fall back to `default_access_level` for a team that has no rules of its own. On
+ their own they will therefore grant editor in a team the user was explicitly denied, so
+ anything resolving access across several teams has to consult this separately.
+ """
+ if self._team is None:
+ return True
+ level = self.access_level_for_object(self._team, "project")
+ return bool(level and level != NO_ACCESS_LEVEL)
+
@cached_property
def blocked_resources(self) -> list[str]:
"""Sorted list of resources the user has no access to at the resource level."""
@@ -1228,10 +1287,52 @@ class UserAccessControl:
candidate_resources = {ac.resource for ac in self._cached_access_controls if ac.resource_id is None}
return sorted(resource for resource in candidate_resources if not self.has_resource_access(resource))
- def filter_and_annotate_file_system_queryset(self, queryset: QuerySet["FileSystem"]) -> QuerySet["FileSystem"]:
+ def object_ids_matching(
+ self, resources: Sequence[APIScopeObject], predicate: Callable[[_AccessControl], bool]
+ ) -> dict[str, set[str]]:
+ """Object ids whose access control rows satisfy `predicate`, per resource.
+
+ Considers the same rows the queryset filters consider: every row applicable to this user
+ for the resource, whether it came from the team default, their membership, or a role.
+ Rows without a `resource_id` are resource-level rather than object-level and are skipped.
+
+ `predicate` decides per row, so a resource appears in the result when *any* of its rows
+ matches. Callers wanting a rule that depends on the whole set for an object (for example
+ "explicit rules win over defaults") want `_blocked_and_allowed_object_ids` instead.
+ """
+ matched: dict[str, set[str]] = {}
+ for resource in resources:
+ object_ids = {
+ access_control.resource_id
+ for access_control in self._get_access_controls(self._access_controls_filters_for_queryset(resource))
+ if access_control.resource_id and predicate(access_control)
+ }
+ if object_ids:
+ matched[resource] = object_ids
+ return matched
+
+ def none_denied_object_ids(self, resources: Sequence[APIScopeObject]) -> dict[str, set[str]]:
+ """Object ids the user has a 'none' grant on, per resource.
+
+ Mirrors the row matching `filter_and_annotate_file_system_queryset` does in SQL: any
+ applicable row (team default, member, or role) at level 'none' denies the object. Kept as
+ a named method rather than a predicate at the call site so the tree filter's two halves,
+ this one and its SQL counterpart, can't drift onto different rules.
+ """
+ return self.object_ids_matching(resources, lambda ac: ac.access_level == NO_ACCESS_LEVEL)
+
+ def filter_and_annotate_file_system_queryset(
+ self, queryset: QuerySet["FileSystem"], extra_denied_refs: Optional[dict[tuple[str, int], list[str]]] = None
+ ) -> QuerySet["FileSystem"]:
"""
Annotate each FileSystem with the effective_access_level (either 'none' or 'some')
and exclude items that end up with 'none', unless the user is the creator or project-admin or org-admin/staff.
+
+ `extra_denied_refs` maps a (file system type, team_id) pair to refs denied by a grant this
+ queryset's own `ref`-to-`resource_id` comparison can't see, because the ref isn't the
+ object's primary key. Keyed by team_id, like the rest of this method, because the queryset
+ can span every environment in a project - a denial made in one team must not hide a
+ same-valued ref that happens to belong to a different team.
"""
user = self._user
@@ -1298,7 +1399,12 @@ class UserAccessControl:
# 4) Exclude items that are "none" if the user is not the creator,
# not a project admin, and not an org-admin/staff (already handled in step #1).
- queryset = queryset.exclude(Q(effective_access_level="none") & Q(is_project_admin=False) & ~Q(created_by=user))
+ denied = Q(effective_access_level="none")
+ for (entry_type, team_id), refs in (extra_denied_refs or {}).items():
+ if refs:
+ denied |= Q(team_id=team_id, type=entry_type, ref__in=refs)
+
+ queryset = queryset.exclude(denied & Q(is_project_admin=False) & ~Q(created_by=user))
return queryset