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(replay): cap shared-link snapshot fetches per token, not per IP (#58958)

Tue Haulund20514c0b6e8f
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 99ecc7cd16e5..ff09925065d1 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import os
import re
import json
+import time
import struct
import asyncio
import builtins
@@ -39,6 +40,7 @@ from rest_framework.mixins import UpdateModelMixin
from rest_framework.renderers import JSONRenderer
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework.throttling import SimpleRateThrottle
from rest_framework.utils.encoders import JSONEncoder
from temporalio.service import RPCError, RPCStatusCode
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_random_exponential
@@ -64,6 +66,7 @@ from posthog.auth import (
OAuthAccessTokenAuthentication,
PersonalAPIKeyAuthentication,
SharingAccessTokenAuthentication,
+ SharingPasswordProtectedAuthentication,
)
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.cloud_utils import is_cloud
@@ -75,7 +78,14 @@ from posthog.models.activity_logging.activity_log import Detail, log_activity
from posthog.models.comment import Comment
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team.extensions import get_or_create_team_extension
-from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle, PersonalApiKeyRateThrottle
+from posthog.models.utils import hash_key_value
+from posthog.rate_limit import (
+ ClickHouseBurstRateThrottle,
+ ClickHouseSustainedRateThrottle,
+ PersonalApiKeyRateThrottle,
+ is_rate_limit_enabled,
+ team_is_allowed_to_bypass_throttle,
+)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.renderers import ServerSentEventRenderer
@@ -685,6 +695,36 @@ class ListingSustainedRateThrottle(_TierAwareReplayThrottle):
return listing_rates()
+class SharingTokenReplayThrottle(SimpleRateThrottle):
+ """Per-token cap for replay endpoints reached via a sharing-token authenticator."""
+
+ scope = "replay_sharing_token"
+
+ def __init__(self) -> None:
+ # Read at instantiation so override_settings takes effect.
+ self.rate = settings.REPLAY_SHARING_TOKEN_RATE
+ super().__init__()
+
+ def get_cache_key(self, request, view) -> str | None:
+ auth = request.successful_authenticator
+ token = getattr(getattr(auth, "sharing_configuration", None), "access_token", None)
+ if not token:
+ return None
+ # Hash the bearer token before composing the key — mirrors PersonalApiKeyRateThrottle.
+ return self.cache_format % {"scope": self.scope, "ident": hash_key_value(token)}
+
+ def allow_request(self, request, view) -> bool:
+ if not is_rate_limit_enabled(round(time.time() / 60)):
+ return True
+ team_id = PersonalApiKeyRateThrottle.safely_get_team_id_from_view(view)
+ if team_id is not None and team_is_allowed_to_bypass_throttle(team_id):
+ return True
+ if super().allow_request(request, view):
+ return True
+ SESSION_RECORDING_THROTTLED.labels(location=self.scope, auth_type="sharing_token").inc()
+ return False
+
+
def _length_prefix_blocks(blocks: list[bytes]) -> bytes:
chunks = []
for block in blocks:
@@ -747,6 +787,12 @@ class SessionRecordingViewSet(
return SessionRecording.get_or_build(session_id=self.kwargs["pk"], team=self.team)
def get_throttles(self):
+ if isinstance(
+ self.request.successful_authenticator,
+ SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication,
+ ):
+ # Sharing-token requests get a per-token cap instead of per-IP / per-team.
+ return [SharingTokenReplayThrottle()]
if self.action == "list":
return [*super().get_throttles(), ListingBurstRateThrottle(), ListingSustainedRateThrottle()]
return super().get_throttles()
diff --git a/posthog/session_recordings/test/test_session_recording_throttle.py b/posthog/session_recordings/test/test_session_recording_throttle.py
index 8af5685ac81b..bc12e784f519 100644
--- a/posthog/session_recordings/test/test_session_recording_throttle.py
+++ b/posthog/session_recordings/test/test_session_recording_throttle.py
@@ -5,14 +5,24 @@ from django.core.cache import cache
from django.test import override_settings
from parameterized import parameterized
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
-from posthog.auth import PersonalAPIKeyAuthentication
+from posthog.auth import (
+ PersonalAPIKeyAuthentication,
+ SharingAccessTokenAuthentication,
+ SharingPasswordProtectedAuthentication,
+)
+from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.models.utils import hash_key_value
from posthog.session_recordings.session_recording_api import (
LISTING_RATES,
REPLAY_TIER_CACHE_TTL_SECONDS,
SNAPSHOT_DEFAULT_TIER,
SNAPSHOT_RATES,
ListingBurstRateThrottle,
+ SessionRecordingViewSet,
+ SharingTokenReplayThrottle,
SnapshotsBurstRateThrottle,
SnapshotsSustainedRateThrottle,
get_cached_org_tier,
@@ -295,3 +305,161 @@ class TestSnapshotAndListingThrottlesUseIndependentRates(BaseTest):
assert listing_throttle._get_rates() == listing_rates()
assert snapshot_throttle._get_rates() == snapshot_rates()
assert listing_throttle._get_rates() == listing_rates()
+
+
+def _counter_value(location: str, auth_type: str) -> float:
+ from posthog.session_recordings.session_recording_api import SESSION_RECORDING_THROTTLED
+
+ sample = SESSION_RECORDING_THROTTLED.labels(location=location, auth_type=auth_type)
+ return sample._value.get() # prometheus_client's internal counter accessor
+
+
+def _fake_sharing_token_request(token: str, auth_cls: type = SharingAccessTokenAuthentication):
+ auth = auth_cls()
+ auth.sharing_configuration = SharingConfiguration(access_token=token, enabled=True)
+ return type("FakeRequest", (), {"META": {}, "auth": None, "successful_authenticator": auth})()
+
+
+class TestSharingTokenReplayThrottle(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def tearDown(self) -> None:
+ super().tearDown()
+ cache.clear()
+
+ def test_cache_key_uses_hashed_token_not_raw(self) -> None:
+ # Raw bearer tokens must never appear in cache keys (Redis MONITOR / log leakage).
+ throttle = SharingTokenReplayThrottle()
+
+ key = throttle.get_cache_key(_fake_sharing_token_request("token-abc"), view=None)
+
+ assert key is not None
+ assert "token-abc" not in key
+ assert hash_key_value("token-abc") in key
+ assert throttle.scope in key
+
+ def test_different_tokens_have_different_cache_keys(self) -> None:
+ throttle = SharingTokenReplayThrottle()
+
+ key_a = throttle.get_cache_key(_fake_sharing_token_request("token-a"), view=None)
+ key_b = throttle.get_cache_key(_fake_sharing_token_request("token-b"), view=None)
+
+ assert key_a != key_b
+
+ def test_same_token_from_different_requests_shares_one_bucket(self) -> None:
+ throttle = SharingTokenReplayThrottle()
+
+ key_first = throttle.get_cache_key(_fake_sharing_token_request("token-shared"), view=None)
+ key_second = throttle.get_cache_key(_fake_sharing_token_request("token-shared"), view=None)
+
+ assert key_first == key_second
+
+ def test_password_protected_auth_shares_bucket_with_access_token_auth(self) -> None:
+ # Both authenticators expose `sharing_configuration.access_token` — same recording, same bucket.
+ throttle = SharingTokenReplayThrottle()
+
+ key_access = throttle.get_cache_key(
+ _fake_sharing_token_request("token-x", SharingAccessTokenAuthentication), view=None
+ )
+ key_password = throttle.get_cache_key(
+ _fake_sharing_token_request("token-x", SharingPasswordProtectedAuthentication), view=None
+ )
+
+ assert key_access == key_password
+
+ def test_returns_none_cache_key_when_no_sharing_configuration(self) -> None:
+ # Defensive guard against misrouted requests.
+ throttle = SharingTokenReplayThrottle()
+ request = type("FakeRequest", (), {"META": {}, "auth": None, "successful_authenticator": None})()
+
+ assert throttle.get_cache_key(request, view=None) is None
+
+ def test_rate_reads_from_settings_default(self) -> None:
+ throttle = SharingTokenReplayThrottle()
+
+ assert throttle.rate == "600/minute"
+
+ @override_settings(REPLAY_SHARING_TOKEN_RATE="42/minute")
+ def test_rate_is_configurable_via_settings(self) -> None:
+ throttle = SharingTokenReplayThrottle()
+
+ assert throttle.rate == "42/minute"
+
+ @patch("posthog.session_recordings.session_recording_api.is_rate_limit_enabled", return_value=False)
+ def test_allow_request_short_circuits_when_kill_switch_off(self, _mock) -> None:
+ throttle = SharingTokenReplayThrottle()
+ view = type("FakeView", (), {"team_id": 1})()
+
+ for _ in range(10_000):
+ assert throttle.allow_request(_fake_sharing_token_request("token"), view=view) is True
+
+ @patch("posthog.session_recordings.session_recording_api.is_rate_limit_enabled", return_value=True)
+ @patch("posthog.session_recordings.session_recording_api.team_is_allowed_to_bypass_throttle", return_value=True)
+ def test_allow_request_short_circuits_for_bypass_listed_team(self, _mock_bypass, _mock_enabled) -> None:
+ # Without enabling the kill switch, the test would short-circuit on it and never exercise bypass.
+ throttle = SharingTokenReplayThrottle()
+ view = type("FakeView", (), {"team_id": 7})()
+
+ for _ in range(10_000):
+ assert throttle.allow_request(_fake_sharing_token_request("token"), view=view) is True
+
+ @patch("posthog.session_recordings.session_recording_api.is_rate_limit_enabled", return_value=True)
+ @override_settings(REPLAY_SHARING_TOKEN_RATE="2/minute")
+ def test_allow_request_emits_throttled_counter_on_rejection(self, _mock) -> None:
+ throttle = SharingTokenReplayThrottle()
+ view = type("FakeView", (), {"team_id": 1})()
+ before = _counter_value("replay_sharing_token", "sharing_token")
+
+ # Burn the bucket then attempt one more — only the rejected one bumps the counter.
+ for _ in range(2):
+ throttle.allow_request(_fake_sharing_token_request("token-counted"), view=view)
+ throttle.allow_request(_fake_sharing_token_request("token-counted"), view=view)
+
+ after = _counter_value("replay_sharing_token", "sharing_token")
+ assert after - before == 1
+
+
+class TestSessionRecordingViewSetThrottleSelection(BaseTest):
+ def _viewset(self, action: str, authenticator) -> SessionRecordingViewSet:
+ viewset = SessionRecordingViewSet()
+ viewset.action = action
+ request = Request(APIRequestFactory().get("/"))
+ request._authenticator = authenticator # type: ignore[attr-defined] # backs read-only @property
+ viewset.request = request # ty: ignore[invalid-assignment]
+ return viewset
+
+ @parameterized.expand(
+ [
+ ("access_token", SharingAccessTokenAuthentication),
+ ("password_protected", SharingPasswordProtectedAuthentication),
+ ]
+ )
+ def test_sharing_token_requests_only_use_per_token_throttle(self, _name: str, auth_cls: type) -> None:
+ auth = auth_cls()
+ auth.sharing_configuration = SharingConfiguration(access_token="tok", enabled=True)
+ viewset = self._viewset(action="snapshots", authenticator=auth)
+
+ throttles = viewset.get_throttles()
+
+ assert len(throttles) == 1
+ assert isinstance(throttles[0], SharingTokenReplayThrottle)
+
+ def test_sharing_token_on_list_does_not_include_listing_throttles(self) -> None:
+ # Defence in depth: `list` isn't sharing-enabled, but if it ever is, the per-token cap must be the only throttle.
+ auth = SharingAccessTokenAuthentication()
+ auth.sharing_configuration = SharingConfiguration(access_token="tok", enabled=True)
+ viewset = self._viewset(action="list", authenticator=auth)
+
+ throttles = viewset.get_throttles()
+
+ assert all(not isinstance(t, ListingBurstRateThrottle) for t in throttles)
+ assert any(isinstance(t, SharingTokenReplayThrottle) for t in throttles)
+
+ def test_non_sharing_requests_keep_default_throttles(self) -> None:
+ viewset = self._viewset(action="retrieve", authenticator=PersonalAPIKeyAuthentication())
+
+ throttles = viewset.get_throttles()
+
+ assert not any(isinstance(t, SharingTokenReplayThrottle) for t in throttles)
diff --git a/posthog/settings/session_replay.py b/posthog/settings/session_replay.py
index b57571bd034f..8f1240778204 100644
--- a/posthog/settings/session_replay.py
+++ b/posthog/settings/session_replay.py
@@ -36,3 +36,6 @@ LISTING_RATE_PAID_BURST = get_from_env("LISTING_RATE_PAID_BURST", "60/minute")
LISTING_RATE_PAID_SUSTAINED = get_from_env("LISTING_RATE_PAID_SUSTAINED", "300/hour")
LISTING_RATE_ENTERPRISE_BURST = get_from_env("LISTING_RATE_ENTERPRISE_BURST", "100/minute")
LISTING_RATE_ENTERPRISE_SUSTAINED = get_from_env("LISTING_RATE_ENTERPRISE_SUSTAINED", "400/hour")
+
+# Per-token cap for replay endpoints reached via a SharingAccessToken.
+REPLAY_SHARING_TOKEN_RATE = get_from_env("REPLAY_SHARING_TOKEN_RATE", "600/minute")