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.

fix(access-control): require viewer access to objects referenced by id (#116630)

Felipe Rosa de Almeida47411c537cad
diff --git a/posthog/api/resource_transfer.py b/posthog/api/resource_transfer.py
index 37ab18fcae86..265b4f2ed640 100644
--- a/posthog/api/resource_transfer.py
+++ b/posthog/api/resource_transfer.py
@@ -1,6 +1,9 @@
from typing import Any, cast
-from django.core.exceptions import ObjectDoesNotExist
+from django.core.exceptions import (
+ ObjectDoesNotExist,
+ ValidationError as DjangoValidationError,
+)
from django.db.models import Q
from rest_framework import exceptions, serializers, status, viewsets
@@ -83,7 +86,7 @@ class ResourceTransferViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
raise exceptions.ValidationError(str(e))
dag = dag_sort_duplication_graph(graph)
- self._check_access_controls(user, source_team, destination_team, dag)
+ dest_access_control = self._check_access_controls(user, source_team, destination_team, dag)
suggested = get_suggested_substitutions(dag, destination_team)
suggested_map: dict[ResourceTransferKey, ResourceTransferKey] = {}
@@ -112,11 +115,12 @@ class ResourceTransferViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
try:
dest_model = cast(Any, dest_visitor.get_model())
dest_resource = dest_model.objects.get(pk=dest_pk)
- entry["suggested_substitution"] = {
- "resource_kind": dest_kind,
- "resource_id": str(dest_pk),
- "display_name": dest_visitor.get_display_name(dest_resource),
- }
+ if dest_access_control.check_access_level_for_object(dest_resource, required_level="viewer"):
+ entry["suggested_substitution"] = {
+ "resource_kind": dest_kind,
+ "resource_id": str(dest_pk),
+ "display_name": dest_visitor.get_display_name(dest_resource),
+ }
except ObjectDoesNotExist:
pass
@@ -145,8 +149,6 @@ class ResourceTransferViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
raise exceptions.ValidationError(str(e))
dag = dag_sort_duplication_graph(graph)
- self._check_access_controls(user, source_team, destination_team, dag)
-
for sub in data["substitutions"]:
if sub["source_resource_kind"] != sub["destination_resource_kind"]:
raise exceptions.ValidationError(
@@ -154,6 +156,8 @@ class ResourceTransferViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
f"with {sub['destination_resource_kind']}"
)
+ self._check_access_controls(user, source_team, destination_team, dag, data["substitutions"])
+
substitution_pairs: list[tuple[ResourceTransferKey, ResourceTransferKey]] = [
(
(sub["source_resource_kind"], sub["source_resource_id"]),
@@ -298,11 +302,13 @@ class ResourceTransferViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
source_team: Team,
destination_team: Team,
dag: tuple[ResourceTransferVertex, ...],
- ) -> None:
+ substitutions: list[dict[str, Any]] | None = None,
+ ) -> UserAccessControl:
"""
Walk the DAG and verify the user has read access on every resource in the
source team and write access for every mutable resource type in the
- destination team.
+ destination team. Also verify read access on every existing destination
+ resource named as a substitution.
"""
source_ac = UserAccessControl(user=user, team=source_team)
dest_ac = UserAccessControl(user=user, team=destination_team)
@@ -330,6 +336,27 @@ class ResourceTransferViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
dest_resource_types_checked.add(resource_type)
+ for sub in substitutions or []:
+ dest_visitor = ResourceTransferVisitor.get_visitor(sub["destination_resource_kind"])
+ if dest_visitor is None:
+ continue
+ try:
+ dest_resource = (
+ cast(Any, dest_visitor.get_model()).objects.filter(pk=sub["destination_resource_id"]).first()
+ )
+ except (ValueError, TypeError, DjangoValidationError):
+ raise exceptions.ValidationError(f"Invalid {dest_visitor.kind} id: {sub['destination_resource_id']}")
+ # duplicate_resource_to_new_team rejects a missing or foreign substitution with a 400
+ if dest_resource is None or dest_visitor.get_resource_team(dest_resource).pk != destination_team.pk:
+ continue
+ if not dest_ac.check_access_level_for_object(dest_resource, required_level="viewer"):
+ raise exceptions.PermissionDenied(
+ f"You do not have read access to {dest_visitor.kind} {sub['destination_resource_id']} "
+ "in the destination project"
+ )
+
+ return dest_ac
+
def _is_immutable(resource: Any) -> bool:
visitor = ResourceTransferVisitor.get_visitor(resource)
diff --git a/posthog/api/test/test_resource_transfer.py b/posthog/api/test/test_resource_transfer.py
index 30c1c8fa34e9..5e246c533285 100644
--- a/posthog/api/test/test_resource_transfer.py
+++ b/posthog/api/test/test_resource_transfer.py
@@ -337,6 +337,39 @@ class TestResourceTransferTransfer(APIBaseTest):
tile_insight_ids = set(new_tiles.values_list("insight_id", flat=True))
assert dest_insight.pk in tile_insight_ids
+ @parameterized.expand(
+ [
+ ("kind_mismatch", "Insight", "Survey", "1"),
+ ("malformed_integer_id", "Insight", "Insight", "not-an-id"),
+ ("malformed_uuid", "Survey", "Survey", "1"),
+ ]
+ )
+ def test_transfer_rejects_a_malformed_substitution(
+ self, _name: str, source_kind: str, dest_kind: str, dest_id: str
+ ) -> None:
+ insight = Insight.objects.create(team=self.team, name="My insight")
+
+ response = self.client.post(
+ self._transfer_url(),
+ {
+ "source_team_id": self.team.pk,
+ "destination_team_id": self.dest_team.pk,
+ "resource_kind": "Insight",
+ "resource_id": str(insight.pk),
+ "substitutions": [
+ {
+ "source_resource_kind": source_kind,
+ "source_resource_id": str(insight.pk),
+ "destination_resource_kind": dest_kind,
+ "destination_resource_id": dest_id,
+ }
+ ],
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
def test_transfer_without_substitutions_copies_everything(self) -> None:
insight = Insight.objects.create(team=self.team, name="My insight")
initial_insight_count = Insight.objects.filter(team=self.dest_team).count()
@@ -933,3 +966,43 @@ class TestResourceTransferProjectAccessControl(APIBaseTest):
ids = {r["resource_id"] for r in response.json()["results"]}
assert str(visible.id) in ids
assert str(restricted.id) not in ids
+
+ @patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
+ )
+ def test_substitution_needs_read_access_to_the_destination_object(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="Source dashboard")
+ insight = Insight.objects.create(team=self.team, name="Source insight")
+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)
+ restricted = Insight.objects.create(team=self.dest_team, name="Restricted insight", created_by=self.user)
+ AccessControl.objects.create(
+ team=self.dest_team, resource="insight", resource_id=str(restricted.id), access_level="none"
+ )
+ ResourceTransfer.objects.create(
+ source_team=self.team,
+ destination_team=self.dest_team,
+ resource_kind="Insight",
+ resource_id=str(insight.pk),
+ duplicated_resource_id=str(restricted.pk),
+ )
+ payload = {
+ "source_team_id": self.team.pk,
+ "destination_team_id": self.dest_team.pk,
+ "resource_kind": "Dashboard",
+ "resource_id": str(dashboard.pk),
+ }
+ substitution = {
+ "source_resource_kind": "Insight",
+ "source_resource_id": str(insight.pk),
+ "destination_resource_kind": "Insight",
+ "destination_resource_id": str(restricted.pk),
+ }
+
+ self.client.force_login(self.other_user)
+ preview = self.client.post(self._preview_url(), payload)
+ transfer = self.client.post(self._transfer_url(), {**payload, "substitutions": [substitution]}, format="json")
+
+ assert preview.status_code == status.HTTP_200_OK, preview.json()
+ assert all("suggested_substitution" not in resource for resource in preview.json()["resources"])
+ assert transfer.status_code == status.HTTP_403_FORBIDDEN, transfer.json()
+ assert not Dashboard.objects.filter(team=self.dest_team).exists()
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index 2091b6e7d10f..09186d76e659 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -883,6 +883,28 @@ class UserAccessControl:
# If no access control exists
return access_level_satisfied_for_resource(resource, access_level, required_level)
+ def denied_object_ids(
+ self,
+ resource: APIScopeObject,
+ objects: Iterable[tuple[str, int, Optional[int]]],
+ required_level: AccessControlLevel,
+ ) -> list[str]:
+ """Ids of the objects, given as (id, team_id, created_by_id), that this user lacks `required_level` on.
+
+ Each object is checked with its own team's rules, so an object from a sibling environment resolves correctly.
+ """
+ refs = [
+ ObjectAccessRef(resource=resource, id=object_id, team_id=team_id, created_by_id=created_by_id)
+ for object_id, team_id, created_by_id in objects
+ ]
+ access_controls = self.for_team_ids({ref.team_id for ref in refs})
+ return [
+ ref.id
+ for ref in refs
+ if ref.team_id not in access_controls
+ or not access_controls[ref.team_id].check_access_level_for_ref(ref, required_level)
+ ]
+
def check_can_modify_access_levels_for_object(self, obj: Model) -> bool:
"""
Special case for checking if the user can modify the access levels for an object.
diff --git a/products/annotations/backend/api/annotation.py b/products/annotations/backend/api/annotation.py
index 8468f1128e70..1bee20c539bf 100644
--- a/products/annotations/backend/api/annotation.py
+++ b/products/annotations/backend/api/annotation.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Any
+from typing import Any, Literal
from django.db.models import Q, QuerySet
@@ -9,6 +9,7 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
+from posthog.models.user import User
from products.annotations.backend.models.annotation import Annotation
from products.dashboards.backend.models.dashboard import Dashboard
@@ -138,11 +139,15 @@ class AnnotationSerializer(serializers.ModelSerializer):
dashboard.deleted and dashboard.id != getattr(self.instance, "dashboard_id", None)
):
raise serializers.ValidationError({"dashboard_id": "Dashboard not found."})
+ if dashboard.id != getattr(self.instance, "dashboard_id", None):
+ self._require_viewer_access(dashboard, "dashboard_id", "dashboard")
elif self.instance is not None:
dashboard = self.instance.dashboard
if "dashboard_item" in attrs:
insight = attrs["dashboard_item"]
+ if insight is not None and insight.pk != getattr(self.instance, "dashboard_item_id", None):
+ self._require_viewer_access(insight, "dashboard_item", "insight")
else:
insight = getattr(self.instance, "dashboard_item", None)
@@ -185,6 +190,15 @@ class AnnotationSerializer(serializers.ModelSerializer):
return attrs
+ def _require_viewer_access(
+ self, parent: Dashboard | Insight, field: str, resource: Literal["dashboard", "insight"]
+ ) -> None:
+ user_access_control = self.context["view"].user_access_control
+ if isinstance(self.context["request"].user, User) and user_access_control.denied_object_ids(
+ resource, [(str(parent.pk), parent.team_id, parent.created_by_id)], "viewer"
+ ):
+ raise serializers.ValidationError({field: f"You need viewer access to this {resource} to annotate it."})
+
def create(self, validated_data: dict[str, Any], *args: Any, **kwargs: Any) -> Annotation:
request = self.context["request"]
team = self.context["get_team"]()
diff --git a/products/annotations/backend/api/test/test_annotation.py b/products/annotations/backend/api/test/test_annotation.py
index 8c1b9f10c7ba..02dcb337b086 100644
--- a/products/annotations/backend/api/test/test_annotation.py
+++ b/products/annotations/backend/api/test/test_annotation.py
@@ -13,6 +13,7 @@ from rest_framework import status
from posthog.models import Organization, Team, User
+from products.access_control.backend.models.access_control import AccessControl
from products.annotations.backend.models.annotation import Annotation
from products.dashboards.backend.models.dashboard import Dashboard
from products.product_analytics.backend.facade.models import Insight
@@ -509,6 +510,39 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):
assert response.status_code == 400
assert response.json()["detail"] == f"Invalid date range: {error_message}"
+ @parameterized.expand([("dashboard", "dashboard_id"), ("dashboard_item", "dashboard_item")])
+ @patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
+ )
+ def test_attaching_needs_viewer_access_to_the_parent(self, scope: str, field: str) -> None:
+ parent: Dashboard | Insight
+ if scope == "dashboard":
+ parent = Dashboard.objects.create(team=self.team, name="Restricted")
+ AccessControl.objects.create(
+ team=self.team, resource="dashboard", resource_id=str(parent.id), access_level="none"
+ )
+ stored = Annotation.objects.create(
+ organization=self.organization, team=self.team, scope=scope, dashboard=parent
+ )
+ else:
+ parent = Insight.objects.create(team=self.team, name="Restricted")
+ AccessControl.objects.create(
+ team=self.team, resource="insight", resource_id=str(parent.id), access_level="none"
+ )
+ stored = Annotation.objects.create(
+ organization=self.organization, team=self.team, scope=scope, dashboard_item=parent
+ )
+ self.client.force_login(self._create_user("[email protected]"))
+ payload = {"content": "x", "scope": scope, "date_marker": "2024-01-01T00:00:00.000000Z", field: parent.id}
+
+ created = self.client.post(f"/api/projects/{self.team.id}/annotations/", payload)
+ edited = self.client.patch(f"/api/projects/{self.team.id}/annotations/{stored.id}/", payload)
+
+ assert created.status_code == status.HTTP_400_BAD_REQUEST, created.json()
+ assert created.json()["attr"] == field
+ assert Annotation.objects.filter(team=self.team).count() == 1
+ assert edited.status_code == status.HTTP_200_OK, edited.json()
+
def test_creating_annotation_with_dashboard_from_same_team(self) -> None:
dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard")
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.py
index 0b7c72d6b637..54b9c4e87769 100644
--- a/products/cdp/backend/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -80,6 +80,7 @@ from products.cdp.backend.validation import (
compile_hog,
generate_template_bytecode,
masked_secret_input_keys,
+ require_viewer_access_to_added_actions,
reserved_functions_used,
)
@@ -698,6 +699,11 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
instance = cast(Optional[HogFunction], self.context.get("instance", self.instance))
current_filters = instance.filters if isinstance(instance, HogFunction) else {}
proposed_filters = attrs.get("filters", current_filters)
+ require_viewer_access_to_added_actions(
+ self.context,
+ {"filters": attrs.get("filters"), "mappings": attrs.get("mappings")},
+ {"filters": instance.filters, "mappings": instance.mappings} if isinstance(instance, HogFunction) else None,
+ )
# `to_internal_value` injects the stored schema whenever the request omits it, so the field
# itself cannot reject duplicate keys: a row saved before the rule could no longer be
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index 21ad3b193baa..7f565c802d08 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -12,6 +12,7 @@ from rest_framework import status
from posthog.models.integration import Integration
+from products.access_control.backend.models.access_control import AccessControl
from products.actions.backend.models.action import Action
from products.cdp.backend.api.hog_function import (
MAX_HOG_CODE_SIZE_BYTES,
@@ -1639,6 +1640,34 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
},
}
+ @parameterized.expand([("actions", str), ("events", str), ("actions", float)])
+ @patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
+ )
+ def test_filter_action_needs_viewer_access_unless_already_used(self, filter_list: str, id_type: type):
+ action = Action.objects.create(
+ team=self.team, name="restricted", steps_json=[{"event": "$pageview"}], created_by=self.user
+ )
+ AccessControl.objects.create(team=self.team, resource="action", resource_id=str(action.id), access_level="none")
+ filters = {filter_list: [{"id": id_type(action.id), "name": "restricted", "type": "actions", "order": 0}]}
+ stored = self.client.post(
+ f"/api/projects/{self.team.id}/hog_functions/", data={**EXAMPLE_FULL, "filters": filters}
+ )
+ assert stored.status_code == status.HTTP_201_CREATED, stored.json()
+ self.client.force_login(self._create_user("[email protected]"))
+
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/hog_functions/", data={**EXAMPLE_FULL, "filters": filters}
+ )
+ edited = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{stored.json()['id']}/",
+ data={"name": "Renamed", "filters": filters},
+ )
+
+ assert created.status_code == status.HTTP_400_BAD_REQUEST, created.json()
+ assert HogFunction.objects.filter(team=self.team).count() == 1
+ assert edited.status_code == status.HTTP_200_OK, edited.json()
+
def test_generates_filters_bytecode(self, *args):
action = Action.objects.create(
team=self.team,
diff --git a/products/cdp/backend/presentation/serializers.py b/products/cdp/backend/presentation/serializers.py
index 833b00a2c339..78de717168e9 100644
--- a/products/cdp/backend/presentation/serializers.py
+++ b/products/cdp/backend/presentation/serializers.py
@@ -7,4 +7,5 @@ from products.cdp.backend.validation import (
HogFunctionFiltersSerializer as HogFunctionFiltersSerializer,
InputsSchemaSerializer as InputsSchemaSerializer,
InputsSerializer as InputsSerializer,
+ require_viewer_access_to_added_actions as require_viewer_access_to_added_actions,
)
diff --git a/products/cdp/backend/validation.py b/products/cdp/backend/validation.py
index 4cf886b96fff..17965a2e4c30 100644
--- a/products/cdp/backend/validation.py
+++ b/products/cdp/backend/validation.py
@@ -1,6 +1,7 @@
import re
import json
import logging
+import contextlib
from collections.abc import Iterable
from typing import Any, Optional
@@ -19,6 +20,7 @@ from posthog.hogql.visitor import TraversingVisitor
from posthog.models.integration import POSTHOG_CONNECT_KIND, Integration
from posthog.models.team.team import Team
+from posthog.models.user import User
from products.actions.backend.models.action import Action
from products.cdp.backend.filters import (
@@ -1098,6 +1100,57 @@ def _contains_behavioral_property(filters: dict) -> bool:
)
+def _action_ids_in_filters(filters: dict[str, Any]) -> set[int]:
+ # Mirrors compile_filters_expr, which compiles every entry typed "actions" in either list.
+ action_ids: set[int] = set()
+ for key in ("events", "actions"):
+ entries = filters.get(key)
+ for entry in entries if isinstance(entries, list) else []:
+ if isinstance(entry, dict) and entry.get("type") == "actions":
+ with contextlib.suppress(KeyError, TypeError, ValueError, OverflowError):
+ action_id = int(entry["id"])
+ # Postgres rejects an id outside the bigint range in a query, and no row can match one.
+ if 0 < action_id < 2**63:
+ action_ids.add(action_id)
+ return action_ids
+
+
+def _filter_action_ids(value: Any) -> set[int]:
+ if isinstance(value, list):
+ return set().union(*(_filter_action_ids(item) for item in value))
+ if not isinstance(value, dict):
+ return set()
+ action_ids: set[int] = set()
+ for key, item in value.items():
+ if key == "filters" and isinstance(item, dict):
+ action_ids |= _action_ids_in_filters(item)
+ elif key != "inputs":
+ action_ids |= _filter_action_ids(item)
+ return action_ids
+
+
+def require_viewer_access_to_added_actions(context: dict[str, Any], submitted: Any, stored: Any) -> None:
+ user = getattr(context.get("request"), "user", None)
+ user_access_control = getattr(context.get("view"), "user_access_control", None)
+ # Synthetic principals (project secret API keys) bypass access control, and callers without a view
+ # (template installs, plugin migrations) write no references a user picked.
+ if not isinstance(user, User) or user_access_control is None:
+ return
+ added_ids = _filter_action_ids(submitted) - _filter_action_ids(stored)
+ if not added_ids:
+ return
+
+ actions = Action.objects.filter(team__project_id=context["get_team"]().project_id, id__in=added_ids)
+ denied_ids = user_access_control.denied_object_ids(
+ "action", [(str(action.id), action.team_id, action.created_by_id) for action in actions], "viewer"
+ )
+ if denied_ids:
+ raise serializers.ValidationError(
+ f"You don't have viewer access to action(s) {', '.join(denied_ids)}. "
+ "Remove them from the filters, or ask for access."
+ )
+
+
class HogFunctionFiltersSerializer(serializers.Serializer):
source = serializers.ChoiceField(
choices=["events", "internal-events", "person-updates", *DATA_WAREHOUSE_SOURCES],
diff --git a/products/experiments/backend/experiment_saved_metric_service.py b/products/experiments/backend/experiment_saved_metric_service.py
index 3dba5f958de7..d56f5dbd44b3 100644
--- a/products/experiments/backend/experiment_saved_metric_service.py
+++ b/products/experiments/backend/experiment_saved_metric_service.py
@@ -43,7 +43,7 @@ class ExperimentSavedMetricService:
) -> ExperimentSavedMetric:
"""Create a saved metric with full business-logic validation."""
normalized_query = self.normalize_query_for_write(query)
- validate_metric_action_ids([normalized_query], self.team.id)
+ validate_metric_action_ids([normalized_query], self.team, user=self.user)
enforce_warehouse_metric_access([normalized_query], team=self.team, user=self.user)
return ExperimentSavedMetric.objects.create(
@@ -65,7 +65,9 @@ class ExperimentSavedMetricService:
update_data["query"], existing_query=saved_metric.query
)
_, stored_action_ids = extract_entity_nodes([saved_metric.query] if saved_metric.query else [])
- validate_metric_action_ids([update_data["query"]], self.team.id, known_action_ids=stored_action_ids)
+ validate_metric_action_ids(
+ [update_data["query"]], self.team, user=self.user, known_action_ids=stored_action_ids
+ )
enforce_warehouse_metric_access([update_data["query"]], team=self.team, user=self.user)
for attr, value in update_data.items():
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index ef9f84a57c58..422877c71bd8 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -1157,8 +1157,11 @@ class ExperimentService:
running_time_calculation = running_time_calculation or {}
self.validate_experiment_metrics(metrics)
self.validate_experiment_metrics(metrics_secondary)
- validate_metric_action_ids(metrics, self.team.id)
- validate_metric_action_ids(metrics_secondary, self.team.id)
+ validate_metric_action_ids(metrics, self.team, user=self.user)
+ validate_metric_action_ids(metrics_secondary, self.team, user=self.user)
+ validate_metric_action_ids(
+ self._collect_saved_metric_queries(saved_metrics_ids), self.team, user=self.user, require_existing=False
+ )
if not allow_unknown_events:
self.validate_metric_event_names(metrics)
self.validate_metric_event_names(metrics_secondary)
@@ -3399,7 +3402,9 @@ class ExperimentService:
if "metrics" in update_data:
update_data["metrics"] = self._assign_uuids_to_metrics(update_data["metrics"], seen=seen_metric_uuids)
self.validate_experiment_metrics(update_data["metrics"])
- validate_metric_action_ids(update_data["metrics"], self.team.id, known_action_ids=persisted_action_ids)
+ validate_metric_action_ids(
+ update_data["metrics"], self.team, user=self.user, known_action_ids=persisted_action_ids
+ )
if not allow_unknown_events:
self.validate_metric_event_names(update_data["metrics"], known_event_names=persisted_event_names)
if "metrics_secondary" in update_data:
@@ -3408,13 +3413,29 @@ class ExperimentService:
)
self.validate_experiment_metrics(update_data["metrics_secondary"])
validate_metric_action_ids(
- update_data["metrics_secondary"], self.team.id, known_action_ids=persisted_action_ids
+ update_data["metrics_secondary"], self.team, user=self.user, known_action_ids=persisted_action_ids
)
if not allow_unknown_events:
self.validate_metric_event_names(
update_data["metrics_secondary"], known_event_names=persisted_event_names
)
+ if "saved_metrics_ids" in update_data:
+ _, linked_action_ids = extract_entity_nodes(
+ [
+ link.saved_metric.query
+ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric")
+ if link.saved_metric.query
+ ]
+ )
+ validate_metric_action_ids(
+ self._collect_saved_metric_queries(update_data["saved_metrics_ids"]),
+ self.team,
+ user=self.user,
+ known_action_ids=persisted_action_ids | linked_action_ids,
+ require_existing=False,
+ )
+
enforce_warehouse_metric_access(
[
*(update_data.get("metrics") or []),
diff --git a/products/experiments/backend/metric_validation.py b/products/experiments/backend/metric_validation.py
index aa89f64e3d86..bcc3506d158e 100644
--- a/products/experiments/backend/metric_validation.py
+++ b/products/experiments/backend/metric_validation.py
@@ -2,13 +2,16 @@
Inline metrics (on the experiment) and saved/shared metrics (ExperimentSavedMetric.query) are the same
metric types, so both write paths parse and validate through `parse_and_validate_metric` and check
-referenced actions through `validate_metric_action_ids`. Checks that need a user or that the caller can
-waive (team ownership, permissions, whether a referenced event exists) stay with the callers.
+referenced actions, including the caller's access to them, through `validate_metric_action_ids`. Other
+checks that need a user or that the caller can waive (team ownership, permissions, whether a referenced
+event exists) stay with the callers.
"""
+from typing import Any
+
import pydantic
import structlog
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
from posthog.schema import (
Breakdown,
@@ -19,6 +22,10 @@ from posthog.schema import (
ExperimentRetentionMetric,
)
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.actions.backend.models.action import Action
from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_math
from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidator
@@ -216,9 +223,15 @@ def extract_entity_nodes(metrics: list[dict] | None) -> tuple[set[str], set[int]
def validate_metric_action_ids(
- metrics: list[dict] | None, team_id: int, *, known_action_ids: set[int] | None = None
+ metrics: list[dict] | None,
+ team: Team,
+ *,
+ user: Any,
+ known_action_ids: set[int] | None = None,
+ require_existing: bool = True,
) -> None:
- """Validate that all ActionsNode IDs reference existing, non-deleted actions for the team.
+ """Validate that all ActionsNode IDs reference existing, non-deleted actions for the team,
+ and that ``user`` has viewer access to each of them.
Actions are explicitly created entities with stable IDs, so a reference to a
nonexistent action is almost certainly a mistake, so we raise a hard validation error.
@@ -227,6 +240,9 @@ def validate_metric_action_ids(
metric, so an update is checked for what it introduces rather than for everything it
resends. Without it, deleting a referenced action makes every later metric
edit fail on the resent arrays. See ``update_experiment``.
+
+ ``require_existing=False`` checks access only. Attached saved metrics use it, because a saved
+ metric keeps working after one of its actions is deleted.
"""
_, action_ids = extract_entity_nodes(metrics)
if known_action_ids:
@@ -234,17 +250,24 @@ def validate_metric_action_ids(
if not action_ids:
return
- existing_ids = set(
- Action.objects.filter(
- id__in=action_ids,
- team_id=team_id,
- deleted=False,
- ).values_list("id", flat=True)
- )
- missing = action_ids - existing_ids
- if missing:
+ referenced = Action.objects.filter(id__in=action_ids, team_id=team.id)
+ actions = list(referenced.filter(deleted=False) if require_existing else referenced)
+ missing = action_ids - {action.id for action in actions}
+ if require_existing and missing:
missing_str = ", ".join(str(aid) for aid in sorted(missing))
raise ValidationError(
f"Action(s) with ID {missing_str} not found or deleted. "
"Each ActionsNode must reference an existing action belonging to this project."
)
+
+ # Synthetic principals (project secret API keys) and userless system writes bypass access control.
+ if not isinstance(user, User):
+ return
+ denied = UserAccessControl(user=user, team=team).denied_object_ids(
+ "action", [(str(action.id), action.team_id, action.created_by_id) for action in actions], "viewer"
+ )
+ if denied:
+ raise PermissionDenied(
+ f"You don't have viewer access to action(s) {', '.join(denied)}. "
+ "Remove them from the metric, or ask for access."
+ )
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index b1eb84563ac9..8b64c0a8eb59 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -6813,6 +6813,33 @@ class TestExperimentService(APIBaseTest):
assert "999999" in str(ctx.exception.detail)
+ @parameterized.expand([("inline",), ("saved_metric",)])
+ @patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
+ )
+ def test_metric_action_needs_viewer_access_unless_already_referenced(self, placement: str):
+ action = Action.objects.create(team=self.team, name="restricted action", created_by=self.user)
+ AccessControl.objects.create(team=self.team, resource="action", resource_id=str(action.id), access_level="none")
+ metric = {"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "ActionsNode", "id": action.id}}
+ definition: dict = {"metrics": [metric], "metrics_secondary": []}
+ if placement == "saved_metric":
+ saved_metric = ExperimentSavedMetric.objects.create(
+ team=self.team, name="Restricted", query={**metric, "uuid": "restricted-sm"}, created_by=self.user
+ )
+ definition = {"saved_metrics_ids": [{"id": saved_metric.id, "metadata": {"type": "primary"}}]}
+ experiment = self._service().create_experiment(
+ name="Restricted Action", feature_flag_key=f"restricted-action-{placement}", **definition
+ )
+ member_service = ExperimentService(team=self.team, user=self._create_user("[email protected]"))
+
+ with self.assertRaises(PermissionDenied):
+ member_service.create_experiment(
+ name="Member Restricted Action", feature_flag_key=f"member-restricted-action-{placement}", **definition
+ )
+ member_service.update_experiment(experiment, definition)
+
+ assert len(experiment.metrics or []) + experiment.experimenttosavedmetric_set.count() == 1
+
def test_funnel_metric_with_empty_series_raises(self):
# The experiment exposure event is prepended as step_0 at query time, so an
# empty series would produce a degenerate single-step funnel with no conversion event.
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index c17542d3a2b3..626c761b184d 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -1254,8 +1254,39 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
if not isinstance(value, dict):
raise serializers.ValidationError("Conditions must be an object")
+ self._require_viewer_access_to_added_actions(value)
return value
+ def _require_viewer_access_to_added_actions(self, conditions: dict) -> None:
+ actions_condition = conditions.get("actions")
+ if not isinstance(actions_condition, dict) or not isinstance(self.context["request"].user, User):
+ return
+
+ action_ids: set[int] | None
+ try:
+ action_ids = {
+ int(value["id"])
+ for value in actions_condition.get("values") or []
+ if isinstance(value, dict) and value.get("id") is not None
+ }
+ except (TypeError, ValueError, OverflowError):
+ action_ids = None
+ # Postgres rejects an id outside the bigint range in a query, so check the range before the lookup.
+ if action_ids is None or not all(0 < action_id < 2**63 for action_id in action_ids):
+ raise serializers.ValidationError("Each action in the survey conditions needs a valid id.")
+
+ added_actions = Action.objects.filter(team__project_id=self.context["project_id"], id__in=action_ids)
+ if self.instance is not None:
+ added_actions = added_actions.exclude(id__in=self.instance.actions.values("id"))
+ denied_ids = self.context["view"].user_access_control.denied_object_ids(
+ "action", [(str(action.id), action.team_id, action.created_by_id) for action in added_actions], "viewer"
+ )
+ if denied_ids:
+ raise serializers.ValidationError(
+ f"You don't have viewer access to action(s) {', '.join(denied_ids)}. "
+ "Remove them from the survey conditions, or ask for access."
+ )
+
def validate_targeting_flag_filters(self, value):
if value is None:
return value
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 77393189900c..12edd87f7a42 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -4993,6 +4993,54 @@ class TestSurveyWithActions(APIBaseTest):
assert survey.actions.filter(name="user subscribed").exists()
assert not survey.actions.filter(name="user unsubscribed").exists()
+ @patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
+ )
+ def test_linking_an_action_needs_viewer_access_to_it(self) -> None:
+ restricted = Action.objects.create(team=self.team, name="restricted", steps_json=[{"event": "$pageview"}])
+ AccessControl.objects.create(
+ team=self.team, resource="action", resource_id=str(restricted.id), access_level="none"
+ )
+ questions = [{"type": "open", "question": "Why's a hedgehog?"}]
+ stored = Survey.objects.create(
+ team=self.team, created_by=self.user, name="linked", type="popover", questions=questions
+ )
+ stored.actions.set([restricted])
+ conditions = {"actions": {"values": [{"name": "restricted", "id": restricted.id}]}}
+ self.client.force_login(self._create_user("[email protected]"))
+
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={"name": "new", "type": "popover", "questions": questions, "conditions": conditions},
+ format="json",
+ )
+ edited = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{stored.id}/",
+ data={"name": "renamed", "conditions": conditions},
+ format="json",
+ )
+
+ assert created.status_code == status.HTTP_400_BAD_REQUEST, created.json()
+ assert created.json()["attr"] == "conditions"
+ assert not Survey.objects.filter(team=self.team, name="new").exists()
+ assert edited.status_code == status.HTTP_200_OK, edited.json()
+
+ @parameterized.expand([("text", "abc"), ("object", {"id": 1}), ("too_large", "9" * 30)])
+ def test_linking_an_action_rejects_an_invalid_id(self, _name: str, action_id: object) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={
+ "name": "bad action id",
+ "type": "popover",
+ "questions": [{"type": "open", "question": "Why's a hedgehog?"}],
+ "conditions": {"actions": {"values": [{"name": "bad", "id": action_id}]}},
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "conditions"
+
def test_can_clear_associated_actions(self):
Action.objects.create(
team=self.team,
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 05c23eebe5ab..2e4aa792c322 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -118,6 +118,7 @@ from products.cdp.backend.presentation.serializers import (
HogFunctionFiltersSerializer,
InputsSchemaSerializer,
InputsSerializer,
+ require_viewer_access_to_added_actions,
)
from products.messaging.backend.presentation.views.serializers import DesignOperationSerializer
from products.notifications.backend.facade.api import publish_resource_edited
@@ -3073,6 +3074,12 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
raise serializers.ValidationError({"actions": f"Duplicate action id(s): {', '.join(duplicate_ids)}"})
actions = data.get("actions", instance.actions if instance else [])
+ stored = instance or self.context.get("instance")
+ require_viewer_access_to_added_actions(
+ self.context,
+ {"actions": submitted_actions, "conversion": data.get("conversion")},
+ {"actions": stored.actions, "conversion": stored.conversion} if stored else None,
+ )
# When activating a draft, re-validate actions from the instance with full (non-draft) checks
status = data.get("status", instance.status if instance else "draft")
diff --git a/products/workflows/backend/tests/api/test_hog_flow_access_control.py b/products/workflows/backend/tests/api/test_hog_flow_access_control.py
index bc0474582683..2a57bd864d7a 100644
--- a/products/workflows/backend/tests/api/test_hog_flow_access_control.py
+++ b/products/workflows/backend/tests/api/test_hog_flow_access_control.py
@@ -13,6 +13,7 @@ from posthog.models.user import User
from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES, model_to_resource
from products.access_control.backend.models.access_control import AccessControl
+from products.actions.backend.models.action import Action
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule
@@ -172,6 +173,41 @@ class TestHogFlowAccessControl(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
self.assertTrue(HogFlow.objects.filter(team=self.team, name="editor_create").exists())
+ @parameterized.expand([("trigger",), ("conversion",)])
+ def test_action_reference_needs_viewer_access_unless_already_used(self, placement: str):
+ action = Action.objects.create(
+ team=self.team, name="restricted", steps_json=[{"event": "$pageview"}], created_by=self.user
+ )
+ self._create_access_control(self.editor_user, access_level="editor")
+ self._create_access_control(
+ self.editor_user, resource="action", resource_id=str(action.id), access_level="none"
+ )
+ filters = {"actions": [{"id": str(action.id), "name": "restricted", "type": "actions", "order": 0}]}
+ definition: dict = (
+ {"actions": [{**TRIGGER_ACTION, "config": {"type": "event", "filters": filters}}]}
+ if placement == "trigger"
+ else {"actions": [TRIGGER_ACTION], "conversion": {"events": [{"filters": filters}], "window": "7d"}}
+ )
+ stored = HogFlow.objects.create(
+ team=self.team, name="uses_action", created_by=self.user, status=HogFlow.State.DRAFT, **definition
+ )
+ self.client.force_login(self.editor_user)
+
+ created = self.client.post(self._list_url(), data={"name": "editor_action", **definition}, format="json")
+ edited = self.client.patch(self._detail_url(stored.id), data=definition, format="json")
+ with patch("products.workflows.backend.presentation.views.hog_flow.create_hog_flow_invocation_test") as invoke:
+ invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})
+ tested = self.client.post(
+ f"{self._detail_url(stored.id)}/invocations/",
+ data={"configuration": definition, "globals": {"event": {"event": "$pageview"}}},
+ format="json",
+ )
+
+ self.assertEqual(created.status_code, status.HTTP_400_BAD_REQUEST, created.json())
+ self.assertFalse(HogFlow.objects.filter(team=self.team, name="editor_action").exists())
+ self.assertEqual(edited.status_code, status.HTTP_200_OK, edited.json())
+ self.assertEqual(tested.status_code, status.HTTP_200_OK, tested.json())
+
@parameterized.expand(
[
("batch_jobs_list", "get", "/batch_jobs", None),