: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(api): identify the personal API key consistently when throttling (#93790)
Tom Piccirello89759e51d196
diff --git a/posthog/auth.py b/posthog/auth.pyindex bc82feac529a..6ef58e3e32c5 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -199,6 +199,9 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):keyword = "Bearer"personal_api_key: PersonalAPIKeypersonal_api_key_source: Optional[str] = None+ # Set once the key is validated, so rate limiting can identify the key without re-reading the+ # request body. See `hashed_personal_api_key_for_throttling` in posthog/rate_limit.py.+ personal_api_key_hash: Optional[str] = None# Normalized source identifiers returned by find_key_with_sourceSOURCE_HEADER = "header"@@ -306,7 +309,7 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):if not personal_api_key_with_source:return None- _, source = personal_api_key_with_source+ key_value, source = personal_api_key_with_sourcespan.set_attribute("auth.source", source)personal_api_key_object = self.validate_key(personal_api_key_with_source)@@ -338,6 +341,7 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):self.personal_api_key = personal_api_key_objectself.personal_api_key_source = source+ self.personal_api_key_hash = hash_key_value(key_value)return personal_api_key_object.user, Nonediff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex c603c3ab409f..61044676e03c 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -143,6 +143,28 @@ def get_route_from_path(path: str | None) -> str:return path_by_org_pattern.sub("/api/organizations/ORG_ID/", route_id)+def hashed_personal_api_key_for_throttling(request: "Request") -> str | None:+ """+ Return a hash of the personal API key that authenticated this request, or None.++ The authenticator comes first because it holds the key that actually passed validation.+ Scraping the request instead would trust whichever candidate `find_key_with_source` reaches+ first, and that is not always the one that authenticated: the search stops at the header, then+ the body, then the query string, so a request carrying a real key in its body never validates+ the query string. Bucketing on an unvalidated value lets a caller pick its own bucket.++ The scrape stays as a fallback for requests no personal-key authenticator handled. It gets an+ empty body on purpose, because reading `request.data` here consumes the stream and leaves+ `request.body` unreadable for downstream signature verification.+ """+ key_hash = getattr(getattr(request, "successful_authenticator", None), "personal_api_key_hash", None)+ if isinstance(key_hash, str):+ return key_hash++ key_with_source = PersonalAPIKeyAuthentication.find_key_with_source(request, request_data={})+ return hash_key_value(key_with_source[0]) if key_with_source is not None else None++class PersonalApiKeyRateThrottle(SimpleRateThrottle):@staticmethoddef safely_get_team_id_from_view(view):@@ -191,8 +213,8 @@ class PersonalApiKeyRateThrottle(SimpleRateThrottle):if not is_rate_limit_enabled(round(time.time() / 60)):return True- personal_api_key = PersonalAPIKeyAuthentication.find_key_with_source(request, request_data={})- if personal_api_key_only and request.user.is_authenticated and personal_api_key is None:+ hashed_personal_api_key = hashed_personal_api_key_for_throttling(request)+ if personal_api_key_only and request.user.is_authenticated and hashed_personal_api_key is None:return Truetry:@@ -229,7 +251,7 @@ class PersonalApiKeyRateThrottle(SimpleRateThrottle):"scope": scope,"rate": rate,"route": route,- "hashed_personal_api_key": hash_key_value(personal_api_key[0]) if personal_api_key else None,+ "hashed_personal_api_key": hashed_personal_api_key,},)RATE_LIMIT_EXCEEDED_COUNTER.labels(team_id=team_id, scope=scope, path=route, route=route).inc()@@ -256,10 +278,8 @@ class PersonalApiKeyRateThrottle(SimpleRateThrottle):"""ident = Noneif request.user.is_authenticated:- api_key = PersonalAPIKeyAuthentication.find_key_with_source(request, request_data={})- if api_key is not None:- ident = hash_key_value(api_key[0])- else:+ ident = hashed_personal_api_key_for_throttling(request)+ if ident is None:try:team_id = self.safely_get_team_id_from_view(view)if team_id:@@ -550,8 +570,7 @@ class _UserBucketRateThrottle(PersonalApiKeyOrUserRateThrottle):def get_cache_key(self, request: "Request", view: "APIView") -> str:if request.user.is_authenticated:- api_key = PersonalAPIKeyAuthentication.find_key_with_source(request, request_data={})- ident = hash_key_value(api_key[0]) if api_key is not None else request.user.pk+ ident = hashed_personal_api_key_for_throttling(request) or request.user.pkelse:ident = self.get_ident(request)return self.cache_format % {"scope": self.scope, "ident": ident}diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.pyindex b55991303c49..6a25a2cc09c2 100644--- a/posthog/test/test_rate_limit.py+++ b/posthog/test/test_rate_limit.py@@ -163,6 +163,78 @@ class TestUserAPI(APIBaseTest):},)+ @parameterized.expand(+ [+ ("body",),+ ("query_string",),+ ]+ )+ @patch("posthog.rate_limit.BurstRateThrottle.rate", new="5/minute")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_burst_rate_limit_applies_to_every_personal_api_key_source(self, source, rate_limit_enabled_mock):+ # The client is logged in by default, and a session would authenticate the request on its own,+ # hiding whether the personal API key was picked up at all.+ self.client.logout()++ url = f"/api/projects/{self.team.pk}/feature_flags/"+ body: dict = {}+ if source == "body":+ body["personal_api_key"] = self.personal_api_key+ else:+ url = f"{url}?personal_api_key={quote(self.personal_api_key)}"++ for _ in range(5):+ response = self.client.post(url, body, format="json")+ # The body omits the required fields, so the endpoint rejects it. What matters is that+ # the request reached the endpoint, which means it authenticated and was not throttled.+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)++ response = self.client.post(url, body, format="json")+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS, response.content)++ @patch("posthog.rate_limit.BurstRateThrottle.rate", new="5/minute")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_burst_rate_limit_shares_one_bucket_across_key_sources(self, rate_limit_enabled_mock):+ # One key gets one budget. If each source got its own bucket, alternating between them+ # would multiply what a single key is allowed.+ self.client.logout()++ url = f"/api/projects/{self.team.pk}/feature_flags/"+ requests = [+ lambda: self.client.post(url, {"personal_api_key": self.personal_api_key}, format="json"),+ lambda: self.client.post(url, {}, headers={"authorization": f"Bearer {self.personal_api_key}"}),+ ]++ for index in range(5):+ response = requests[index % 2]()+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)++ response = requests[1]()+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS, response.content)++ @patch("posthog.rate_limit.BurstRateThrottle.rate", new="5/minute")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_burst_rate_limit_ignores_an_unvalidated_query_string_key(self, rate_limit_enabled_mock):+ # Authentication reads the header, then the body, then the query string, and stops at the+ # first hit. A request that authenticates on its body key never validates the query string,+ # so bucketing on that value would let a caller mint a fresh budget on every request.+ self.client.logout()++ for index in range(5):+ response = self.client.post(+ f"/api/projects/{self.team.pk}/feature_flags/?personal_api_key=junk-{index}",+ {"personal_api_key": self.personal_api_key},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)++ response = self.client.post(+ f"/api/projects/{self.team.pk}/feature_flags/?personal_api_key=junk-5",+ {"personal_api_key": self.personal_api_key},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS, response.content)+@patch("posthog.rate_limit.SustainedRateThrottle.rate", new="5/hour")@patch("posthog.rate_limit.statsd.incr")@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)