Skip to content

: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.

fix(amazon-ads): say which amazon ads credential check failed (#115255)

Tom Owers68dbe26dbe76
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
index f92f51360f1f..32f87b15d3af 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py
@@ -13,6 +13,7 @@ from structlog.types import FilteringBoundLogger
from tenacity import Retrying, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import (
AMAZON_ADS_ENDPOINTS,
@@ -44,6 +45,19 @@ REPORT_ROWS_PER_BATCH = 2000
# keeps a tampered `url` from pointing the download somewhere else.
REPORT_URL_HOST_SUFFIXES = (".amazonaws.com", ".amazon.com")
+INVALID_REGION_MESSAGE = (
+ "Your Amazon Ads region isn't supported. Pick North America, Europe or Far East, then reconnect."
+)
+LWA_REJECTED_MESSAGE = (
+ "Login with Amazon rejected your client ID, client secret or refresh token. "
+ "Check that all three come from the same LWA app, then reconnect."
+)
+PROFILES_DENIED_MESSAGE = (
+ "Your credentials can't read Amazon Ads profiles. "
+ "Check that your LWA app has Advertising API access and the region matches your account, then reconnect."
+)
+UNAVAILABLE_MESSAGE = "PostHog couldn't check your Amazon Ads credentials. Try again in a few minutes."
+
class AmazonAdsRetryableError(Exception):
pass
@@ -114,20 +128,39 @@ def _mint_token(session: requests.Session, client_id: str, client_secret: str, r
return response.json()["access_token"]
-def validate_credentials(region: str, client_id: str, client_secret: str, refresh_token: str) -> bool:
+def validate_credentials(
+ region: str, client_id: str, client_secret: str, refresh_token: str
+) -> tuple[bool, str | None]:
"""Confirm the LWA credentials are valid by minting a token and listing profiles."""
try:
- _base_url(region)
- session = _get_session(client_secret, refresh_token, client_id)
+ base_url = _base_url(region)
+ except ValueError:
+ return False, INVALID_REGION_MESSAGE
+
+ session = _get_session(client_secret, refresh_token, client_id)
+ try:
token = _mint_token(session, client_id, client_secret, refresh_token)
response = session.get(
- f"{_base_url(region)}/v2/profiles",
+ f"{base_url}/v2/profiles",
headers={"Authorization": f"Bearer {token}"},
timeout=15,
)
- return response.status_code == 200
- except Exception:
- return False
+ except requests.HTTPError as e:
+ # Only the token exchange raises an HTTPError here; a 4xx means LWA refused the credentials.
+ if e.response is not None and 400 <= e.response.status_code < 500:
+ return False, LWA_REJECTED_MESSAGE
+ return False, UNAVAILABLE_MESSAGE
+ except requests.RequestException:
+ return False, UNAVAILABLE_MESSAGE
+ except Exception as e:
+ capture_exception(e)
+ return False, UNAVAILABLE_MESSAGE
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, PROFILES_DENIED_MESSAGE
+ return False, UNAVAILABLE_MESSAGE
def as_report_date(value: Any) -> Optional[dt.date]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py
index e64a3bada5ed..8c53248024b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py
@@ -147,10 +147,9 @@ You need a Login with Amazon (LWA) application with Advertising API access: ente
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- if validate_amazon_ads_credentials(config.region, config.client_id, config.client_secret, config.refresh_token):
- return True, None
-
- return False, "Invalid Amazon Ads credentials"
+ return validate_amazon_ads_credentials(
+ config.region, config.client_id, config.client_secret, config.refresh_token
+ )
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AmazonAdsResumeConfig]:
return ResumableSourceManager[AmazonAdsResumeConfig](inputs, AmazonAdsResumeConfig)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
index 50ded310ef29..7b431322df03 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
@@ -11,8 +11,12 @@ from unittest import mock
import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.amazon_ads import (
+ INVALID_REGION_MESSAGE,
+ LWA_REJECTED_MESSAGE,
LWA_TOKEN_URL,
+ PROFILES_DENIED_MESSAGE,
REPORT_POLL_MAX_ATTEMPTS,
+ UNAVAILABLE_MESSAGE,
AmazonAdsReportError,
AmazonAdsResumeConfig,
AmazonAdsRetryableError,
@@ -100,34 +104,43 @@ class TestBaseUrl:
_base_url("evil")
-class TestValidateCredentials:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_valid_when_token_mints_and_profiles_list(self, mock_session):
- mock_session.return_value.post.return_value = _token_response()
- mock_session.return_value.get.return_value = _json_response([{"profileId": 1}])
+def _status_response(status_code: int) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ return resp
- assert validate_credentials("na", "cid", "sec", "rt") is True
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_invalid_when_token_mint_fails(self, mock_session):
- resp = mock.MagicMock()
- resp.raise_for_status.side_effect = requests.HTTPError("400 Client Error", response=mock.MagicMock())
- mock_session.return_value.post.return_value = resp
+def _failed_token_response(status_code: int) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.raise_for_status.side_effect = requests.HTTPError(response=_status_response(status_code))
+ return resp
- assert validate_credentials("na", "cid", "sec", "rt") is False
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "token_response, profiles_response, expected",
+ [
+ (_token_response(), _json_response([{"profileId": 1}]), (True, None)),
+ (_failed_token_response(400), None, (False, LWA_REJECTED_MESSAGE)),
+ (_failed_token_response(503), None, (False, UNAVAILABLE_MESSAGE)),
+ (_token_response(), _status_response(403), (False, PROFILES_DENIED_MESSAGE)),
+ (_token_response(), _status_response(500), (False, UNAVAILABLE_MESSAGE)),
+ (requests.ConnectionError(), None, (False, UNAVAILABLE_MESSAGE)),
+ ],
+ )
@mock.patch(f"{_MODULE}.make_tracked_session")
- def test_invalid_when_profiles_forbidden(self, mock_session):
- mock_session.return_value.post.return_value = _token_response()
- forbidden = mock.MagicMock()
- forbidden.status_code = 403
- mock_session.return_value.get.return_value = forbidden
+ def test_validate_credentials_outcomes(self, mock_session, token_response, profiles_response, expected):
+ if isinstance(token_response, Exception):
+ mock_session.return_value.post.side_effect = token_response
+ else:
+ mock_session.return_value.post.return_value = token_response
+ mock_session.return_value.get.return_value = profiles_response
- assert validate_credentials("na", "cid", "sec", "rt") is False
+ assert validate_credentials("na", "cid", "sec", "rt") == expected
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_invalid_region_rejected_without_request(self, mock_session):
- assert validate_credentials("evil", "cid", "sec", "rt") is False
+ assert validate_credentials("evil", "cid", "sec", "rt") == (False, INVALID_REGION_MESSAGE)
mock_session.return_value.post.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py
deleted file mode 100644
index f6839d9d0f99..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import pytest
-from unittest import mock
-
-from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.source import AmazonAdsSource
-from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amazonads import (
- AmazonAdsSourceConfig,
-)
-
-
-class TestAmazonAdsSource:
- def setup_method(self):
- self.source = AmazonAdsSource()
- self.team_id = 123
- self.config = AmazonAdsSourceConfig(region="na", client_id="cid", client_secret="sec", refresh_token="rt")
-
- @pytest.mark.parametrize(
- "mock_return, expected_valid, expected_message",
- [
- (True, True, None),
- (False, False, "Invalid Amazon Ads credentials"),
- ],
- )
- @mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.source.validate_amazon_ads_credentials"
- )
- def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
- mock_validate.return_value = mock_return
-
- is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
-
- assert is_valid is expected_valid
- assert error_message == expected_message
- mock_validate.assert_called_once_with("na", "cid", "sec", "rt")