: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(warehouse-sources): Apple Ads ad account lookup message leads with the accounts it found (#103472)
jake sciotto188ccc2029d6
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 cb8bf1aa4456..7830acdcbcab 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@@ -146,10 +146,7 @@ def missing_context_id(credentials: AppleSearchAdsCredentials, api_version: str)"""Message naming the context id this version needs, when the form did not collect it."""if api_version == APPLE_ADS_API_VERSION_V1:if not credentials.ad_account_id:- return (- "Enter the ad account ID. The Apple Ads Platform API scopes every request to an "- "ad account, which is not the same as the organization ID the older API used."- )+ return "Enter the ad account ID."return Noneif not credentials.org_id:return "Enter the organization ID. The Apple Search Ads API scopes every request to an organization."@@ -308,7 +305,9 @@ def validate_credentials(# message can name the ids this API client can actually read.missing = missing_context_id(credentials, api_version)if missing is not None:- return False, missing + _readable_ad_accounts(client, api_version)+ if api_version == APPLE_ADS_API_VERSION_V1:+ return False, _blank_ad_account_message(_readable_ad_accounts(client, api_version))+ return False, missing# The campaign list is the cheapest account-scoped read: it exercises the access token# *and* the `X-AP-Context` id, which the ACL endpoint would not.@@ -333,14 +332,13 @@ def validate_credentials(return False, f"The Apple Ads API returned an unexpected status code: {status}"-def _readable_ad_accounts(client: AppleSearchAdsClient, api_version: str) -> str:- """Sentence naming the ad accounts these credentials can read, to append to an error.+def _readable_ad_accounts(client: AppleSearchAdsClient, api_version: str) -> Optional[list[tuple[str, Optional[str]]]]:+ """Ad accounts these credentials can read as ``(id, name)`` pairs, or None when the lookup fails.- Best effort. The ACL lookup carries no context id, so it works before one is entered, but- a failure here must not replace the more useful message asking for the id.+ Best effort. The ACL lookup carries no context id, so it works before one is entered."""if api_version != APPLE_ADS_API_VERSION_V1:- return ""+ return Noneconfig = endpoints_for_version(api_version)["acls"]request = page_request(config, api_version, RequestScope(), offset=0)@@ -349,19 +347,45 @@ def _readable_ad_accounts(client: AppleSearchAdsClient, api_version: str) -> strrequest.method, request.path, params=request.params, body=request.body, requires_context=False)except (requests.RequestException, ValueError):- return ""+ return None- named = []+ accounts: list[tuple[str, Optional[str]]] = []for account in flatten_acl_rows(page_rows(payload, config, api_version)):account_id = account.get("id")if account_id is None:continuename = account.get("name")- named.append(f"{account_id} ({name})" if name else str(account_id))+ accounts.append((str(account_id), str(name) if name else None))+ return accounts+++_AD_ACCOUNT_SCOPING = (+ "The Platform API scopes every request to one ad account, which is not the organization ID the older API used."+)+- if not named:- return " These credentials cannot read any ad account yet. Check the API user's role in Apple Ads."- return " These credentials can read: " + ", ".join(named) + "."+def _blank_ad_account_message(accounts: Optional[list[tuple[str, Optional[str]]]]) -> str:+ if accounts is None:+ return (+ "Enter the ad account ID. PostHog could not list the ad accounts these credentials can "+ "read. Read adAccount.id from Apple's Get User ACL endpoint, "+ f"GET https://api.ads.apple.com/v1/acls, and connect again. {_AD_ACCOUNT_SCOPING}"+ )+ if not accounts:+ return (+ "These credentials cannot read any ad account yet. Give the API user the API Account "+ "Read Only role for the ad account in Apple Ads, then connect again."+ )+ named = ", ".join(f"{account_id} ({name})" if name else account_id for account_id, name in accounts)+ if len(accounts) == 1:+ return (+ f"These credentials can read one ad account: {named}. Enter {accounts[0][0]} in Ad "+ f"account ID and connect again. {_AD_ACCOUNT_SCOPING}"+ )+ return (+ f"These credentials can read these ad accounts: {named}. Enter one of those IDs in Ad "+ f"account ID and connect again. {_AD_ACCOUNT_SCOPING}"+ )def _today() -> date: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 94ffe1aa79ba..399c11455e4e 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@@ -120,7 +120,7 @@ Apple does not generate an API key for you. You supply your own key pair, and on2. Generate an EC P-256 key pair. On macOS or Linux, run `openssl ecparam -genkey -name prime256v1 -noout -out private-key.pem` and then `openssl ec -in private-key.pem -pubout -out public-key.pem`.3. Signed in as that user, open **Account settings > API**, paste the contents of `public-key.pem` into the public key field and save. Saving the key creates the client.4. Apple then shows the client ID, team ID and key ID above the field. Enter those below, along with the contents of `private-key.pem`.-5. Leave **Ad account ID** blank and connect. The connection won't complete, but PostHog reads Apple's ACL for you and the message names the ad account IDs your credentials can read. Paste one in and connect again. To look it up yourself, read `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`. That call needs an access token, so follow [Apple's OAuth guide](https://developer.apple.com/documentation/apple_ads/implementing-oauth-for-the-apple-search-ads-api) to exchange the credentials from step 4 for one. The ad account ID is not the same value as your organization ID.+5. Leave **Ad account ID** blank on the first connect. PostHog stops and shows the ad account IDs your credentials can read. That stop is the expected result of the first connect, not a credential failure. Enter one of the IDs and connect again. To look it up yourself, read `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, with an access token signed by the credentials from step 4 — follow [Apple's OAuth guide](https://developer.apple.com/documentation/apple_ads/implementing-oauth-for-the-apple-search-ads-api) to exchange them for one. The ad account ID is not the same value as your organization ID.PostHog stores the private key encrypted and uses it to sign a short-lived token on every sync. The token itself is never stored.@@ -144,7 +144,7 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days# requires whichever one the source's API version uses.required=False,placeholder="123456789",- caption="Leave this blank and connect, and PostHog lists the ad account IDs your credentials can read. To look it up yourself, read `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`. That call needs an access token signed with the credentials above, not the credentials themselves.",+ caption="Leave this blank on the first connect. PostHog stops and shows the ad account IDs your credentials can read. That stop is the expected result, not a credential failure. Enter one of the IDs and connect again. To look it up yourself, read `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, with an access token signed by the credentials above.",secret=False,),SourceFieldInputConfig(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 f834c0f7032c..279f0a29979a 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@@ -938,7 +938,30 @@ class TestValidateCredentials:assert session.api_calls[0]["url"] == expected_urlassert session.api_calls[0]["headers"]["X-AP-Context"] == expected_context- def test_a_missing_ad_account_id_names_the_accounts_the_client_can_read(self) -> None:+ def test_a_blank_ad_account_id_leads_with_the_several_accounts_it_found(self) -> None:+ credentials = dataclasses.replace(CREDENTIALS, ad_account_id=None)+ session = _FakeSession(+ [+ _acls_page(+ [+ {"adAccount": {"id": 123456789, "name": "Account A"}, "roles": []},+ {"adAccount": {"id": 987654321, "name": "Account B"}, "roles": []},+ ]+ )+ ]+ )++ with mock.patch(SESSION_PATCH, return_value=session):+ is_valid, message = validate_credentials(credentials, V1)++ assert is_valid is False+ assert message is not None+ assert message.startswith("These credentials can read these ad accounts:")+ assert "123456789 (Account A)" in message+ assert "987654321 (Account B)" in message+ assert "connect again" in message++ def test_a_blank_ad_account_id_names_the_single_account_as_the_value_to_enter(self) -> None:credentials = dataclasses.replace(CREDENTIALS, ad_account_id=None)session = _FakeSession([_acls_page([{"adAccount": {"id": 123456789, "name": "Account A"}, "roles": []}])])@@ -947,19 +970,35 @@ class TestValidateCredentials:assert is_valid is Falseassert message is not None- assert "ad account ID" in message- # The ACL lookup carries no context id, so it can answer before one is entered.+ assert message.startswith("These credentials can read one ad account:")assert "123456789 (Account A)" in message+ assert "Enter 123456789 in Ad account ID" in message- def test_a_missing_ad_account_id_is_still_reported_when_the_acl_lookup_fails(self) -> None:+ def test_a_blank_ad_account_id_with_no_readable_account_names_the_role_to_grant(self) -> None:credentials = dataclasses.replace(CREDENTIALS, ad_account_id=None)- session = _FakeSession([_FakeResponse(500, url=BASE_URL[V1]), _FakeResponse(500, url=BASE_URL[V1])])+ session = _FakeSession([_acls_page([])])with mock.patch(SESSION_PATCH, return_value=session):is_valid, message = validate_credentials(credentials, V1)assert is_valid is False- assert message is not None and "ad account ID" in message+ assert message is not None+ assert message.startswith("These credentials cannot read any ad account yet.")+ assert "API Account Read Only" in message+ assert "connect again" in message++ def test_a_blank_ad_account_id_falls_back_to_the_self_service_path_when_the_lookup_fails(self) -> None:+ credentials = dataclasses.replace(CREDENTIALS, ad_account_id=None)+ session = _FakeSession([_FakeResponse(500, url=BASE_URL[V1])])++ with mock.patch(SESSION_PATCH, return_value=session):+ is_valid, message = validate_credentials(credentials, V1)++ assert is_valid is False+ assert message is not None+ assert message.startswith("Enter the ad account ID.")+ assert "https://api.ads.apple.com/v1/acls" in message+ assert "connect again" in messagedef test_a_missing_org_id_is_reported_for_the_older_api(self) -> None:credentials = dataclasses.replace(CREDENTIALS, org_id=None)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 789a2110d80f..a59555ddcdfd 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@@ -186,6 +186,21 @@ class TestAppleSearchAdsSource:assert (credentials.ad_account_id, credentials.org_id) == ("123456789", "555")+ def test_the_field_caption_and_step_five_describe_the_same_blank_connect_flow(self) -> None:+ config = self.source.get_source_config+ field_caption = next(+ field.caption+ for field in config.fields+ if isinstance(field, SourceFieldInputConfig) and field.name == "ad_account_id"+ )+ assert field_caption is not None+ assert config.caption is not None+ step_five = next(line for line in config.caption.splitlines() if line.startswith("5."))++ for text in (field_caption, step_five):+ assert "connect again" in text+ assert "expected" in text+def test_the_connect_form_does_not_require_either_context_id(self) -> None:# `required` cannot express "depends on the version pin", so `validate_credentials`# enforces whichever one applies instead.