: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay): give the player a token for the replay asset proxy (#111519)
Paul D'Ambra216c8bf217d9
diff --git a/posthog/jwt.py b/posthog/jwt.pyindex c8a7f6828d89..17028b8528ea 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -21,6 +21,7 @@ class PosthogJwtAudience(Enum):HOGQL_LANGUAGE_SERVICE = "hogql-language-service"SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"RECORDING_API = "posthog:recording_api"+ REPLAY_PROXY = "posthog:replay_proxy"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_proxy_jwt.py b/posthog/session_recordings/recordings/replay_proxy_jwt.pynew file mode 100644index 000000000000..a057d6bb6a9c--- /dev/null+++ b/posthog/session_recordings/recordings/replay_proxy_jwt.py@@ -0,0 +1,23 @@+from datetime import timedelta++from django.conf import settings++from posthog.jwt import PosthogJwtAudience+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose++# The player gets one token when it lists a recording's sources, then fetches fonts through the proxy+# for as long as someone watches. The export rasterizer also reuses one token for a whole render.+REPLAY_PROXY_TOKEN_TTL = timedelta(hours=1)++REPLAY_PROXY_JWT_PURPOSE = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.REPLAY_PROXY,+ settings_name="REPLAY_PROXY_JWT_SECRET",+ default_ttl=REPLAY_PROXY_TOKEN_TTL,+)+++def mint_replay_proxy_token(team_id: int) -> str | None:+ if not REPLAY_PROXY_JWT_PURPOSE.enabled():+ return None+ # One proxy serves US and EU, whose team ids overlap, so the proxy logs the region next to the team id.+ return REPLAY_PROXY_JWT_PURPOSE.mint({"team_id": team_id, "region": settings.CLOUD_DEPLOYMENT})diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex cb0945cb8410..e1e440062db4 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -64,6 +64,7 @@ from posthog.auth import (JwtAuthentication,OAuthAccessTokenAuthentication,PersonalAPIKeyAuthentication,+ SessionAuthentication,SharingAccessTokenAuthentication,SharingPasswordProtectedAuthentication,)@@ -100,6 +101,7 @@ from posthog.session_recordings.queries.session_replay_events import ()from posthog.session_recordings.recordings.errors import BlockFetchError, RecordingDeletedErrorfrom posthog.session_recordings.recordings.recording_api_client import RecordingApiClient, recording_api_client+from posthog.session_recordings.recordings.replay_proxy_jwt import mint_replay_proxy_tokenfrom posthog.session_recordings.session_recording_v2_service import list_blocks, list_blocks_asyncfrom posthog.session_recordings.utils import (clean_prompt_whitespace,@@ -190,6 +192,22 @@ def _request_auth_type(request) -> str:return "logged_in"+# The replay asset proxy serves only the web player under a login session, a share link, or an export.+# Every OAuth client gets no token, which includes the player in standalone OAuth mode, and so do personal API keys.+_PLAYER_AUTHENTICATION_CLASSES = (+ SessionAuthentication,+ SharingAccessTokenAuthentication,+ SharingPasswordProtectedAuthentication,+ ExportRendererAuthentication,+)+++def _replay_proxy_token_for_player(request, team_id: int) -> str | None:+ if not isinstance(getattr(request, "successful_authenticator", None), _PLAYER_AUTHENTICATION_CLASSES):+ return None+ return mint_replay_proxy_token(team_id)++# Type alias to avoid shadowing by SessionRecordingViewSet.list methodBlockList = list[Any]@@ -435,6 +453,11 @@ class SessionRecordingSnapshotsSourceSerializer(serializers.Serializer):class SessionRecordingSourcesSerializer(serializers.Serializer):sources = serializers.ListField(child=SessionRecordingSnapshotsSourceSerializer(), required=False)snapshots = serializers.ListField(required=False)+ replay_proxy_token = serializers.CharField(+ required=False,+ 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.",+ )class SessionRecordingUpdateSerializer(serializers.Serializer):@@ -1536,7 +1559,10 @@ class SessionRecordingViewSet(with timer("serialize_data__gather_session_recording_sources"):serializer = SessionRecordingSourcesSerializer(- {"sources": sorted(sources, key=lambda x: x.get("start_timestamp", -1))}+ {+ "sources": sorted(sources, key=lambda x: x.get("start_timestamp", -1)),+ "replay_proxy_token": _replay_proxy_token_for_player(self.request, self.team_id),+ })return Response(serializer.data)diff --git a/posthog/session_recordings/test/test_replay_proxy_jwt.py b/posthog/session_recordings/test/test_replay_proxy_jwt.pynew file mode 100644index 000000000000..967baf792b89--- /dev/null+++ b/posthog/session_recordings/test/test_replay_proxy_jwt.py@@ -0,0 +1,24 @@+from datetime import UTC, datetime++from django.test import override_settings++from posthog.jwt import PosthogJwtAudience, decode_jwt+from posthog.session_recordings.recordings.replay_proxy_jwt import mint_replay_proxy_token+++class TestMintReplayProxyToken:+ @override_settings(REPLAY_PROXY_JWT_SECRET="primary-key,old-key", CLOUD_DEPLOYMENT="EU")+ def test_mints_team_scoped_token_the_proxy_accepts(self):+ before = datetime.now(tz=UTC)+ token = mint_replay_proxy_token(123)++ assert token is not None+ decoded = decode_jwt(token, PosthogJwtAudience.REPLAY_PROXY, verification_keys=["primary-key"])+ assert decoded["aud"] == "posthog:replay_proxy"+ assert decoded["team_id"] == 123+ assert decoded["region"] == "EU"+ assert 59 * 60 < decoded["exp"] - before.timestamp() < 61 * 60++ @override_settings(REPLAY_PROXY_JWT_SECRET="")+ def test_returns_none_without_a_secret(self):+ assert mint_replay_proxy_token(123) is Nonediff --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.pyindex 4be5a9e34cbc..edf04e5fd5b0 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@@ -1,10 +1,13 @@from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.test import override_settings+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.clickhouse.client import sync_execute+from posthog.jwt import PosthogJwtAudience, decode_jwtfrom posthog.models import PersonalAPIKey, SessionRecordingfrom posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed@@ -141,6 +144,48 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMaassert 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")+ @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(+ self,+ auth: str,+ expects_token: bool,+ _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)+ headers = {}+ if auth == "personal_api_key":+ personal_api_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(personal_api_key),+ scopes=["session_recording:read"],+ scoped_teams=[self.team.pk],+ )+ headers = {"authorization": f"Bearer {personal_api_key}"}++ response = self.client.get(+ f"/api/projects/{self.team.pk}/session_recordings/{session_id}/snapshots/", 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"])+ assert claims["team_id"] == self.team.pk+ else:+ assert token is None+@parameterized.expand([("0", "", ""),diff --git a/posthog/session_recordings/test/test_session_recordings_sharing.py b/posthog/session_recordings/test/test_session_recordings_sharing.pyindex 36aaf9e69a94..ccd86468a3bd 100644--- a/posthog/session_recordings/test/test_session_recordings_sharing.py+++ b/posthog/session_recordings/test/test_session_recordings_sharing.py@@ -2,6 +2,7 @@ import pytestimport time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest+from django.test import override_settingsfrom django.utils.timezone import nowfrom dateutil.relativedelta import relativedelta@@ -11,6 +12,7 @@ from rest_framework import statusfrom posthog.api.test.test_team import create_teamfrom posthog.clickhouse.client import sync_executefrom posthog.constants import AvailableFeature+from posthog.jwt import PosthogJwtAudience, decode_jwtfrom posthog.models import SessionRecordingfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import User@@ -125,6 +127,7 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchi"end_time": "2022-12-31T12:00:00Z",}+ @override_settings(REPLAY_PROXY_JWT_SECRET="replay-proxy-key")@time_machine.travel("2023-01-01T12:00:00Z", tick=False)def test_sharing_token_allows_snapshot_access(self) -> None:token = self._enable_sharing(self.session_id)@@ -135,6 +138,12 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchif"/api/projects/{self.team.id}/session_recordings/{self.session_id}/snapshots?sharing_access_token={token}")assert response.status_code == status.HTTP_200_OK, response.json()+ proxy_claims = decode_jwt(+ response.json()["replay_proxy_token"],+ PosthogJwtAudience.REPLAY_PROXY,+ verification_keys=["replay-proxy-key"],+ )+ assert proxy_claims["team_id"] == self.team.id@pytest.mark.eediff --git a/posthog/settings/session_replay_v2.py b/posthog/settings/session_replay_v2.pyindex 1eb54be9c34f..f7694b4ddf1a 100644--- a/posthog/settings/session_replay_v2.py+++ b/posthog/settings/session_replay_v2.py@@ -39,3 +39,8 @@ else:RECORDING_API_JWT_SECRET = os.getenv("RECORDING_API_JWT_SECRET", "dev-recording-api-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.+REPLAY_PROXY_JWT_SECRET = os.getenv("REPLAY_PROXY_JWT_SECRET", "")