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: execute publicly shared queries without warehouse access control (#68311)

Alex Liderce228aee0894
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 52b9bdfd9e89..faee85062bc0 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -43,6 +43,7 @@ from posthog.rbac.user_access_control import UserAccessControl, access_level_sat
from posthog.scopes import APIScopeObject
from posthog.security.url_validation import is_url_allowed
from posthog.session_recordings.session_recording_api import SessionRecordingSerializer
+from posthog.shared_link_user import SharedLinkUser
from posthog.user_permissions import UserPermissions
from posthog.utils import get_ip_address, render_template
from posthog.views import preflight_check
@@ -702,13 +703,15 @@ def custom_404_response(request):
return render(request, "shared_resource_404.html", status=404)
-def _compute_inline_query_results_for_shared_notebook(notebook: Notebook, team: Team) -> dict[str, Any]:
+def _compute_inline_query_results_for_shared_notebook(
+ notebook: Notebook, team: Team, user: Optional[User]
+) -> dict[str, Any]:
"""Pre-compute results for every inline (non-saved-insight) ``ph-query`` node in a notebook.
Mirrors the shared-insight path (`InsightSerializer.insight_result`) but for queries that
live inline in node attrs rather than as a `SavedInsightNode`. Each query is executed under
`shared_insights_execution_mode`, which uses the cache aggressively and refreshes async if
- stale — the same throttle dashboards use.
+ stale — the same throttle dashboards use. Queries run as the shared-link user (anonymous).
Returns a map of ``nodeId -> serialized result dict``. Nodes whose query fails to execute
are silently omitted; the frontend renders ``UnsupportedNodePlaceholder`` for any inline
@@ -727,7 +730,7 @@ def _compute_inline_query_results_for_shared_notebook(notebook: Notebook, team:
team,
query,
execution_mode=execution_mode,
- user=None,
+ user=user,
)
if isinstance(result, BaseModel):
serialized = result.model_dump(mode="json")
@@ -928,6 +931,12 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
message="Failed to parse cache_keys parameter - continuing without it",
)
+ # The /shared/ page resolves the token from the URL, so no authenticator runs and request.user
+ # is a bare AnonymousUser. Shared queries execute without warehouse access control.
+ shared_link_user = (
+ cast("User | None", SharedLinkUser(resource)) if isinstance(resource, SharingConfiguration) else None
+ )
+
context = {
"view": self,
"request": request,
@@ -936,6 +945,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
"get_team": lambda: resource.team,
"insight_variables": InsightVariable.objects.filter(team=resource.team).all(),
"export_cache_keys": export_cache_keys,
+ "shared_link_user": shared_link_user,
}
exported_data: dict[str, Any] = {"type": "embed" if embedded else "scene"}
@@ -1245,7 +1255,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
exported_data.update(
{
"inline_query_results": _compute_inline_query_results_for_shared_notebook(
- resource.notebook, resource.team
+ resource.notebook, resource.team, shared_link_user
)
}
)
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index 4630765166b1..2034bf9d0d6e 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -1663,3 +1663,94 @@ class TestSharingResourceEditChecks(APIBaseTest):
check_can_edit_sharing_configuration(view, request, sharing)
assert "cannot be shared through this endpoint" in str(caught.exception)
+
+
+def _warehouse_ac_flag(key: str, *args, **kwargs) -> bool:
+ return key == "hogql-warehouse-access-control"
+
+
+@patch("posthoganalytics.feature_enabled", new=Mock(side_effect=_warehouse_ac_flag))
+class TestSharedLinkWarehouseExecution(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+
+ 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()
+
+ 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,
+ )
+ self.client.logout()
+
+ def test_shared_insight_over_warehouse_executes_via_token_api(self):
+ config = SharingConfiguration.objects.create(team=self.team, insight=self.insight, enabled=True)
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/"
+ f"?sharing_access_token={config.access_token}&refresh=blocking"
+ )
+
+ # Warehouse-backed shared insight executes (AC bypassed) instead of failing closed userless.
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert not response.json().get("result_error")
+
+ def test_shared_dashboard_page_refresh_computes_warehouse_tile(self):
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+ DashboardTile.objects.create(dashboard=dashboard, insight=self.insight)
+ config = SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
+
+ # The /shared/ page normally serves cached results and refreshes them async; refresh=blocking
+ # is the only flow that executes the query during this request. That execution runs as the
+ # shared-link user from the page context - if that wiring breaks, it runs userless and fails closed.
+ response = self.client.get(f"/shared/{config.access_token}.json?refresh=blocking")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ tiles = response.json()["dashboard"]["tiles"]
+ assert len(tiles) == 1
+ assert tiles[0]["insight"]["result"], tiles[0]["insight"].get("result_error")
+
+ def test_shared_notebook_inline_warehouse_query_executes(self):
+ from products.notebooks.backend.models import Notebook
+
+ 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"},
+ },
+ },
+ }
+ ],
+ },
+ )
+ config = SharingConfiguration.objects.create(team=self.team, notebook=notebook, enabled=True)
+
+ response = self.client.get(f"/shared/{config.access_token}.json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ results = response.json().get("inline_query_results", {})
+ assert "wh" in results
+ assert not results["wh"].get("error")
diff --git a/posthog/auth.py b/posthog/auth.py
index 33fb5a06bffa..630ecccc1e98 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -47,6 +47,7 @@ from posthog.models.user import User
from posthog.models.utils import hash_key_value
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.passkey import verify_passkey_authentication_response
+from posthog.shared_link_user import SharedLinkUser
from posthog.synthetic_user import SyntheticUser
@@ -764,7 +765,7 @@ class SharingAccessTokenAuthentication(authentication.BaseAuthentication):
raise AuthenticationFailed(detail="Sharing access token is invalid.")
self.sharing_configuration = sharing_configuration
- return (AnonymousUser(), None)
+ return (SharedLinkUser(sharing_configuration), None)
return None
@@ -826,7 +827,7 @@ class SharingPasswordProtectedAuthentication(authentication.BaseAuthentication):
self.sharing_configuration = sharing_configuration
self.share_password = share_password
- return (AnonymousUser(), None)
+ return (SharedLinkUser(sharing_configuration), None)
except jwt.InvalidTokenError:
# Expected: JWT decode failed (likely a personal API key was passed)
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 02a4641cf8ca..e69a0c763ce6 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -151,6 +151,7 @@ from posthog.ph_client import feature_enabled_or_false
from posthog.rbac.user_access_control import NO_ACCESS_LEVEL, UserAccessControl
from posthog.schema_enums import DatabaseSerializedFieldType, PersonsOnEventsMode, SessionTableVersion
from posthog.scopes import APIScopeObject
+from posthog.shared_link_user import SharedLinkUser
from posthog.synthetic_user import SyntheticUser
from products.data_tools.backend.models.join import DataWarehouseJoin
@@ -205,7 +206,7 @@ class HogQLDatabaseSources:
build phase runs without any queries."""
team: "Team"
- user: Optional["User | SyntheticUser"]
+ user: Optional["User | SyntheticUser | SharedLinkUser"]
connection_id: str | None
modifiers: "HogQLQueryModifiers"
is_managed_viewset_enabled: bool
@@ -462,7 +463,7 @@ def _system_table_access_scopes() -> tuple[tuple[str, APIScopeObject], ...]:
def _compute_system_table_access_decision(
team: "Team",
- user: Optional["User | SyntheticUser"],
+ user: Optional["User | SyntheticUser | SharedLinkUser"],
user_access_control: Optional["UserAccessControl"] = None,
) -> tuple[Optional["UserAccessControl"], set[str]]:
"""Decide which scoped system tables to hide, doing the access-control I/O here so the build phase
@@ -472,8 +473,8 @@ def _compute_system_table_access_decision(
Pass user_access_control when it's already preloaded to reuse the instance and avoid an extra query."""
scoped_tables = _system_table_access_scopes()
- # Anonymous or synthetic principal: keep only access-controlled tables its scopes cover (none for anonymous / team token).
- if user is None or isinstance(user, SyntheticUser):
+ # Anonymous or synthetic principal: keep only access-controlled tables its scopes cover (none for shared link / team token).
+ if user is None or isinstance(user, SyntheticUser | SharedLinkUser):
readable_scopes = user.readable_system_table_access_scopes() if user is not None else set()
return None, {name for name, access_scope in scoped_tables if access_scope not in readable_scopes}
@@ -1064,7 +1065,7 @@ class Database(BaseModel):
team_id: int | None = None,
*,
team: Optional["Team"] = None,
- user: Optional["User | SyntheticUser"] = None,
+ user: Optional["User | SyntheticUser | SharedLinkUser"] = None,
user_access_control: Optional["UserAccessControl"] = None,
modifiers: "HogQLQueryModifiers | None" = None,
timings: HogQLTimings | None = None,
@@ -1094,7 +1095,7 @@ class Database(BaseModel):
team_id: int | None = None,
*,
team: Optional["Team"] = None,
- user: Optional["User | SyntheticUser"] = None,
+ user: Optional["User | SyntheticUser | SharedLinkUser"] = None,
user_access_control: Optional["UserAccessControl"] = None,
modifiers: "HogQLQueryModifiers | None" = None,
timings: HogQLTimings | None = None,
@@ -1323,11 +1324,12 @@ class Database(BaseModel):
modifiers=modifiers,
is_managed_viewset_enabled=is_managed_viewset_enabled,
is_hogql_warehouse_access_control_enabled=is_hogql_warehouse_access_control_enabled,
- # Synthetic principals (project secret API keys) are project-wide and bypass object-level
- # RBAC by design, so they bypass warehouse access control too. System tables stay
- # scope-gated for them via _compute_system_table_access_decision above. This field only
- # gates the warehouse checks in _build_from_sources.
- bypass_warehouse_access_control=bypass_warehouse_access_control or isinstance(user, SyntheticUser),
+ # Principals that skip warehouse access control by design:
+ # - synthetic users (project-wide service tokens, bypass object-level RBAC)
+ # - shared-link users (publishing is the explicit access grant).
+ # System tables stay gated for both.
+ bypass_warehouse_access_control=bypass_warehouse_access_control
+ or isinstance(user, SyntheticUser | SharedLinkUser),
direct_connection_metadata=direct_connection_metadata,
user_access_control=user_access_control,
denied_system_table_names=denied_system_table_names,
diff --git a/posthog/hogql/printer/test/test_hogql_access_control.py b/posthog/hogql/printer/test/test_hogql_access_control.py
index 312f939b5eed..75a25aec27ff 100644
--- a/posthog/hogql/printer/test/test_hogql_access_control.py
+++ b/posthog/hogql/printer/test/test_hogql_access_control.py
@@ -1,8 +1,12 @@
+from typing import cast
+
from posthog.test.base import BaseTest
from unittest.mock import Mock, patch
from parameterized import parameterized
+from posthog.schema import HogQLQuery
+
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
@@ -10,7 +14,11 @@ from posthog.hogql.database.schema.system import SystemTables
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
from posthog.hogql.printer.access_control import build_access_control_guard
-from posthog.models import OrganizationMembership
+from posthog.hogql_queries.query_runner import get_query_runner
+from posthog.models import OrganizationMembership, User
+from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.shared_link_user import SharedLinkUser
+from posthog.synthetic_user import SyntheticUser
class TestAccessControlSystemTables(BaseTest):
@@ -839,6 +847,63 @@ class TestWarehouseViewAccessControl(BaseTest):
assert "denied_view" not in database._denied_tables
assert "allowed_view" not in database._denied_tables
+ def test_shared_link_user_skips_warehouse_view_acl_but_hides_system_tables(self):
+ self._create_ac(
+ resource="warehouse_view",
+ resource_id=str(self.denied_view.id),
+ access_level="none",
+ member=self._membership(),
+ )
+ viewer = SharedLinkUser(SharingConfiguration(team=self.team, enabled=True))
+
+ database = Database.create_for(team=self.team, user=viewer)
+
+ # A shared-link viewer executes without warehouse access control - the deny is skipped.
+ assert "denied_view" not in database._denied_tables
+ assert "allowed_view" not in database._denied_tables
+ # But scoped system tables stay hidden, exactly like a userless build.
+ assert "system.dashboards" in database._denied_tables
+
+ def test_shared_link_user_requires_enabled_configuration(self):
+ with self.assertRaises(ValueError):
+ SharedLinkUser(SharingConfiguration(team=self.team, enabled=False))
+
+ def test_shared_link_cache_key_differs_from_denied_member(self):
+ # Resource-level deny: no per-object IDs land in the cache payload, so the restriction
+ # lists alone must keep the two principals' cache keys apart.
+ self._create_ac(resource="warehouse_objects", access_level="none")
+ query = HogQLQuery(query="SELECT id FROM denied_view")
+ shared_user = cast(User, SharedLinkUser(SharingConfiguration(team=self.team, enabled=True)))
+
+ shared_key = get_query_runner(query, self.team, user=shared_user).get_cache_key()
+ denied_key = get_query_runner(query, self.team, user=self.user).get_cache_key()
+
+ # A shared-link run executes with the warehouse bypass and writes its result to cache;
+ # if the keys collided, the denied member would be served that result on a cache hit
+ assert shared_key != denied_key
+
+ # Queries touching no access-controlled tables keep sharing one cache entry across
+ # principals - the partition must not cost public dashboards their warmed cache results
+ events_query = HogQLQuery(query="SELECT count() FROM events")
+ assert (
+ get_query_runner(events_query, self.team, user=shared_user).get_cache_key()
+ == get_query_runner(events_query, self.team, user=self.user).get_cache_key()
+ )
+
+ def test_synthetic_principal_skips_warehouse_view_acl(self):
+ self._create_ac(
+ resource="warehouse_view",
+ resource_id=str(self.denied_view.id),
+ access_level="none",
+ member=self._membership(),
+ )
+
+ database = Database.create_for(team=self.team, user=SyntheticUser(self.team, "test-token"))
+
+ # Service-token principals bypass warehouse access control by design (see Database.create_for).
+ assert "denied_view" not in database._denied_tables
+ assert "system.dashboards" in database._denied_tables
+
def _materialize(self, view):
"""Attach a same-named backing DataWarehouseTable to a saved query, mirroring materialization."""
from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 17a73ec245a9..904287627792 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -124,9 +124,10 @@ from posthog.hogql_queries.validation.validation import (
from posthog.models import Team, User
from posthog.models.team import WeekStartDay
from posthog.models.team.event_retention import events_retention_months_for_team
-from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError
+from posthog.rbac.user_access_control import WAREHOUSE_ACCESS_SCOPES, UserAccessControl, UserAccessControlError
from posthog.schema_helpers import to_dict
from posthog.scopes import APIScopeObject
+from posthog.shared_link_user import SharedLinkUser
from posthog.slo.context import JsonValue, SloSpec, slo_operation
from posthog.slo.types import SloArea, SloOperation, SloOutcome
from posthog.synthetic_user import SyntheticUser
@@ -1664,10 +1665,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
properties=slo_properties,
) as slo:
try:
- # Abort early if the user doesn't have access to the query runner
- # We'll proceed as usual if there's no user connected to this request
+ # Abort early if the user doesn't have access to the query runner.
+ # We'll proceed as usual if there's no user connected to this request, or for an
+ # anonymous principal (SharedLinkUser) - the share link is its authorization.
# We're capturing the error for analytics purposes, but we reraise the same one
- if user is not None:
+ if user is not None and not user.is_anonymous:
try:
self.validate_query_runner_access(user)
except UserAccessControlError as error:
@@ -2372,12 +2374,10 @@ class AnalyticsQueryRunner(QueryRunner, Generic[AR]):
@property
def user_access_control(self) -> Optional[UserAccessControl]:
"""Access-control snapshot for the cache fingerprint. Built lazily - the fingerprint runs
- before any database exists, which a cache hit never reaches. None for userless runs and for
- synthetic principals (e.g. a project secret API key)."""
- # user is typed Optional[User] but a project secret API key passes a SyntheticUser at runtime;
- # broaden for isinstance.
- user = cast("Optional[User | SyntheticUser]", self.user)
- if user is None or isinstance(user, SyntheticUser):
+ before any database exists, which a cache hit never reaches. None if the principal is not a
+ real User (service tokens and shared-link viewers have no RBAC)."""
+ user = self.user
+ if not isinstance(user, User):
return None
if self._user_access_control is None:
self._user_access_control = UserAccessControl(user=user, team=self.team)
@@ -2386,13 +2386,9 @@ class AnalyticsQueryRunner(QueryRunner, Generic[AR]):
def get_cache_payload(self) -> dict:
payload = super().get_cache_payload()
- # Don't include restricted resources/objects in cache_payload if the ACCESS_CONTROL
- # feature is unavailable and a user is provided (i.e. not a userless query or a project token)
- user = cast("Optional[User | SyntheticUser]", self.user)
- if (
- user is not None
- and not isinstance(user, SyntheticUser)
- and not self.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
+ # Don't include restricted resources/objects in cache_payload if the ACCESS_CONTROL is unavailable
+ if isinstance(self.user, User) and not self.team.organization.is_feature_available(
+ AvailableFeature.ACCESS_CONTROL
):
return payload
@@ -2427,18 +2423,24 @@ class AnalyticsQueryRunner(QueryRunner, Generic[AR]):
def _get_resource_access_restrictions(self, queried_resources: Optional[set[str]]) -> list[str] | None:
"""Resources the user has no resource-level access to, scoped to the resources this query reads."""
- user = cast("Optional[User | SyntheticUser]", self.user)
+ # user is typed Optional[User] but runtime also passes SyntheticUser (project secret keys)
+ # and SharedLinkUser (shared renders); broaden for isinstance.
+ user = cast("Optional[User | SyntheticUser | SharedLinkUser]", self.user)
# Userless runs fail-closed - every access-controlled table is denied.
if user is None:
return ["*"] if queried_resources is None else sorted(queried_resources) or None
- # Synthetic principals (e.g. a project secret API key) are scope-gated; partition on the readable
- # scopes so a narrower token can't be served a broader principal's cached result.
- if isinstance(user, SyntheticUser):
+ # Non-real principals (service tokens, shared-link viewers) are scope-gated on system tables;
+ # partition on the readable scopes so a narrower token can't be served a broader principal's
+ # cached result. Warehouse scopes are excluded: these principals bypass warehouse access
+ # control (see Database.create_for), so warehouse tables are readable for them and listing
+ # them as restricted would collide with users who are genuinely denied those resources.
+ if not isinstance(user, User):
if queried_resources is None:
return ["*"]
- return sorted(queried_resources - user.readable_system_table_access_scopes()) or None
+ restricted = queried_resources - user.readable_system_table_access_scopes() - WAREHOUSE_ACCESS_SCOPES
+ return sorted(restricted) or None
user_access_control = self.user_access_control
if user_access_control is None:
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 381a725fa82b..43010d8ed97f 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -105,6 +105,13 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {
"marketing_analytics": "web_analytics",
}
+WAREHOUSE_ACCESS_SCOPES: frozenset[str] = frozenset(
+ {
+ "warehouse_objects",
+ *(child for child, parent in RESOURCE_INHERITANCE_MAP.items() if parent == "warehouse_objects"),
+ }
+)
+
tracer = trace.get_tracer(__name__)
diff --git a/posthog/shared_link_user.py b/posthog/shared_link_user.py
new file mode 100644
index 000000000000..baf83978c4e0
--- /dev/null
+++ b/posthog/shared_link_user.py
@@ -0,0 +1,29 @@
+"""Lives outside posthog.auth so the hogql layer can import it without a circular import."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from django.contrib.auth.models import AnonymousUser
+
+if TYPE_CHECKING:
+ from posthog.models.sharing_configuration import SharingConfiguration
+
+
+class SharedLinkUser(AnonymousUser):
+ """Anonymous viewer of a publicly shared dashboard/insight/notebook"""
+
+ # Django's AnonymousUser has no email; query modifiers read user.email for internal-user tagging.
+ email: str | None = None
+
+ def __init__(self, sharing_configuration: SharingConfiguration):
+ if not sharing_configuration.enabled:
+ raise ValueError("SharedLinkUser requires an enabled sharing configuration")
+ super().__init__()
+ self.sharing_configuration = sharing_configuration
+ # Read by query analytics tagging (QueryRunner.run) and modifier resolution.
+ self.distinct_id = f"shared-viewer-{sharing_configuration.team_id}"
+
+ def readable_system_table_access_scopes(self) -> set[str]:
+ """No RBAC identity - no access-controlled system tables (read by Database.create_for)."""
+ return set()
diff --git a/products/access_control/backend/property_access_control.py b/products/access_control/backend/property_access_control.py
index 1dd47f6fd44d..92cec6ef86ec 100644
--- a/products/access_control/backend/property_access_control.py
+++ b/products/access_control/backend/property_access_control.py
@@ -15,6 +15,8 @@ from celery.signals import task_postrun, task_prerun
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership
from posthog.models.team import Team
+from posthog.shared_link_user import SharedLinkUser
+from posthog.synthetic_user import SyntheticUser
from products.access_control.backend.facade.contracts import PropertyAccessLevel
from products.access_control.backend.models.property_access_control import PropertyAccessControl
@@ -276,7 +278,7 @@ def get_non_writable_property_names(
def get_restricted_properties_for_team(
*,
- user: User | None,
+ user: User | SyntheticUser | SharedLinkUser | None,
team: Team | None = None,
team_id: int | None = None,
) -> set[tuple[str, int]]:
@@ -298,6 +300,11 @@ def get_restricted_properties_for_team(
:returns: A set of (property_name, property_definition_type) tuples that are restricted.
"""
+ # Shared-link user and synthetic user have no membership to resolve restrictions against;
+ # treat them as userless so only the default rules apply.
+ if isinstance(user, SyntheticUser | SharedLinkUser):
+ user = None
+
if team is not None:
if team_id is not None:
raise ValueError("pass either team or team_id, not both")
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index a514b517e579..0b9e2b1bcfcf 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -119,6 +119,7 @@ from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade import upgrade
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.settings import CAPTURE_TIME_TO_SEE_DATA, SITE_URL
+from posthog.shared_link_user import SharedLinkUser
from posthog.user_permissions import UserPermissionsSerializerMixin
from posthog.utils import (
filters_override_requested_by_client,
@@ -1120,10 +1121,17 @@ class InsightSerializer(InsightBasicSerializer):
# tags here. No-op overwrite for authenticated paths (same values).
shared_tags = {"access_method": AccessMethod.SHARING_TOKEN} if is_shared else {}
request_user = None if self.context["request"].user.is_anonymous else self.context["request"].user
+ if request_user is None and is_shared:
+ # Anonymous shared views execute as the shared-link user, so
+ # warehouse-backed tiles resolve instead of failing with "no access"
+ request_user = self.context.get("shared_link_user")
# Reuse the request's single UserAccessControl across all of a dashboard's insight
# runners, so the cache fingerprint resolves access once per request, not per tile.
+ # Real users only - a shared-link viewer has no access-control snapshot.
view = self.context.get("view")
- request_user_access_control = getattr(view, "user_access_control", None) if request_user else None
+ request_user_access_control = (
+ getattr(view, "user_access_control", None) if isinstance(request_user, User) else None
+ )
with tags_context(product=ProductKey.PRODUCT_ANALYTICS, feature=Feature.INSIGHT, **shared_tags):
return calculate_for_query_based_insight(
insight,
@@ -1509,6 +1517,10 @@ class InsightViewSet(
self.request.successful_authenticator,
SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication,
)
+ if isinstance(self.request.user, SharedLinkUser):
+ # Sharing-token API refreshes authenticate as the shared-link viewer; expose it under
+ # the same context key the /shared/ page render uses (SharingViewerPageViewSet).
+ context["shared_link_user"] = self.request.user
context["insight_variables"] = InsightVariable.objects.filter(team=self.team).all()
return context