: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(apple-search-ads): replace the raw token exchange error with a clear message (#111728)
Tom Owersd8261cd57dc0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.pyindex 31c7aed81f49..858465ee4c65 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py@@ -12,6 +12,7 @@ from structlog.types import FilteringBoundLoggerfrom urllib3.util.retry import Retryfrom posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exceptionfrom products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (APPLE_ADS_API_VERSION_V1,@@ -69,6 +70,20 @@ class AppleSearchAdsAuthError(Exception):pass+def token_exchange_error_message(error: requests.RequestException) -> str:+ """Setup-form text for a token exchange that raised, without Apple's raw URL and status."""+ response = error.response+ # Apple answers a client secret it can't verify with `invalid_client`, which only says one of+ # the four values is wrong or they come from different API users.+ if response is not None and 400 <= response.status_code < 500 and response.status_code != 429:+ return (+ "Apple rejected these API credentials. Check that the client ID, team ID, key ID, and "+ "private key all belong to the same Apple Ads API user, then reconnect."+ )+ capture_exception(error)+ return "PostHog couldn't reach Apple to check these credentials. Wait a few minutes, then connect again."++@dataclasses.dataclass(frozen=True)class AppleSearchAdsCredentials:client_id: str@@ -311,7 +326,7 @@ def validate_credentials(except AppleSearchAdsAuthError as e:return False, str(e)except requests.RequestException as e:- return False, f"Could not exchange the Apple Ads credentials for an access token: {e}"+ return False, token_exchange_error_message(e)# Checked after the token exchange so a bad key pair is reported as such, and so the# message can name the ids this API client can actually read.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.pyindex 6731a41233cb..fc96d4720b84 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.apple_searAppleSearchAdsResumeConfig,apple_search_ads_source,readable_ad_accounts,+ token_exchange_error_message,validate_credentials as validate_apple_search_ads_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (@@ -291,9 +292,7 @@ Reporting tables use daily granularity, which Apple serves for the last 90 daysexcept AppleSearchAdsAuthError as e:raise IntegrationAccountListingError(str(e)) from eexcept requests.RequestException as e:- raise IntegrationAccountListingError(- f"Could not exchange the Apple Ads credentials for an access token: {e}"- ) from e+ raise IntegrationAccountListingError(token_exchange_error_message(e)) from e# None means the ACL lookup itself failed. The picker has no better answer than an empty# list either way, and its field stays free text, so the user can still type an id.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.pyindex 279f0a29979a..d9bedb6bf480 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py@@ -108,7 +108,7 @@ class _FakeResponse:def raise_for_status(self) -> None:if not self.ok:kind = "Client Error" if self.status_code < 500 else "Server Error"- raise HTTPError(f"{self.status_code} {kind}: for url: {self.url}", response=cast(Any, None))+ raise HTTPError(f"{self.status_code} {kind}: for url: {self.url}", response=cast(Any, self))def _token_response(token: str = "access-token") -> _FakeResponse:@@ -1022,14 +1022,24 @@ class TestValidateCredentials:assert message is not None and "private key" in messageassert session.calls == []- def test_a_token_endpoint_rejection_is_reported(self) -> None:- session = _FakeSession([], token_responses=[_FakeResponse(400, url=APPLE_OAUTH_TOKEN_URL)])+ @parameterized.expand(+ [+ ("rejected_credentials", 400, "Apple rejected these API credentials"),+ ("apple_unavailable", 503, "couldn't reach Apple"),+ ("still_rate_limited", 429, "couldn't reach Apple"),+ ]+ )+ def test_a_token_endpoint_failure_is_reported_without_the_raw_http_error(+ self, _name: str, status: int, expected: str+ ) -> None:+ session = _FakeSession([], token_responses=[_FakeResponse(status, url=APPLE_OAUTH_TOKEN_URL)])with mock.patch(SESSION_PATCH, return_value=session):is_valid, message = validate_credentials(CREDENTIALS, V5)assert is_valid is False- assert message is not None+ assert message is not None and expected in message+ assert APPLE_OAUTH_TOKEN_URL not in messagedef test_a_token_response_without_an_access_token_is_reported(self) -> None:session = _FakeSession([], token_responses=[_FakeResponse(200, {}, url=APPLE_OAUTH_TOKEN_URL)])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.pyindex e0f0d8aea71a..9cafca86706a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py@@ -258,7 +258,7 @@ class TestAppleSearchAdsSource:("apple being unreachable",requests.ConnectionError("connection refused"),- "Could not exchange the Apple Ads credentials for an access token",+ "couldn't reach Apple",),])