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: check table access when a subscription is saved (#111099)

Alex Liderfcf82597b400
diff --git a/ee/hogai/tools/test/test_create_insight.py b/ee/hogai/tools/test/test_create_insight.py
index 53a8cb136c67..664200dcd1ff 100644
--- a/ee/hogai/tools/test/test_create_insight.py
+++ b/ee/hogai/tools/test/test_create_insight.py
@@ -228,7 +228,7 @@ class TestCreateInsightTool(ClickhouseTestMixin, NonAtomicBaseTest):
tool = await self._create_tool()
await SharingConfiguration.objects.acreate(team=self.team, insight=insight, enabled=True)
- with patch("posthog.api.sharing_publish_gate.blocked_access_for_user", return_value=["restricted table"]):
+ with patch("posthog.api.query_access_check.blocked_access_for_user", return_value=["restricted table"]):
with self.assertRaisesRegex(MaxToolRetryableError, "publicly shared"):
await tool._save_insight_query(insight, {"kind": "TrendsQuery", "series": [], "interval": "week"})
diff --git a/posthog/api/query_access_check.py b/posthog/api/query_access_check.py
new file mode 100644
index 000000000000..94625f80ebda
--- /dev/null
+++ b/posthog/api/query_access_check.py
@@ -0,0 +1,55 @@
+"""Which tables a user cannot read among a set of saved queries.
+
+The compile core behind every save-time access gate: publishing a public link, editing an exposed
+artifact, and saving a subscription all ask this one question about the acting person.
+"""
+
+from typing import Any
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import TableAccessDeniedError
+from posthog.hogql.modifiers import create_default_modifiers_for_user
+from posthog.hogql.printer import prepare_ast_for_printing
+
+from posthog.hogql_queries.query_runner import get_query_runner_or_none
+from posthog.models import Team, User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControlError
+
+
+def blocked_access_for_user(user: User, team: Team, queries: list[dict[str, Any]]) -> list[str]:
+ """Tables (and runner-level resources) the user can't access among everything the given
+ queries read. Each query is compiled (resolved, not executed) as the user, the same resolution
+ the read path uses. Non-access compile errors don't gate. Empty list = the user can run them all."""
+ if not queries:
+ return []
+
+ # One context per distinct modifier set: the schema is built on first prepare and reused. The
+ # query's own modifiers must shape it, because a warehouse events mapping can put an expression
+ # into the schema, and the run would compile that expression against the same modifiers.
+ contexts: dict[str, HogQLContext] = {}
+ blocked: set[str] = set()
+ for query in queries:
+ try:
+ # get_query_runner unwraps container nodes (DataTableNode, InsightVizNode, ...) itself.
+ runner = get_query_runner_or_none(query, team, user=user)
+ if runner is None:
+ continue
+ # Resource-level check first for product runners (logs, metrics, customer analytics, ...)
+ runner.validate_query_runner_access(user)
+ modifiers = create_default_modifiers_for_user(user, team, runner.modifiers)
+ context_key = modifiers.model_dump_json()
+ context = contexts.get(context_key)
+ if context is None:
+ context = contexts[context_key] = HogQLContext(
+ team_id=team.pk, team=team, user=user, enable_select_queries=True, modifiers=modifiers
+ )
+ prepare_ast_for_printing(runner.to_query(), context=context, dialect="clickhouse")
+ except UserAccessControlError as e:
+ blocked.add(e.resource)
+ except TableAccessDeniedError as e:
+ blocked.add(e.table_name)
+ except Exception:
+ # Only access denials gate publishing; anything else is the query's own problem.
+ continue
+ return sorted(blocked)
diff --git a/posthog/api/sharing_publish_gate.py b/posthog/api/sharing_publish_gate.py
index d3e824b4fdb9..58a41c89d90e 100644
--- a/posthog/api/sharing_publish_gate.py
+++ b/posthog/api/sharing_publish_gate.py
@@ -13,19 +13,15 @@ from django.db.models import Q
from rest_framework import serializers
-from posthog.hogql.context import HogQLContext
-from posthog.hogql.errors import TableAccessDeniedError
from posthog.hogql.escape_sql import backquote_escape_chars_map
-from posthog.hogql.modifiers import create_default_modifiers_for_user
-from posthog.hogql.printer import prepare_ast_for_printing
from posthog.api.property_filter_access_gate import table_blocking_property_filters
+from posthog.api.query_access_check import blocked_access_for_user
from posthog.constants import AvailableFeature
-from posthog.hogql_queries.query_runner import get_query_runner_or_none
from posthog.models import Team, User
from posthog.models.sharing_configuration import SharingConfiguration
-from products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlError
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.dashboards.backend.models.dashboard import Dashboard
from products.notebooks.backend.facade.content import extract_inline_query_nodes, extract_referenced_insight_short_ids
from products.notebooks.backend.models import Notebook
@@ -125,41 +121,6 @@ def _breakdown_as_hogql(breakdown_type: str, key: str) -> str | None:
return ".".join("`" + "".join(backquote_escape_chars_map.get(c, c) for c in part) + "`" for part in chain)
-def blocked_access_for_user(user: User, team: Team, queries: list[dict[str, Any]]) -> list[str]:
- """Tables (and runner-level resources) the user can't access among everything the given
- queries read - the compile core shared by the publish gate and the save-time block on
- already-shared artifacts."""
- if not queries:
- return []
-
- # One context for all queries: the publisher's schema is built on first prepare and reused.
- context = HogQLContext(
- team_id=team.pk,
- team=team,
- user=user,
- enable_select_queries=True,
- modifiers=create_default_modifiers_for_user(user, team),
- )
- blocked: set[str] = set()
- for query in queries:
- try:
- # get_query_runner unwraps container nodes (DataTableNode, InsightVizNode, ...) itself.
- runner = get_query_runner_or_none(query, team, user=user)
- if runner is None:
- continue
- # Resource-level check first for product runners (logs, metrics, customer analytics, ...)
- runner.validate_query_runner_access(user)
- prepare_ast_for_printing(runner.to_query(), context=context, dialect="clickhouse")
- except UserAccessControlError as e:
- blocked.add(e.resource)
- except TableAccessDeniedError as e:
- blocked.add(e.table_name)
- except Exception:
- # Only access denials gate publishing; anything else is the query's own problem.
- continue
- return sorted(blocked)
-
-
def _queries_exposed_by(config: SharingConfiguration) -> list[dict[str, Any]]:
queries: list[dict[str, Any]] = []
insight_ids = config.get_connected_insight_ids()
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index e28416b1020d..352d0494024b 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -2481,6 +2481,47 @@ class TestSaveTimeAccessBlock(APIBaseTest):
f"/api/projects/{self.team.id}/insights/{self.insight.id}/", {"query": self._DENIED_QUERY}
)
+ def test_query_update_blocked_when_a_modifier_reads_the_denied_view(self):
+ # A warehouse events mapping parses id_field as an expression, so a saved query can reach a
+ # denied view through its modifiers without naming it in the SQL.
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="open_view",
+ query={"kind": "HogQLQuery", "query": "SELECT 2 AS id"},
+ columns={"id": "String"},
+ )
+ governed_view = DataWarehouseSavedQuery.objects.get(team=self.team, name="governed_view")
+ AccessControl.objects.create(
+ team=self.team, resource="warehouse_view", resource_id=str(governed_view.id), access_level="none"
+ )
+ SharingConfiguration.objects.create(team=self.team, insight=self.insight, enabled=True)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/",
+ {
+ "query": {
+ "kind": "DataTableNode",
+ "source": {
+ "kind": "HogQLQuery",
+ "query": "SELECT id FROM open_view",
+ "modifiers": {
+ "dataWarehouseEventsModifiers": [
+ {
+ "table_name": "open_view",
+ "id_field": "(SELECT id FROM governed_view LIMIT 1)",
+ "distinct_id_field": "id",
+ "timestamp_field": "id",
+ }
+ ]
+ },
+ },
+ }
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "governed_view" in str(response.json())
+
@parameterized.expand([("direct",), ("dashboard",), ("notebook",)])
def test_query_update_blocked_when_insight_is_publicly_shared(self, coverage: str):
self._deny_editor()
diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.py
index 7642847d547e..a04e7c651097 100644
--- a/products/product_analytics/backend/facade/api.py
+++ b/products/product_analytics/backend/facade/api.py
@@ -214,7 +214,8 @@ def user_can_view_insight(*, team: Team, user: User, insight_id: int) -> bool:
def save_saved_insight_query(
*, team: Team, user: User, insight_id: int, expected_query: dict[str, Any], query: dict[str, Any]
) -> str | None:
- from posthog.api.sharing_publish_gate import blocked_access_for_user, is_publicly_shared # noqa: PLC0415, I001 — avoids HogQL import cycle
+ from posthog.api.query_access_check import blocked_access_for_user # noqa: PLC0415, I001 — avoids HogQL import cycle
+ from posthog.api.sharing_publish_gate import is_publicly_shared # noqa: PLC0415, I001 — avoids HogQL import cycle
with transaction.atomic():
insight = Insight.objects.select_for_update().filter(team=team, pk=insight_id, deleted=False).first()
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index bc6607ac92b7..1e44cd43e14c 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -44,9 +44,10 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
+from posthog.api.query_access_check import blocked_access_for_user
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
-from posthog.api.sharing_publish_gate import blocked_access_for_user, is_publicly_shared
+from posthog.api.sharing_publish_gate import is_publicly_shared
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action
from posthog.auth import (
diff --git a/products/subscriptions/backend/facade/api.py b/products/subscriptions/backend/facade/api.py
index d12e647d1dfc..6bf31cff75eb 100644
--- a/products/subscriptions/backend/facade/api.py
+++ b/products/subscriptions/backend/facade/api.py
@@ -10,9 +10,9 @@ from __future__ import annotations
from collections.abc import Collection
from datetime import datetime
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
-from products.subscriptions.backend.logic import auto_disable, queries, subscription_utils
+from products.subscriptions.backend.logic import auto_disable, queries, subscription_query_access, subscription_utils
from products.subscriptions.backend.logic.subscription_utils import MAX_INSIGHTS as MAX_INSIGHTS
from products.subscriptions.backend.logic.teams_subscriptions import (
TEAMS_WEBHOOK_URL_ERROR as TEAMS_WEBHOOK_URL_ERROR,
@@ -35,8 +35,11 @@ from products.subscriptions.backend.temporal.types import (
from . import contracts
if TYPE_CHECKING:
+ from posthog.models import Team, User
from posthog.models.sharing_configuration import SharingConfiguration
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
__all__ = [
"AI_PROMPT_MAX_LENGTH",
"AI_REPORT_CHARTS_KEY",
@@ -49,12 +52,14 @@ __all__ = [
"TEAMS_WEBHOOK_URL_ERROR",
"TEAMS_WEBHOOK_URL_MASKED_ERROR",
"ai_query_plan_status",
+ "blocked_access_for_subscription",
"dashboard_ids_with_subscriptions",
"delete_insight_subscriptions",
"failed_delivery_counts",
"insight_ids_with_subscriptions",
"render_shared_insight_image",
"sanitize_prompt",
+ "should_check_table_access",
"subscription_ids_in_team",
"unsubscribe",
"validate_re_enable",
@@ -130,3 +135,26 @@ def dashboard_ids_with_subscriptions(dashboard_ids: Collection[int]) -> set[int]
"dashboard_id", flat=True
)
)
+
+
+def should_check_table_access(*, team_id: int, subscription_id: int | None, attrs: dict[str, Any]) -> bool:
+ """Whether a subscription write must pass the table-access check: a create, a change to what
+ is delivered or to who receives it, or a write that enables or restores the subscription."""
+ return subscription_query_access.should_check_table_access(
+ team_id=team_id, subscription_id=subscription_id, attrs=attrs
+ )
+
+
+def blocked_access_for_subscription(
+ *,
+ user: User,
+ team: Team,
+ user_access_control: UserAccessControl,
+ subscription_id: int | None,
+ attrs: dict[str, Any],
+) -> list[str]:
+ """Names of the tables and query resources the requester cannot read among the queries the
+ subscription delivers after this write. Empty when the write passes the check."""
+ return subscription_query_access.blocked_access_for_subscription(
+ user=user, team=team, user_access_control=user_access_control, subscription_id=subscription_id, attrs=attrs
+ )
diff --git a/products/subscriptions/backend/logic/subscription_query_access.py b/products/subscriptions/backend/logic/subscription_query_access.py
new file mode 100644
index 000000000000..57c174665177
--- /dev/null
+++ b/products/subscriptions/backend/logic/subscription_query_access.py
@@ -0,0 +1,107 @@
+"""Save-time table-access check for insight and dashboard subscriptions.
+
+A subscription keeps delivering its queries' results after the person who saved it has stopped
+looking at them. The requester who decides what is delivered, and who receives it, must
+therefore be able to read every table those queries use. Otherwise a subscription would be an
+escalation channel: point it at a query over a restricted table, and read the results from the
+delivery.
+"""
+
+from typing import Any
+
+from posthog.api.query_access_check import blocked_access_for_user
+from posthog.constants import AvailableFeature
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.subscriptions.backend.models.subscription import Subscription
+
+_RECIPIENT_FIELDS = ("target_type", "target_value", "integration_id")
+_TARGET_FIELDS = ("insight", "dashboard")
+
+
+def _subscription(team_id: int, subscription_id: int | None) -> Subscription | None:
+ if subscription_id is None:
+ return None
+ return Subscription.objects.get(team_id=team_id, id=subscription_id)
+
+
+def should_check_table_access(*, team_id: int, subscription_id: int | None, attrs: dict[str, Any]) -> bool:
+ """Decide if a write to a subscription must pass the table-access check.
+
+ These writes need the check: a create, a change to what the subscription delivers, a change
+ to who receives it, and a write that enables or restores the subscription.
+
+ A write that only disables or deletes the subscription does not need the check. This lets a
+ member without table access turn a subscription off. A write that also changes the delivery
+ or the recipients needs the check, because those changes stay in place after someone else
+ enables the subscription again.
+ """
+ instance = _subscription(team_id, subscription_id)
+ if instance is None:
+ return True
+ if any(field in attrs and attrs[field] != getattr(instance, field) for field in _RECIPIENT_FIELDS):
+ return True
+ if any(
+ field in attrs and getattr(attrs[field], "id", None) != getattr(instance, f"{field}_id")
+ for field in _TARGET_FIELDS
+ ):
+ return True
+ if "dashboard_export_insights" in attrs and set(attrs["dashboard_export_insights"]) != set(
+ instance.dashboard_export_insights.values_list("id", flat=True)
+ ):
+ return True
+ if attrs.get("deleted") is True or attrs.get("enabled") is False:
+ return False
+ return (instance.deleted and attrs.get("deleted") is False) or (
+ not instance.enabled and attrs.get("enabled") is True
+ )
+
+
+def delivered_queries(instance: Subscription | None, attrs: dict[str, Any]) -> list[dict[str, Any]]:
+ """The saved queries of the insights a delivery exports once this write is applied.
+
+ The selection matches `_resolve_exportable_insights` in the delivery activities: the selected
+ insights that are still live tiles of the dashboard, every live tile when there is no
+ selection, or the single insight of an insight subscription.
+ """
+ dashboard = attrs["dashboard"] if "dashboard" in attrs else (instance.dashboard if instance else None)
+ if dashboard is not None:
+ if dashboard.deleted:
+ return []
+ live_tiles = dashboard.tiles.filter(insight__isnull=False, insight__deleted=False)
+ if "dashboard_export_insights" in attrs:
+ selected_ids = list(attrs["dashboard_export_insights"])
+ else:
+ selected_ids = list(instance.dashboard_export_insights.values_list("id", flat=True)) if instance else []
+ if selected_ids:
+ live_tiles = live_tiles.filter(insight_id__in=selected_ids)
+ return [query for query in live_tiles.values_list("insight__query", flat=True) if isinstance(query, dict)]
+
+ insight = attrs["insight"] if "insight" in attrs else (instance.insight if instance else None)
+ if insight is not None and not insight.deleted and isinstance(insight.query, dict):
+ return [insight.query]
+ return []
+
+
+def blocked_access_for_subscription(
+ *,
+ user: User,
+ team: Team,
+ user_access_control: UserAccessControl,
+ subscription_id: int | None,
+ attrs: dict[str, Any],
+) -> list[str]:
+ """Names of the tables, and of query resources such as logs, that the requester cannot read
+ among the queries the subscription delivers after this write.
+
+ An empty list means that the write passes the check. The queries are not compiled when the
+ organization does not have access control, or when the requester is an organization admin,
+ because no rule can deny a table in those cases.
+ """
+ if not team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
+ return []
+ if user_access_control.is_organization_admin:
+ return []
+ return blocked_access_for_user(user, team, delivered_queries(_subscription(team.id, subscription_id), attrs))
diff --git a/products/subscriptions/backend/presentation/views.py b/products/subscriptions/backend/presentation/views.py
index 0faed0a56800..899fa0d88b39 100644
--- a/products/subscriptions/backend/presentation/views.py
+++ b/products/subscriptions/backend/presentation/views.py
@@ -87,7 +87,9 @@ from products.subscriptions.backend.facade.api import (
TEAMS_WEBHOOK_URL_ERROR,
TEAMS_WEBHOOK_URL_MASKED_ERROR,
ai_query_plan_status,
+ blocked_access_for_subscription,
sanitize_prompt,
+ should_check_table_access,
validate_re_enable,
)
from products.subscriptions.backend.facade.contracts import (
@@ -1012,8 +1014,32 @@ class SubscriptionWriteSerializer(serializers.ModelSerializer):
organization = self.context["get_organization"]()
self._validate_summary_enabled_org_limit(organization)
+ self._check_query_access(attrs, resource_type)
+
return attrs
+ def _check_query_access(self, attrs: dict, resource_type: str) -> None:
+ if resource_type == Subscription.ResourceType.AI_PROMPT:
+ return
+ team = self.context["get_team"]()
+ subscription_id = self.instance.id if self.instance else None
+ if not should_check_table_access(team_id=team.id, subscription_id=subscription_id, attrs=attrs):
+ return
+ user = self.context["request"].user
+ # Compiling the queries as the requester needs a real user.
+ if not isinstance(user, User):
+ return
+ blocked_names = blocked_access_for_subscription(
+ user=user,
+ team=team,
+ user_access_control=self.context["view"].user_access_control,
+ subscription_id=subscription_id,
+ attrs=attrs,
+ )
+ if blocked_names:
+ blocked = ", ".join(f"`{name}`" for name in blocked_names)
+ raise ValidationError(f"Can't save this subscription: you don't have access to {blocked}.")
+
def _is_becoming_active_summary(self, attrs: dict) -> bool:
pre_summary_enabled = self.instance.summary_enabled if self.instance else False
pre_deleted = self.instance.deleted if self.instance else False
diff --git a/products/subscriptions/backend/tests/test_subscription.py b/products/subscriptions/backend/tests/test_subscription.py
index 9e4b45aa6203..6bb835289956 100644
--- a/products/subscriptions/backend/tests/test_subscription.py
+++ b/products/subscriptions/backend/tests/test_subscription.py
@@ -29,6 +29,7 @@ from posthog.test.insight_queries import browser_filtered_pageview_query, defaul
from products.access_control.backend.models.access_control import AccessControl
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.product_analytics.backend.facade.models import Insight
from products.subscriptions.backend.facade.api import (
AI_REPORT_CHARTS_KEY,
@@ -54,6 +55,7 @@ from products.subscriptions.backend.tests.subscriptions_test_factory import crea
from ee.api.test.base import APILicensedTest
+WAREHOUSE_ACCESS_CONTROL_FLAG = "posthog.hogql.database.database._evaluate_warehouse_access_control_flag"
VALID_TEAMS_WEBHOOK_URL = "https://prod-25.westeurope.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke"
GALLERY_ON_PROMPT_ERROR = (
"post_all_insights_in_main_message only applies to insight and dashboard subscriptions. This "
@@ -4792,3 +4794,81 @@ class TestSubscriptionObjectAccessControl(APILicensedTest):
assert body["attr"] == "dashboard", body
assert "Viewer access to every insight on this dashboard" in body["detail"], body
self.mock_temporal_client.start_workflow.assert_not_called()
+
+ def _insight_over_a_governed_view(self) -> Insight:
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="governed_view",
+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"},
+ columns={"id": "String"},
+ )
+ return Insight.objects.create(
+ team=self.team,
+ query={
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"},
+ },
+ )
+
+ def _deny_warehouse_tables(self) -> None:
+ self._rule("warehouse_objects", for_member=False)
+
+ def _insight_target(self, insight: Insight) -> dict:
+ return {"insight": insight.id}
+
+ def _dashboard_target(self, insight: Insight) -> dict:
+ return {"dashboard": self._dashboard_with_tiles(insight).id, "dashboard_export_insights": [insight.id]}
+
+ @parameterized.expand([("an insight", "_insight_target"), ("a dashboard tile", "_dashboard_target")])
+ def test_create_is_rejected_when_the_caller_cannot_read_a_delivered_table(self, _name, target_builder):
+ insight = self._insight_over_a_governed_view()
+ self._deny_warehouse_tables()
+
+ with patch(WAREHOUSE_ACCESS_CONTROL_FLAG, return_value=True):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions", self._payload(**getattr(self, target_builder)(insight))
+ )
+
+ body = response.json()
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, body
+ assert "Can't save this subscription" in body["detail"], body
+ assert "governed_view" in body["detail"], body
+ assert not Subscription.objects.filter(team_id=self.team.id).exists()
+ self.mock_temporal_client.start_workflow.assert_not_called()
+
+ def test_create_allows_a_member_who_can_read_the_delivered_table(self):
+ insight = self._insight_over_a_governed_view()
+
+ with patch(WAREHOUSE_ACCESS_CONTROL_FLAG, return_value=True):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions", self._payload(insight=insight.id)
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ @parameterized.expand(
+ [
+ ("a new recipient", {}, {"target_value": "[email protected]"}, status.HTTP_400_BAD_REQUEST),
+ ("turning it off", {}, {"deleted": True}, status.HTTP_200_OK),
+ ("disabling it", {}, {"enabled": False}, status.HTTP_200_OK),
+ # The recipient change would outlive the disable, so turning it off does not excuse it.
+ (
+ "disabling it and changing recipients",
+ {},
+ {"enabled": False, "target_value": "[email protected]"},
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ ("restoring it", {"deleted": True}, {"deleted": False}, status.HTTP_400_BAD_REQUEST),
+ ("re-enabling it", {"enabled": False}, {"enabled": True}, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_update_by_a_caller_denied_a_delivered_table_may_only_turn_it_off(self, _name, state, body, expected):
+ subscription = self._subscription_for(insight=self._insight_over_a_governed_view(), **state)
+ self._deny_warehouse_tables()
+
+ with patch(WAREHOUSE_ACCESS_CONTROL_FLAG, return_value=True):
+ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}", body)
+
+ assert response.status_code == expected, response.json()
+ subscription.refresh_from_db()
+ assert subscription.target_value == "[email protected],[email protected]"