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(replay): let the player fetch blocks straight from recording-api (#128419)

Tue Haulundeab103031d67
diff --git a/common/replay-shared/src/types.ts b/common/replay-shared/src/types.ts
index 589b48fa4891..2b210f11b0b3 100644
--- a/common/replay-shared/src/types.ts
+++ b/common/replay-shared/src/types.ts
@@ -27,6 +27,8 @@ export interface SessionRecordingSnapshotSource {
start_timestamp?: string
end_timestamp?: string
blob_key?: string
+ /** Fetch this block here directly, with the listing's block token, instead of through the snapshots endpoint. */
+ url?: string
}
export interface SessionRecordingSnapshotSourceResponse {
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 31d80a13813d..b633e1e992ed 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -4435,6 +4435,51 @@ const api = {
return []
},
+ /**
+ * Fetches blocks straight from recording-api, one request per block so the browser caches each one. Returns
+ * the same length-prefixed bytes as getSnapshots with decompress=false.
+ */
+ async getBlocksDirectly(urls: string[], token: string): Promise<Uint8Array> {
+ // One failed block fails the batch, so the other downloads stop too. The deadline matches Django's upstream
+ // read limit, so a stalled block falls back instead of holding the loader forever.
+ const controller = new AbortController()
+ const deadline = setTimeout(() => controller.abort(), 30_000)
+ const blocks = await Promise.all(
+ urls.map(async (url) => {
+ try {
+ const response = await fetch(url, {
+ headers: { Authorization: `Bearer ${token}` },
+ credentials: 'omit',
+ signal: controller.signal,
+ })
+ if (!response.ok) {
+ const data = await response.json().catch(() => null)
+ throw asRecordingDeletedError(
+ new ApiError('Block fetch failed', response.status, undefined, data)
+ )
+ }
+ // Without a route to recording-api the app shell answers with HTML, which is not a block.
+ if (!response.headers.get('Content-Type')?.startsWith('application/octet-stream')) {
+ throw new Error('Block fetch returned something other than a block')
+ }
+ return new Uint8Array(await response.arrayBuffer())
+ } catch (e) {
+ controller.abort()
+ throw e
+ }
+ })
+ ).finally(() => clearTimeout(deadline))
+ const framed = new Uint8Array(blocks.reduce((total, block) => total + 4 + block.length, 0))
+ const view = new DataView(framed.buffer)
+ let offset = 0
+ for (const block of blocks) {
+ view.setUint32(offset, block.length)
+ framed.set(block, offset + 4)
+ offset += 4 + block.length
+ }
+ return framed
+ },
+
async listPlaylists(params: string): Promise<SavedSessionRecordingPlaylistsResult> {
return await new ApiRequest().recordingPlaylists().withQueryString(params).get()
},
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
index 3934be2e73f2..150fdf26ebd9 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
@@ -1,4 +1,5 @@
import { expectLogic } from 'kea-test-utils'
+import { HttpResponse } from 'msw'
import { EventType, IncrementalSource, NodeType, mutationData } from 'posthog-js/rrweb-types'
import { chunkMutationSnapshot, MUTATION_CHUNK_SIZE } from '@posthog/replay-shared'
@@ -9,6 +10,7 @@ import { parseEncodedSnapshots } from 'scenes/session-recordings/player/snapshot
import { RecordingSnapshot, SessionRecordingSnapshotSource } from '~/types'
+import { snapshotsAsJSONLines } from '../__mocks__/recording_snapshots'
import { overrideSessionRecordingMocks, setupSessionRecordingTest } from './__mocks__/test-setup'
import { snapshotDataLogic } from './snapshotDataLogic'
@@ -168,6 +170,70 @@ describe('snapshotDataLogic', () => {
})
})
+ describe('direct block fetch', () => {
+ const BLOCK_PATH = '/replay-blocks/1/2/u1/v1.ref0'
+ const DIRECT_SOURCE: SessionRecordingSnapshotSource = {
+ ...BLOB_SOURCE,
+ url: `${window.location.origin}${BLOCK_PATH}`,
+ }
+
+ it.each([
+ ['reads the block from its url', 200, false, 'loadSnapshotsForSourceSuccess'],
+ [
+ 'falls back to the snapshots endpoint when the block fetch fails',
+ 500,
+ true,
+ 'loadSnapshotsForSourceSuccess',
+ ],
+ [
+ 'falls back when the block route answers with the app shell',
+ 'html',
+ true,
+ 'loadSnapshotsForSourceSuccess',
+ ],
+ ['shows the recording as deleted on a 410', 410, false, 'loadSnapshotsForSourceFailure'],
+ [
+ 'reports a rate limit instead of reading through the snapshots endpoint',
+ 429,
+ false,
+ 'loadSnapshotsForSourceFailure',
+ ],
+ ] as const)('%s', async (_, blockStatus, expectsSnapshotsEndpoint, expectedAction) => {
+ let snapshotsEndpointBlockReads = 0
+ overrideSessionRecordingMocks({
+ getMocks: {
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ snapshotsEndpointBlockReads += 1
+ return new HttpResponse(snapshotsAsJSONLines())
+ }
+ return [200, { sources: [DIRECT_SOURCE], block_token: 'block.token.sig' }]
+ },
+ [BLOCK_PATH]: () =>
+ blockStatus === 200
+ ? new HttpResponse(snapshotsAsJSONLines(), {
+ headers: { 'Content-Type': 'application/octet-stream' },
+ })
+ : blockStatus === 'html'
+ ? new HttpResponse('<!doctype html><html></html>', {
+ headers: { 'Content-Type': 'text/html' },
+ })
+ : [blockStatus, { error: 'recording_deleted', deleted_at: 1700000000 }],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.loadSnapshotSources()).toDispatchActions([
+ 'loadSnapshotSourcesSuccess',
+ ])
+
+ await expectLogic(logic, () => logic.actions.loadSnapshotsForSource([DIRECT_SOURCE])).toDispatchActions([
+ expectedAction,
+ ])
+
+ expect(snapshotsEndpointBlockReads > 0).toBe(expectsSnapshotsEndpoint)
+ expect(logic.values.isRecordingDeleted).toBe(blockStatus === 410)
+ })
+ })
+
describe('isSnapshotUnauthorized', () => {
it('is false when no error', () => {
expect(logic.values.isSnapshotUnauthorized).toBe(false)
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
index a075bc396404..1d0a643801c8 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
@@ -53,6 +53,7 @@ export interface snapshotDataLogicValues {
getWindowId: (uuid: string | undefined) => number | undefined // windowIdRegistryLogic
uuidToIndex: Record<string, number> // windowIdRegistryLogic
allSourcesLoaded: boolean
+ blockToken: string | null
isLoadingSnapshots: boolean
isPolling: boolean
isRecordingDeleted: boolean
@@ -161,6 +162,9 @@ export interface snapshotDataLogicActions {
retrySnapshotLoading: () => {
value: true
}
+ setBlockToken: (token: string | null) => {
+ token: string | null
+ }
setPlayerActive: (active: boolean) => {
active: boolean
}
@@ -248,6 +252,47 @@ export type snapshotDataLogicType = MakeLogicType<
snapshotDataLogicMeta
>
+// Reads a batch straight from recording-api when the listing gave every block a url, so the browser caches each
+// block. Returns null to use the snapshots endpoint instead, which serves every recording.
+async function loadBlocksDirectly(
+ sources: Pick<SessionRecordingSnapshotSource, 'source' | 'blob_key'>[],
+ listedSources: SessionRecordingSnapshotSource[] | null,
+ token: string | null,
+ direct: { unauthorizedCount: number },
+ onTokenExpired: () => void
+): Promise<Uint8Array | null> {
+ const urlsByKey = new Map((listedSources ?? []).map((s) => [s.blob_key, s.url]))
+ const urls = sources.map((s) => urlsByKey.get(s.blob_key))
+ // A second 401 after a fresh token means the token can never work here, so stop paying for a failed batch.
+ if (!token || direct.unauthorizedCount > 1 || urls.some((url) => !url)) {
+ return null
+ }
+ try {
+ // nosemgrep: prefer-codegen-api-namespaced-replay -- fetches recording-api block urls, not a Django endpoint
+ const blocks = await api.recordings.getBlocksDirectly(urls as string[], token)
+ direct.unauthorizedCount = 0
+ return blocks
+ } catch (e) {
+ // The snapshots endpoint reads the same blocks, so falling back would get round the rate limit.
+ if (e instanceof RecordingDeletedError || (e instanceof ApiError && e.status === 429)) {
+ throw e
+ }
+ const status = e instanceof ApiError ? e.status : undefined
+ if (status === 401) {
+ direct.unauthorizedCount += 1
+ // Listing the sources again gets a new token for the next batch.
+ onTokenExpired()
+ }
+ // Without this, a broken rollout looks healthy while every batch pays for a failed download.
+ posthog.capture('replay direct block fetch fell back', {
+ status: status ?? null,
+ reason: e instanceof Error ? e.name : 'unknown',
+ block_count: urls.length,
+ })
+ return null
+ }
+}
+
// Reactivity note (#53893): `cache.store` (SnapshotStore) lives outside Kea, so any listener that mutates it (markFetched, setSources) MUST dispatch `storeUpdated()` afterwards, and any selector reading it MUST depend on `storeVersion`.
export const snapshotDataLogic = kea<snapshotDataLogicType>([
path((key) => ['scenes', 'session-recordings', 'snapshotLogic', key]),
@@ -287,6 +332,7 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
// dispatch after any mutation to cache.store — it lives outside Kea's reactivity and needs explicit invalidation
storeUpdated: true,
setReplayProxyToken: (token: string | null) => ({ token }),
+ setBlockToken: (token: string | null) => ({ token }),
}),
reducers(() => ({
replayProxyToken: [
@@ -295,6 +341,12 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
setReplayProxyToken: (_, { token }) => token,
},
],
+ blockToken: [
+ null as string | null,
+ {
+ setBlockToken: (_, { token }) => token,
+ },
+ ],
storeUpdateCount: [
0,
{
@@ -376,6 +428,7 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
}
// Each listing mints a new token, so polling the sources keeps the proxy token fresh.
actions.setReplayProxyToken(response.replay_proxy_token ?? null)
+ actions.setBlockToken(response.block_token ?? null)
const anyBlobV2 = response.sources.some((s) => s.source === SnapshotSourceType.blob_v2)
if (anyBlobV2) {
@@ -418,11 +471,20 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
headers.Authorization = `Bearer ${props.accessToken}`
}
- const response = await api.recordings.getSnapshots(
- props.sessionRecordingId,
- { decompress: false, ...params },
- headers
- )
+ const response =
+ (await loadBlocksDirectly(
+ sources,
+ values.snapshotSources,
+ values.blockToken,
+ (cache.directBlocks ??= { unauthorizedCount: 0 }),
+ () => actions.loadSnapshotSources()
+ )) ??
+ // nosemgrep: prefer-codegen-api-namespaced-replay -- binary length-prefixed body the generated client does not decode
+ (await api.recordings.getSnapshots(
+ props.sessionRecordingId,
+ { decompress: false, ...params },
+ headers
+ ))
breakpoint()
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 4c06d4a2c671..55ccf805a7f2 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1531,6 +1531,8 @@ export interface SessionRecordingSnapshotResponse {
sources?: SessionRecordingSnapshotSource[]
snapshots?: EncodedRecordingSnapshot[]
replay_proxy_token?: string | null
+ block_token?: string | null
+ block_token_expires_at?: string | null
}
export interface SessionPlayerSnapshotData {
diff --git a/posthog/jwt.py b/posthog/jwt.py
index f7b81e15b2d8..8b4a1c9e2f11 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -26,6 +26,7 @@ class PosthogJwtAudience(Enum):
SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"
RECORDING_API = "posthog:recording_api"
REPLAY_PROXY = "posthog:replay_proxy"
+ REPLAY_BLOCKS = "posthog:replay:blocks"
WORKFLOWS_RESCHEDULE_PARKED = "posthog:workflows:reschedule_parked"
WORKFLOWS_CANCEL_INVOCATIONS = "posthog:workflows:cancel_invocations"
WORKFLOWS_CANCEL_BATCH = "posthog:workflows:cancel_batch"
diff --git a/posthog/session_recordings/recordings/replay_blocks_jwt.py b/posthog/session_recordings/recordings/replay_blocks_jwt.py
new file mode 100644
index 000000000000..3c176d7bf9f5
--- /dev/null
+++ b/posthog/session_recordings/recordings/replay_blocks_jwt.py
@@ -0,0 +1,59 @@
+import time
+from datetime import UTC, datetime, timedelta
+from typing import Literal
+
+import posthoganalytics
+
+from posthog.dataclasses import frozen
+from posthog.jwt import PosthogJwtAudience
+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
+
+# recording-api refuses a token older than 2 hours. One hour leaves room for clock skew, and the player gets a new
+# token each time it lists sources.
+REPLAY_BLOCKS_TOKEN_TTL = timedelta(hours=1)
+
+REPLAY_BLOCKS_JWT_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.REPLAY_BLOCKS,
+ settings_name="RECORDING_API_BLOCKS_JWT_SECRET",
+ default_ttl=REPLAY_BLOCKS_TOKEN_TTL,
+)
+
+REPLAY_DIRECT_BLOCKS_FLAG = "replay-direct-blocks"
+
+
+def is_direct_blocks_enabled(team_id: int) -> bool:
+ """Gate for giving the player block urls. The player polls the listing for a live recording, so the check sends
+ no flag-called event."""
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(REPLAY_DIRECT_BLOCKS_FLAG, str(team_id), send_feature_flag_events=False)
+ )
+ except Exception:
+ return False
+
+
+# recording-api gives the browser tier a budget per viewer and the API tiers one budget per team.
+ReplayBlocksTier = Literal["browser", "free", "paid", "enterprise"]
+
+
+@frozen
+class ReplayBlocksToken:
+ token: str
+ expires_at: datetime
+
+
+def mint_replay_blocks_token(
+ team_id: int, session_id: str, viewer: str, tier: ReplayBlocksTier
+) -> ReplayBlocksToken | None:
+ """A token that reads the blocks of one session. `viewer` is also a segment of every block URL, so the browser
+ keeps a separate cache entry for each viewer. Returns None until the signing key is provisioned."""
+ if not REPLAY_BLOCKS_JWT_PURPOSE.enabled():
+ return None
+ now = int(time.time())
+ expires_at = datetime.fromtimestamp(now, tz=UTC) + REPLAY_BLOCKS_TOKEN_TTL
+ token = REPLAY_BLOCKS_JWT_PURPOSE.mint(
+ # recording-api checks the token's age against iat, which encode_jwt does not set.
+ {"team_id": team_id, "session_id": session_id, "sub": viewer, "tier": tier, "iat": now},
+ ttl=REPLAY_BLOCKS_TOKEN_TTL,
+ )
+ return ReplayBlocksToken(token=token, expires_at=expires_at)
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index f43107abeec4..a72d09e20d67 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -10,7 +10,7 @@ from collections.abc import Generator
from contextlib import contextmanager
from json import JSONDecodeError
from typing import Any, Literal, cast
-from urllib.parse import urlparse
+from urllib.parse import quote, urlparse
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
@@ -110,6 +110,11 @@ from posthog.session_recordings.queries.session_replay_events import (
)
from posthog.session_recordings.recordings.errors import BlockFetchError, RecordingDeletedError
from posthog.session_recordings.recordings.recording_api_client import RecordingApiClient, recording_api_client
+from posthog.session_recordings.recordings.replay_blocks_jwt import (
+ ReplayBlocksToken,
+ is_direct_blocks_enabled,
+ mint_replay_blocks_token,
+)
from posthog.session_recordings.recordings.replay_proxy_jwt import mint_replay_proxy_token
from posthog.session_recordings.session_recording_v2_service import list_blocks, list_blocks_async
from posthog.session_recordings.utils import (
@@ -228,6 +233,36 @@ def _replay_proxy_token_for_player(request, team_id: int) -> str | None:
return mint_replay_proxy_token(team_id)
+def _replay_blocks_viewer(request) -> str | None:
+ """Who the player is watching as, for the block URLs and the per-viewer rate limit. An export renders as the user
+ who created it. None for any caller that is not the player, which keeps reading blocks through Django. Share links
+ also stay on Django, because a block token cannot see a share being disabled or its password revoked."""
+ authenticator = getattr(request, "successful_authenticator", None)
+ if isinstance(authenticator, (SessionAuthentication, ExportRendererAuthentication)) and isinstance(
+ request.user, User
+ ):
+ return f"u{request.user.pk}"
+ return None
+
+
+@frozen
+class ReplayBlocksAccess:
+ path_prefix: str
+ token: ReplayBlocksToken
+
+
+def _replay_blocks_access_for_player(request, team_id: int, session_id: str) -> ReplayBlocksAccess | None:
+ viewer = _replay_blocks_viewer(request)
+ if viewer is None or not is_direct_blocks_enabled(team_id):
+ return None
+ token = mint_replay_blocks_token(team_id, session_id, viewer, "browser")
+ if token is None:
+ return None
+ return ReplayBlocksAccess(
+ path_prefix=f"/replay-blocks/{team_id}/{quote(session_id, safe='')}/{viewer}/", token=token
+ )
+
+
# Type alias to avoid shadowing by SessionRecordingViewSet.list method
BlockList = list[Any]
@@ -465,6 +500,10 @@ class SessionRecordingSnapshotsSourceSerializer(serializers.Serializer):
start_timestamp = serializers.DateTimeField(allow_null=True)
end_timestamp = serializers.DateTimeField(allow_null=True)
blob_key = serializers.CharField(allow_null=True)
+ url = serializers.CharField(
+ required=False,
+ help_text="Where the player fetches this block directly, sending block_token as a Bearer token. Absent when the block must be read through this endpoint.",
+ )
class SessionRecordingSourcesSerializer(serializers.Serializer):
@@ -475,6 +514,16 @@ class SessionRecordingSourcesSerializer(serializers.Serializer):
allow_null=True,
help_text="Short-lived token that the player sends to the replay asset proxy with each font or script request. Null when this install has no proxy signing key.",
)
+ block_token = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Short-lived token for the source urls, scoped to this recording. Null when no source has a url.",
+ )
+ block_token_expires_at = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text="When block_token expires. List the sources again for a new one.",
+ )
class SessionRecordingUpdateSerializer(serializers.Serializer):
@@ -1749,21 +1798,31 @@ class SessionRecordingViewSet(
# Uncached, so a recording deleted a moment ago fails here before the player asks for any block.
blocks = list_blocks(recording, use_cache=False)
+ # Only encrypted recordings get refs, so a recording from before encryption has no urls.
+ access = (
+ _replay_blocks_access_for_player(self.request, self.team_id, str(recording.session_id))
+ if any(block.ref for block in blocks)
+ else None
+ )
+
for i, block in enumerate(blocks):
- sources.append(
- {
- "source": "blob_v2",
- "start_timestamp": block.start_timestamp,
- "end_timestamp": block.end_timestamp,
- "blob_key": str(i),
- }
- )
+ source = {
+ "source": "blob_v2",
+ "start_timestamp": block.start_timestamp,
+ "end_timestamp": block.end_timestamp,
+ "blob_key": str(i),
+ }
+ if access and block.ref:
+ source["url"] = self.request.build_absolute_uri(access.path_prefix + block.ref)
+ sources.append(source)
with timer("serialize_data__gather_session_recording_sources"):
serializer = SessionRecordingSourcesSerializer(
{
"sources": sorted(sources, key=lambda x: x.get("start_timestamp", -1)),
"replay_proxy_token": _replay_proxy_token_for_player(self.request, self.team_id),
+ "block_token": access.token.token if access else None,
+ "block_token_expires_at": access.token.expires_at if access else None,
}
)
diff --git a/posthog/session_recordings/session_recording_v2_service.py b/posthog/session_recordings/session_recording_v2_service.py
index 57e2c70ed943..86c6c44f77b6 100644
--- a/posthog/session_recordings/session_recording_v2_service.py
+++ b/posthog/session_recordings/session_recording_v2_service.py
@@ -27,6 +27,9 @@ class RecordingBlock:
end_byte: int
start_timestamp: str
end_timestamp: str
+ # recording-api's opaque name for the block, which the player can fetch directly. None for a recording from
+ # before encryption.
+ ref: str | None = None
FIVE_SECONDS = 5
@@ -59,6 +62,7 @@ async def fetch_blocks_from_recording_api(session_id: str, team_id: int) -> list
end_byte=b["end_byte"],
start_timestamp=b["start_timestamp"],
end_timestamp=b["end_timestamp"],
+ ref=b.get("ref"),
)
for b in raw_blocks
]
diff --git a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py
index 188f674b1414..15a4aab782e3 100644
--- a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py
+++ b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py
@@ -7,15 +7,18 @@ from django.test import override_settings
from parameterized import parameterized
from rest_framework import status
+from posthog.auth import mint_export_renderer_token
from posthog.clickhouse.client import sync_execute
from posthog.jwt import PosthogJwtAudience, decode_jwt
-from posthog.models import PersonalAPIKey, SessionRecording
+from posthog.models import PersonalAPIKey, SessionRecording, SharingConfiguration
from posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7
from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.session_recordings.recordings.errors import RecordingDeletedError
from posthog.session_recordings.session_recording_v2_service import RecordingBlock, listing_cache_key
+from products.exports.backend.models.exported_asset import ExportedAsset
+
class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest):
def setUp(self):
@@ -145,25 +148,71 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMa
assert call_args_list[1].args == ("key1", 101, 200, session_id, self.team.id)
assert call_args_list[1].kwargs.get("decompress") is True
- @parameterized.expand([("logged_in", True), ("personal_api_key", False)])
- @override_settings(REPLAY_PROXY_JWT_SECRET="replay-proxy-key")
+ @parameterized.expand(
+ [
+ ("logged_in", "session", True, True, True),
+ ("logged_in_flag_off", "session", False, True, False),
+ ("logged_in_unencrypted_recording", "session", True, False, False),
+ ("personal_api_key", "personal_api_key", True, True, False),
+ ("export_renderer", "export_renderer", True, True, True),
+ ("share_link", "share_link", True, True, False),
+ ]
+ )
+ @override_settings(REPLAY_PROXY_JWT_SECRET="replay-proxy-key", RECORDING_API_BLOCKS_JWT_SECRET="replay-blocks-key")
@patch(
"posthog.session_recordings.queries.session_replay_events.SessionReplayEvents.exists",
return_value=True,
)
@patch("posthog.session_recordings.session_recording_api.SessionRecording.get_or_build")
- @patch("posthog.session_recordings.session_recording_api.list_blocks", return_value=[])
- def test_sources_listing_gives_a_replay_proxy_token_only_to_the_player(
+ @patch("posthog.session_recordings.session_recording_api.list_blocks")
+ @patch("posthog.session_recordings.recordings.replay_blocks_jwt.posthoganalytics.feature_enabled")
+ def test_sources_listing_gives_player_tokens_only_to_the_player(
self,
+ _name: str,
auth: str,
- expects_token: bool,
- _mock_list_blocks,
+ flag_on: bool,
+ encrypted: bool,
+ expects_block_urls: bool,
+ mock_feature_enabled,
+ mock_list_blocks,
mock_get_session_recording,
_mock_exists,
) -> None:
session_id = str(uuid7())
mock_get_session_recording.return_value = SessionRecording(session_id=session_id, team=self.team, deleted=False)
+ mock_feature_enabled.return_value = flag_on
+ mock_list_blocks.return_value = [
+ RecordingBlock(
+ key=f"key{i}",
+ start_byte=0,
+ end_byte=10,
+ start_timestamp=f"2026-01-01T00:00:0{i}Z",
+ end_timestamp=f"2026-01-01T00:00:0{i}Z",
+ ref=f"v1.ref{i}" if encrypted else None,
+ )
+ for i in range(2)
+ ]
+ is_player = auth != "personal_api_key"
headers = {}
+ query = ""
+ viewer = f"u{self.user.pk}"
+ if auth == "export_renderer":
+ asset = ExportedAsset.objects.create(
+ team=self.team,
+ created_by=self.user,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ export_context={"session_recording_id": session_id},
+ )
+ renderer_token = mint_export_renderer_token(
+ user_id=self.user.id, team_id=self.team.id, exported_asset_id=asset.id, scope="session_recording:read"
+ )
+ headers = {"authorization": f"Bearer {renderer_token}"}
+ if auth == "share_link":
+ recording = SessionRecording.objects.create(session_id=session_id, team=self.team)
+ sharing = SharingConfiguration.objects.create(team=self.team, recording=recording, enabled=True)
+ mock_get_session_recording.return_value = recording
+ query = f"?sharing_access_token={sharing.access_token}"
+ self.client.logout()
if auth == "personal_api_key":
personal_api_key = generate_random_token_personal()
PersonalAPIKey.objects.create(
@@ -176,16 +225,38 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMa
headers = {"authorization": f"Bearer {personal_api_key}"}
response = self.client.get(
- f"/api/projects/{self.team.pk}/session_recordings/{session_id}/snapshots/", headers=headers
+ f"/api/projects/{self.team.pk}/session_recordings/{session_id}/snapshots/{query}", headers=headers
)
assert response.status_code == status.HTTP_200_OK, response.json()
- token = response.json()["replay_proxy_token"]
- if expects_token:
- claims = decode_jwt(token, PosthogJwtAudience.REPLAY_PROXY, verification_keys=["replay-proxy-key"])
+ body = response.json()
+ if is_player:
+ claims = decode_jwt(
+ body["replay_proxy_token"], PosthogJwtAudience.REPLAY_PROXY, verification_keys=["replay-proxy-key"]
+ )
assert claims["team_id"] == self.team.pk
else:
- assert token is None
+ assert body["replay_proxy_token"] is None
+
+ urls = [source.get("url") for source in body["sources"]]
+ if expects_block_urls:
+ assert urls == [
+ f"http://testserver/replay-blocks/{self.team.pk}/{session_id}/{viewer}/v1.ref{i}" for i in range(2)
+ ]
+ claims = decode_jwt(
+ body["block_token"], PosthogJwtAudience.REPLAY_BLOCKS, verification_keys=["replay-blocks-key"]
+ )
+ assert {k: claims[k] for k in ("team_id", "session_id", "sub", "tier")} == {
+ "team_id": self.team.pk,
+ "session_id": session_id,
+ "sub": viewer,
+ "tier": "browser",
+ }
+ assert isinstance(claims["iat"], int)
+ assert body["block_token_expires_at"] is not None
+ else:
+ assert urls == [None, None]
+ assert body["block_token"] is None
@parameterized.expand(
[
diff --git a/posthog/settings/session_replay_v2.py b/posthog/settings/session_replay_v2.py
index f7694b4ddf1a..f953a1e2ce5b 100644
--- a/posthog/settings/session_replay_v2.py
+++ b/posthog/settings/session_replay_v2.py
@@ -40,6 +40,13 @@ RECORDING_API_JWT_SECRET = os.getenv(
"RECORDING_API_JWT_SECRET", "dev-recording-api-jwt-secret" if (TEST or DEBUG) else ""
)
+# Signs the tokens the replay player sends to recording-api's public block route. Kept apart from
+# RECORDING_API_JWT_SECRET because the internet-facing recording-api pods hold this key, and an HMAC key that verifies
+# can also sign. The dev/test default matches the recording-api Node default. Comma-separated `new,old` for rotation.
+RECORDING_API_BLOCKS_JWT_SECRET = os.getenv(
+ "RECORDING_API_BLOCKS_JWT_SECRET", "dev-recording-api-blocks-jwt-secret" if (TEST or DEBUG) else ""
+)
+
# Signs the replay player's tokens for replay.ph-proxy.com, which holds the same comma-separated `new,old` keys.
# Never reuse SECRET_KEY or JWT_SIGNING_KEY. No dev default, because a key in public source lets anyone mint tokens.
# Empty means no token, so self-hosted installs never use the proxy.