: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
fix(sharing): rate-limit and harden share password checks (#74435)
Tom Piccirello45af079d841f
diff --git a/frontend/src/exporter/ExporterLogin.tsx b/frontend/src/exporter/ExporterLogin.tsxindex e9e2db8c0891..a5d588c3374e 100644--- a/frontend/src/exporter/ExporterLogin.tsx+++ b/frontend/src/exporter/ExporterLogin.tsx@@ -134,6 +134,8 @@ export const loginLogic = kea<loginLogicType>([if (response.status === 200) {actions.setSuccess()window.location.reload()+ } else if (response.status === 429) {+ actions.setGeneralError('throttled', 'Too many attempts on this link. Wait a minute and try again.')} else {actions.setGeneralError(response.statusText, (await response.json()).error)}diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 6ee001437276..9e8951b8e377 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -41,6 +41,12 @@ from posthog.models import SessionRecording, SharePassword, SharingConfigurationfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.resource_transfer.visitors.insight import InsightVisitorfrom posthog.models.user import User+from posthog.rate_limit import (+ BurstRateThrottle,+ SharePasswordThrottle,+ SharePasswordVolumeThrottle,+ SustainedRateThrottle,+)from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import (UserAccessControl,@@ -832,6 +838,9 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe# Only use sharing-specific authentication, ignore regular PostHog authauthentication_classes = [SharingPasswordProtectedAuthentication, SharingAccessTokenAuthentication]permission_classes = []+ # SharePasswordThrottle is deliberately not here - it's charged manually in retrieve(),+ # only on a wrong password, so a correct one always succeeds regardless of its budget.+ throttle_classes = [BurstRateThrottle, SustainedRateThrottle, SharePasswordVolumeThrottle]serializer_class = SharingConfigurationSerializer # Required by DRF but not used in practice# Set by get_object() when the resolved resource is an ExportedAsset whose token carried a purpose claim.@@ -1003,7 +1012,9 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe# Check if user is already authenticated via JWT token (Bearer or cookie)is_jwt_authenticated = isinstance(request.successful_authenticator, SharingPasswordProtectedAuthentication)- if request.method == "GET" and not is_jwt_authenticated:+ # Anything that isn't a password submission needs the unlock page unless it already+ # carries a valid share token - DRF routes HEAD through the same action as GET+ if request.method != "POST" and not is_jwt_authenticated:exported_data["type"] = "unlock"settings_data = getattr(resource, "settings", {}) or {}@@ -1024,7 +1035,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe"add_og_tags": None,},)- elif request.method == "GET" and is_jwt_authenticated:+ elif request.method != "POST":# JWT authenticated (via cookie or Bearer) - render full app context# Include the JWT token from the cookie so frontend can use it for API calls@@ -1038,6 +1049,19 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSevalidated_password = self._validate_share_password(resource, request.data["password"])if not validated_password:+ # Charged only on a wrong guess, so a correct password always succeeds even+ # if an attacker has driven this link's wrong-guess budget to its cap -+ # SharePasswordVolumeThrottle bounds the total POST rate this depends on.+ wrong_password_throttle = SharePasswordThrottle()+ if not wrong_password_throttle.allow_request(request, self):+ # Logged only below the cap, not here: logging every throttled guess too would+ # write activity-log rows at SharePasswordVolumeThrottle's rate instead of this one's.+ throttle_response = response.Response(+ {"error": "Too many attempts on this link. Wait a minute and try again."}, status=429+ )+ throttle_response["Retry-After"] = str(int(wrong_password_throttle.wait()))+ return throttle_response+_log_share_password_attempt(resource, request, success=False)return response.Response({"error": "Incorrect password"}, status=401)diff --git a/posthog/api/test/test_share_password_api.py b/posthog/api/test/test_share_password_api.pyindex 2746c9a3c9cc..97313c62ff79 100644--- a/posthog/api/test/test_share_password_api.py+++ b/posthog/api/test/test_share_password_api.py@@ -1,13 +1,19 @@import json+from types import SimpleNamespacefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.core.cache import cache+from rest_framework import status+from rest_framework.test import APIRequestFactoryfrom posthog.api.test.test_sharing import mock_exporter_templatefrom posthog.constants import AvailableFeaturefrom posthog.models import SharePassword, SharingConfiguration+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.rate_limit import SharePasswordThrottle, SharePasswordVolumeThrottlefrom products.dashboards.backend.models.dashboard import Dashboard@@ -177,6 +183,124 @@ class TestSharePasswordAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)self.assertIn("Incorrect password", response.json()["error"])+ def test_repeated_wrong_passwords_are_throttled(self):+ SharePassword.create_password(+ sharing_configuration=self.sharing_config, created_by=self.user, raw_password="secure-test-password"+ )++ statuses = []+ throttled_response = None+ for attempt in range(25):+ # Each guess comes from a different address, so the budget has to follow the share link+ source_ip = f"10.0.0.{attempt}"+ response = self.client.post(+ f"/shared/{self.sharing_config.access_token}",+ data=json.dumps({"password": f"wrong-password-{attempt}"}),+ content_type="application/json",+ REMOTE_ADDR=source_ip,+ HTTP_X_FORWARDED_FOR=source_ip,+ )+ statuses.append(response.status_code)+ if response.status_code == status.HTTP_429_TOO_MANY_REQUESTS:+ throttled_response = response+ break++ self.assertEqual(statuses[0], status.HTTP_401_UNAUTHORIZED)+ self.assertEqual(statuses[-1], status.HTTP_429_TOO_MANY_REQUESTS)+ assert throttled_response is not None+ self.assertEqual(throttled_response["Retry-After"], "60")++ # A throttled guess never reaches password validation, so it must not log an attempt -+ # otherwise a flood logs at the volume throttle's rate instead of the wrong-guess one.+ failed_attempt_logs = ActivityLog.objects.filter(+ activity="share_login_failed", item_id=str(self.dashboard.id)+ ).count()+ self.assertEqual(failed_attempt_logs, statuses.count(status.HTTP_401_UNAUTHORIZED))++ def test_attempts_are_counted_atomically(self):+ # Submissions that arrive together must each consume budget. A read-modify-write throttle+ # lets them all read the same below-limit state and overwrite each other, so the cap only+ # holds for strictly serial guessing - which an attacker has no reason to do.+ SharePassword.create_password(+ sharing_configuration=self.sharing_config, created_by=self.user, raw_password="secure-test-password"+ )+ throttle = SharePasswordThrottle()+ request = APIRequestFactory().post(f"/shared/{self.sharing_config.access_token}")+ view = SimpleNamespace(kwargs={"access_token": self.sharing_config.access_token})++ key = throttle.get_cache_key(request, view) # type: ignore[arg-type]+ cache.delete(key)+ for _ in range(3):+ throttle.allow_request(request, view) # type: ignore[arg-type]++ self.assertEqual(cache.get(key), 3)++ def test_correct_password_succeeds_after_wrong_guess_budget_exhausted(self):+ # SharePasswordThrottle's budget is shared by every viewer of a link, keyed only on the+ # token. If a wrong guess and a correct one both drew from it, an attacker holding just+ # the URL could submit garbage passwords to deny everyone else who knows the real one.+ SharePassword.create_password(+ sharing_configuration=self.sharing_config, created_by=self.user, raw_password="secure-test-password"+ )++ statuses = []+ for attempt in range(15):+ source_ip = f"10.0.1.{attempt}"+ wrong_response = self.client.post(+ f"/shared/{self.sharing_config.access_token}",+ data=json.dumps({"password": f"wrong-password-{attempt}"}),+ content_type="application/json",+ REMOTE_ADDR=source_ip,+ HTTP_X_FORWARDED_FOR=source_ip,+ )+ statuses.append(wrong_response.status_code)+ if wrong_response.status_code == status.HTTP_429_TOO_MANY_REQUESTS:+ break++ self.assertEqual(statuses[-1], status.HTTP_429_TOO_MANY_REQUESTS)++ correct_response = self.client.post(+ f"/shared/{self.sharing_config.access_token}",+ data=json.dumps({"password": "secure-test-password"}),+ content_type="application/json",+ REMOTE_ADDR="10.0.2.1",+ HTTP_X_FORWARDED_FOR="10.0.2.1",+ )++ self.assertEqual(correct_response.status_code, status.HTTP_200_OK)+ self.assertIn("shareToken", correct_response.json())++ def test_volume_throttle_caps_attempts_regardless_of_correctness(self):+ # SharePasswordThrottle only meters wrong guesses, so nothing else bounds sheer POST+ # volume - and thus password-hashing cost - per link. SharePasswordVolumeThrottle is+ # that backstop; losing it from throttle_classes would leave submissions uncapped.+ throttle = SharePasswordVolumeThrottle()+ request = APIRequestFactory().post(f"/shared/{self.sharing_config.access_token}")+ view = SimpleNamespace(kwargs={"access_token": self.sharing_config.access_token})++ key = throttle.get_cache_key(request, view) # type: ignore[arg-type]+ cache.delete(key)+ results = [throttle.allow_request(request, view) for _ in range(throttle.num_requests + 1)] # type: ignore[arg-type]++ self.assertTrue(all(results[: throttle.num_requests]))+ self.assertFalse(results[-1])++ @mock_exporter_template+ def test_head_request_does_not_bypass_password_gate(self):+ SharePassword.create_password(+ sharing_configuration=self.sharing_config, created_by=self.user, raw_password="secure-test-password"+ )++ head_response = self.client.head(f"/shared/{self.sharing_config.access_token}")+ unlock_page = self.client.get(f"/shared/{self.sharing_config.access_token}")++ self.assertEqual(head_response.status_code, status.HTTP_200_OK)+ # Django strips HEAD bodies, so compare against the unlock page an anonymous GET receives+ self.assertEqual(head_response["Content-Length"], unlock_page["Content-Length"])+ # Rendering the shared dashboard stamps last_accessed_at, so it stays unset while locked+ self.dashboard.refresh_from_db()+ self.assertIsNone(self.dashboard.last_accessed_at)+@mock_exporter_templatedef test_jwt_token_invalidation_on_password_deletion(self):"""Test that JWT tokens are invalidated when their associated password is deleted, but remain valid when other passwords are deleted."""diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex b5d8c7e7ad24..56d9c767300a 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -1120,6 +1120,81 @@ class RestoreRedeemThrottle(SimpleRateThrottle):return self.cache_format % {"scope": self.scope, "ident": self.get_ident(request)}+class _SharedLinkAtomicThrottle(SimpleRateThrottle):+ """+ Rate limit requests to a shared link, counted atomically per link rather than per caller.++ Deliberately not a PersonalApiKeyRateThrottle subclass: this must apply even when the+ RATE_LIMIT_ENABLED instance setting is off. Keyed on the share link rather than the caller+ so rotating source addresses doesn't hand out a fresh budget. Subclasses set `scope` and+ `rate`; each gets its own counter since the cache key includes `scope`.+ """++ # Assigned by SimpleRateThrottle.__init__ from the parsed rate; the stubs don't declare them.+ num_requests: int+ duration: int++ def allow_request(self, request: "Request", view: "APIView") -> bool:+ # Only POSTs cost budget - every viewer of a link shares one bucket, so counting+ # ordinary page loads would lock out a popular share.+ if request.method != "POST":+ return True++ self.key = self.get_cache_key(request, view)++ # A counter incremented in place, rather than SimpleRateThrottle's read-modify-write of a+ # timestamp list: that reads the history, appends, and writes it back, so submissions+ # arriving together each observe a below-limit history and overwrite one another. Guessing+ # in parallel would then slip past the cap this throttle exists to enforce.+ self.cache.add(self.key, 0, self.duration)+ try:+ count = self.cache.incr(self.key)+ except ValueError:+ # The window expired between the add and the incr, so this request starts the next one.+ self.cache.set(self.key, 1, self.duration)+ count = 1++ return count <= self.num_requests++ def wait(self) -> float:+ # allow_request keeps a counter rather than the timestamp history SimpleRateThrottle.wait+ # reads, so retry after the whole window instead.+ return float(self.duration)++ def get_cache_key(self, request: "Request", view: "APIView") -> str:+ # File extensions ("<token>.json") address the same share, so they share a bucket+ access_token = (view.kwargs.get("access_token") or "").split(".")[0]+ ident = hashlib.sha256(access_token.encode()).hexdigest() if access_token else self.get_ident(request)+ return self.cache_format % {"scope": self.scope, "ident": ident}+++class SharePasswordVolumeThrottle(_SharedLinkAtomicThrottle):+ """+ Caps total share-password POST volume per link, regardless of whether the password is right.++ Runs automatically via throttle_classes, ahead of any password hashing, so a flood of+ submissions can't burn unbounded CPU on password checks before SharePasswordThrottle -+ which only meters wrong guesses - ever gets consulted. Sized loosely so a share handed to a+ large group doesn't trip it under normal use.+ """++ scope = "share_password_volume"+ rate = "60/minute"+++class SharePasswordThrottle(_SharedLinkAtomicThrottle):+ """+ Meters wrong share-password guesses per link.++ Called manually from the view, and only charged on a wrong guess: a correct password always+ succeeds, so one attacker flooding wrong guesses can't lock out every other viewer of the+ same link. SharePasswordVolumeThrottle bounds the total POST rate this depends on.+ """++ scope = "share_password"+ rate = "10/minute"++class CodeInviteThrottle(UserRateThrottle):scope = "code_invite"rate = "20000/hour"