:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(rbac): fail closed in queryset filter when resource access is none (#88569)
Alex Lider15a0e9364be3
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex 079c6a3e71d6..94e448d9d3cf 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -395,8 +395,8 @@ class EntitySearchContext:def _list_feature_flags_sync(self, limit: int = 100, offset: int = 0, active_filter: str | None = None) -> tuple[list[dict[str, Any]], int]:- # Resource-level gate: filter_queryset_by_access_level only prunes object-level denials, so a- # role without feature flag access would still see flags here (also reachable via list_data).+ # Stricter than filter_queryset_by_access_level's fail-closed baseline: a caller without+ # feature flag access gets nothing, not even flags they created (also reachable via list_data).if not self.user_access_control.check_access_level_for_resource("feature_flag", "viewer"):return [], 0diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex ae21d735efe8..0f1836d8c115 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -890,9 +890,8 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVreturn queryset.none()return queryset- # filter_queryset_by_access_level trusts the view to have enforced resource-level access- # already, and this view is authorized as `comment` — so a caller denied the ticket resource- # would otherwise get the unfiltered ticket queryset back here.+ # Stricter than filter_queryset_by_access_level's fail-closed baseline: a caller denied+ # the ticket resource sees no ticket comments at all, not even on tickets they created.if not self.user_access_control.check_access_level_for_resource("ticket", "viewer") and not self.user_access_control.has_any_specific_access_for_resource("ticket", "viewer"):diff --git a/posthog/api/search.py b/posthog/api/search.pyindex f735a8517485..5913fe73655a 100644--- a/posthog/api/search.py+++ b/posthog/api/search.py@@ -124,9 +124,9 @@ class SearchViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@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."+ "Full-text search across project entities. Objects the user cannot access are left out. "+ "Each result includes `user_access_level`, the requesting user's resolved access level for "+ "that object; `null` when access controls don't apply to the entity type."),)def list(self, request: Request, **kw) -> HttpResponse:diff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.pyindex 4c64b6947d39..afb89210dac5 100644--- a/posthog/api/test/test_search.py+++ b/posthog/api/test/test_search.py@@ -400,18 +400,16 @@ class TestSearchAccessLevels(APIBaseTest):if result["type"] == entity_type}- def test_blocked_resource_results_are_annotated_none(self):+ def test_blocked_resource_results_are_hidden_except_own(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)+ own = FeatureFlag.objects.create(key="searchable-b", team=self.team, created_by=self.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, "feature_flag")) == {str(own.id)}assert set(self._levels_by_result_id(response, "event_definition").values()) == {None}def test_object_grants_resolve_by_pk_for_short_id_entities(self):diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.pyindex db53e205adb5..873f94c6bdb2 100644--- a/products/access_control/backend/facade/user_access_control.py+++ b/products/access_control/backend/facade/user_access_control.py@@ -1124,9 +1124,10 @@ class UserAccessControl:decision = self._blocked_and_allowed_object_ids(access_controls)# Apply filtering logic based on resource-level access- if not self.has_resource_access(resource) and decision.allowed_ids:- # User has "none" resource access but specific object access- # Only show objects they have explicit access to (plus created objects)+ if not self.has_resource_access(resource):+ # Resource-level "none": show only granted objects and the user's own objects, also+ # when there are no grants at all. Logic-layer and background callers reach this+ # filter with no permission layer above it, so it must fail closed on its own.if model_has_creator:queryset = queryset.filter(Q(id__in=decision.allowed_ids) | Q(created_by=self._user))else:diff --git a/products/access_control/backend/tests/test_user_access_control.py b/products/access_control/backend/tests/test_user_access_control.pyindex 2f3393b95382..4f8698afa295 100644--- a/products/access_control/backend/tests/test_user_access_control.py+++ b/products/access_control/backend/tests/test_user_access_control.py@@ -1286,6 +1286,23 @@ class TestSpecificObjectAccessControl(BaseUserAccessControlTest):assert self.notebook_3.id in notebook_ids # Created by userassert self.notebook_2.id not in notebook_ids # No access+ def test_filter_queryset_with_none_resource_and_no_grants_shows_only_created(self):+ from products.notebooks.backend.models import Notebook++ self._create_access_control(resource="notebook", access_level="none")+ self._clear_uac_caches()++ notebook_ids = list(+ self.user_access_control.filter_queryset_by_access_level(Notebook.objects.all()).values_list(+ "id", flat=True+ )+ )++ # Fail closed without object grants: only self-created notebooks, never the unfiltered+ # queryset. Logic-layer and background callers reach this filter with no permission layer+ # above it, so it cannot rely on the view to enforce the resource level.+ assert notebook_ids == [self.notebook_3.id]+def test_filter_queryset_by_access_level_with_resource_access(self):"""Test queryset filtering when user has resource-level access"""from products.notebooks.backend.models import Notebookdiff --git a/products/access_control/backend/tests/test_user_access_control_pbt.py b/products/access_control/backend/tests/test_user_access_control_pbt.pyindex bcb945ad973c..0db74a53f2d2 100644--- a/products/access_control/backend/tests/test_user_access_control_pbt.py+++ b/products/access_control/backend/tests/test_user_access_control_pbt.py@@ -466,7 +466,7 @@ def oracle_visible_object_ids(has_resource_access = oracle_resource_access_level(resource, resource_specs, is_org_admin) != NO_ACCESS_LEVELcreators = creator_ids if model_has_creator else set()- if not has_resource_access and allowed:+ if not has_resource_access:return (allowed | creators) & all_idsif blocked:return all_ids - (blocked - creators)@@ -741,8 +741,13 @@ class TestUserAccessControlProperties(BaseAccessControlPropertyTest):allowlisted = uac.allowlisted_resource_ids_by_scope.get(resource)blocked = uac.blocked_resource_ids_by_scope.get(resource, frozenset())model_has_creator = model_has_created_by(model_cls)+ has_resource_access = uac.has_resource_access(resource)def guard_admits(object_id: str) -> bool:+ # No resource access and no allowlist: Database.create_for drops the table, so+ # nothing is readable.+ if not has_resource_access and not allowlisted:+ return Falseif model_has_creator and object_id in creator_ids:return Trueif allowlisted:@@ -750,7 +755,7 @@ class TestUserAccessControlProperties(BaseAccessControlPropertyTest):return object_id not in blockedvisible = {object_id for object_id in object_specs_by_id if guard_admits(object_id)}- assert visible == oracle_visible_object_ids(+ expected = oracle_visible_object_ids(resource,resource_specs,object_specs_by_id,@@ -758,6 +763,12 @@ class TestUserAccessControlProperties(BaseAccessControlPropertyTest):model_has_creator=model_has_creator,is_org_admin=False,)+ if has_resource_access or allowlisted:+ assert visible == expected+ else:+ # REST still shows the user's own rows here. HogQL has no table to show them from.+ assert visible == set()+ assert expected <= creator_ids@given(data=object_resource_and_rows(),diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex 454eab667205..e4d95d3932d4 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -25,11 +25,10 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, NamedTuplefrom uuid import UUID-from django.db.models import Q, QuerySet+from django.db.models import QuerySetfrom posthog.models.team import Team-from products.access_control.backend.facade.user_access_control import NO_ACCESS_LEVELfrom products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedErrorfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.sources import github_schema_repo_endpoint@@ -321,16 +320,6 @@ def _accessible_sources()if user_access_control is not None:sources = user_access_control.filter_queryset_by_access_level(sources)- if not user_access_control.has_resource_access("external_data_source"):- # "none" resource-level access: the platform filter drops nothing when the user holds no- # object grants, so fail closed here to self-created or explicitly granted sources.- granted_ids = [- source.id- for source in sources- if (level := user_access_control.access_level_for_object(source, explicit=True))- and level != NO_ACCESS_LEVEL- ]- sources = sources.filter(Q(created_by=user_access_control.user) | Q(id__in=granted_ids))return sourcesdiff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.pyindex 918e5ee13ce9..6dce0a336216 100644--- a/products/engineering_analytics/backend/tests/test_views.py+++ b/products/engineering_analytics/backend/tests/test_views.py@@ -42,9 +42,9 @@ class TestListGithubSourcesAccessControl(BaseTest):self.organization.save()def test_none_resource_access_fails_closed_to_self_created_sources(self) -> None:- # filter_queryset_by_access_level returns the queryset UNFILTERED for a user with "none"- # resource access and no object grants — without the guard, such a user enumerates every- # GitHub source on the team.+ # A user with "none" resource access and no object grants must not enumerate the+ # team's sources. The product surface relies on filter_queryset_by_access_level to+ # fail closed here.mine = create_github_source(self.team, prefix="mine_", source_id="gh-mine")mine.created_by = self.usermine.save()@@ -59,9 +59,14 @@ class TestListGithubSourcesAccessControl(BaseTest):)assert [source.id for source in visible] == [str(mine.id)]- # An explicit object grant survives the fail-closed guard.+ # An explicit object grant survives the fail-closed guard. The filter counts only member+ # and role rows as grants. A default ("everyone") object row does not count.AccessControl.objects.create(- team=self.team, resource="external_data_source", resource_id=str(theirs.id), access_level="editor"+ team=self.team,+ resource="external_data_source",+ resource_id=str(theirs.id),+ access_level="editor",+ organization_member=self.organization_membership,)visible = list_github_sources(team=self.team, user_access_control=UserAccessControl(user=self.user, team=self.team)diff --git a/products/replay_vision/backend/tests/helpers.py b/products/replay_vision/backend/tests/helpers.pyindex 17c666e5d2bf..75b8c1b49fba 100644--- a/products/replay_vision/backend/tests/helpers.py+++ b/products/replay_vision/backend/tests/helpers.py@@ -2,7 +2,7 @@ from typing import Anyfrom django.utils import timezone-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.models.utils import uuid7from products.experiments.backend.models.experiment import Experiment@@ -54,11 +54,11 @@ def seed_scanner_spend(scanner: ReplayScanner, credits: int, *, observations: in)-def create_experiment(team: Team, flag_key: str) -> Experiment:+def create_experiment(team: Team, flag_key: str, created_by: User | None = None) -> Experiment:"""A launched-enough experiment with a multivariate flag, for targeting tests."""flag = FeatureFlag.objects.create(team=team,key=flag_key,filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)- return Experiment.objects.create(team=team, name=f"exp-{flag_key}", feature_flag=flag)+ return Experiment.objects.create(team=team, name=f"exp-{flag_key}", feature_flag=flag, created_by=created_by)diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.pyindex 71b642a3b7db..befff1b569a9 100644--- a/products/replay_vision/backend/tests/test_access_control.py+++ b/products/replay_vision/backend/tests/test_access_control.py@@ -224,7 +224,7 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):def test_experiment_targeting_hidden_from_a_viewer_without_experiment_access(self) -> None:# A scanner is viewable at a coarser grain than its targeted experiment; a viewer who can't# access the experiment must not learn its id or variants from the scanner payload.- experiment = create_experiment(self.team, "hidden-flag")+ experiment = create_experiment(self.team, "hidden-flag", created_by=self.user)targeting = {"experiment_id": experiment.id, "variant": "test"}scanner = self._create_scanner(name="targeted", experiment_targeting=targeting)self._set_resource_default("replay_scanner", "viewer")@@ -245,7 +245,7 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):# The API redacts experiment_targeting to null for such an editor, and the editor form# writes the whole object back on save. Without the write-side guard, renaming the scanner# would silently clear targeting the caller can't even see.- experiment = create_experiment(self.team, "hidden-flag")+ experiment = create_experiment(self.team, "hidden-flag", created_by=self.user)targeting = {"experiment_id": experiment.id, "variant": "test"}scanner = self._create_scanner(name="targeted", experiment_targeting=targeting)self._set_resource_default("replay_scanner", "editor")@@ -292,7 +292,7 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):# Guards the ?experiment_id= disclosure: a scanner-viewer who can't access the experiment must# not confirm a scanner targets it via the filter's match count. Distinct code path from the# serializer redaction above — the scanner is hidden from the list entirely, not just nulled.- experiment = create_experiment(self.team, "hidden-flag")+ experiment = create_experiment(self.team, "hidden-flag", created_by=self.user)targeting = {"experiment_id": experiment.id, "variant": "test"}self._create_scanner(name="targeted", experiment_targeting=targeting)self._set_resource_default("replay_scanner", "viewer")