: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(oauth): translate pgbouncer query_wait_timeout into 503 on token refresh (#60541)
posthog[bot]8a665a6277fa
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex b18ba2489674..b98f3c7366d7 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -10,6 +10,7 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom django.conf import settings+from django.db import OperationalErrorfrom django.test import override_settingsfrom django.utils import timezone@@ -1061,6 +1062,31 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(body["error"], "invalid_grant")self.assertIn("error_description", body)+ def test_token_endpoint_returns_temporarily_unavailable_on_pgbouncer_query_wait_timeout(self):+ token_data = {**self.base_token_body, "code": "does_not_matter"}++ with patch(+ "oauth2_provider.views.base.TokenView.post",+ side_effect=OperationalError("query_wait_timeout"),+ ):+ response = self.post("/oauth/token/", token_data)++ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)+ self.assertEqual(response["Retry-After"], "1")+ body = response.json()+ self.assertEqual(body["error"], "temporarily_unavailable")+ self.assertIn("error_description", body)++ def test_token_endpoint_does_not_swallow_unrelated_operational_errors(self):+ token_data = {**self.base_token_body, "code": "does_not_matter"}++ with patch(+ "oauth2_provider.views.base.TokenView.post",+ side_effect=OperationalError("something else broke"),+ ):+ with self.assertRaises(OperationalError):+ self.post("/oauth/token/", token_data)+def test_pkce_code_verifier_validation(self):response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)self.assertEqual(response.status_code, status.HTTP_200_OK)diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 78de1981f122..298600545f82 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -8,6 +8,7 @@ from urllib.parse import urlparsefrom django.conf import settingsfrom django.core.exceptions import DisallowedRedirect+from django.db import OperationalErrorfrom django.http import JsonResponsefrom django.utils import timezonefrom django.utils.decorators import method_decorator@@ -81,6 +82,23 @@ def get_region_info() -> dict | None:return None+def _temporarily_unavailable_response(retry_after_seconds: int = 1) -> JsonResponse:+ """RFC 6749 `temporarily_unavailable` response with HTTP 503 and Retry-After.++ Use for transient failures (e.g. database connection-pool saturation) so OAuth+ clients back off and retry instead of treating the request as permanently failed.+ """+ response = JsonResponse(+ {+ "error": "temporarily_unavailable",+ "error_description": "The authorization server is temporarily unable to handle the request. Please retry.",+ },+ status=503,+ )+ response["Retry-After"] = str(retry_after_seconds)+ return response++def _impersonator_id_for_request(request) -> int | None:"""Return the staff user id that should tag any OAuth token minted on behalf of this request.@@ -794,6 +812,20 @@ class OAuthTokenView(TokenView):},status=400,)+ except OperationalError as e:+ # PgBouncer kills queries that wait too long for a backend connection with+ # `query_wait_timeout`. The resulting OperationalError otherwise bubbles up+ # as an unhandled 500 — translate it into a retryable response.+ if "query_wait_timeout" not in str(e):+ raise+ logger.warning(+ "oauth_token_db_pool_pressure",+ grant_type=grant_type,+ client_id_prefix=client_id_prefix,+ redirect_uri=redirect_uri,+ error=str(e),+ )+ return _temporarily_unavailable_response()logger.info("oauth_token_response",