: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(custom): say which OAuth2 credential a provider rejected (#95570)
Tom Owers744e357ab1cf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.pyindex da4c7e65f707..4cb9ca85c27d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py@@ -1032,17 +1032,8 @@ class CustomSource(SimpleSource[CustomSourceConfig]):except CustomOAuth2Integration.DoesNotExist:return False, OAUTH2_CREDENTIALS_GONE_MESSAGEexcept OAuth2AuthRequestError as exc:- auth_config = manifest.get("client", {}).get("auth", {})- injected_secrets = tuple(- str(auth_config[key])- for key in ("client_secret", "refresh_token", "access_token")- if auth_config.get(key)- )if exc.is_permanent:- return False, _redact_secrets(- f"The OAuth2 token endpoint rejected the request: {strip_oauth2_permanent_marker(str(exc))}",- injected_secrets,- )+ return False, _oauth2_token_error_message(exc)# Transient (429 / 5xx): don't block creation — the first real sync retries the mint.return True, None@@ -1065,10 +1056,10 @@ class CustomSource(SimpleSource[CustomSourceConfig]):return False, f"Invalid auth configuration: {exc}"# OAuth2 mints its access token lazily on the first request, so pre-mint it now —- # a bad client_secret / token_url then fails with a pointed "the OAuth2 token- # endpoint rejected the request: …" instead of a misleading "resource unreachable"- # on the first data probe. Minting before the probe session is built also lets the- # freshly-minted access token join that session's redaction set. A transient+ # a bad client_secret / token_url then fails with a pointed credential message instead+ # of a misleading "resource unreachable" on the first data probe. Minting before the+ # probe session is built also lets the freshly-minted access token join that session's+ # redaction set. A transient# (429 / 5xx) token error must not block creation — the first real sync retries —# so only a permanent error (invalid_client / invalid_grant / other 4xx) is surfaced.#@@ -1085,11 +1076,7 @@ class CustomSource(SimpleSource[CustomSourceConfig]):probe_auth._obtain_token(timeout=(PROBE_CONNECT_TIMEOUT, PROBE_READ_TIMEOUT))except OAuth2AuthRequestError as exc:if exc.is_permanent:- # Strip the internal sync-time classifier marker — it's not user-facing copy.- return False, _redact_secrets(- f"The OAuth2 token endpoint rejected the request: {strip_oauth2_permanent_marker(str(exc))}",- auth_secret_values(probe_auth),- )+ return False, _oauth2_token_error_message(exc)# Transient (429 / 5xx): don't block creation — the first real sync retries the# token exchange. Skip the data probe too: it has no minted token to authenticate# with, so requests would re-invoke the auth (re-running the failing mint) and turn@@ -1723,6 +1710,44 @@ OAUTH2_CREDENTIALS_GONE_MESSAGE = ()+# A permanent token rejection carries the provider's own wording — an HTTP status, the OAuth2+# error code, and a vendor description. None of that tells someone which field to change, so the+# standard codes are mapped to the field they point at and everything else falls back to the whole+# credential set. The raw text stays on the exception for the sync-time classifier.+_OAUTH2_TOKEN_ERROR_MESSAGES: dict[str, str] = {+ "invalid_client": (+ "Your provider rejected the OAuth2 client ID or secret. "+ "Check both values in your provider's app settings, then try again."+ ),+ "invalid_grant": (+ "Your provider rejected the OAuth2 grant for this source. "+ "Issue a new refresh token, or reconnect the source, then try again."+ ),+ "unauthorized_client": (+ "Your provider does not let this OAuth2 app use the configured grant type. "+ "Enable that grant type for the app, then try again."+ ),+ "invalid_scope": (+ "Your provider rejected the OAuth2 scopes for this source. "+ "Check the scopes match the ones your provider's app allows, then try again."+ ),+ "invalid_request": (+ "Your provider rejected the OAuth2 token request. "+ "Check the token URL, grant type, and any extra token parameters, then try again."+ ),+}++_OAUTH2_TOKEN_ERROR_FALLBACK = (+ "Your provider rejected the OAuth2 credentials for this source. "+ "Check the client ID, secret, token URL, and grant type, then try again."+)+++def _oauth2_token_error_message(exc: OAuth2AuthRequestError) -> str:+ """User-facing copy for a permanent token-endpoint rejection."""+ return _OAUTH2_TOKEN_ERROR_MESSAGES.get(exc.error_code or "", _OAUTH2_TOKEN_ERROR_FALLBACK)++def _oauth2_row_config(auth: dict[str, Any]) -> dict[str, Any]:"""The non-secret OAuth2 client config a manifest declares, in row-`config` shape.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.pyindex f7251d26a9e8..3c9f9315a542 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py@@ -1092,24 +1092,29 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):assert ok, errassert err is None- @patch.object(- OAuth2Auth,- "_obtain_token",- side_effect=OAuth2AuthRequestError(- "HTTP 401 from the OAuth2 token endpoint: invalid_client: bad creds",- error_code="invalid_client",- is_permanent=True,- ),+ @parameterized.expand(+ [+ ("invalid_client", "client ID or secret"),+ ("invalid_scope", "scopes"),+ ("some_provider_code", "client ID, secret, token URL"),+ (None, "client ID, secret, token URL"),+ ])- def test_oauth2_probe_permanent_token_error_blocks_with_clear_message(self, _mock_mint):- # A bad client_secret / token_url must fail at create time with a pointed token-endpoint- # message — not the generic "resource unreachable" of the data probe.+ def test_oauth2_probe_permanent_token_error_blocks_with_clear_message(self, error_code, expected_fragment):+ # A bad client_secret / token_url must fail at create time with copy that names the field+ # to change — not the provider's raw status-and-code text, and not the generic "resource+ # unreachable" of the data probe. An unmapped or absent code falls back to the whole+ # credential set.+ mint_error = OAuth2AuthRequestError("raw provider text", error_code=error_code, is_permanent=True)source = CustomSource()config = CustomSourceConfig(manifest_json=json.dumps(_oauth2_manifest()), auth_oauth2_client_secret="cs")- ok, err = source.validate_credentials(config, team_id=999)++ with patch.object(OAuth2Auth, "_obtain_token", side_effect=mint_error):+ ok, err = source.validate_credentials(config, team_id=999)+assert not ok- assert "OAuth2 token endpoint rejected" in (err or "")- assert "invalid_client" in (err or "")+ assert expected_fragment in (err or "")+ assert "raw provider text" not in (err or "")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")@patch.object(