: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
chore(auth): assert each authenticator runs once per request (#101856)
Paul D'Ambra62e8267c2922
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex fe77d59f06c8..d06c2e381441 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -1,6 +1,7 @@import jsonimport timeimport uuid+from collections.abc import Callablefrom datetime import UTC, datetime, timedeltafrom typing import cast@@ -27,7 +28,7 @@ from django_otp.plugins.otp_static.models import StaticDevicefrom django_otp.util import random_hexfrom httpx import ASGITransport, AsyncClientfrom parameterized import parameterized-from rest_framework import status+from rest_framework import authentication, statusfrom rest_framework.exceptions import AuthenticationFailedfrom rest_framework.parsers import JSONParserfrom rest_framework.request import Request@@ -40,8 +41,10 @@ from posthog.api.email_verification import is_email_verification_disabledfrom posthog.auth import (InternalAPIUser,OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,ProjectSecretAPIKeyAuthentication,ProjectSecretAPIKeyUser,+ SessionAuthentication,TeamSecretTokenAuthentication,TeamSecretTokenUser,_extract_phs_token,@@ -2978,6 +2981,66 @@ class TestOAuthAccessTokenAuthentication(APIBaseTest):self.assertIsNone(result)+class TestAuthenticatorsRunOncePerRequest(APIBaseTest):+ def _personal_api_key_header(self) -> str:+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="once per request",+ user=self.user,+ secure_value=hash_key_value(value),+ scopes=["dashboard:read"],+ )+ return f"Bearer {value}"++ def _oauth_access_token_header(self) -> str:+ application = OAuthApplication.objects.create(+ name="Once per request",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=self.organization,+ user=self.user,+ )+ token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token="pha_once_per_request",+ expires=timezone.now() + timedelta(hours=1),+ scope="dashboard:read",+ )+ return f"Bearer {token.token}"++ @parameterized.expand(+ [+ ("session", SessionAuthentication, None),+ ("personal_api_key", PersonalAPIKeyAuthentication, _personal_api_key_header),+ ("oauth_access_token", OAuthAccessTokenAuthentication, _oauth_access_token_header),+ ]+ )+ def test_authenticate_runs_once_per_request(+ self,+ _name: str,+ authenticator_class: type[authentication.BaseAuthentication],+ authorization_header: Callable[..., str] | None,+ ) -> None:+ headers = {}+ if authorization_header is not None:+ self.client.logout()+ headers["authorization"] = authorization_header(self)++ with patch.object(+ authenticator_class,+ "authenticate",+ autospec=True,+ wraps=authenticator_class.authenticate,+ ) as authenticate:+ response = self.client.get(f"/api/projects/{self.team.pk}/dashboards/", headers=headers)++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(authenticate.call_count, 1)++class TestOAuthLoginNotification(APIBaseTest):CONFIG_AUTO_LOGIN = False