Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: gate public sharing on the publisher's table access (#69743)

Alex Lider73c6cd49f34a
diff --git a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts
index e344fb26ea80..53a50a802720 100644
--- a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts
+++ b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts
@@ -276,6 +276,12 @@ export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([
actions.setScrollIndex(values.orderedDashboards.findIndex((d) => d.id === dashboard.id))
},
+ updateInsightFailure: ({ errorObject }) => {
+ // Surface hard rejections (e.g. the target dashboard is publicly shared and the
+ // editor lacks access to this insight's tables) - the modal otherwise fails silently.
+ const detail = (errorObject as { detail?: unknown } | null)?.detail
+ lemonToast.error(typeof detail === 'string' ? detail : 'Could not update dashboards')
+ },
addToDashboard: async ({ dashboardId }) => {
// TODO be able to update not by patching `dashboards` against insight
// either patch dashboard_tiles on the insight or add a dashboard_tiles API
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index 8fefa4b1a4e9..e4ae1cab3dff 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -1857,7 +1857,14 @@ export const notebookLogic = kea<notebookLogicType>([
}
actions.processPendingMarkdownStreamEvents()
},
- saveNotebookFailure: () => {
+ saveNotebookFailure: ({ error }) => {
+ // Surface hard rejections (e.g. adding a query the editor can't run to a publicly shared notebook)
+ // Otherwise autosave fails silently and edits look saved when they aren't.
+ // Transient/network failures keep the quiet retry behavior.
+ const detail = (error as { status?: number; detail?: unknown } | null)?.detail
+ if ((error as { status?: number } | null)?.status === 400 && typeof detail === 'string') {
+ lemonToast.error(detail)
+ }
actions.processPendingMarkdownStreamEvents()
},
loadNotebookSuccess: ({ notebook }) => {
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 367684deb59d..ac07c0130924 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -28,6 +28,7 @@ from posthog.api.data_color_theme import DataColorTheme, DataColorThemeSerialize
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.services.query import process_query_dict
from posthog.api.shared import TeamPublicSerializer
+from posthog.api.sharing_publish_gate import blocked_access_for_publisher
from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication
from posthog.clickhouse.client.async_task_chain import task_chain_context
from posthog.constants import AvailableFeature
@@ -486,6 +487,24 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
# Special case where we need to save the instance for recordings so that the actual record gets created
recording.save()
+ # Publishing is the access decision for shared links (queries on the public page execute
+ # without warehouse access control), so gate the enable transition: the publisher must have
+ # access to everything the artifact queries, or sharing becomes an escalation channel.
+ if (
+ request.data.get("enabled")
+ and not instance.enabled
+ and self.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
+ # org admins have full access, so skip the gate for a faster enable
+ and not self.user_access_control.is_organization_admin
+ ):
+ blocked_names = blocked_access_for_publisher(cast(User, request.user), self.team, instance)
+ if blocked_names:
+ blocked = ", ".join(f"`{name}`" for name in blocked_names)
+ raise ValidationError(
+ f"Can't enable sharing: you don't have access to {blocked}, "
+ "which the shared queries use. Ask an admin for access, or remove those queries first."
+ )
+
serializer = self.get_serializer(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
diff --git a/posthog/api/sharing_publish_gate.py b/posthog/api/sharing_publish_gate.py
new file mode 100644
index 000000000000..0ff8ef369306
--- /dev/null
+++ b/posthog/api/sharing_publish_gate.py
@@ -0,0 +1,163 @@
+"""Publish-time access gate for public sharing.
+
+Shared links execute without warehouse access control (the publish act is the access
+decision - see SharedLinkUser), so the gate moves to the moment of publishing: the member
+enabling a share must be able to run every query it exposes. Otherwise sharing would be an
+escalation channel - save a query over a restricted table, publish, read it through the
+public link.
+"""
+
+from typing import Any
+
+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.modifiers import create_default_modifiers_for_user
+from posthog.hogql.printer import prepare_ast_for_printing
+
+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 posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError
+
+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
+from products.product_analytics.backend.models.insight import Insight
+
+
+def check_can_add_insight_to_shared_dashboard(
+ user: User,
+ dashboard: Dashboard,
+ query: Any,
+ user_access_control: UserAccessControl | None = None,
+) -> None:
+ """Raise if binding an insight with this query to the dashboard would expose, through the
+ dashboard's public link, a query the editor can't run themselves. No-op when the dashboard
+ isn't shared, the org lacks the access control entitlement, or the editor is an org admin."""
+ if not isinstance(query, dict):
+ return
+ if not dashboard.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
+ return
+ uac = user_access_control or UserAccessControl(user=user, team=dashboard.team)
+ # org admins have full access, so skip the gate for a faster write
+ if uac.is_organization_admin:
+ return
+ if not is_publicly_shared(dashboard):
+ return
+ blocked = blocked_access_for_user(user, dashboard.team, [query])
+ if blocked:
+ blocked_list = ", ".join(f"`{name}`" for name in blocked)
+ raise serializers.ValidationError(
+ f"Can't add this insight: you don't have access to {blocked_list}, and this dashboard is publicly shared."
+ )
+
+
+def blocked_access_for_publisher(user: User, team: Team, config: SharingConfiguration) -> list[str]:
+ """
+ Tables and runner-level resources that stop the publisher from running the shared
+ artifact's queries. Each query is compiled (resolved, not executed) as the publisher,
+ the same resolution the read path uses. Non-access compile errors don't gate.
+ Empty list = safe to publish.
+ """
+ return blocked_access_for_user(user, team, _queries_exposed_by(config))
+
+
+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()
+ if insight_ids:
+ queries.extend(
+ q
+ for q in Insight.objects.filter(team_id=config.team_id, id__in=insight_ids).values_list("query", flat=True)
+ if isinstance(q, dict)
+ )
+ if config.notebook:
+ queries.extend(query for _node_id, query in extract_inline_query_nodes(config.notebook.content))
+ return queries
+
+
+def is_publicly_shared(artifact: "Dashboard | Notebook | Insight") -> bool:
+ """Whether an active share exposes the artifact. Dashboards and notebooks are covered by
+ their own share; an insight also transitively - by a shared dashboard's tile or a shared
+ notebook embedding it."""
+ if isinstance(artifact, Insight):
+ live_tile = Q(dashboard__tiles__insight=artifact) & (
+ Q(dashboard__tiles__deleted__isnull=True) | Q(dashboard__tiles__deleted=False)
+ )
+ if SharingConfiguration.objects.filter(
+ SharingConfiguration.tokens_active_q(), Q(insight=artifact) | live_tile
+ ).exists():
+ return True
+ # Notebooks reference insights inside their content JSON, so the few active notebook
+ # shares per team are scanned rather than joined.
+ return any(
+ artifact.short_id in extract_referenced_insight_short_ids(content)
+ for content in SharingConfiguration.objects.filter(
+ SharingConfiguration.tokens_active_q(), team_id=artifact.team_id, notebook__isnull=False
+ ).values_list("notebook__content", flat=True)
+ )
+ field = "dashboard" if isinstance(artifact, Dashboard) else "notebook"
+ return SharingConfiguration.objects.filter(SharingConfiguration.tokens_active_q(), **{field: artifact}).exists()
+
+
+def blocked_access_in_notebook_edit(user: User, notebook: Any, new_content: dict[str, Any] | None) -> list[str]:
+ """Only queries the edit adds or changes are checked,
+ so untouched content (and anything mid-typing that doesn't resolve) never gates."""
+ old_content = notebook.content or {}
+ old_inline = dict(extract_inline_query_nodes(old_content))
+ changed_queries = [
+ query for node_id, query in extract_inline_query_nodes(new_content or {}) if old_inline.get(node_id) != query
+ ]
+
+ added_short_ids = set(extract_referenced_insight_short_ids(new_content or {})) - set(
+ extract_referenced_insight_short_ids(old_content)
+ )
+ if added_short_ids:
+ changed_queries.extend(
+ q
+ for q in Insight.objects.filter(
+ team_id=notebook.team_id, short_id__in=added_short_ids, deleted=False
+ ).values_list("query", flat=True)
+ if isinstance(q, dict)
+ )
+ return blocked_access_for_user(user, notebook.team, changed_queries)
diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
index 49145f7f22eb..d7813752fd0f 100644
--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
@@ -946,6 +946,48 @@
'''
# ---
# name: TestNotebooks.test_updates_notebook.21
+ '''
+ SELECT "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_organization"
+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid
+ LIMIT 21
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.22
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -970,7 +1012,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.22
+# name: TestNotebooks.test_updates_notebook.23
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -993,7 +1035,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.23
+# name: TestNotebooks.test_updates_notebook.24
'''
SELECT "posthog_sharingconfiguration"."id",
"posthog_sharingconfiguration"."team_id",
@@ -1012,7 +1054,7 @@
WHERE "posthog_sharingconfiguration"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.24
+# name: TestNotebooks.test_updates_notebook.25
'''
SELECT "posthog_sharingconfiguration"."id",
"posthog_sharingconfiguration"."team_id",
@@ -1031,7 +1073,7 @@
WHERE "posthog_sharingconfiguration"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.25
+# name: TestNotebooks.test_updates_notebook.26
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
@@ -1041,7 +1083,7 @@
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.26
+# name: TestNotebooks.test_updates_notebook.27
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
@@ -1051,7 +1093,7 @@
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.27
+# name: TestNotebooks.test_updates_notebook.28
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -1097,7 +1139,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.28
+# name: TestNotebooks.test_updates_notebook.29
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."account_id"
@@ -1108,7 +1150,21 @@
LIMIT 1
'''
# ---
-# name: TestNotebooks.test_updates_notebook.29
+# name: TestNotebooks.test_updates_notebook.3
+ '''
+ SELECT "posthog_project"."updated_at",
+ "posthog_project"."id",
+ "posthog_project"."organization_id",
+ "posthog_project"."name",
+ "posthog_project"."created_at",
+ "posthog_project"."product_description",
+ "posthog_project"."is_pending_deletion"
+ FROM "posthog_project"
+ WHERE "posthog_project"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.30
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -1153,21 +1209,7 @@
AND "posthog_user"."id" = 99999)
'''
# ---
-# name: TestNotebooks.test_updates_notebook.3
- '''
- SELECT "posthog_project"."updated_at",
- "posthog_project"."id",
- "posthog_project"."organization_id",
- "posthog_project"."name",
- "posthog_project"."created_at",
- "posthog_project"."product_description",
- "posthog_project"."is_pending_deletion"
- FROM "posthog_project"
- WHERE "posthog_project"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestNotebooks.test_updates_notebook.30
+# name: TestNotebooks.test_updates_notebook.31
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -1209,7 +1251,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.31
+# name: TestNotebooks.test_updates_notebook.32
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1347,7 +1389,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.32
+# name: TestNotebooks.test_updates_notebook.33
'''
SELECT "posthog_project"."updated_at",
"posthog_project"."id",
@@ -1361,7 +1403,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.33
+# name: TestNotebooks.test_updates_notebook.34
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -1412,7 +1454,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.34
+# name: TestNotebooks.test_updates_notebook.35
'''
SELECT "ee_accesscontrol"."id",
"ee_accesscontrol"."team_id",
@@ -1436,7 +1478,7 @@
AND "ee_accesscontrol"."team_id" = 99999))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.35
+# name: TestNotebooks.test_updates_notebook.36
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -1485,7 +1527,7 @@
WHERE "posthog_organizationmembership"."user_id" = 99999
'''
# ---
-# name: TestNotebooks.test_updates_notebook.36
+# name: TestNotebooks.test_updates_notebook.37
'''
SELECT COUNT(*) AS "__count"
FROM "posthog_activitylog"
@@ -1493,7 +1535,7 @@
AND "posthog_activitylog"."team_id" = 99999)
'''
# ---
-# name: TestNotebooks.test_updates_notebook.37
+# name: TestNotebooks.test_updates_notebook.38
'''
SELECT "posthog_activitylog"."id",
"posthog_activitylog"."team_id",
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index bc3a070c88b4..f16263a3f098 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -24,7 +24,7 @@ from posthog.api.sharing import (
shared_url_as_png,
)
from posthog.constants import AvailableFeature
-from posthog.models import ActivityLog
+from posthog.models import ActivityLog, OrganizationMembership
from posthog.models.filters.filter import Filter
from posthog.models.share_password import SharePassword
from posthog.models.sharing_configuration import SharingConfiguration
@@ -34,9 +34,13 @@ from products.dashboards.backend.access import DashboardAccessMethod
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.exports.backend.models.exported_asset import ExportedAsset, get_render_access_token
+from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
+from ee.models.rbac.access_control import AccessControl
+
def mock_exporter_template(test_func):
"""
@@ -1777,3 +1781,452 @@ class TestSharedLinkWarehouseExecution(APIBaseTest):
results = response.json().get("inline_query_results", {})
assert "wh" in results
assert not results["wh"].get("error")
+
+
+@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True))
+class TestSharingPublishGate(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="governed_view",
+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"},
+ columns={"id": "String"},
+ )
+ self.insight = Insight.objects.create(
+ team=self.team,
+ query={
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"},
+ },
+ created_by=self.user,
+ )
+
+ def _deny_warehouse(self) -> None:
+
+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")
+
+ def _enable_sharing(self, kind: str):
+ if kind == "insight":
+ url = f"/api/projects/{self.team.id}/insights/{self.insight.id}/sharing"
+ elif kind == "dashboard":
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+ DashboardTile.objects.create(dashboard=dashboard, insight=self.insight)
+ url = f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/sharing"
+ else:
+ notebook = Notebook.objects.create(
+ team=self.team,
+ created_by=self.user,
+ content={
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "wh",
+ "query": {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"},
+ },
+ },
+ }
+ ],
+ },
+ )
+ url = f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/sharing"
+ return self.client.patch(url, {"enabled": True})
+
+ @parameterized.expand([("insight",), ("dashboard",), ("notebook",)])
+ def test_denied_publisher_cannot_enable_sharing(self, kind: str):
+ self._deny_warehouse()
+
+ response = self._enable_sharing(kind)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "Can't enable sharing" in str(response.json())
+ assert "governed_view" in str(response.json())
+ assert not SharingConfiguration.objects.filter(team=self.team, enabled=True).exists()
+
+ def test_publisher_with_access_can_enable_sharing(self):
+ response = self._enable_sharing("dashboard")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["enabled"] is True
+
+ def test_system_table_denial_blocks_publishing(self):
+
+ AccessControl.objects.create(team=self.team, resource="dashboard", access_level="none")
+ self.insight.query = {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM system.dashboards"},
+ }
+ self.insight.save()
+
+ response = self._enable_sharing("insight")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "system.dashboards" in str(response.json())
+
+ @parameterized.expand([("denied",), ("allowed",)])
+ def test_runner_level_resource_access_gates_publishing(self, case: str):
+ # AccountsQuery enforces access in validate_query_runner_access (resource level),
+ # not per-table - the compile check alone is blind to it.
+ self.insight.query = {"kind": "AccountsQuery"}
+ self.insight.save()
+ if case == "denied":
+ AccessControl.objects.create(team=self.team, resource="customer_analytics", access_level="none")
+
+ response = self._enable_sharing("insight")
+
+ if case == "denied":
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "customer_analytics" in str(response.json())
+ assert not SharingConfiguration.objects.filter(team=self.team, enabled=True).exists()
+ else:
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ def test_already_enabled_share_is_not_regated(self):
+ config = SharingConfiguration.objects.create(team=self.team, insight=self.insight, enabled=True)
+ self._deny_warehouse()
+
+ # Not an enable transition: settings edits on an already-published share stay possible
+ # even if the editor has since lost access to the underlying tables.
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/sharing",
+ {"enabled": True, "settings": {"whitelabel": True}},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ config.refresh_from_db()
+ assert config.enabled is True
+
+ @parameterized.expand([("non_materialized",), ("materialized",)])
+ def test_granted_view_over_denied_table_gates_unless_materialized(self, case: str):
+
+ inner = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="restricted_inner",
+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"},
+ columns={"id": "String"},
+ )
+ outer = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="safe_view",
+ query={"kind": "HogQLQuery", "query": "SELECT id FROM restricted_inner"},
+ columns={"id": "String"},
+ )
+ AccessControl.objects.create(
+ team=self.team, resource="warehouse_view", resource_id=str(inner.id), access_level="none"
+ )
+ self.insight.query = {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM safe_view"},
+ }
+ self.insight.save()
+ if case == "materialized":
+ from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
+
+ credential = DataWarehouseCredential.objects.create(access_key="k", access_secret="s", team=self.team)
+ backing = DataWarehouseTable.objects.create(
+ name=outer.name,
+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ team=self.team,
+ credential=credential,
+ url_pattern=outer.url_pattern,
+ columns={"id": "String"},
+ )
+ outer.table = backing
+ outer.is_materialized = True
+ outer.save(update_fields=["table", "is_materialized"])
+
+ response = self._enable_sharing("insight")
+
+ if case == "materialized":
+ # A granted materialized view resolves to its backing table - the recommended
+ # "grant safe views" setup stays publishable.
+ assert response.status_code == status.HTTP_200_OK, response.content
+ else:
+ # A non-materialized view re-resolves through its underlying tables, exactly like
+ # the publisher's own in-app run - so it can't be published either. This is the
+ # compile-vs-name-level distinction: a name-level check would let this through.
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "restricted_inner" in str(response.json())
+
+ def test_unparseable_query_does_not_block_publishing(self):
+ self._deny_warehouse()
+ self.insight.query = {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT FROM WHERE ((("},
+ }
+ self.insight.save()
+
+ # A broken query errors for everyone at view time - that's not an access problem,
+ # so it must not block publishing.
+ response = self._enable_sharing("insight")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+
+@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True))
+class TestSaveTimeAccessBlock(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="governed_view",
+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"},
+ columns={"id": "String"},
+ )
+ self.insight = Insight.objects.create(
+ team=self.team,
+ query={"kind": "DataTableNode", "source": {"kind": "HogQLQuery", "query": "SELECT 1 AS one"}},
+ created_by=self.user,
+ )
+
+ def _deny_editor(self) -> None:
+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")
+
+ _DENIED_QUERY = {"kind": "DataTableNode", "source": {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"}}
+
+ def _patch_insight_query(self):
+ return self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/", {"query": self._DENIED_QUERY}
+ )
+
+ @parameterized.expand([("direct",), ("dashboard",), ("notebook",)])
+ def test_query_update_blocked_when_insight_is_publicly_shared(self, coverage: str):
+ self._deny_editor()
+ if coverage == "direct":
+ SharingConfiguration.objects.create(team=self.team, insight=self.insight, enabled=True)
+ elif coverage == "dashboard":
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+ DashboardTile.objects.create(dashboard=dashboard, insight=self.insight)
+ SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
+ else:
+ notebook = Notebook.objects.create(
+ team=self.team,
+ created_by=self.user,
+ content={
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "e1",
+ "query": {"kind": "SavedInsightNode", "shortId": self.insight.short_id},
+ },
+ }
+ ],
+ },
+ )
+ SharingConfiguration.objects.create(team=self.team, notebook=notebook, enabled=True)
+
+ response = self._patch_insight_query()
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "publicly shared" in str(response.json())
+ self.insight.refresh_from_db()
+ assert self.insight.query == {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT 1 AS one"},
+ }
+
+ def test_query_update_allowed_when_not_shared(self):
+ self._deny_editor()
+
+ response = self._patch_insight_query()
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ def test_adding_insight_to_shared_dashboard_blocked(self):
+ self._deny_editor()
+ self.insight.query = self._DENIED_QUERY
+ self.insight.save()
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+ SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/", {"dashboards": [dashboard.id]}
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "publicly shared" in str(response.json())
+ assert not DashboardTile.objects.filter(dashboard=dashboard, insight=self.insight).exists()
+
+ def test_adding_insight_to_unshared_dashboard_allowed(self):
+ self._deny_editor()
+ self.insight.query = self._DENIED_QUERY
+ self.insight.save()
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/", {"dashboards": [dashboard.id]}
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ def _shared_notebook(self, content: dict) -> Notebook:
+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, content=content, version=1)
+ SharingConfiguration.objects.create(team=self.team, notebook=notebook, enabled=True)
+ return notebook
+
+ def _patch_notebook_content(self, notebook: Notebook, content: dict):
+ return self.client.patch(
+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/",
+ {"content": content, "version": notebook.version},
+ )
+
+ @parameterized.expand(
+ [
+ ("inline_query", {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"}),
+ ("incomplete_query", {"kind": "HogQLQuery", "query": "SELECT FROM WHERE ((("}),
+ ]
+ )
+ def test_notebook_edit_adding_inline_query(self, case: str, source: dict):
+ self._deny_editor()
+ notebook = self._shared_notebook({"type": "doc", "content": []})
+ new_content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {"nodeId": "n1", "query": {"kind": "DataTableNode", "source": source}},
+ }
+ ],
+ }
+
+ response = self._patch_notebook_content(notebook, new_content)
+
+ if case == "inline_query":
+ # A publicly shared notebook must not accept queries the editor can't run.
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "publicly shared" in str(response.json())
+ else:
+ # Broken mid-typing content isn't an access problem - autosave keeps flowing.
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ def test_notebook_edit_untouched_denied_query_does_not_gate(self):
+ self._deny_editor()
+ denied_node = {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "n1",
+ "query": {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"},
+ },
+ },
+ }
+ notebook = self._shared_notebook({"type": "doc", "content": [denied_node]})
+ # Only the edit's delta is checked - pre-existing content never re-gates an autosave.
+ new_content = {"type": "doc", "content": [denied_node, {"type": "paragraph"}]}
+
+ response = self._patch_notebook_content(notebook, new_content)
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ def test_notebook_collab_save_blocked_for_denied_query(self):
+ # Collab saves write content directly (not through NotebookSerializer.update), so the
+ # guard must exist on that path too - otherwise collab-enabled notebooks bypass the gate.
+ self._deny_editor()
+ notebook = self._shared_notebook({"type": "doc", "content": []})
+ new_content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "n1",
+ "query": {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"},
+ },
+ },
+ }
+ ],
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/collab/save/",
+ data={"client_id": "c1", "version": notebook.version, "steps": [], "content": new_content},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "publicly shared" in str(response.json())
+ notebook.refresh_from_db()
+ assert notebook.content == {"type": "doc", "content": []}
+
+ def test_notebook_markdown_save_blocked_for_denied_query(self):
+ # The markdown editor autosaves through collab/markdown_save, a third write path that also
+ # persists content directly - without the guard here, markdown notebooks bypass the gate.
+ self._deny_editor()
+ notebook = self._shared_notebook({"type": "doc", "content": []})
+ denied_query = {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT id FROM governed_view"},
+ }
+ new_content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-markdown-notebook",
+ "attrs": {
+ "nodeId": "markdown-notebook-v2",
+ "markdown": '<Query nodeId="q1" query={' + json.dumps(denied_query) + "} />",
+ },
+ }
+ ],
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/collab/markdown_save/",
+ data={"client_id": "c1", "version": notebook.version, "content": new_content, "text_content": ""},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "publicly shared" in str(response.json())
+ notebook.refresh_from_db()
+ assert notebook.content == {"type": "doc", "content": []}
+
+ def test_notebook_embedding_denied_insight_blocked(self):
+ self._deny_editor()
+ self.insight.query = self._DENIED_QUERY
+ self.insight.save()
+ notebook = self._shared_notebook({"type": "doc", "content": []})
+ new_content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "e1",
+ "query": {"kind": "SavedInsightNode", "shortId": self.insight.short_id},
+ },
+ }
+ ],
+ }
+
+ response = self._patch_notebook_content(notebook, new_content)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "publicly shared" in str(response.json())
diff --git a/posthog/auth.py b/posthog/auth.py
index 63fd1c58b5b8..d1f61a6d6057 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -728,9 +728,9 @@ class SharingAccessTokenAuthentication(authentication.BaseAuthentication):
if request.method not in ["GET", "HEAD"]:
raise AuthenticationFailed(detail="Sharing access token can only be used for GET requests.")
try:
- sharing_configuration = SharingConfiguration.objects.filter(
- models.Q(expires_at__isnull=True) | models.Q(expires_at__gt=timezone.now())
- ).get(access_token=sharing_access_token, enabled=True)
+ sharing_configuration = SharingConfiguration.objects.filter(SharingConfiguration.tokens_active_q()).get(
+ access_token=sharing_access_token
+ )
# If password is required, don't authenticate via direct access_token
# Let the view handle showing the unlock page
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index b5e44b96de52..12ff9e190f15 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -139,7 +139,7 @@ from posthog.hogql.database.schema.web_stats_preaggregated import WebStatsPreagg
from posthog.hogql.database.schema.web_vitals_paths_preaggregated import WebVitalsPathsPreaggregatedTable
from posthog.hogql.database.utils import get_join_field_chain, qualify_join_key_expr
from posthog.hogql.database.warehouse_join_resolvers import data_warehouse_resolver_params
-from posthog.hogql.errors import QueryError, ResolutionError
+from posthog.hogql.errors import QueryError, ResolutionError, TableAccessDeniedError
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr
from posthog.hogql.timings import HogQLTimings
@@ -586,7 +586,7 @@ class Database(BaseModel):
if isinstance(table_name, list):
table_name = ".".join(table_name)
if table_name in self._denied_tables:
- raise QueryError(f"You don't have access to table `{table_name}`.") from e
+ raise TableAccessDeniedError(table_name) from e
suggestions = self._suggest_table_names(table_name)
suffix = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
raise QueryError(f"Unknown table `{table_name}`.{suffix}") from e
diff --git a/posthog/hogql/errors.py b/posthog/hogql/errors.py
index 6e5d563b1f8a..9f4113995869 100644
--- a/posthog/hogql/errors.py
+++ b/posthog/hogql/errors.py
@@ -59,6 +59,16 @@ class QueryError(ExposedHogQLError):
pass
+class TableAccessDeniedError(QueryError):
+ """The user has no access to the table (raised by Database.get_table)."""
+
+ table_name: str
+
+ def __init__(self, table_name: str):
+ super().__init__(f"You don't have access to table `{table_name}`.")
+ self.table_name = table_name
+
+
class NotImplementedError(InternalHogQLError):
"""This feature isn't implemented in HogQL (yet)."""
diff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.py
index b441a49d379e..dc577d56450d 100644
--- a/posthog/models/sharing_configuration.py
+++ b/posthog/models/sharing_configuration.py
@@ -100,6 +100,14 @@ class SharingConfiguration(models.Model):
"interviewee_context": interviewee_context,
}
+ @classmethod
+ def tokens_active_q(cls) -> models.Q:
+ """Matches shares whose public tokens currently work: enabled, and either unexpired or
+ inside the rotation grace period. This is the exposure question ("does a working link
+ exist?") - distinct from queryset_active_for_resource, which picks the current config row
+ for a resource and ignores grace-period duplicates."""
+ return models.Q(enabled=True) & (models.Q(expires_at__isnull=True) | models.Q(expires_at__gt=timezone.now()))
+
@classmethod
def queryset_active_for_resource(cls, **resource_lookup: Any) -> models.QuerySet["SharingConfiguration"]:
return cls.objects.filter(**resource_lookup, expires_at__isnull=True).order_by("-created_at")
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index d85d074a1321..d054e3b90979 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -53,6 +53,7 @@ from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
+from posthog.api.sharing_publish_gate import check_can_add_insight_to_shared_dashboard
from posthog.api.streaming import sse_streaming_response
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action
@@ -1715,7 +1716,9 @@ class DashboardSerializer(DashboardMetadataSerializer):
)
@staticmethod
- def _update_existing_tile_display_fields(instance: Dashboard, tile_data: dict) -> tuple[DashboardTile | None, bool]:
+ def _update_existing_tile_display_fields(
+ instance: Dashboard, tile_data: dict, user: User
+ ) -> tuple[DashboardTile | None, bool]:
"""Update display fields on an existing tile, or skip silently if the id is unknown.
A display-only payload carries no insight/text/button_tile FK, so it cannot satisfy
@@ -1747,6 +1750,18 @@ class DashboardSerializer(DashboardMetadataSerializer):
return None, False
became_deleted = bool(tile_defaults.get("deleted")) and not existing.deleted
+ # `deleted` is raw request input; coerce it exactly as the ORM will on save, so a value
+ # Django stores as False but Python reads as truthy ("0", "False") can't skip the gate.
+ deleted_field = DashboardTile._meta.get_field("deleted")
+ became_live = (
+ existing.deleted and "deleted" in tile_defaults and not deleted_field.to_python(tile_defaults["deleted"])
+ )
+
+ # Un-deleting a tile re-exposes its insight on the dashboard's public link.
+ insight = existing.insight
+ if became_live and insight is not None:
+ check_can_add_insight_to_shared_dashboard(user, instance, insight.query)
+
for attr, val in tile_defaults.items():
setattr(existing, attr, val)
# update_fields scopes the UPDATE to only the columns we changed, so concurrent writes
@@ -1908,7 +1923,9 @@ class DashboardSerializer(DashboardMetadataSerializer):
or "transparent_background" in tile_data
):
tile_data.pop("insight", None) # don't ever update insight tiles here
- updated_tile, became_deleted = DashboardSerializer._update_existing_tile_display_fields(instance, tile_data)
+ updated_tile, became_deleted = DashboardSerializer._update_existing_tile_display_fields(
+ instance, tile_data, user
+ )
# The dashboard UI soft-deletes tiles through this PATCH path rather than the
# delete_tile endpoint, so removal analytics must fire here too.
if became_deleted and updated_tile is not None:
@@ -2513,6 +2530,11 @@ class DashboardsViewSet(
if tile.widget is None:
raise exceptions.ValidationError("Widget tile is missing its widget.")
DashboardSerializer._check_widget_tile_product_access(tile.widget, user_access_control)
+ if tile.insight is not None:
+ # The destination's public link must not expose a query the editor can't run.
+ check_can_add_insight_to_shared_dashboard(
+ cast(User, request.user), to_dashboard_obj, tile.insight.query, self.user_access_control
+ )
try:
with transaction.atomic():
tile.prepare_move_to_dashboard(to_dashboard)
@@ -2586,6 +2608,11 @@ class DashboardsViewSet(
if DashboardTile.objects.filter(dashboard=destination, insight=tile.insight).exists():
raise exceptions.ValidationError("This insight is already on the destination dashboard.")
+
+ # The destination's public link must not expose a query the editor can't run.
+ check_can_add_insight_to_shared_dashboard(
+ cast(User, request.user), destination, tile.insight.query, user_access_control
+ )
elif tile.text is not None:
if DashboardTile.objects.filter(dashboard=destination, text=tile.text).exists():
raise exceptions.ValidationError("This text card is already on the destination dashboard.")
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 15a1fc3398b6..f7133cbe149b 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -33,9 +33,11 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
+from posthog.api.sharing_publish_gate import blocked_access_in_notebook_edit, is_publicly_shared
from posthog.api.streaming import sse_streaming_response
from posthog.api.utils import action
from posthog.auth import SessionAuthentication
+from posthog.constants import AvailableFeature
from posthog.exceptions import Conflict
from posthog.helpers.impersonation import is_impersonated
from posthog.models import User
@@ -291,6 +293,27 @@ class NotebookSerializer(NotebookMinimalSerializer):
raise Conflict("Someone else edited the Notebook")
validated_data["version"] = locked_instance.version + 1
+
+ # A publicly shared notebook's link would expose any query this save adds or
+ # changes, so the editor must be able to run them. Only changed queries are
+ # checked, and only when a share exists - normal autosave on unshared
+ # notebooks does no access work at all.
+ if (
+ locked_instance.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
+ # org admins have full access, so skip the gate for a faster save
+ and not (self.user_access_control and self.user_access_control.is_organization_admin)
+ and is_publicly_shared(locked_instance)
+ ):
+ blocked = blocked_access_in_notebook_edit(
+ self.context["request"].user, locked_instance, validated_data.get("content")
+ )
+ if blocked:
+ blocked_list = ", ".join(f"`{name}`" for name in blocked)
+ raise serializers.ValidationError(
+ f"Can't save: you don't have access to {blocked_list}, "
+ "and this notebook is publicly shared."
+ )
+
content = validated_data.get("content")
if isinstance(content, dict):
validated_data["content"] = annotate_python_nodes(content)
@@ -1284,6 +1307,22 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
user = cast(User, request.user)
user_name = _collab_user_name(user)
+ # Same guard as NotebookSerializer.update - collab saves write content directly, so
+ # without it the collab path would bypass the shared-notebook access block entirely.
+ # Must run before submit_steps: once steps are accepted, peers have already applied them.
+ if (
+ notebook.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
+ # org admins have full access, so skip the gate for a faster save
+ and not self.user_access_control.is_organization_admin
+ and is_publicly_shared(notebook)
+ ):
+ blocked = blocked_access_in_notebook_edit(user, notebook, data.get("content"))
+ if blocked:
+ blocked_list = ", ".join(f"`{name}`" for name in blocked)
+ raise serializers.ValidationError(
+ f"Can't save: you don't have access to {blocked_list}, and this notebook is publicly shared."
+ )
+
result = submit_steps(
team_id=notebook.team_id,
notebook_id=str(notebook.short_id),
@@ -1371,6 +1410,21 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
user = cast(User, request.user)
submitted_content = data["content"]
+ # Same guard as NotebookSerializer.update and collab_save - markdown saves also write
+ # content directly, so without it this path would bypass the shared-notebook access block.
+ if (
+ notebook.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
+ # org admins have full access, so skip the gate for a faster save
+ and not self.user_access_control.is_organization_admin
+ and is_publicly_shared(notebook)
+ ):
+ blocked = blocked_access_in_notebook_edit(user, notebook, submitted_content)
+ if blocked:
+ blocked_list = ", ".join(f"`{name}`" for name in blocked)
+ raise serializers.ValidationError(
+ f"Can't save: you don't have access to {blocked_list}, and this notebook is publicly shared."
+ )
+
notebook_before: Notebook | None = None
with transaction.atomic():
# The row lock serializes the Postgres version check with the Redis stream append, so
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 95cdba7c4ddc..a18159ed8d27 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -51,6 +51,11 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.services.query import process_query_dict, process_query_model
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
+from posthog.api.sharing_publish_gate import (
+ blocked_access_for_user,
+ check_can_add_insight_to_shared_dashboard,
+ is_publicly_shared,
+)
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action, format_paginated_url
from posthog.auth import (
@@ -63,7 +68,7 @@ from posthog.caching.fetch_from_cache import InsightResult, fetch_cached_respons
from posthog.clickhouse.cancel import cancel_query_on_cluster
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import AccessMethod, tags_context
-from posthog.constants import INSIGHT
+from posthog.constants import INSIGHT, AvailableFeature
from posthog.errors import ExposedCHQueryError
from posthog.event_usage import EventSource, get_event_source, get_request_analytics_properties, report_user_action
from posthog.exceptions_capture import capture_exception
@@ -742,6 +747,11 @@ class InsightSerializer(InsightBasicSerializer):
if dashboard.team_id != team_id:
raise serializers.ValidationError("Dashboard not found")
+ # The dashboard's public link must not expose a query the editor can't run.
+ check_can_add_insight_to_shared_dashboard(
+ request.user, dashboard, validated_data.get("query"), self.user_access_control
+ )
+
# Counts the field being accepted as write input (even an empty list), after
# permission checks so rejected requests don't inflate the metric.
_record_deprecated_dashboards_field_used(self.context, usage="write")
@@ -822,6 +832,26 @@ class InsightSerializer(InsightBasicSerializer):
instance.last_modified_at = now()
instance.last_modified_by = self.context["request"].user
+ # Shared links execute without access checks, so an edit that adds a table
+ # the editor can't run must not reach a publicly shared surface.
+ # Unshared insights save without any access query.
+ new_query = validated_data.get("query")
+ if (
+ isinstance(new_query, dict)
+ and new_query != instance.query
+ and instance.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
+ # org admins have full access, so skip the gate for a faster save
+ and not (self.user_access_control and self.user_access_control.is_organization_admin)
+ and is_publicly_shared(instance)
+ ):
+ blocked = blocked_access_for_user(self.context["request"].user, instance.team, [new_query])
+ if blocked:
+ blocked_list = ", ".join(f"`{name}`" for name in blocked)
+ raise serializers.ValidationError(
+ f"Can't save this query: you don't have access to {blocked_list}, "
+ "and this insight is publicly shared."
+ )
+
if validated_data.get("deleted", False):
DashboardTile.objects_including_soft_deleted.filter(insight__id=instance.id).update(deleted=True)
for alert in instance.alertconfiguration_set.all():
@@ -930,6 +960,11 @@ class InsightSerializer(InsightBasicSerializer):
if dashboard.team != instance.team:
raise serializers.ValidationError("Dashboard not found")
+ # The dashboard's public link must not expose a query the editor can't run.
+ check_can_add_insight_to_shared_dashboard(
+ self.context["request"].user, dashboard, instance.query, self.user_access_control
+ )
+
tile, _ = DashboardTile.objects_including_soft_deleted.get_or_create(insight=instance, dashboard=dashboard)
if tile.deleted: