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): show appsflyer's rejection reason during setup (#108688)

posthog[bot]a0bfff783d82
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py
index 991fce7956df..47a4785c0747 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py
@@ -52,6 +52,9 @@ MAX_RETRY_ATTEMPTS = 5
CHUNK_SIZE = 5000
# Pull the report CSV off the wire in 64 KiB reads.
REPORT_CHUNK_BYTES = 1 << 16
+# Keep AppsFlyer's rejection reason short enough to read in a setup error.
+MAX_REJECTION_REASON_CHARS = 300
+_HTML_MARKUP = re.compile(r"<\s*(!doctype|html|head|body)\b", re.IGNORECASE)
@frozen
@@ -100,7 +103,13 @@ class AppsFlyerCredentialsError(Exception):
pass
+def _normalize_token(api_token: str) -> str:
+ # A token copied out of a curl command or an Authorization header often keeps its "Bearer " prefix.
+ return re.sub(r"^bearer\s+", "", api_token.strip(), flags=re.IGNORECASE)
+
+
def _get_session(api_token: str) -> requests.Session:
+ api_token = _normalize_token(api_token)
# the v5 docs are a bit ambiguous about whether the return format defaults to CSV
# or JSON, so we explicitly request CSV for safety.
return make_tracked_session(
@@ -113,9 +122,26 @@ def _validate_app_id(app_id: str) -> str:
app_id = app_id.strip()
if not re.fullmatch(r"[a-zA-Z0-9._-]+", app_id):
raise ValueError(f"Invalid AppsFlyer app id: {app_id}")
+ # AppsFlyer names iOS apps "id<App Store number>", but users often paste the bare number.
+ # An Android package name always contains a letter, so a digits-only id is always iOS.
+ if app_id.isdecimal():
+ return f"id{app_id}"
return app_id
+def _rejection_reason(response: requests.Response, api_token: str) -> str | None:
+ """Return AppsFlyer's own reason for a rejected request, or None when the body has no plain text."""
+ reason = " ".join(response.text.split())
+ if not reason or reason.startswith("<") or _HTML_MARKUP.search(reason):
+ return None
+ return reason.replace(_normalize_token(api_token), "[redacted]")[:MAX_REJECTION_REASON_CHARS]
+
+
+def _credentials_error(message: str, response: requests.Response, api_token: str) -> AppsFlyerCredentialsError:
+ reason = _rejection_reason(response, api_token)
+ return AppsFlyerCredentialsError(f"{message} AppsFlyer said: {reason}" if reason else message)
+
+
def _normalize_header(header: str) -> str:
"""CSV headers like 'Media Source (pid)' become stable snake_case columns."""
return re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()
@@ -284,25 +310,34 @@ def validate_credentials(api_token: str, app_id: str) -> bool:
raise AppsFlyerRetryableError(f"AppsFlyer API error (retryable): status={response.status_code}")
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.
+ # 401 is an auth failure (bad token); 403 means the token can't reach this app; 404 means
+ # the app id is wrong. Surface which one so the user isn't left guessing.
if response.status_code == 401:
- raise AppsFlyerCredentialsError(
+ raise _credentials_error(
"AppsFlyer rejected the API token. Check that you pasted a valid API token (V2) from "
- "your account's Security center → AppsFlyer API tokens."
+ "your account's Security center → AppsFlyer API tokens.",
+ response,
+ api_token,
)
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."
+ raise _credentials_error(
+ "AppsFlyer denied access to this app. Check that the API token (V2) belongs to an admin or to "
+ "a user with access to this app, that the app id matches the dashboard (e.g. 'id123456789' for "
+ "iOS), and that your AppsFlyer plan includes the aggregate Pull API.",
+ response,
+ api_token,
)
if response.status_code == 404:
- raise AppsFlyerCredentialsError("AppsFlyer couldn't find an app with that app id. Please check the app id.")
+ raise _credentials_error(
+ "AppsFlyer couldn't find an app with that app id. Please check the app id.", response, api_token
+ )
# Any other status is unexpected (e.g. a 400 from a malformed request) — surface the real
# code rather than blaming the token or app id, which sends users debugging the wrong thing.
- raise AppsFlyerCredentialsError(
+ raise _credentials_error(
f"AppsFlyer returned an unexpected response (HTTP {response.status_code}) while validating credentials. "
- "If your app id and API token (V2) look correct, please try again shortly or contact support."
+ "If your app id and API token (V2) look correct, please try again shortly or contact support.",
+ response,
+ api_token,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
index 6350c8094de4..90cc099a039f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
@@ -134,6 +134,35 @@ class TestValidateCredentials:
validate_credentials("token", "id123")
assert expected_substring in str(exc.value)
+ @pytest.mark.parametrize(
+ "body, expected_reason",
+ [
+ ("Pull API is not enabled\nfor this account", "AppsFlyer said: Pull API is not enabled for this account"),
+ ("token secret-token is not allowed", "AppsFlyer said: token [redacted] is not allowed"),
+ ("<html><body>Forbidden</body></html>", None),
+ ("Forbidden: <!DOCTYPE html><html><body>Denied</body></html>", None),
+ ],
+ )
+ def test_validate_credentials_surfaces_appsflyer_reason(self, body: str, expected_reason: str | None) -> None:
+ with scripted_network([ScriptedResponse(status=403, body=body.encode())]):
+ with pytest.raises(AppsFlyerCredentialsError) as exc:
+ validate_credentials("Bearer secret-token", "id123")
+ message = str(exc.value)
+ if expected_reason is None:
+ assert "AppsFlyer said" not in message
+ else:
+ assert message.endswith(expected_reason)
+ assert "secret-token" not in message
+
+ @pytest.mark.parametrize("api_token", [" token ", "Bearer token", "bearer token"])
+ def test_validate_credentials_sends_a_clean_token_and_ios_app_id(self, api_token: str) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ validate_credentials(api_token, "123456789")
+
+ request = network.requests_log[0]
+ assert request.headers["authorization"] == "Bearer token"
+ assert "/app/id123456789/" in request.path
+
def test_validate_rejects_bad_app_id_without_request(self) -> None:
with scripted_network([]) as network:
with pytest.raises(AppsFlyerCredentialsError) as exc: