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(appsflyer): distinguish bad API token from bad app id on validation (#64223)

Tom Owersbac0e151a52f
diff --git a/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py b/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py
index 746ffce3d1ac..a0ef2c80b51b 100644
--- a/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py
+++ b/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py
@@ -30,6 +30,12 @@ class AppsFlyerRetryableError(Exception):
pass
+class AppsFlyerCredentialsError(Exception):
+ """A credential check failed for a reason we can explain to the user (bad token, bad app id)."""
+
+ pass
+
+
def _get_session(api_token: str) -> requests.Session:
return make_tracked_session(headers={"Authorization": f"Bearer {api_token}"}, redact_values=(api_token,))
@@ -79,13 +85,18 @@ def _parse_csv_rows(text: str, logger: FilteringBoundLogger | None = None) -> It
def validate_credentials(api_token: str, app_id: str) -> bool:
"""Confirm the token and app id are valid with a one-day report probe.
- Raises ``AppsFlyerRetryableError`` on rate-limit / 5xx responses and lets transport
+ Returns ``True`` when the probe succeeds. Raises ``AppsFlyerCredentialsError`` with a
+ user-facing message when AppsFlyer rejects the token or app id (the status code tells the
+ two apart), ``AppsFlyerRetryableError`` on rate-limit / 5xx responses, and lets transport
errors propagate so the caller can tell a transient failure apart from a bad credential.
"""
try:
app = _validate_app_id(app_id)
except ValueError:
- return False
+ raise AppsFlyerCredentialsError(
+ "The AppsFlyer app id looks invalid. Use your app's identifier from the dashboard "
+ "(e.g. 'id123456789' for iOS or the package name for Android)."
+ ) from None
today = datetime.now(UTC).strftime("%Y-%m-%d")
response = _get_session(api_token).get(
f"{APPSFLYER_BASE_URL}/api/agg-data/export/app/{quote(app)}/dailyreport/v5"
@@ -94,7 +105,23 @@ def validate_credentials(api_token: str, app_id: str) -> bool:
)
if response.status_code == 429 or response.status_code >= 500:
raise AppsFlyerRetryableError(f"AppsFlyer API error (retryable): status={response.status_code}")
- return response.status_code == 200
+ if response.status_code == 200:
+ return True
+ # 401 is an auth failure (bad token); 403/404 mean the token is fine but the app id or
+ # subscription is wrong — surface which one so the user isn't left guessing.
+ if response.status_code == 401:
+ raise AppsFlyerCredentialsError(
+ "AppsFlyer rejected the API token. Check that you pasted a valid API token (V2) from "
+ "your account's Security center → AppsFlyer API tokens."
+ )
+ if response.status_code == 403:
+ raise AppsFlyerCredentialsError(
+ "AppsFlyer denied access. Check that your account's subscription includes the aggregate "
+ "Pull API and that the app id is correct."
+ )
+ if response.status_code == 404:
+ raise AppsFlyerCredentialsError("AppsFlyer couldn't find an app with that app id. Please check the app id.")
+ return False
def get_rows(
diff --git a/posthog/temporal/data_imports/sources/appsflyer/source.py b/posthog/temporal/data_imports/sources/appsflyer/source.py
index ca9b3d332947..56195efca041 100644
--- a/posthog/temporal/data_imports/sources/appsflyer/source.py
+++ b/posthog/temporal/data_imports/sources/appsflyer/source.py
@@ -13,6 +13,7 @@ from posthog.schema import (
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.appsflyer.appsflyer import (
+ AppsFlyerCredentialsError,
AppsFlyerRetryableError,
appsflyer_source,
validate_credentials as validate_appsflyer_credentials,
@@ -110,6 +111,9 @@ You can find your API token (V2) in AppsFlyer under your account menu > Security
try:
if validate_appsflyer_credentials(config.api_token, config.app_id):
return True, None
+ except AppsFlyerCredentialsError as e:
+ # The token or app id was rejected — surface which one rather than a conflated message.
+ return False, str(e)
except (AppsFlyerRetryableError, requests.RequestException):
# A rate-limit, 5xx, or network blip isn't a bad credential — don't mislabel it.
return (
diff --git a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
index 95bd97a108a3..ffc12e094af5 100644
--- a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
+++ b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
@@ -8,6 +8,7 @@ from posthog.temporal.data_imports.sources.appsflyer.appsflyer import (
CHUNK_SIZE,
LOOKBACK_DAYS,
MAX_WINDOW_DAYS,
+ AppsFlyerCredentialsError,
AppsFlyerRetryableError,
_normalize_header,
_parse_csv_rows,
@@ -86,24 +87,34 @@ class TestHelpers:
class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_succeeds_on_200(self, mock_session):
+ mock_session.return_value.get.return_value = _response("", status=200)
+
+ assert validate_credentials("token", "id123") is True
+
@pytest.mark.parametrize(
- "status_code, expected",
+ "status_code, expected_substring",
[
- (200, True),
- (401, False),
- (403, False),
- (404, False),
+ # 401 means the token is bad; 403/404 mean the app id (or subscription) is the problem.
+ (401, "API token"),
+ (403, "denied access"),
+ (404, "app id"),
],
)
@mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ def test_validate_credentials_distinguishes_token_from_app_id(self, mock_session, status_code, expected_substring):
mock_session.return_value.get.return_value = _response("", status=status_code)
- assert validate_credentials("token", "id123") is expected
+ with pytest.raises(AppsFlyerCredentialsError) as exc:
+ validate_credentials("token", "id123")
+ assert expected_substring in str(exc.value)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_validate_rejects_bad_app_id_without_request(self, mock_session):
- assert validate_credentials("token", "bad app!") is False
+ with pytest.raises(AppsFlyerCredentialsError) as exc:
+ validate_credentials("token", "bad app!")
+ assert "app id" in str(exc.value)
mock_session.return_value.get.assert_not_called()
@pytest.mark.parametrize("status_code", [429, 500, 503])
diff --git a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py
index f855e0429781..56bb70461512 100644
--- a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py
+++ b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py
@@ -5,7 +5,7 @@ import requests
from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
-from posthog.temporal.data_imports.sources.appsflyer.appsflyer import AppsFlyerRetryableError
+from posthog.temporal.data_imports.sources.appsflyer.appsflyer import AppsFlyerCredentialsError, AppsFlyerRetryableError
from posthog.temporal.data_imports.sources.appsflyer.settings import ENDPOINTS, INCREMENTAL_FIELDS
from posthog.temporal.data_imports.sources.appsflyer.source import AppsFlyerSource
from posthog.temporal.data_imports.sources.generated_configs import AppsFlyerSourceConfig
@@ -121,6 +121,17 @@ class TestAppsFlyerSource:
assert error_message is not None
assert "temporary" in error_message
+ @mock.patch("posthog.temporal.data_imports.sources.appsflyer.source.validate_appsflyer_credentials")
+ def test_validate_credentials_surfaces_specific_rejection_message(self, mock_validate):
+ # A rejected token/app id raises AppsFlyerCredentialsError; its message reaches the user
+ # verbatim instead of the conflated "Invalid AppsFlyer API token or app id".
+ mock_validate.side_effect = AppsFlyerCredentialsError("AppsFlyer rejected the API token.")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "AppsFlyer rejected the API token."
+
@mock.patch("posthog.temporal.data_imports.sources.appsflyer.source.appsflyer_source")
def test_source_for_pipeline_plumbs_arguments(self, mock_af_source):
inputs = mock.MagicMock()