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(insights): keep shared-link identity on async recalculation (#78098)

Sam Penningtonfc09276b62a8
diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.py
index 5350cffebd6b..892f6dd98458 100644
--- a/posthog/clickhouse/client/execute_async.py
+++ b/posthog/clickhouse/client/execute_async.py
@@ -1,6 +1,6 @@
import uuid
import datetime
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Optional, cast
import orjson as json
import structlog
@@ -18,6 +18,7 @@ from posthog import celery, redis
from posthog.clickhouse.client.async_task_chain import add_task_to_on_commit
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import get_query_tags, tag_queries
+from posthog.constants import AvailableFeature
from posthog.errors import ExposedCHQueryError
from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
@@ -26,6 +27,7 @@ from posthog.renderers import SafeJSONRenderer
if TYPE_CHECKING:
from posthog.event_usage import AnalyticsProps
from posthog.models.team.team import Team
+ from posthog.models.user import User
logger = structlog.get_logger(__name__)
@@ -178,6 +180,33 @@ class QueryStatusManager:
self.redis_client.hdel(self.running_queries_key, cache_key)
+def _shared_link_user_for(sharing_configuration_id: int, team: "Team") -> Optional["User"]:
+ """Rebuild the anonymous viewer of a public share so an async recalculation runs as the same
+ principal the request did. None if the share was disabled, expired, or deleted, or the
+ organization turned off public sharing, in the meantime - the query then runs userless and is
+ denied, which is the correct outcome for a revoked share."""
+ from posthog.models.sharing_configuration import SharingConfiguration # noqa: PLC0415
+ from posthog.shared_link_user import SharedLinkUser # noqa: PLC0415
+
+ # Same predicate as SharingViewerPageViewSet._is_blocked_by_public_sharing_setting: the org-level
+ # kill switch must also cover recalculations enqueued just before it was flipped.
+ organization = team.organization
+ if (
+ organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS)
+ and not organization.allow_publicly_shared_resources
+ ):
+ return None
+
+ sharing_configuration = SharingConfiguration.objects.filter(
+ SharingConfiguration.tokens_active_q(), pk=sharing_configuration_id, team_id=team.id
+ ).first()
+ if sharing_configuration is None:
+ return None
+ # The query stack types its principal as Optional[User] but accepts the anonymous shared-link
+ # viewer at runtime, so cast at the boundary the same way SharingViewerPageViewSet does.
+ return cast("User", SharedLinkUser(sharing_configuration))
+
+
def execute_process_query(
team_id: int,
user_id: Optional[int],
@@ -186,6 +215,7 @@ def execute_process_query(
limit_context: Optional[LimitContext],
is_query_service: bool = False,
analytics_props: Optional["AnalyticsProps"] = None,
+ sharing_configuration_id: Optional[int] = None,
):
tag_queries(client_query_id=query_id, team_id=team_id, user_id=user_id)
manager = QueryStatusManager(query_id, team_id)
@@ -197,10 +227,16 @@ def execute_process_query(
team = Team.objects.get(pk=team_id)
is_staff_user = False
- user = None
+ user: Optional[User] = None
if user_id:
user = User.objects.only("email", "is_staff").get(pk=user_id)
is_staff_user = user.is_staff
+ elif sharing_configuration_id:
+ # A shared-link viewer has no user row, so the identity has to be rebuilt from the share it
+ # came in on. Without it the run is userless, which fails closed on every warehouse table
+ # ("You don't have access to table `X`.") and fingerprints the cache differently than the
+ # request that enqueued it.
+ user = _shared_link_user_for(sharing_configuration_id, team)
query_status = manager.get_query_status()
@@ -303,6 +339,7 @@ def enqueue_process_query_task(
is_query_service: bool = False,
is_posthog_ai: bool = False,
analytics_props: Optional["AnalyticsProps"] = None,
+ sharing_configuration_id: Optional[int] = None,
) -> QueryStatus:
if not query_id:
query_id = uuid.uuid4().hex
@@ -364,6 +401,10 @@ def enqueue_process_query_task(
from posthog.tasks.tasks import process_query_task # noqa: PLC0415
limit_context = LimitContext.POSTHOG_AI if is_posthog_ai else LimitContext.QUERY_ASYNC
+ # Attached only when set: during a rolling deploy a worker still on the old task signature
+ # rejects unknown kwargs, so an always-present kwarg would fail every async query, not just
+ # shared-link ones.
+ shared_kwargs = {"sharing_configuration_id": sharing_configuration_id} if sharing_configuration_id else {}
task_signature = process_query_task.si(
team.id,
user_id,
@@ -373,6 +414,7 @@ def enqueue_process_query_task(
is_query_service,
limit_context,
analytics_props=analytics_props,
+ **shared_kwargs,
)
if _test_only_bypass_celery:
diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.py
index d71c36c89757..64b3274115f5 100644
--- a/posthog/clickhouse/client/test/test_execute_async.py
+++ b/posthog/clickhouse/client/test/test_execute_async.py
@@ -1,5 +1,6 @@
import json
import uuid
+import datetime
from typing import Any
from posthog.test.base import ClickhouseTestMixin, snapshot_clickhouse_queries
@@ -22,11 +23,14 @@ from posthog.clickhouse.client import (
from posthog.clickhouse.client.async_task_chain import task_chain_context
from posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, execute_process_query
from posthog.clickhouse.query_tagging import tag_queries
+from posthog.constants import AvailableFeature
from posthog.errors import ExposedCHQueryError
from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded
from posthog.models import Organization, Team
+from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.user import User
from posthog.redis import get_client
+from posthog.shared_link_user import SharedLinkUser
def build_query(sql):
@@ -181,6 +185,49 @@ class TestExecuteProcessQuery(TestCase):
self.assertEqual(mock_capture_exception.called, should_capture)
+ @parameterized.expand(
+ [
+ ("live", {}, True, True),
+ ("disabled", {"enabled": False}, True, False),
+ ("expired", {"expires_at": datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC)}, True, False),
+ ("org_disallows_public_sharing", {}, False, False),
+ ]
+ )
+ @patch("posthog.clickhouse.client.execute_async.redis.get_client")
+ @patch("posthog.api.services.query.process_query_dict")
+ def test_shared_link_run_rebuilds_the_viewer_while_the_share_is_live(
+ self, _name, overrides, org_allows_sharing, expect_viewer, mock_process_query_dict, mock_redis_client
+ ):
+ mock_redis = MagicMock()
+ mock_redis.get.return_value = json.dumps(
+ {"id": self.query_id, "team_id": self.team.id, "complete": False, "error": False}
+ ).encode()
+ mock_redis_client.return_value = mock_redis
+ mock_process_query_dict.return_value = []
+ sharing_configuration = SharingConfiguration.objects.create(team=self.team, **{"enabled": True, **overrides})
+ if not org_allows_sharing:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS, "name": "Organization security settings"}
+ ]
+ self.organization.allow_publicly_shared_resources = False
+ self.organization.save()
+
+ execute_process_query(
+ self.team.id,
+ None,
+ self.query_id,
+ self.query_json,
+ self.limit_context,
+ sharing_configuration_id=sharing_configuration.id,
+ )
+
+ user = mock_process_query_dict.call_args.kwargs["user"]
+ if expect_viewer:
+ assert isinstance(user, SharedLinkUser)
+ assert user.sharing_configuration.id == sharing_configuration.id
+ else:
+ assert user is None
+
class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):
def setUp(self):
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 032c58db1ef2..45f144f40132 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -1528,9 +1528,17 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
groups=(groups(self.team.organization, self.team)),
)
+ # A shared-link viewer has no user row, so `user_id` is None and the worker would otherwise
+ # run userless - denying every warehouse table and fingerprinting the cache differently than
+ # this request. Carry the share along so the worker can rebuild the same principal.
+ # `user` is typed Optional[User] but shared renders pass a SharedLinkUser at runtime.
+ principal = cast("Optional[User | SyntheticUser | SharedLinkUser]", user)
+ sharing_configuration_id = principal.sharing_configuration.pk if isinstance(principal, SharedLinkUser) else None
+
return enqueue_process_query_task(
team=self.team,
user_id=user.id if user else None,
+ sharing_configuration_id=sharing_configuration_id,
insight_id=cache_manager.insight_id,
dashboard_id=cache_manager.dashboard_id,
query_json=self.query.model_dump(),
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index abf09d45605e..9e22dffdfd6b 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -63,6 +63,7 @@ from posthog.hogql_queries.query_runner import (
)
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.organization import OrganizationMembership
+from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team.team import Team, WeekStartDay
from posthog.query_cache.failures import (
BASE_BACKOFF,
@@ -73,6 +74,7 @@ from posthog.query_cache.failures import (
QueryFailureCache,
)
from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError
+from posthog.shared_link_user import SharedLinkUser
try:
from ee.models.rbac.access_control import AccessControl
@@ -1362,6 +1364,20 @@ class TestSharedInsightsExecutionMode(BaseTest):
self.assertEqual(result_mode, expected_mode)
self.assertEqual(cache_age_seconds, expected_cache_age_seconds)
+ @parameterized.expand([("shared_link_viewer", True), ("member", False)])
+ @mock.patch("posthog.hogql_queries.query_runner.enqueue_process_query_task")
+ def test_async_calculation_carries_the_share_for_a_shared_link_viewer(
+ self, _name: str, is_shared_viewer: bool, mock_enqueue: mock.MagicMock
+ ) -> None:
+ sharing_configuration = SharingConfiguration.objects.create(team=self.team, enabled=True)
+ user = SharedLinkUser(sharing_configuration) if is_shared_viewer else self.user
+ runner = setup_test_query_runner_class()(query={"some_attr": "bla"}, team=self.team)
+
+ runner.enqueue_async_calculation(cache_manager=mock.MagicMock(), user=user)
+
+ expected = sharing_configuration.pk if is_shared_viewer else None
+ assert mock_enqueue.call_args.kwargs["sharing_configuration_id"] == expected
+
@pytest.mark.ee
class TestQueryRunnerAccessControlFingerprint(BaseTest):
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 43c5de938fb0..76264152497d 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -405,6 +405,7 @@ def process_query_task(
is_query_service: bool,
limit_context: Optional[LimitContext] = None,
analytics_props: Optional["AnalyticsProps"] = None,
+ sharing_configuration_id: Optional[int] = None,
) -> None:
"""
Kick off query
@@ -427,6 +428,7 @@ def process_query_task(
limit_context=limit_context,
is_query_service=is_query_service,
analytics_props=analytics_props,
+ sharing_configuration_id=sharing_configuration_id,
)