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(experiments): enforce per-recording access on session context endpoints (#74315)

Marcel Poelkere3656f8cbd39
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 6975a1527d48..6e1f12c49a9e 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1641,7 +1641,8 @@ class ExperimentSessionContextsResponseSerializer(serializers.Serializer):
help_text=(
"Per-session experiment context, in the order the session IDs were requested. Sessions whose "
"recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, "
- "as are sessions beyond the batch's recording-day budget (only the most recent days are computed). "
- "Fetch omitted sessions individually via the single-session endpoint."
+ "as are recordings you don't have access to and sessions beyond the batch's recording-day budget "
+ "(only the most recent days are computed). Fetch omitted sessions individually via the "
+ "single-session endpoint."
),
)
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 6642ee92d37b..e5de03d47f20 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -34,6 +34,7 @@ from posthog.models.activity_logging.activity_page import ActivityLogPaginatedRe
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
+from posthog.permissions import is_service_auth
from posthog.rate_limit import (
ClickHouseBurstRateThrottle,
ClickHouseSustainedRateThrottle,
@@ -41,6 +42,8 @@ from posthog.rate_limit import (
SessionContextsSustainedRateThrottle,
)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
+from posthog.rbac.user_access_control import UserAccessControl
+from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.temporal.common.client import sync_connect
from posthog.temporal.experiments.models import ExperimentTimeseriesRecalculationWorkflowInputs
from posthog.user_permissions import UserPermissions
@@ -195,6 +198,35 @@ def _slugify_feature_flag_key(name: str, *, team_id: int) -> str:
return candidate
+def _accessible_session_ids(
+ request: Request, user_access_control: UserAccessControl, team: Team, session_ids: list[str]
+) -> list[str]:
+ """Drop session ids whose recording the viewer is denied at the object level.
+
+ The resource-level `session_recording` check the session-context actions run first grants
+ access to the replay product, not to every recording in it: a recording can carry its own
+ access controls, which the replay retrieve endpoint enforces via `check_object_permissions`.
+ Without this filter a viewer denied one recording could still read which experiments it saw.
+
+ Object-level controls can only target a recording that has a Postgres row, so an id without
+ one is returned as accessible. That matches replay, which serves those ids from an unsaved
+ `SessionRecording` no access control row can point at.
+ """
+ if is_service_auth(request):
+ # Mirrors AccessControlPermission.has_object_permission: service credentials authenticate
+ # as synthetic users that UserAccessControl cannot evaluate, so they are gated by API
+ # scope and project membership instead of object-level RBAC.
+ return session_ids
+
+ recordings = SessionRecording.objects.filter(team=team, session_id__in=session_ids)
+ denied_ids = {
+ recording.session_id
+ for recording in recordings
+ if not user_access_control.check_access_level_for_object(recording, required_level="viewer")
+ }
+ return [session_id for session_id in session_ids if session_id not in denied_ids]
+
+
@extend_schema_view(
# PATCH /experiments/{id}/
# DRF mixin calls implementation at ExperimentSerializer.update
@@ -1279,6 +1311,9 @@ class EnterpriseExperimentsViewSet(
if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
raise PermissionDenied("Reading session experiment context requires session replay access.")
+ if not _accessible_session_ids(request, self.user_access_control, self.team, [session_id]):
+ raise PermissionDenied("You don't have access to this recording.")
+
# detail=False actions skip the automatic list-action ACL filtering, so filter here —
# private experiments must not leak into another user's session context.
experiments = self.user_access_control.filter_queryset_by_access_level(
@@ -1317,15 +1352,20 @@ class EnterpriseExperimentsViewSet(
query string; the endpoint only reads. Already-computed sessions are served from (and
cold ones written to) the same short-lived per-viewer cache the single-session endpoint
uses, so opening any prefetched recording renders its context instantly. Sessions whose
- recording metadata doesn't exist yet are omitted from the response, as are sessions
- beyond the batch's recording-day budget (each distinct recording day costs its own set
- of ClickHouse scans, so only the most recent days are computed per request).
+ recording metadata doesn't exist yet are omitted from the response, as are recordings
+ the caller can't access and sessions beyond the batch's recording-day budget (each
+ distinct recording day costs its own set of ClickHouse scans, so only the most recent
+ days are computed per request).
"""
session_ids: list[str] = request.validated_data["session_ids"]
if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
raise PermissionDenied("Reading session experiment context requires session replay access.")
+ # Denied recordings are omitted rather than rejecting the batch, matching how the response
+ # already treats a session whose recording metadata doesn't exist.
+ session_ids = _accessible_session_ids(request, self.user_access_control, self.team, session_ids)
+
# detail=False actions skip the automatic list-action ACL filtering, so filter here —
# private experiments must not leak into another user's session context.
experiments = self.user_access_control.filter_queryset_by_access_level(
diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.py
index 7e6c028002f3..437d6c80d8d0 100644
--- a/products/experiments/backend/session_context.py
+++ b/products/experiments/backend/session_context.py
@@ -73,14 +73,13 @@ MAX_CANDIDATE_EXPERIMENTS = 50
# is a backstop far above any real configuration — without it HogQL applies an implicit
# LIMIT 100, which would silently and nondeterministically truncate legitimate rows.
MAX_EXPOSURE_ROWS = 10_000
-# Short-lived because the context is not immutable — late-arriving events, experiment edits,
-# and access-control changes must all surface within minutes. The key includes the viewer:
-# the experiment set is filtered by per-user access control, so entries must never be shared
-# across users. That per-viewer key is also why the TTL is an acceptable ACL boundary: there
-# is no cross-user leak to begin with, the only exposure is a bounded revocation lag for a
-# viewer who legitimately had access moments before — matching how other short-TTL caches in
-# this codebase behave on permission changes. Per-endpoint ACL-version invalidation would add
-# complexity and a lookup to a path that exists to cut latency.
+# Short-lived because the context is not immutable: late-arriving events and experiment edits
+# must surface within minutes. The key includes the viewer because the experiment set is
+# filtered by per-user access control, so entries must never be shared across users.
+# The TTL is not an access-control boundary. Entries are re-filtered against the viewer's
+# current experiment access on read (see _accessible_items), and whether the viewer may open
+# the recording at all is decided per request in the view, so neither kind of revocation waits
+# for expiry. That keeps invalidation out of a path whose only job is to cut latency.
SESSION_CONTEXT_CACHE_TTL = 10 * 60
# Hard cap on the batch endpoint's id list. A playlist page holds 20 recordings, and every
# extra session widens the grouped scans; anything larger should arrive as separate batches.
@@ -150,6 +149,19 @@ def _cache_key(team: Team, user: User, session_id: str) -> str:
return f"experiment_session_context_v2_{team.pk}_{user.pk}_{session_id}"
+def _accessible_items(
+ items: list[ExperimentSessionContextItem], accessible_experiment_ids: set[int]
+) -> list[ExperimentSessionContextItem]:
+ """Re-check cached items against the viewer's current experiment access.
+
+ An entry was filtered against `experiments` when it was computed, so without this a viewer
+ whose access to an experiment is revoked would keep seeing it until the entry expires.
+ Re-checking on read makes revocation take effect immediately; a newly granted experiment
+ still waits for the entry to expire, which is the safe direction to lag in.
+ """
+ return [item for item in items if item.experiment_id in accessible_experiment_ids]
+
+
def get_session_experiment_context(
team: Team, session_id: str, experiments: QuerySet[Experiment], user: User
) -> Optional[list[ExperimentSessionContextItem]]:
@@ -168,7 +180,7 @@ def get_session_experiment_context(
cache_key = _cache_key(team, user, session_id)
cached = get_safe_cache(cache_key)
if cached is not None:
- return cached
+ return _accessible_items(cached, set(experiments.values_list("id", flat=True)))
metadata = SessionReplayEvents().get_metadata(session_id, team)
if metadata is None:
@@ -204,10 +216,14 @@ def get_session_experiment_contexts(
unique_ids = list(dict.fromkeys(session_ids))
results: dict[str, list[ExperimentSessionContextItem]] = {}
cold_ids: list[str] = []
+ # Resolved once for the whole batch, and only when something is actually served from cache.
+ accessible_experiment_ids: Optional[set[int]] = None
for session_id in unique_ids:
cached = get_safe_cache(_cache_key(team, user, session_id))
if cached is not None:
- results[session_id] = cached
+ if accessible_experiment_ids is None:
+ accessible_experiment_ids = set(experiments.values_list("id", flat=True))
+ results[session_id] = _accessible_items(cached, accessible_experiment_ids)
else:
cold_ids.append(session_id)
diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.py
index ff0b40da0298..86c759b94ed1 100644
--- a/products/experiments/backend/test/test_session_context_api.py
+++ b/products/experiments/backend/test/test_session_context_api.py
@@ -18,6 +18,7 @@ from posthog.models import PropertyDefinition, Team, User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7
from posthog.rate_limit import SessionContextsBurstRateThrottle
+from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from products.access_control.backend.facade.api import upsert_property_access_control
@@ -650,6 +651,38 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):
response = self._get_session_context()
assert [result["flag_key"] for result in response.json()["results"]] == ["checkout-cta"]
+ def test_cached_context_drops_experiments_the_viewer_lost_access_to(self) -> None:
+ self._enable_access_controls()
+ other_user = self._create_user("[email protected]")
+ self._create_recording()
+ self._create_experiment()
+ revoked_experiment = self._create_experiment(
+ key="revoked-exp", name="Revoked experiment", created_by=other_user
+ )
+ self._create_session_event(
+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},
+ )
+ self._create_session_event(
+ properties={"$feature_flag": "revoked-exp", "$feature_flag_response": "control"},
+ )
+ flush_persons_and_events()
+
+ first = self._get_session_context()
+ assert [result["flag_key"] for result in first.json()["results"]] == ["checkout-cta", "revoked-exp"]
+
+ AccessControl.objects.create(
+ team=self.team, resource="experiment", resource_id=str(revoked_experiment.pk), access_level="none"
+ )
+
+ # Both endpoints serve this session from the warm entry, so the revocation is only
+ # honored if the cached items are re-checked on read rather than at compute time.
+ with patch("products.experiments.backend.session_context._compute_session_experiment_contexts") as compute:
+ single = self._get_session_context()
+ batch = self._post_session_contexts([SESSION_ID])
+ compute.assert_not_called()
+ assert [result["flag_key"] for result in single.json()["results"]] == ["checkout-cta"]
+ assert [result["flag_key"] for result in batch.json()["results"][0]["results"]] == ["checkout-cta"]
+
def test_repeat_request_is_served_from_cache(self) -> None:
self._create_recording()
self._create_experiment()
@@ -725,6 +758,25 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):
response = self._get_session_context()
assert response.status_code == status.HTTP_403_FORBIDDEN
+ def test_denies_recordings_blocked_by_object_level_access(self) -> None:
+ self._enable_access_controls()
+ self._create_recording()
+ self._create_experiment()
+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})
+ self._create_day_two_recording_with_exposure()
+ flush_persons_and_events()
+
+ blocked = SessionRecording.objects.create(team=self.team, session_id=SESSION_ID)
+ AccessControl.objects.create(
+ team=self.team, resource="session_recording", resource_id=str(blocked.id), access_level="none"
+ )
+
+ assert self._get_session_context().status_code == status.HTTP_403_FORBIDDEN
+
+ batch = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID])
+ assert batch.status_code == status.HTTP_200_OK
+ assert [result["session_id"] for result in batch.json()["results"]] == [DAY_TWO_SESSION_ID]
+
def test_requires_session_recording_read_scope(self) -> None:
self._create_recording()
self.client.logout()
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 83dc11e32eb8..587cd356b435 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2357,7 +2357,7 @@ export interface ExperimentSessionContextsRequestApi {
* Experiment/variant context for a batch of session recordings.
*/
export interface ExperimentSessionContextsResponseApi {
- /** Per-session experiment context, in the order the session IDs were requested. Sessions whose recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, as are sessions beyond the batch's recording-day budget (only the most recent days are computed). Fetch omitted sessions individually via the single-session endpoint. */
+ /** Per-session experiment context, in the order the session IDs were requested. Sessions whose recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, as are recordings you don't have access to and sessions beyond the batch's recording-day budget (only the most recent days are computed). Fetch omitted sessions individually via the single-session endpoint. */
results: ExperimentSessionContextResponseApi[]
}
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index d0bee2c65adf..cc99278e6344 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -1081,9 +1081,10 @@ export const getExperimentsSessionContextsCreateUrl = (projectId: string) => {
* query string; the endpoint only reads. Already-computed sessions are served from (and
* cold ones written to) the same short-lived per-viewer cache the single-session endpoint
* uses, so opening any prefetched recording renders its context instantly. Sessions whose
- * recording metadata doesn't exist yet are omitted from the response, as are sessions
- * beyond the batch's recording-day budget (each distinct recording day costs its own set
- * of ClickHouse scans, so only the most recent days are computed per request).
+ * recording metadata doesn't exist yet are omitted from the response, as are recordings
+ * the caller can't access and sessions beyond the batch's recording-day budget (each
+ * distinct recording day costs its own set of ClickHouse scans, so only the most recent
+ * days are computed per request).
*/
export const experimentsSessionContextsCreate = async (
projectId: string,
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index 35701649f8b3..c6cc6ff30e93 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -1252,9 +1252,10 @@ export const ExperimentsCreateFromPromptCreateBody = /* @__PURE__ */ zod.object(
* query string; the endpoint only reads. Already-computed sessions are served from (and
* cold ones written to) the same short-lived per-viewer cache the single-session endpoint
* uses, so opening any prefetched recording renders its context instantly. Sessions whose
- * recording metadata doesn't exist yet are omitted from the response, as are sessions
- * beyond the batch's recording-day budget (each distinct recording day costs its own set
- * of ClickHouse scans, so only the most recent days are computed per request).
+ * recording metadata doesn't exist yet are omitted from the response, as are recordings
+ * the caller can't access and sessions beyond the batch's recording-day budget (each
+ * distinct recording day costs its own set of ClickHouse scans, so only the most recent
+ * days are computed per request).
*/
export const experimentsSessionContextsCreateBodySessionIdsMax = 20
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f7dd5b20d622..a1c1cd12da69 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27924,7 +27924,7 @@ export namespace Schemas {
* Experiment/variant context for a batch of session recordings.
*/
export interface ExperimentSessionContextsResponse {
- /** Per-session experiment context, in the order the session IDs were requested. Sessions whose recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, as are sessions beyond the batch's recording-day budget (only the most recent days are computed). Fetch omitted sessions individually via the single-session endpoint. */
+ /** Per-session experiment context, in the order the session IDs were requested. Sessions whose recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, as are recordings you don't have access to and sessions beyond the batch's recording-day budget (only the most recent days are computed). Fetch omitted sessions individually via the single-session endpoint. */
results: ExperimentSessionContextResponse[];
}