: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(signup): count only successful signups against the per-ip limit (#129583)
Rafael Audibert8d46dd600bbd
diff --git a/frontend/src/scenes/authentication/auth/signupLogic.test.ts b/frontend/src/scenes/authentication/auth/signupLogic.test.tsindex e69fc117b734..efaf16aa3367 100644--- a/frontend/src/scenes/authentication/auth/signupLogic.test.ts+++ b/frontend/src/scenes/authentication/auth/signupLogic.test.ts@@ -2,6 +2,7 @@ import { setPendingOAuthConnectionCookie } from 'scenes/authentication/shared/peimport { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { HttpResponse } from 'msw'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -375,18 +376,63 @@ describe('signupLogic — name handling', () => {expect(logic.values.panel).toBe(2)})- it('sends a password API error back to the password step and lets the next submit through', async () => {+ it.each([+ ['a password signup', false],+ ['a passkey signup', true],+ ])(+ 'sends a password API error on %s back to the password step and lets the next submit through',+ async (_name, withPasskey) => {+ useMocks({+ post: {+ '/api/signup/': () => [+ 400,+ {+ type: 'validation_error',+ code: 'password_too_weak',+ detail: 'Add another word or two. Uncommon words are better.',+ attr: 'password',+ },+ ],+ },+ })+ await advanceToOnboardingPanel()+ if (withPasskey) {+ logic.actions.setPasskeyRegistered(true)+ }+ logic.actions.setSignupPanelOnboardingValues({+ name: 'John Smith',+ organization_name: 'Hogflix',+ role_at_organization: 'engineer',+ referral_source: '',+ referral_source_ai_prompt: '',+ })+ logic.actions.submitSignupPanelOnboarding()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.panel).toBe(1)+ expect(logic.values.signupPanelAuthManualErrors.password).toBe(+ 'Add another word or two. Uncommon words are better.'+ )+ expect(logic.values.signupPanelOnboardingManualErrors.generic).toBeUndefined()+ expect(logic.values.passkeyRegistered).toBe(false)++ logic.actions.setSignupPanelAuthValue('password', 'An0ther-Str0ng-Pass!')+ logic.actions.submitSignupPanelAuth()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.panel).toBe(2)+ expect(logic.values.signupPanelAuthManualErrors.password).toBeUndefined()+ }+ )++ it('shows when to retry after the signup is throttled', async () => {useMocks({post: {- '/api/signup/': () => [- 400,- {- type: 'validation_error',- code: 'password_too_weak',- detail: 'Add another word or two. Uncommon words are better.',- attr: 'password',- },- ],+ '/api/signup/': () =>+ HttpResponse.json(+ { type: 'throttled_error', code: 'throttled', detail: 'Request was throttled.', attr: null },+ { status: 429, headers: { 'Retry-After': '3600' } }+ ),},})await advanceToOnboardingPanel()@@ -397,21 +443,14 @@ describe('signupLogic — name handling', () => {referral_source: '',referral_source_ai_prompt: '',})- logic.actions.submitSignupPanelOnboarding()- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.panel).toBe(1)- expect(logic.values.signupPanelAuthManualErrors.password).toBe(- 'Add another word or two. Uncommon words are better.'- )- expect(logic.values.signupPanelOnboardingManualErrors.generic).toBeUndefined()- logic.actions.setSignupPanelAuthValue('password', 'An0ther-Str0ng-Pass!')- logic.actions.submitSignupPanelAuth()+ logic.actions.submitSignupPanelOnboarding()await expectLogic(logic).toFinishAllListeners()- expect(logic.values.panel).toBe(2)- expect(logic.values.signupPanelAuthManualErrors.password).toBeUndefined()+ expect(logic.values.signupPanelOnboardingManualErrors.generic).toMatchObject({+ code: 'throttled',+ detail: 'Too many signup attempts from your network. Try again in an hour.',+ })})it('drops a stale password error when a different email is submitted', async () => {diff --git a/frontend/src/scenes/authentication/auth/signupLogic.ts b/frontend/src/scenes/authentication/auth/signupLogic.tsindex dcbb82301667..3df33cf7a96d 100644--- a/frontend/src/scenes/authentication/auth/signupLogic.ts+++ b/frontend/src/scenes/authentication/auth/signupLogic.ts@@ -7,10 +7,11 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiError } from 'lib/api'import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'import { getReferralFollowUp } from 'lib/components/SignupReferralSource'import { CLOUD_HOSTNAMES, FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'lib/logic/preflightLogic'import { splitFullName } from 'lib/utils/strings'@@ -297,6 +298,19 @@ export function maintenanceSignupRedirectUrl(return `https://${CLOUD_HOSTNAMES[region.toUpperCase() as keyof typeof CLOUD_HOSTNAMES]}${urls.signup()}?${params}`}+function getRetryAfterSeconds(error: unknown): number | null {+ const header = error instanceof ApiError ? error.headers?.get('Retry-After') : null+ const seconds = header ? Number(header) : NaN+ return Number.isFinite(seconds) && seconds > 0 ? seconds : null+}++function throttledSignupMessage(retryAfterSeconds: number | null, googleAvailable: boolean): string {+ const retryAfter =+ retryAfterSeconds !== null ? dayjs.duration(retryAfterSeconds, 'seconds').humanize(true) : 'later'+ const googleSuggestion = googleAvailable ? ', or sign up with Google instead' : ''+ return `Too many signup attempts from your network. Try again ${retryAfter}${googleSuggestion}.`+}+export const signupLogic = kea<signupLogicType>([path(['scenes', 'authentication', 'auth', 'signupLogic']),connect(() => ({@@ -561,6 +575,10 @@ export const signupLogic = kea<signupLogicType>([// never scored can reach the server and be refused there. Send the user back to the// password step.if (error.attr === 'password') {+ // The session lost the passkey, so a submit without a password would fail the same way+ if (values.passkeyRegistered) {+ actions.setPasskeyRegistered(false)+ }actions.setSignupPanelAuthManualErrors({password: String(error.detail || 'Please choose a stronger password'),})@@ -580,10 +598,16 @@ export const signupLogic = kea<signupLogicType>([}if (error.code === 'throttled') {+ const retryAfterSeconds = getRetryAfterSeconds(e)+ posthog.capture('signup throttled', {+ retry_after_seconds: retryAfterSeconds,+ with_passkey: values.passkeyRegistered,+ })+ const googleAvailable = !!values.preflight?.available_social_auth_providers?.['google-oauth2']actions.setSignupPanelOnboardingManualErrors({generic: {code: error.code,- detail: 'Too many signup attempts. Please try again later.',+ detail: throttledSignupMessage(retryAfterSeconds, googleAvailable),},})} else {diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 6f8c81f3a95c..c7d85d9b8828 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -18,6 +18,7 @@ import structlogimport posthoganalyticsfrom rest_framework import exceptions, generics, permissions, response, serializers, statusfrom rest_framework.request import Request+from rest_framework.throttling import BaseThrottlefrom social_core.backends.base import BaseAuthfrom social_core.exceptions import AuthFailedfrom social_core.pipeline.partial import partial@@ -59,7 +60,12 @@ from posthog.models.identity_provider_config import ConfigScope, IdentityProvidefrom posthog.models.organization_invite import INVITE_DAYS_VALIDITYfrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.permissions import CanCreateOrg-from posthog.rate_limit import SignupEmailPrecheckThrottle, SignupIPThrottle, SignupResendInviteThrottle+from posthog.rate_limit import (+ SignupAttemptIPThrottle,+ SignupEmailPrecheckThrottle,+ SignupIPThrottle,+ SignupResendInviteThrottle,+)from posthog.utils import get_can_create_org, get_trusted_client_ip, is_relative_urlfrom posthog.workos_radar import RadarAction, RadarAuthMethod, evaluate_auth_attempt@@ -531,7 +537,29 @@ class SignupViewset(generics.CreateAPIView):serializer_class = SignupSerializer# Enables E2E testing of signup flowpermission_classes = (permissions.AllowAny,) if settings.E2E_TESTING else (CanCreateOrg,)- throttle_classes = [] if settings.E2E_TESTING else [SignupIPThrottle]+ throttle_classes = [] if settings.E2E_TESTING else [SignupAttemptIPThrottle, SignupIPThrottle]++ account_created = False++ def get_throttles(self) -> list[BaseThrottle]:+ # DRF builds new instances per call, and only the ones that checked this request know its reserved slot+ if not hasattr(self, "_throttles"):+ self._throttles = super().get_throttles()+ return self._throttles++ def perform_create(self, serializer: serializers.BaseSerializer) -> None:+ try:+ super().perform_create(serializer)+ finally:+ # The account commits before the verification email goes out, so a later failure still counts.+ self.account_created = getattr(serializer, "_user", None) is not None++ def handle_exception(self, exc: Exception) -> response.Response:+ if not self.account_created:+ for throttle in self.get_throttles():+ if isinstance(throttle, SignupIPThrottle):+ throttle.release()+ return super().handle_exception(exc)class InviteSignupSerializer(serializers.Serializer):diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 3248124caadb..dff7c0a22491 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -5,6 +5,7 @@ from zoneinfo import ZoneInfoimport pytestimport unittest+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest import mockfrom unittest.mock import ANY, patch@@ -1815,13 +1816,14 @@ class TestSignupAPI(APIBaseTest):@pytest.mark.skip_on_multitenancy@patch("posthog.utils.get_ip_address", return_value="192.168.1.100")def test_signup_rate_limit_by_ip(self, mock_get_ip):- """Test that signup is rate limited by IP address to 5 signups per day"""# Ensure the internal system metrics org doesn't prevent org-creationOrganization.objects.create(name="PostHog Internal Metrics", for_internal_metrics=True)-- # Clear any existing rate limit cachecache.clear()+ for i in range(3):+ failed = self.client.post("/api/signup/", {"first_name": "Failed", "email": f"failed{i}@example.com"})+ self.assertEqual(failed.status_code, status.HTTP_400_BAD_REQUEST)+for i in range(6):response = self.client.post("/api/signup/",@@ -1840,8 +1842,40 @@ class TestSignupAPI(APIBaseTest):User.objects.filter(email=f"user{i}@example.com").delete()else:self.assertEqual(- response.status_code, status.HTTP_429_TOO_MANY_REQUESTS, "6th request should be rate limited"+ response.status_code, status.HTTP_429_TOO_MANY_REQUESTS, "6th signup should be rate limited")+ self.assertIn("Retry-After", response.headers)++ @pytest.mark.skip_on_multitenancy+ @patch("posthog.utils.get_ip_address", return_value="192.168.1.100")+ def test_signup_rate_limits_failed_attempts_by_ip(self, mock_get_ip):+ Organization.objects.create(name="PostHog Internal Metrics", for_internal_metrics=True)+ cache.clear()++ def signup(i: int):+ return self.client.post(+ "/api/signup/",+ {+ "first_name": f"User{i}",+ "email": f"user{i}@example.com",+ "password": VALID_TEST_PASSWORD,+ "organization_name": f"Org{i}",+ },+ )++ with time_machine.travel(datetime(2026, 1, 1, 12, 0, 0), tick=False) as traveller:+ for i in range(10):+ failed = self.client.post("/api/signup/", {"first_name": "Failed", "email": f"failed{i}@example.com"})+ self.assertEqual(failed.status_code, status.HTTP_400_BAD_REQUEST)++ self.assertEqual(signup(0).status_code, status.HTTP_429_TOO_MANY_REQUESTS)++ traveller.shift(timedelta(hours=2))++ for i in range(5):+ self.assertEqual(signup(i).status_code, status.HTTP_201_CREATED, f"Signup {i + 1} should succeed")+ Organization.objects.filter(for_internal_metrics=False).delete()+ User.objects.filter(email=f"user{i}@example.com").delete()@pytest.mark.skip_on_multitenancydef test_signup_rate_limit_different_ips(self):diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 5581fb1c8211..558163c25772 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -3,17 +3,19 @@ import jsonimport timeimport uuidimport hashlib-from contextlib import suppress+from collections.abc import Iterator+from contextlib import contextmanager, suppressfrom datetime import timedeltafrom functools import lru_cachefrom typing import TYPE_CHECKINGfrom django.conf import settings-from django.core.cache import cache+from django.core.cache import cache, cachesfrom django.urls import resolvefrom django.utils import timezonefrom prometheus_client import Counter+from redis.exceptions import RedisErrorfrom rest_framework import exceptionsfrom rest_framework.throttling import SimpleRateThrottle, UserRateThrottlefrom statshog.defaults.django import statsd@@ -31,6 +33,7 @@ from posthog.metrics import LABEL_PATH, LABEL_ROUTE, LABEL_TEAM_IDfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.team.team import Teamfrom posthog.models.utils import hash_key_value+from posthog.redis import get_clientfrom posthog.settings.utils import get_listfrom posthog.utils import get_trusted_client_ip, patchable@@ -358,11 +361,73 @@ class SSOLoginThrottle(IPThrottle):class SignupIPThrottle(IPThrottle):"""- Rate limit signups by IP address to avoid a single IP address from creating too many accounts.+ Limit how many accounts one IP address can create.++ Like any DRF throttle, the check reserves a slot when the request arrives, so concurrent requests+ cannot all pass against the same count. The view calls `release` when a request ends without creating+ an account, because a user who retries a form that keeps failing (validation errors, challenges,+ passkey retries) would otherwise lock out their IP for a day. `SignupAttemptIPThrottle` bounds the+ failed attempts instead.++ The reservation and the release both read, change and write the cached history. A per-IP Redis lock+ serializes them, because otherwise one request's write can erase another request's reservation."""scope = "signup_ip"rate = settings.SIGNUP_IP_THROTTLE_RATE+ cache = caches["signup_throttle"]+ reserved = False++ @contextmanager+ def _history_lock(self, key: str) -> Iterator[None]:+ lock = get_client().lock(f"{key}:lock", timeout=5, blocking_timeout=5)+ try:+ acquired = lock.acquire()+ except RedisError as e:+ # Without the lock the throttle still works, with the same race as any DRF throttle.+ capture_exception(e)+ acquired = False+ try:+ yield+ finally:+ if acquired:+ with suppress(RedisError):+ lock.release()++ def allow_request(self, request: "Request", view: "APIView") -> bool:+ key = self.get_cache_key(request, view) if self.rate is not None else None+ if key is None:+ return super().allow_request(request, view)+ with self._history_lock(key):+ return super().allow_request(request, view)++ def throttle_success(self) -> bool:+ self.reserved = True+ return super().throttle_success()++ def release(self) -> None:+ if not self.reserved or self.key is None:+ return+ self.reserved = False+ try:+ _, duration = self.parse_rate(self.rate)+ with self._history_lock(self.key):+ history = self.cache.get(self.key, [])+ with suppress(ValueError):+ history.remove(self.now)+ self.cache.set(self.key, history, duration)+ except Exception as e:+ # The request is already failing, so a cache error here must not replace its original error.+ capture_exception(e)+++class SignupAttemptIPThrottle(IPThrottle):+ """+ Limit signup requests by IP address, whether they succeed or fail.+ """++ scope = "signup_attempt_ip"+ rate = settings.SIGNUP_ATTEMPT_IP_THROTTLE_RATEclass WebAuthnSignupRegistrationThrottle(IPThrottle):diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex d1baee8d4c87..2cdd0b696cbe 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -771,6 +771,13 @@ CACHES["task_artifact_preview"] = {"LOCATION": REDIS_URL,}+# The signup throttle reads its per-IP history, changes it and writes it back under a lock. A lagging+# replica would hand it a stale history, and the write-back would erase another request's reservation.+CACHES["signup_throttle"] = {+ **CACHES["default"],+ "LOCATION": REDIS_URL,+}+# Metrics dashboard tiles wait for one loader to write the variable options and hold a lock while it runs.# A replica that lags would hide the result and the lock, so another tile would run the same query again.CACHES["metrics_variable_options"] = {@@ -853,6 +860,7 @@ if TEST:CACHES["task_artifact_preview"] = CACHES["default"]CACHES["metrics_variable_options"] = CACHES["default"]CACHES["warehouse_destination_connect"] = CACHES["default"]+ CACHES["signup_throttle"] = CACHES["default"]# Cache timeout for materialized columns metadata (in seconds)MATERIALIZED_COLUMNS_CACHE_TIMEOUT: int = get_from_env("MATERIALIZED_COLUMNS_CACHE_TIMEOUT", 900, type_cast=int)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 2ceb763f232e..9efeadc0f288 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -544,9 +544,10 @@ WHITENOISE_ADD_HEADERS_FUNCTION = static_varies_origin# cache-bust can hold a stale SDK bundle after a release.WHITENOISE_MAX_AGE = get_from_env("WHITENOISE_MAX_AGE", 3600, type_cast=int)-# Per-IP signup throttle rate (see posthog.rate_limit.SignupIPThrottle). Overridable per-env so-# non-prod (e.g. dev deploy smoke-tests) can raise it without weakening the prod default.+# Per-IP signup throttle rates (see posthog.rate_limit). Overridable per-env so non-prod+# (e.g. dev deploy smoke-tests) can raise them without weakening the prod defaults.SIGNUP_IP_THROTTLE_RATE = get_from_env("SIGNUP_IP_THROTTLE_RATE", "5/day")+SIGNUP_ATTEMPT_IP_THROTTLE_RATE = get_from_env("SIGNUP_ATTEMPT_IP_THROTTLE_RATE", "10/hour")# Billing usage and spend exports stream a file from the billing service for as long as the# browser reads it, so both limits are per user (see ee.api.billing): how often an export may