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(exports): close authorization gaps in the export API (#83017)

Tue Haulund0e9955b92ef5
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
index 40269c5dd30c..b53e24debe63 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
@@ -51,6 +51,11 @@ describe('config', () => {
expect(() => validateInput(baseInput())).not.toThrow()
})
+ // Dots are legal inside an id; only a dot-only id is a path segment.
+ it('accepts a session_id containing dots', () => {
+ expect(() => validateInput(baseInput({ session_id: 'a..b' }))).not.toThrow()
+ })
+
it.each([
{ field: 'playback_speed', value: 0, error: 'playback_speed must be positive' },
{ field: 'playback_speed', value: -1, error: 'playback_speed must be positive' },
@@ -71,6 +76,15 @@ describe('config', () => {
expect(() => validateInput(baseInput({ session_id: '' }))).toThrow('session_id is required')
})
+ it.each(['../../2/recordings/other', 'abc\\..\\def', '%2e%2e%2f2', 'abc?x=1', 'a b', '..', '.', 'abc\n'])(
+ 'rejects session_id %s',
+ (id) => {
+ expect(() => validateInput(baseInput({ session_id: id }))).toThrow(
+ 'session_id contains illegal characters'
+ )
+ }
+ )
+
it('rejects invalid team_id', () => {
expect(() => validateInput(baseInput({ team_id: 0 }))).toThrow('team_id must be a positive integer')
expect(() => validateInput(baseInput({ team_id: -1 }))).toThrow('team_id must be a positive integer')
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
index 4bcd9681ffe9..7063bb5ae10a 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
@@ -45,7 +45,11 @@ export class BlockProxy {
this.sessionId = input.session_id
this.recordingApiToken = input.recording_api_token ?? ''
- const url = `${this.cfg.recordingApiBaseUrl}/api/projects/${input.team_id}/recordings/${input.session_id}/blocks`
+ // Encoded: the fetch client normalizes the URL, so a raw session id containing `../`
+ // would repoint the request at another team's recording.
+ const url = `${this.cfg.recordingApiBaseUrl}/api/projects/${input.team_id}/recordings/${encodeURIComponent(
+ input.session_id
+ )}/blocks`
const resp = await internalFetch(url, {
headers: this.authHeaders(),
})
@@ -85,7 +89,7 @@ export class BlockProxy {
decompress: 'true',
})
const apiBase = `${this.cfg.recordingApiBaseUrl}/api/projects`
- const url = `${apiBase}/${this.teamId}/recordings/${this.sessionId}/block?${params}`
+ const url = `${apiBase}/${this.teamId}/recordings/${encodeURIComponent(this.sessionId)}/block?${params}`
const resp = await internalFetch(url, {
headers: this.authHeaders(),
})
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts b/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
index 0cc38d1f3593..911800b4c324 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
@@ -5,6 +5,9 @@ import { CaptureConfig, RasterizeRecordingInput } from '~/session-replay/recordi
const DEFAULT_PLAYBACK_SPEED = 4
const DEFAULT_FPS = 24
+// Kept in step with SESSION_RECORDING_ID_RE in products/exports/backend/models/exported_asset.py.
+// The lookahead drops a dot-only id, which is a relative path segment rather than a session.
+const SESSION_ID_RE = /^(?!\.+$)[A-Za-z0-9_.:-]{1,200}$/
// Coerce a value interpolated into an ffmpeg option (`-t`) or filter (`setpts=`, `fps=`) to a
// finite number. ffmpeg is spawned without a shell, but a non-finite/non-numeric value reaching
@@ -23,6 +26,11 @@ export function validateInput(input: RasterizeRecordingInput): void {
if (!input.session_id) {
throw new RasterizationError('session_id is required', false, 'INVALID_INPUT')
}
+ // Mirrors the allowlist the Python side enforces: a session id ends up in the internal
+ // recording-api paths the block proxy builds, so it must not carry path structure.
+ if (!SESSION_ID_RE.test(input.session_id)) {
+ throw new RasterizationError('session_id contains illegal characters', false, 'INVALID_INPUT')
+ }
if (!input.team_id || input.team_id <= 0) {
throw new RasterizationError('team_id must be a positive integer', false, 'INVALID_INPUT')
}
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
index d1bc0677506a..c0f2805f655b 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
@@ -9,7 +9,7 @@ from temporalio import activity
from posthog.session_recordings.recordings.recording_api_jwt import mint_recording_api_token, recording_api_jwt_enabled
from posthog.storage import object_storage
-from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.models.exported_asset import ExportedAsset, is_valid_session_recording_id
from ..types import (
RASTERIZE_RENDER_MAX_ATTEMPTS,
@@ -47,6 +47,12 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
session_id = ctx.get("session_recording_id")
if not session_id:
raise ValueError(f"ExportedAsset {exported_asset_id} has no session_recording_id in export_context")
+ # Assets reach this activity from several writers, not all of them behind the exports serializer,
+ # so the id is re-checked here before it becomes part of an internal recording API path.
+ if not is_valid_session_recording_id(session_id):
+ # Logged as well as raised so a session id we reject wrongly is greppable, not just a failed render.
+ logger.warning("rasterize.malformed_session_recording_id", asset_id=exported_asset_id)
+ raise ValueError(f"ExportedAsset {exported_asset_id} has a malformed session_recording_id")
format_map = {"video/webm": "webm", "video/mp4": "mp4", "image/gif": "gif"}
output_format = format_map.get(asset.export_format, "mp4")
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
index 61b70a324a5b..8b958b086477 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
@@ -183,6 +183,23 @@ class TestBuildRasterizationInput:
with pytest.raises(ValueError, match="no session_recording_id"):
build_rasterization_input(100)
+ @parameterized.expand(
+ [
+ ("traversal", "../../2/recordings/other"),
+ ("slash", "abc/def"),
+ ("backslash", "abc\\def"),
+ ("percent_encoded", "%2e%2e%2f2"),
+ ("dot_segment", ".."),
+ ("trailing_newline", "abc\n"),
+ ]
+ )
+ def test_malformed_session_id_raises(self, _name, session_id):
+ asset = _make_asset(pk=101, export_context={"session_recording_id": session_id})
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ with pytest.raises(ValueError, match="malformed session_recording_id"):
+ build_rasterization_input(101)
+
def test_timestamp_and_duration_mapped_to_offsets(self):
asset = _make_asset(
pk=50,
diff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.py
index c8b2d11811d7..0013e2fc20bf 100644
--- a/products/exports/backend/api/exports.py
+++ b/products/exports/backend/api/exports.py
@@ -12,7 +12,7 @@ import posthoganalytics
from asgiref.sync import async_to_sync
from drf_spectacular.utils import extend_schema
from rest_framework import mixins, serializers, viewsets
-from rest_framework.exceptions import NotFound, ValidationError
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.request import Request
from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy
@@ -35,7 +35,11 @@ from posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetW
from posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs
from products.exports.backend.facade.api import EXPORT_WORKFLOW_TIMEOUT
-from products.exports.backend.models.exported_asset import ExportedAsset, get_content_response
+from products.exports.backend.models.exported_asset import (
+ ExportedAsset,
+ get_content_response,
+ is_valid_session_recording_id,
+)
from products.product_analytics.backend.models.insight import Insight
# Full video exports per team per calendar month, tiered by plan.
@@ -133,9 +137,15 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode
if data.get("insight") and data["insight"].team.id != self.context["team_id"]:
raise ValidationError({"insight": ["This insight does not belong to your team."]})
+ export_context = data.get("export_context") or {}
+ # Truthiness, not `is not None`: an absent or empty id is a no-op everywhere downstream,
+ # and rejecting it here would 400 exports that never touch a recording.
+ session_recording_id = export_context.get("session_recording_id")
+ if session_recording_id and not is_valid_session_recording_id(session_recording_id):
+ raise ValidationError({"export_context": ["Invalid session_recording_id."]})
+
# Check full video export limit for team (video session recording exports)
export_format = data.get("export_format")
- export_context = data.get("export_context", {})
is_full_video_export = export_format in ("video/mp4", "video/webm", "image/gif") and export_context.get(
"session_recording_id"
@@ -205,8 +215,29 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode
def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> ExportedAsset:
request = self.context["request"]
+ self._assert_may_export_session_recording(validated_data)
return self._create_asset(validated_data, user=request.user, reason=None)
+ def _assert_may_export_session_recording(self, validated_data: dict) -> None:
+ """Rendering a recording export must need the access that viewing the recording needs."""
+ session_recording_id = (validated_data.get("export_context") or {}).get("session_recording_id")
+ user_access_control = self.user_access_control
+ if not session_recording_id or user_access_control is None:
+ return
+
+ from posthog.session_recordings.models.session_recording import SessionRecording
+
+ recording = SessionRecording.objects.filter(
+ team_id=validated_data["team_id"], session_id=session_recording_id
+ ).first()
+ if recording is not None:
+ allowed = user_access_control.check_access_level_for_object(recording, required_level="viewer")
+ else:
+ allowed = user_access_control.check_access_level_for_resource("session_recording", required_level="viewer")
+
+ if not allowed:
+ raise PermissionDenied("You do not have access to this session recording.")
+
def _create_asset(
self,
validated_data: dict,
@@ -465,7 +496,8 @@ class ExportedAssetViewSet(
viewsets.GenericViewSet,
):
scope_object = "export"
- queryset = ExportedAsset.objects.order_by("-created_at")
+ # Both FKs are read on every retrieve to authorize the asset, so fetch them with it.
+ queryset = ExportedAsset.objects.select_related("dashboard", "insight").order_by("-created_at")
serializer_class = ExportedAssetSerializer
def get_serializer_class(self) -> type[serializers.BaseSerializer]:
@@ -505,25 +537,33 @@ class ExportedAssetViewSet(
session_recording_id = export_context.get("session_recording_id")
- resource = instance.dashboard or instance.insight
- if not resource and session_recording_id:
- from posthog.session_recordings.models.session_recording import SessionRecording
+ # Both can be set on one asset, and the renderer prefers the insight, so checking only the
+ # first non-null one would let an accessible dashboard authorize an inaccessible insight.
+ for related in (instance.dashboard, instance.insight):
+ if related is not None and not self.user_access_control.check_access_level_for_object(
+ related, required_level="viewer"
+ ):
+ raise NotFound()
+
+ if not session_recording_id:
+ return instance
- resource = SessionRecording.objects.filter(
- team_id=instance.team_id, session_id=session_recording_id
- ).first()
+ # Reached even when a dashboard or insight authorized above: an asset carrying both renders
+ # the recording too, so a viewable dashboard must not stand in for access to it.
+ from posthog.session_recordings.models.session_recording import SessionRecording
- if resource is not None:
- if not self.user_access_control.check_access_level_for_object(resource, required_level="viewer"):
+ recording = SessionRecording.objects.filter(team_id=instance.team_id, session_id=session_recording_id).first()
+ if recording is not None:
+ if not self.user_access_control.check_access_level_for_object(recording, required_level="viewer"):
raise NotFound()
- elif session_recording_id and instance.created_by_id != self.request.user.id:
+ elif instance.created_by_id != self.request.user.id:
# No SessionRecording row — cannot run object-level RBAC; still enforce the team's
# session_recording resource default for other users so detail/content are not fail-open.
- # The creator is exempt from this fallback only: they necessarily had the access required
- # to create the export, so retrieval must not be stricter than creation — otherwise a
- # session_recording default below viewer 404s the very user who just took the screenshot,
- # surfacing as an "Export complete!" toast followed by a blank error page. Explicit
- # object-level denies (the branch above) still apply to the creator once a
+ # The creator is exempt from this fallback only, because _assert_may_export_session_recording
+ # ran the same check when they created the export, so retrieval must not be stricter than
+ # creation — otherwise a session_recording default below viewer 404s the very user who just
+ # took the screenshot, surfacing as an "Export complete!" toast followed by a blank error
+ # page. Explicit object-level denies (the branch above) still apply to the creator once a
# SessionRecording row exists.
if not self.user_access_control.check_access_level_for_resource(
"session_recording", required_level="viewer"
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index c2656a283a58..bcf75f4c2b9e 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -848,6 +848,116 @@ class TestExports(APIBaseTest):
if "/content" in url_template:
self.assertEqual(response.content, b"png-bytes")
+ @parameterized.expand(
+ [
+ ("traversal", "../../2/recordings/other-session"),
+ ("slash", "abc/def"),
+ ("backslash", "abc\\def"),
+ ("percent_encoded", "%2e%2e%2f2"),
+ ("not_a_string", 12345),
+ ("dot_segment", ".."),
+ ("trailing_newline", "abc\n"),
+ ]
+ )
+ def test_cannot_create_export_with_unsafe_session_recording_id(self, _name, session_recording_id) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports",
+ {
+ "export_format": "image/png",
+ "export_context": {"session_recording_id": session_recording_id},
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("session_recording_id", str(response.json()))
+
+ @parameterized.expand(
+ [
+ ("retrieve", "/api/projects/{team_id}/exports/{export_id}"),
+ ("content", "/api/projects/{team_id}/exports/{export_id}/content"),
+ ]
+ )
+ def test_cannot_access_export_pairing_allowed_dashboard_with_denied_insight(self, _name, url_template) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+
+ export = ExportedAsset.objects.create(
+ team=self.team,
+ dashboard_id=self.dashboard.id,
+ insight_id=self.insight.id,
+ export_format="image/png",
+ created_by=other_user,
+ )
+
+ self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]
+ self.organization.save()
+
+ # The dashboard stays reachable, so only checking it would authorize the private insight.
+ AccessControl.objects.create(
+ resource="insight",
+ resource_id=str(self.insight.id),
+ team=self.team,
+ access_level="none",
+ )
+
+ self.client.force_login(other_user)
+ response = self.client.get(url_template.format(team_id=self.team.id, export_id=export.id))
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @parameterized.expand(
+ [
+ ("retrieve", "/api/projects/{team_id}/exports/{export_id}"),
+ ("content", "/api/projects/{team_id}/exports/{export_id}/content"),
+ ]
+ )
+ def test_cannot_access_export_pairing_allowed_dashboard_with_denied_recording(self, _name, url_template) -> None:
+ from posthog.session_recordings.models.session_recording import SessionRecording
+
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ recording = SessionRecording.objects.create(team=self.team, session_id="mixed-asset-recording")
+
+ export = ExportedAsset.objects.create(
+ team=self.team,
+ dashboard_id=self.dashboard.id,
+ export_format="image/png",
+ export_context={"session_recording_id": recording.session_id},
+ created_by=other_user,
+ )
+
+ self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]
+ self.organization.save()
+
+ AccessControl.objects.create(
+ resource="session_recording",
+ resource_id=str(recording.id),
+ team=self.team,
+ access_level="none",
+ )
+
+ self.client.force_login(other_user)
+ response = self.client.get(url_template.format(team_id=self.team.id, export_id=export.id))
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_cannot_create_session_recording_export_without_recording_access(self) -> None:
+ self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]
+ self.organization.save()
+
+ AccessControl.objects.create(
+ resource="session_recording",
+ team=self.team,
+ access_level="none",
+ )
+
+ member = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self.client.force_login(member)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports",
+ {
+ "export_format": "image/png",
+ "export_context": {"session_recording_id": "some-session-id"},
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
@parameterized.expand(
[
("retrieve", "/api/projects/{team_id}/exports/{export_id}"),
diff --git a/products/exports/backend/models/exported_asset.py b/products/exports/backend/models/exported_asset.py
index fd5f64dcd28d..d10b6d8be9f2 100644
--- a/products/exports/backend/models/exported_asset.py
+++ b/products/exports/backend/models/exported_asset.py
@@ -1,3 +1,4 @@
+import re
import secrets
from datetime import datetime, timedelta
from pathlib import Path
@@ -35,6 +36,18 @@ SIX_MONTHS = timedelta(days=180)
TWELVE_MONTHS = timedelta(days=365)
+# The rasterizer interpolates this id into an internal recording API path, so anything that could
+# change the shape of that path has to be rejected: separators, percent escapes, and a dot-only id,
+# which is a relative segment that URL normalization collapses. Kept in step with SESSION_ID_RE in
+# nodejs/src/session-replay/recording-rasterizer/capture/config.ts.
+SESSION_RECORDING_ID_RE = re.compile(r"(?!\.+\Z)[A-Za-z0-9_.:-]{1,200}")
+
+
+def is_valid_session_recording_id(session_recording_id: object) -> bool:
+ # fullmatch, not match: `$` would also accept a trailing newline.
+ return isinstance(session_recording_id, str) and bool(SESSION_RECORDING_ID_RE.fullmatch(session_recording_id))
+
+
def get_default_access_token() -> str:
return secrets.token_urlsafe(22)