: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(auth): rate limit SSO login starts (#101627)
Reece Jonesa08394d66939
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex ef2b08327f10..792cc12011b0 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -12,6 +12,7 @@ from unittest.mock import MagicMock, patchfrom django.conf import settingsfrom django.core import mail+from django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.http import HttpResponsefrom django.shortcuts import redirect@@ -689,6 +690,19 @@ class TestEEAuthenticationAPI(APILicensedTest):second_key = self.client.session.session_keyself.assertNotEqual(first_key, second_key)+ def test_sso_login_is_throttled_per_ip(self):+ cache.delete("throttle_sso_login_192.0.2.1")+ self.addCleanup(cache.delete, "throttle_sso_login_192.0.2.1")++ for _ in range(10):+ response = self.client.get("/login/unknown-provider/", HTTP_X_FORWARDED_FOR="192.0.2.1")+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)++ response = self.client.get("/login/unknown-provider/", HTTP_X_FORWARDED_FOR="192.0.2.1")++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response["Retry-After"], "60")+@patch("social_core.backends.base.BaseAuth.request")def test_google_login_returns_to_saved_insight(self, mock_request):UserSocialAuth.objects.create(user=self.user, provider="google-oauth2", uid="google-sub-123")diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex eb69d3d0bb2c..d79faa6d41ea 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -1,5 +1,6 @@import reimport json+import mathimport timeimport randomimport datetime@@ -38,6 +39,7 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import APIExceptionfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.views import APIViewfrom social_core.exceptions import AuthConnectionError, AuthFailed, AuthMissingParameterfrom social_django.strategy import DjangoStrategyfrom social_django.views import auth@@ -76,6 +78,7 @@ from posthog.rate_limit import (CodeBasedVerificationResendThrottle,CodeBasedVerificationThrottle,LoginPrecheckThrottle,+ SSOLoginThrottle,TwoFactorThrottle,UserPasswordResetThrottle,)@@ -146,6 +149,14 @@ def axes_locked_out(*args, **kwargs):def sso_login(request: HttpRequest, backend: str) -> HttpResponse:+ sso_login_throttle = SSOLoginThrottle()+ if not sso_login_throttle.allow_request(cast(Request, request), view=cast(APIView, None)):+ response = HttpResponse("Too many requests. Please try again later.", status=429)+ wait = sso_login_throttle.wait()+ if wait is not None:+ response["Retry-After"] = str(math.ceil(wait))+ return response+sso_providers = get_instance_available_sso_providers()# because SAML is configured at the domain-level, we have to assume it's enabled for someone in the instancesso_providers["saml"] = settings.EE_AVAILABLEdiff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 3c270b573eaf..a3d8a973cc3a 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -349,6 +349,13 @@ class IPThrottle(SimpleRateThrottle):return self.cache_format % {"scope": self.scope, "ident": ip}+class SSOLoginThrottle(IPThrottle):+ """Limit SSO login flow starts from one source IP."""++ scope = "sso_login"+ rate = "10/minute"++class SignupIPThrottle(IPThrottle):"""Rate limit signups by IP address to avoid a single IP address from creating too many accounts.