: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(integrations): explain an expired oauth authorization instead of the raw error (#123176)
Tom Owers41c9350554ae
diff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.pyindex ea4272bdd039..b1ae89f7f884 100644--- a/posthog/models/integration/oauth.py+++ b/posthog/models/integration/oauth.py@@ -66,6 +66,20 @@ def _extract_oauth_error_message(res: requests.Response) -> str | None:return snippet[:300] if snippet else None+_INVALID_GRANT_MESSAGE = (+ "This authorization is no longer valid. Start the connection again and approve access without waiting in between."+)+++def _oauth_error_code(res: requests.Response) -> str | None:+ try:+ body = res.json()+ except Exception:+ return None+ code = body.get("error") if isinstance(body, dict) else None+ return code if isinstance(code, str) else None++def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturn:"""Raise a ValidationError describing a failed OAuth token exchange.@@ -73,6 +87,10 @@ def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturna useful message instead of the generic "Something went wrong" fallback that follows from abare Exception (which surfaces as a 500 with no detail)."""+ if _oauth_error_code(res) == "invalid_grant":+ # The code expired, was already exchanged, or was issued for another account or mode. The+ # provider's description can echo the code itself, so it stays in the logs.+ raise ValidationError(_INVALID_GRANT_MESSAGE)provider_error = _extract_oauth_error_message(res)if provider_error:raise ValidationError(f"{kind} OAuth failed: {provider_error}")diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.pyindex d053df2c0535..f208107f45cb 100644--- a/posthog/models/test/integration/test_oauth.py+++ b/posthog/models/test/integration/test_oauth.py@@ -267,7 +267,17 @@ class TestOauthIntegrationModel(BaseTest):},None,'{"error":"invalid_grant","error_description":"Authorization code does not exist or has expired."}',- ["invalid_grant", "Authorization code does not exist"],+ ["Start the connection again"],+ ["invalid_grant", "Authorization code"],+ ),+ (+ "json_error_body_other_code",+ 400,+ {"error": "invalid_client", "error_description": "Client authentication failed."},+ None,+ '{"error":"invalid_client","error_description":"Client authentication failed."}',+ ["invalid_client", "Client authentication failed"],+ [],),("non_json_error_body",@@ -276,12 +286,21 @@ class TestOauthIntegrationModel(BaseTest):ValueError("not json"),"<html>Bad Gateway</html>",["salesforce"],+ [],),])@patch("posthog.models.integration.oauth.requests.post")def test_oauth_token_exchange_failure_raises_validation_error(- self, _name, status_code, json_return, json_side_effect, body_text, expected_in_message, mock_post+ self,+ _name,+ status_code,+ json_return,+ json_side_effect,+ body_text,+ expected_in_message,+ unexpected_in_message,+ mock_post,):"""A failed token exchange must surface a ValidationError (→ DRF 400 with `detail`) so thefrontend toast renders something useful. Covers both well-formed JSON error bodies (where@@ -306,6 +325,8 @@ class TestOauthIntegrationModel(BaseTest):message = str(e.value).lower()for fragment in expected_in_message:assert fragment.lower() in message+ for fragment in unexpected_in_message:+ assert fragment.lower() not in message@patch("posthog.models.integration.oauth.requests.post")def test_integration_errors_if_id_cannot_be_generated(self, mock_post):