: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(paddle): say what to do when Paddle refuses the API key (#103430)
Tom Owersa7513a2535e7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.pyindex c267faa15744..8b6d346cd670 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py@@ -39,6 +39,10 @@ class PaddlePermissionError(Exception):pass+class PaddleUnreachableError(Exception):+ pass++class PaddlePaginator(JSONResponsePaginator):"""Follows ``meta.pagination.next``, gated on ``meta.pagination.has_more``.@@ -184,6 +188,11 @@ def validate_credentials(api_key: str, table_name: Optional[str] = None) -> bool)if status == 403:raise PaddlePermissionError(f"Missing permissions for {endpoint}")+ if status is None:+ # validate_via_probe reports a missing status for any transport or session failure, so+ # Paddle never judged the key. That is not the same as Paddle rejecting it, and the+ # caller has to say so rather than tell the customer to replace a working key.+ raise PaddleUnreachableError(f"No response from Paddle for {endpoint}")if not ok:return Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.pyindex 7b7ed2385b3d..87572884e9b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py@@ -1,5 +1,7 @@from typing import Optional, cast+from posthog.exceptions_capture import capture_exception+from products.warehouse_sources.backend.facade.source_config import (DataWarehouseSourceCategory,SourceConfig,@@ -21,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.paddle import (PaddlePermissionError,PaddleResumeConfig,+ PaddleUnreachableError,paddle_source,validate_credentials as validate_paddle_credentials,)@@ -30,6 +33,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.set)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Shared by the setup probe and by the sync-time error mapping below, so the same refusal reads+# the same way in the source wizard and in the sync error panel.+INVALID_API_KEY_ERROR = (+ "Your Paddle API key is invalid or has been revoked. Create a new API key in your Paddle dashboard, then reconnect."+)+MISSING_PERMISSIONS_ERROR = (+ "Paddle denied the request. Give your API key read permission for the data you want to sync, then reconnect."+)+KEY_CHECK_FAILED_ERROR = "PostHog could not check your Paddle API key. Wait a few minutes, then try again."+@SourceRegistry.registerclass PaddleSource(ResumableSource[PaddleSourceConfig, PaddleResumeConfig]):@@ -74,8 +87,8 @@ class PaddleSource(ResumableSource[PaddleSourceConfig, PaddleResumeConfig]):def get_non_retryable_errors(self) -> dict[str, str | None]:return {"400 Client Error: Bad Request for url: https://api.paddle.com": "Paddle rejected the request parameters. Please check your source configuration and incremental sync state, then try again.",- "401 Client Error: Unauthorized for url: https://api.paddle.com": "Your Paddle API key is invalid or expired. Please check your API key in Paddle and reconnect.",- "403 Client Error: Forbidden for url: https://api.paddle.com": "Your Paddle API key does not have the required permissions. Please check your API key permissions in Paddle and try again.",+ "401 Client Error: Unauthorized for url: https://api.paddle.com": INVALID_API_KEY_ERROR,+ "403 Client Error: Forbidden for url: https://api.paddle.com": MISSING_PERMISSIONS_ERROR,# 404 on a list endpoint we know exists means the resource isn't reachable for this# account — Paddle Billing isn't enabled, or the API key belongs to a different# environment (sandbox vs. production) than the data. Retrying can't change that.@@ -95,12 +108,17 @@ class PaddleSource(ResumableSource[PaddleSourceConfig, PaddleResumeConfig]):try:if validate_paddle_credentials(config.paddle_api_key, schema_name):return True, None- else:- return False, "Invalid Paddle API key"- except PaddlePermissionError as e:- return False, f"Paddle API key lacks permissions: {e}"+ return False, INVALID_API_KEY_ERROR+ except PaddlePermissionError:+ return False, MISSING_PERMISSIONS_ERROR+ except PaddleUnreachableError:+ return False, KEY_CHECK_FAILED_ERRORexcept Exception as e:- return False, str(e)+ # The probe names the endpoint it could not read, which does not help the person+ # filling in the form. Capture the exception so the detail stays available for+ # debugging, and show fixed guidance instead.+ capture_exception(e)+ return False, KEY_CHECK_FAILED_ERRORdef get_schemas(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.pyindex a512e8622191..e260c6036a3b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py@@ -8,15 +8,23 @@ from unittest import mockfrom requests import Responsefrom requests.adapters import HTTPAdapter+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.paddle import PaddleSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.paddle.paddle import (PADDLE_BASE_URL,PaddlePermissionError,PaddleResumeConfig,+ PaddleUnreachableError,_format_paddle_datetime_query_value,_get_paddle_session,paddle_source,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.source import (+ INVALID_API_KEY_ERROR,+ KEY_CHECK_FAILED_ERROR,+ MISSING_PERMISSIONS_ERROR,+ PaddleSource,+)# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -24,6 +32,7 @@ CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_importsPADDLE_SESSION_PATCH = ("products.warehouse_sources.backend.temporal.data_imports.sources.paddle.paddle.make_tracked_session")+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.paddle.source"def _response(@@ -275,9 +284,56 @@ class TestValidateCredentials:assert validate_credentials("key") is False@mock.patch(PADDLE_SESSION_PATCH)- def test_swallows_exceptions(self, mock_session) -> None:+ def test_transport_failure_is_not_a_rejected_key(self, mock_session) -> None:mock_session.return_value.get.side_effect = Exception("boom")- assert validate_credentials("key") is False+ with pytest.raises(PaddleUnreachableError):+ validate_credentials("key")+++class TestSourceValidateCredentials:+ def _validate(self) -> tuple[bool, str | None]:+ return PaddleSource().validate_credentials(PaddleSourceConfig(paddle_api_key="key"), team_id=1)++ @mock.patch(PADDLE_SESSION_PATCH)+ def test_ok(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert self._validate() == (True, None)++ @pytest.mark.parametrize(+ "status_code,expected",+ [(401, INVALID_API_KEY_ERROR), (403, MISSING_PERMISSIONS_ERROR)],+ )+ @mock.patch(PADDLE_SESSION_PATCH)+ def test_refusal_message(self, mock_session, status_code: int, expected: str) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ valid, message = self._validate()++ assert valid is False+ assert message == expected+ # The wizard shows this string and nothing else, so it has to name a next step and must+ # not carry the probed endpoint name the permission error reports.+ assert "reconnect" in message+ assert "Missing permissions" not in message++ @mock.patch(PADDLE_SESSION_PATCH)+ def test_unreachable_paddle_does_not_blame_the_key(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ valid, message = self._validate()++ # Paddle never judged the key, so telling the customer to replace it would send them+ # rotating a key that works.+ assert valid is False+ assert message == KEY_CHECK_FAILED_ERROR++ @mock.patch(f"{SOURCE_MODULE}.validate_paddle_credentials", side_effect=RuntimeError("probe blew up"))+ @mock.patch(f"{SOURCE_MODULE}.capture_exception")+ def test_unexpected_failure_is_captured_not_shown(self, mock_capture, _mock_validate) -> None:+ valid, message = self._validate()++ assert valid is False+ assert message == KEY_CHECK_FAILED_ERROR+ assert "probe blew up" not in message+ assert mock_capture.call_count == 1class TestPaddleSession: