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.

feat(data-warehouse): add Apple Ads service provider OAuth (#112581)

Tom Owers38dca4fd5522
diff --git a/.agents/skills/implementing-warehouse-sources/references/oauth-app-deployment.md b/.agents/skills/implementing-warehouse-sources/references/oauth-app-deployment.md
index 00db5e15db46..aa33e4854810 100644
--- a/.agents/skills/implementing-warehouse-sources/references/oauth-app-deployment.md
+++ b/.agents/skills/implementing-warehouse-sources/references/oauth-app-deployment.md
@@ -37,6 +37,12 @@ RESEND_APP_CLIENT_SECRET = get_from_env("RESEND_APP_CLIENT_SECRET", "")
Then wire the `oauth_config_for_kind()` branch (raise `NotImplementedError("<Source> app not configured")`
when either is empty — that's the fail-closed message users see).
+A provider that issues no static secret needs more than two vars, and the rest of this page still
+applies to each of them. Apple Ads is the worked example: the registration is a key pair, so it
+declares `APPLE_ADS_APP_CLIENT_ID`, `APPLE_ADS_APP_TEAM_ID`, `APPLE_ADS_APP_KEY_ID` and
+`APPLE_ADS_APP_PRIVATE_KEY`, and `posthog/models/integration/apple_ads.py` signs a short-lived
+assertion from them on every config build. Treat all four as secrets in steps 3 and 4.
+
## 3. Charts — map env var → secret key (PostHog/charts PR)
Add the two vars in **both** stores, mirroring the existing OAuth apps (Stripe, Salesforce, HubSpot…).
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index b4c8d3b3d3a8..1b8ae5f1fe4c 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -102,6 +102,7 @@ export interface integrationsLogicValues {
getIntegrationsByKind: (
kinds: (
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -214,6 +215,7 @@ export interface integrationsLogicActions {
) => {
kind:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -350,6 +352,7 @@ export interface integrationsLogicActions {
installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -414,6 +417,7 @@ export interface integrationsLogicActions {
installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -472,6 +476,7 @@ export interface integrationsLogicActions {
id: string
kind:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -537,6 +542,7 @@ export interface integrationsLogicActions {
requestIntegrationAccessSuccess: (
accessRequest:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -587,6 +593,7 @@ export interface integrationsLogicActions {
) => {
accessRequest:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -683,6 +690,7 @@ export interface integrationsLogicMeta {
) => (
kinds: (
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.ts
index ebf4dc8265af..25a66c942229 100644
--- a/frontend/src/lib/integrations/utils.ts
+++ b/frontend/src/lib/integrations/utils.ts
@@ -126,6 +126,7 @@ export const ICONS: Record<IntegrationKind, any> = {
'customerio-webhook': IconCustomerIO,
'customerio-track': IconCustomerIO,
apns: IconApple,
+ 'apple-ads': IconApple,
postgresql: IconPostgres,
'aws-s3': IconAwsS3,
'aws-redshift': IconRedshift,
@@ -136,7 +137,7 @@ export const ICONS: Record<IntegrationKind, any> = {
// Brand marks that are solid black/monochrome on a transparent background — they vanish against a dark
// surface, so invert them in dark mode (`dark:invert`) wherever the integration icon is rendered.
-export const DARK_MODE_INVERT_ICON_KINDS = new Set<IntegrationKind>(['apns', 'github'])
+export const DARK_MODE_INVERT_ICON_KINDS = new Set<IntegrationKind>(['apns', 'apple-ads', 'github'])
export const getIntegrationNameFromKind = (kind: string): string => {
switch (kind) {
@@ -154,6 +155,8 @@ export const getIntegrationNameFromKind = (kind: string): string => {
return 'Google Search Console'
case 'google-cloud-service-account':
return 'Google Cloud service account'
+ case 'apple-ads':
+ return 'Apple Ads'
case 'linkedin-ads':
return 'LinkedIn Ads'
case 'reddit-ads':
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 6cfee9064eae..e4c3040c1892 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -30982,6 +30982,7 @@
"customerio-webhook",
"customerio-track",
"apns",
+ "apple-ads",
"postgresql",
"aws-s3",
"aws-redshift",
diff --git a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
index 2a0bd50c46d0..b2a0db8c5794 100644
--- a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
@@ -16,6 +16,7 @@ export interface organizationIntegrationsLogicValues {
getOrganizationIntegrationsByKind: (
kinds: (
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -94,6 +95,7 @@ export interface organizationIntegrationsLogicActions {
installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -154,6 +156,7 @@ export interface organizationIntegrationsLogicActions {
installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
@@ -212,6 +215,7 @@ export interface organizationIntegrationsLogicMeta {
) => (
kinds: (
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 7e74375ec9c8..90810501e6db 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5723,6 +5723,7 @@ export const INTEGRATION_KINDS = [
'customerio-webhook',
'customerio-track',
'apns',
+ 'apple-ads',
'postgresql',
'aws-s3',
'aws-redshift',
diff --git a/posthog/models/integration/apple_ads.py b/posthog/models/integration/apple_ads.py
new file mode 100644
index 000000000000..c4aa4a1056ad
--- /dev/null
+++ b/posthog/models/integration/apple_ads.py
@@ -0,0 +1,72 @@
+"""Client-secret signing for the Apple Ads service provider OAuth flow.
+
+Apple issues no static client secret. A service provider registers a public key in Apple Ads and
+signs a short-lived ES256 JWT with the matching private key for every call to Apple's token
+endpoint, presenting it as `client_secret`. The claims are fixed by Apple: `iss` is the team id,
+`sub` is the client id, `aud` is Apple ID, and `kid` in the header is the key id.
+"""
+
+import time
+
+from django.conf import settings
+
+import jwt
+
+APPLE_OAUTH_AUDIENCE = "https://appleid.apple.com"
+
+# Apple accepts a client secret of up to 180 days. A short life is enough here because one is
+# signed per token request, and it keeps a leaked assertion near-worthless. It must outlive the
+# OauthConfig cache (5 minutes), which hands the same signed value to every caller in that window.
+CLIENT_SECRET_TTL_SECONDS = 30 * 60
+
+
+class AppleAdsOauthNotConfigured(Exception):
+ pass
+
+
+def normalize_private_key(private_key: str) -> str:
+ """Accept a PEM supplied with literal ``\\n`` escapes as well as real newlines."""
+ return private_key.replace("\\n", "\n").strip()
+
+
+def build_client_secret(
+ *,
+ client_id: str,
+ team_id: str,
+ key_id: str,
+ private_key: str,
+ issued_at: int | None = None,
+) -> str:
+ now = int(issued_at if issued_at is not None else time.time())
+ return jwt.encode(
+ {
+ "iss": team_id,
+ "iat": now,
+ "exp": now + CLIENT_SECRET_TTL_SECONDS,
+ "aud": APPLE_OAUTH_AUDIENCE,
+ "sub": client_id,
+ },
+ normalize_private_key(private_key),
+ algorithm="ES256",
+ headers={"alg": "ES256", "kid": key_id},
+ )
+
+
+def service_provider_client_secret() -> str:
+ """Sign a client secret for PostHog's own Apple Ads service provider registration."""
+ if not all(
+ (
+ settings.APPLE_ADS_APP_CLIENT_ID,
+ settings.APPLE_ADS_APP_TEAM_ID,
+ settings.APPLE_ADS_APP_KEY_ID,
+ settings.APPLE_ADS_APP_PRIVATE_KEY,
+ )
+ ):
+ raise AppleAdsOauthNotConfigured("Apple Ads service provider app not configured")
+
+ return build_client_secret(
+ client_id=settings.APPLE_ADS_APP_CLIENT_ID,
+ team_id=settings.APPLE_ADS_APP_TEAM_ID,
+ key_id=settings.APPLE_ADS_APP_KEY_ID,
+ private_key=settings.APPLE_ADS_APP_PRIVATE_KEY,
+ )
diff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.py
index 78db7d4cdff6..a6152ce35653 100644
--- a/posthog/models/integration/model.py
+++ b/posthog/models/integration/model.py
@@ -127,6 +127,7 @@ def integration_kind_choices() -> list[tuple[str, str | Promise]]:
class Integration(models.Model):
class IntegrationKind(models.TextChoices):
ANTHROPIC = "anthropic"
+ APPLE_ADS = "apple-ads"
APPLE_PUSH = "apns"
AWS_REDSHIFT = "aws-redshift"
AWS_S3 = "aws-s3"
diff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.py
index 99b9e95c8c42..b829cb38c43f 100644
--- a/posthog/models/integration/oauth.py
+++ b/posthog/models/integration/oauth.py
@@ -7,7 +7,7 @@ import hashlib
import secrets
from dataclasses import field, replace
from datetime import timedelta
-from typing import NoReturn
+from typing import Any, NoReturn
from urllib.parse import parse_qs, urlencode, urlparse
from django.conf import settings
@@ -27,7 +27,7 @@ from posthog.plugins.plugin_server_api import reload_integrations_on_workers
from posthog.schema_enums import SlackIntegrationScope
from posthog.scopes import get_oauth_scopes_supported
-from . import common, model, refresh_tracking
+from . import apple_ads, common, model, refresh_tracking
logger = structlog.get_logger(__name__)
@@ -88,6 +88,19 @@ INSTAGRAM_OAUTH_SCOPE = (
)
+# Apple Ads: where the authorization code is exchanged. Apple's service provider OAuth guide names
+# a different path for the refresh grant, `/auth/token`, which is the Sign in with Apple endpoint
+# rather than a sibling of the `/auth/oauth2/v2/authorize` endpoint this flow starts at.
+# `_post_token_refresh` tries this one first and falls back to that one, so whichever Apple honors
+# keeps working.
+APPLE_ADS_TOKEN_URL = "https://appleid.apple.com/auth/oauth2/token"
+APPLE_ADS_REFRESH_TOKEN_FALLBACK_URL = "https://appleid.apple.com/auth/token"
+# Lists every ad account the granting user can reach, and the organization each sits under. Apple
+# documents it as the call to make once per access token, and it is the only identity Apple exposes
+# for a service provider grant.
+APPLE_ADS_ACL_URL = "https://api.ads.apple.com/v1/acls"
+
+
@frozen
class OauthConfig:
authorize_url: str
@@ -119,6 +132,61 @@ class OauthConfig:
POSTHOG_SLACK_SCOPE = ",".join(scope.value for scope in SlackIntegrationScope)
+def _apple_ads_acl_accounts(access_token: str) -> list[dict[str, Any]]:
+ """Ad accounts an Apple Ads access token can read, flattened one row per account.
+
+ Apple nests each account under `adAccount` and lists the granting user's roles beside it:
+ ``{"result": {"acls": [{"adAccount": {"id", "name", "orgId", ...}, "roles": [...]}]}}``.
+ Returns an empty list rather than raising when Apple rejects the call, so the caller decides
+ what a grant with no readable account means.
+ """
+ try:
+ res = requests.get(
+ APPLE_ADS_ACL_URL,
+ headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"},
+ timeout=10,
+ # This call carries the access token; a 30x must not resend it to another origin.
+ allow_redirects=False,
+ )
+ except requests.RequestException as e:
+ logger.warning("apple_ads_acl_request_failed", error=str(e))
+ return []
+
+ if res.status_code != 200:
+ logger.warning("apple_ads_acl_request_rejected", status_code=res.status_code, response=res.text[:500])
+ return []
+
+ try:
+ payload = res.json()
+ except ValueError:
+ return []
+
+ result = payload.get("result") if isinstance(payload, dict) else None
+ entries = result.get("acls") if isinstance(result, dict) else None
+ if not isinstance(entries, list):
+ return []
+
+ accounts: list[dict[str, Any]] = []
+ for entry in entries:
+ account = entry.get("adAccount") if isinstance(entry, dict) else None
+ if isinstance(account, dict) and account.get("id") is not None:
+ accounts.append({**account, "roles": entry.get("roles") or []})
+ return accounts
+
+
+def _apple_ads_account_name(accounts: list[dict[str, Any]]) -> str:
+ """Label for the connected Apple Ads grant, named after the organizations it reaches."""
+ org_names: list[str] = []
+ for account in accounts:
+ name = account.get("orgName") or account.get("parentOrgName")
+ if name and name not in org_names:
+ org_names.append(str(name))
+ if org_names:
+ return ", ".join(org_names)
+ first = accounts[0]
+ return str(first.get("name") or f"Apple Ads account {first['id']}")
+
+
def _salesforce_instance_host(instance_url: str | None) -> str | None:
# Every Salesforce-issued instance_url host ends in .salesforce.com: login/test, the
# pod hosts (na1.salesforce.com, ...), and My Domain variants like
@@ -254,6 +322,7 @@ class OauthIntegration:
"posthog",
"salesforce",
"hubspot",
+ "apple-ads",
"google-ads",
"google-analytics",
"google-calendar",
@@ -786,6 +855,38 @@ class OauthIntegration:
name_path="resend_account_name",
)
+ elif kind == "apple-ads":
+ if not all(
+ (
+ settings.APPLE_ADS_APP_CLIENT_ID,
+ settings.APPLE_ADS_APP_TEAM_ID,
+ settings.APPLE_ADS_APP_KEY_ID,
+ settings.APPLE_ADS_APP_PRIVATE_KEY,
+ )
+ ):
+ raise NotImplementedError("Apple Ads service provider app not configured")
+
+ # Apple's service provider flow, where a PostHog registration acts on behalf of an
+ # Apple Ads user who grants access. The first-party flow the warehouse source also
+ # supports is a different thing: it uses the customer's own key pair with
+ # `client_credentials` and the `searchadsorg` scope, and never reaches this code.
+ #
+ # The client secret is signed, not stored: Apple issues no static secret, so each
+ # build mints a fresh ES256 assertion. `oauth_config_for_kind` caches the config for
+ # five minutes, well inside the assertion's own lifetime.
+ #
+ # The token response carries no account identifier, so id/name come from Apple's ACL
+ # endpoint below (see the apple-ads branch in integration_from_oauth_response).
+ return OauthConfig(
+ authorize_url="https://appleid.apple.com/auth/oauth2/v2/authorize",
+ token_url=APPLE_ADS_TOKEN_URL,
+ client_id=settings.APPLE_ADS_APP_CLIENT_ID,
+ client_secret=apple_ads.service_provider_client_secret(),
+ scope="searchads",
+ id_path="apple_ads_account_id",
+ name_path="apple_ads_account_name",
+ )
+
raise NotImplementedError(f"Oauth config for kind {kind} not implemented")
@classmethod
@@ -1138,6 +1239,24 @@ class OauthIntegration:
except Exception:
logger.exception("Failed to decode Resend JWT")
+ # Apple's token response carries no account identifier. Apple documents the ACL endpoint as
+ # the call to make once per access token, so it names the grant and checks that it can read
+ # something. The granting user may reach several ad accounts across organizations. A hash
+ # of the opaque grant token keeps separate grants from overwriting one another, while the
+ # account is picked per source afterwards.
+ if kind == "apple-ads" and not integration_id:
+ accounts = _apple_ads_acl_accounts(config["access_token"])
+ if not accounts:
+ raise ValidationError(
+ "This Apple Ads user cannot read any ad account. Ask an account admin to grant "
+ "access in Apple Ads, then connect again."
+ )
+ org_ids = sorted({str(account["orgId"]) for account in accounts if account.get("orgId") is not None})
+ config["apple_ads_account_name"] = _apple_ads_account_name(accounts)
+ config["apple_ads_org_ids"] = org_ids
+ grant_token = config.get("refresh_token") or config["access_token"]
+ integration_id = f"grant:{hashlib.sha256(grant_token.encode()).hexdigest()}"
+
# LinkedIn id_token is a JWT, extract user ID and email from it
# This avoids calling /v2/userinfo which has intermittent REVOKED_ACCESS_TOKEN errors
if kind == "linkedin-ads" and not integration_id:
@@ -1427,6 +1546,21 @@ class OauthIntegration:
headers={"Idempotency-Key": hashlib.sha256(refresh_token.encode()).hexdigest()},
timeout=10,
)
+ elif kind == "apple-ads":
+ # Apple's guide names `/auth/token` for the refresh grant while the exchange it pairs
+ # with uses `/auth/oauth2/token`. Try the exchange endpoint first, then the documented
+ # one, so a wrong guess in either direction costs one extra request on failure instead
+ # of a dead integration. Drop the fallback once Apple's behavior is confirmed.
+ body = {
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "refresh_token": refresh_token,
+ "grant_type": "refresh_token",
+ }
+ res = requests.post(oauth_config.token_url, data=body, timeout=10, allow_redirects=False)
+ if res.status_code == 200:
+ return res
+ return requests.post(APPLE_ADS_REFRESH_TOKEN_FALLBACK_URL, data=body, timeout=10, allow_redirects=False)
else:
token_url = oauth_config.token_url
# Salesforce sandbox integrations are stored under the production kind (the sandbox
diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.py
index 5d2dbc6f03a2..52c8b35ad349 100644
--- a/posthog/models/test/integration/test_oauth.py
+++ b/posthog/models/test/integration/test_oauth.py
@@ -17,7 +17,10 @@ from django.core.cache import cache
from django.db import connection
from django.test import override_settings
+import jwt
import requests
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ec
from parameterized import parameterized
from rest_framework.exceptions import ValidationError
@@ -1667,3 +1670,154 @@ class TestYouTubeAnalyticsIntegrationModel(BaseTest):
def test_oauth_config_unconfigured_raises(self):
with pytest.raises(NotImplementedError, match="YouTube Analytics app not configured"):
OauthIntegration.oauth_config_for_kind("youtube-analytics")
+
+
+_APPLE_ADS_APP_PRIVATE_KEY = (
+ ec.generate_private_key(ec.SECP256R1())
+ .private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ .decode()
+)
+
+_APPLE_ADS_ACL = {
+ "result": {
+ "acls": [
+ {
+ "adAccount": {"id": 123456789, "name": "Hedgebox", "orgId": 555, "orgName": "Hedgebox Inc"},
+ "roles": [{"roleName": "API Account Read Only"}],
+ }
+ ]
+ }
+}
+
+
+@override_settings(
+ APPLE_ADS_APP_CLIENT_ID="SEARCHADS.posthog",
+ APPLE_ADS_APP_TEAM_ID="SEARCHADS.team",
+ APPLE_ADS_APP_KEY_ID="key-1",
+ APPLE_ADS_APP_PRIVATE_KEY=_APPLE_ADS_APP_PRIVATE_KEY,
+)
+class TestAppleAdsIntegrationModel(BaseTest):
+ def _mock_acl(self, mock_get, status_code: int = 200, payload: Optional[dict] = None) -> None:
+ mock_get.return_value.status_code = status_code
+ mock_get.return_value.json.return_value = _APPLE_ADS_ACL if payload is None else payload
+
+ def test_oauth_config_signs_the_client_secret_apple_expects(self):
+ # Apple issues no static secret: it reads `client_secret` as an ES256 assertion naming the
+ # registration. Posting a literal setting value instead fails every grant at the exchange.
+ config = OauthIntegration.oauth_config_for_kind("apple-ads")
+
+ assert config.authorize_url == "https://appleid.apple.com/auth/oauth2/v2/authorize"
+ assert config.token_url == "https://appleid.apple.com/auth/oauth2/token"
+ assert config.client_id == "SEARCHADS.posthog"
+ assert config.scope == "searchads"
+
+ claims = jwt.decode(
+ config.client_secret,
+ _APPLE_ADS_APP_PRIVATE_KEY,
+ algorithms=["ES256"],
+ audience="https://appleid.apple.com",
+ options={"verify_signature": False},
+ )
+ assert claims["iss"] == "SEARCHADS.team"
+ assert claims["sub"] == "SEARCHADS.posthog"
+ assert jwt.get_unverified_header(config.client_secret)["kid"] == "key-1"
+
+ @parameterized.expand(
+ ["APPLE_ADS_APP_CLIENT_ID", "APPLE_ADS_APP_TEAM_ID", "APPLE_ADS_APP_KEY_ID", "APPLE_ADS_APP_PRIVATE_KEY"]
+ )
+ def test_oauth_config_unconfigured_raises(self, missing_setting: str):
+ with override_settings(**{missing_setting: ""}):
+ with pytest.raises(NotImplementedError, match="Apple Ads service provider app not configured"):
+ OauthIntegration.oauth_config_for_kind("apple-ads")
+
+ @patch("posthog.models.integration.oauth.requests.get")
+ @patch("posthog.models.integration.oauth.requests.post")
+ def test_integration_from_oauth_response_names_the_grant_from_apples_acl(self, mock_post, mock_get):
+ # Apple's token response carries no identifier at all, so without the ACL lookup the
+ # callback has nothing to key the integration on and fails after a successful grant.
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.return_value = {
+ "access_token": "at_1",
+ "refresh_token": "rt_1",
+ "expires_in": 3600,
+ "token_type": "Bearer",
+ }
+ self._mock_acl(mock_get)
+
+ integration = OauthIntegration.integration_from_oauth_response(
+ "apple-ads", self.team.id, self.user, {"code": "code", "state": "token=state_token"}
+ )
+
+ assert integration.integration_id == f"grant:{hashlib.sha256(b'rt_1').hexdigest()}"
+ assert integration.config["apple_ads_account_name"] == "Hedgebox Inc"
+ assert integration.config["apple_ads_org_ids"] == ["555"]
+ assert integration.sensitive_config["refresh_token"] == "rt_1"
+
+ @patch("posthog.models.integration.oauth.requests.get")
+ @patch("posthog.models.integration.oauth.requests.post")
+ def test_grants_for_the_same_organization_remain_separate(self, mock_post, mock_get):
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.side_effect = [
+ {"access_token": "at_1", "refresh_token": "rt_1", "expires_in": 3600},
+ {"access_token": "at_2", "refresh_token": "rt_2", "expires_in": 3600},
+ ]
+ self._mock_acl(mock_get)
+
+ first = OauthIntegration.integration_from_oauth_response(
+ "apple-ads", self.team.id, self.user, {"code": "code-1", "state": "token=state_token"}
+ )
+ second = OauthIntegration.integration_from_oauth_response(
+ "apple-ads", self.team.id, self.user, {"code": "code-2", "state": "token=state_token"}
+ )
+
+ assert first.id != second.id
+ assert first.integration_id != second.integration_id
+
+ @parameterized.expand([("rejected", 403, None), ("no_readable_account", 200, {"result": {"acls": []}})])
+ @patch("posthog.models.integration.oauth.requests.get")
+ @patch("posthog.models.integration.oauth.requests.post")
+ def test_a_grant_that_reads_no_ad_account_is_refused(
+ self, _name: str, status_code: int, payload: Optional[dict], mock_post, mock_get
+ ):
+ # An Apple Ads user with no API role can complete the grant and still read nothing. Storing
+ # it leaves a connected-looking integration that fails on every sync instead of at connect.
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.return_value = {"access_token": "at_1", "refresh_token": "rt_1"}
+ self._mock_acl(mock_get, status_code=status_code, payload=payload)
+
+ with pytest.raises(ValidationError, match="cannot read any ad account"):
+ OauthIntegration.integration_from_oauth_response(
+ "apple-ads", self.team.id, self.user, {"code": "code", "state": "token=state_token"}
+ )
+
+ @patch("posthog.models.integration.oauth.requests.post")
+ def test_token_refresh_retries_at_apples_other_documented_path(self, mock_post):
+ # Apple's guide names `/auth/oauth2/token` for the exchange and `/auth/token` for the
+ # refresh. Tokens live an hour, so honoring only one path would kill every integration
+ # within an hour of connecting.
+ rejected = MagicMock(status_code=400)
+ rejected.json.return_value = {"error": "invalid_request"}
+ accepted = MagicMock(status_code=200)
+ accepted.json.return_value = {"access_token": "at_2", "expires_in": 3600}
+ mock_post.side_effect = [rejected, accepted]
+
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="apple-ads",
+ integration_id="555",
+ config={"expires_in": 3600, "refreshed_at": int(time.time()) - 3600},
+ sensitive_config={"refresh_token": "rt_1", "access_token": "at_1"},
+ )
+
+ OauthIntegration(integration).refresh_access_token()
+
+ assert [call.args[0] for call in mock_post.call_args_list] == [
+ "https://appleid.apple.com/auth/oauth2/token",
+ "https://appleid.apple.com/auth/token",
+ ]
+ assert integration.sensitive_config["access_token"] == "at_2"
+ assert integration.errors == ""
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 900902f01299..df6b0a2069d8 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1812,6 +1812,7 @@ class IntegrationKind(StrEnum):
CUSTOMERIO_WEBHOOK = "customerio-webhook"
CUSTOMERIO_TRACK = "customerio-track"
APNS = "apns"
+ APPLE_ADS = "apple-ads"
POSTGRESQL = "postgresql"
AWS_S3 = "aws-s3"
AWS_REDSHIFT = "aws-redshift"
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index b318607d4087..157b1a994eb4 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -28,6 +28,16 @@ INTERCOM_APP_CLIENT_SECRET = get_from_env("INTERCOM_APP_CLIENT_SECRET", "")
RESEND_APP_CLIENT_ID = get_from_env("RESEND_APP_CLIENT_ID", "")
RESEND_APP_CLIENT_SECRET = get_from_env("RESEND_APP_CLIENT_SECRET", "")
+# Apple Ads service provider OAuth. Apple issues no static client secret: the client secret is an
+# ES256 JWT this app signs per token request with the private key whose public half was registered
+# in Apple Ads (see posthog/models/integration/apple_ads.py). Empty defaults keep the app importable
+# and the OAuth auth method dormant until the service provider registration is provisioned.
+APPLE_ADS_APP_CLIENT_ID = get_from_env("APPLE_ADS_APP_CLIENT_ID", "")
+APPLE_ADS_APP_TEAM_ID = get_from_env("APPLE_ADS_APP_TEAM_ID", "")
+APPLE_ADS_APP_KEY_ID = get_from_env("APPLE_ADS_APP_KEY_ID", "")
+# PEM body of the EC P-256 private key. Newlines may be escaped as literal \n.
+APPLE_ADS_APP_PRIVATE_KEY = get_from_env("APPLE_ADS_APP_PRIVATE_KEY", "")
+
SALESFORCE_CONSUMER_KEY = get_from_env("SALESFORCE_CONSUMER_KEY", "")
SALESFORCE_CONSUMER_SECRET = get_from_env("SALESFORCE_CONSUMER_SECRET", "")
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 16301cb0c25d..bd9492ed3cb4 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -5430,6 +5430,7 @@ export const IntegrationKindApi = {
CustomerioWebhook: 'customerio-webhook',
CustomerioTrack: 'customerio-track',
Apns: 'apns',
+ AppleAds: 'apple-ads',
Postgresql: 'postgresql',
AwsS3: 'aws-s3',
AwsRedshift: 'aws-redshift',
diff --git a/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py b/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py
index 4be712ce030f..4bfcd1c76168 100644
--- a/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py
+++ b/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py
@@ -20,11 +20,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
def _stub_source_security_gate(source_mock) -> None:
"""The update path asks the source whether an edit introduces a new connection host or leaves
row-backed credentials preserved; a bare MagicMock returns truthy for both, which would wrongly
- trip the credential-reentry gate. Stub them to their real (falsy) defaults."""
+ trip the credential-reentry gate. Stub them to their real (falsy) defaults.
+
+ It also persists `source.serialize_config(source_config)` rather than `source_config.to_dict()`
+ directly, so a source stays able to retain rollout-compatible fields (see
+ `AppleSearchAdsSource.serialize_config`). A bare MagicMock's `serialize_config` otherwise
+ returns an unconfigured MagicMock, which Django's ORM then tries to treat as a query
+ expression and rejects. Delegate it to the parsed config's own `to_dict()`, matching the base
+ class's default implementation."""
source_mock.connection_host_fields = []
source_mock.server_managed_job_input_fields.return_value = []
source_mock.job_inputs_add_connection_host.return_value = False
source_mock.has_preserved_row_backed_credentials.return_value = False
+ source_mock.serialize_config.side_effect = lambda config: config.to_dict()
class TestPostgresWarehouseMigration(APIBaseTest):
diff --git a/products/data_warehouse/frontend/shared/components/forms/CredentialAccountSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/CredentialAccountSelector.tsx
index 6f5fbaee1b1f..879b97147bc7 100644
--- a/products/data_warehouse/frontend/shared/components/forms/CredentialAccountSelector.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/CredentialAccountSelector.tsx
@@ -15,6 +15,9 @@ export interface CredentialAccountSelectorProps {
fieldLabel: string
/** Sibling payload fields whose values the listing needs, named by the field config. */
credentialFields: string[]
+ /** Name of an OAuth integration id field that lists the same accounts. When the form holds a
+ * value there, it stands in for `credentialFields`, which the other auth branch leaves empty. */
+ integrationField?: string
/** Data warehouse source type used to route the listing endpoint, e.g. "AppleSearchAds". */
sourceType: string
placeholder?: string
@@ -74,9 +77,14 @@ function CredentialAccountSelectorInner({
formKey,
...props
}: CredentialAccountSelectorProps & { formLogic: any; formKey: string }): JSX.Element {
- const { sourceType, credentialFields, fieldName, fieldLabel, placeholder, caption } = props
+ const { sourceType, credentialFields, integrationField, fieldName, fieldLabel, placeholder, caption } = props
const values = useValues(formLogic) as Record<string, any> | null
- const credentials = collectCredentials(values?.[formKey]?.payload, credentialFields)
+ const payload = values?.[formKey]?.payload
+ // A connected account answers the same listing, and the two branches are never both filled in,
+ // so prefer whichever one the form holds rather than requiring the typed-in set.
+ const credentials =
+ (integrationField ? collectCredentials(payload, [integrationField]) : undefined) ??
+ collectCredentials(payload, credentialFields)
const { accounts, accountsLoading, accountsLoaded, accountsError } = useValues(
credentialAccountsLogic({ sourceType })
@@ -119,7 +127,9 @@ function CredentialAccountSelectorInner({
emptyMessage={
credentials
? "Couldn't load your accounts. Type the value in above."
- : 'Fill in the credentials above to list accounts.'
+ : integrationField
+ ? 'Connect your account above to list accounts.'
+ : 'Fill in the credentials above to list accounts.'
}
noMatchMessage={() => 'No accounts match your filter.'}
loadingMessage="Loading accounts…"
diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
index 93882b0af3cc..e635beaa957c 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
@@ -413,6 +413,7 @@ export const sourceFieldToElement = (
fieldName={field.name}
fieldLabel={field.label}
credentialFields={field.credentialFields}
+ integrationField={field.integrationField ?? undefined}
sourceType={sourceConfig.name}
placeholder={field.placeholder ?? undefined}
caption={field.caption ?? undefined}
diff --git a/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
index 755d57c3fa64..05aec849c322 100644
--- a/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
+++ b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
@@ -116,6 +116,7 @@ export interface destinationModalLogicActions {
setIntegrationKind: (kind: IntegrationKind) => {
kind:
| 'apns'
+ | 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index e297e0709d78..30eda29b193d 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -152,6 +152,7 @@ export interface RoleLookupResponseApi {
/**
* * `anthropic` - Anthropic
+ * * `apple-ads` - Apple Ads
* * `apns` - Apple Push
* * `aws-redshift` - Aws Redshift
* * `aws-s3` - Aws S3
@@ -205,6 +206,7 @@ export type IntegrationKindEnumApi = (typeof IntegrationKindEnumApi)[keyof typeo
export const IntegrationKindEnumApi = {
Anthropic: 'anthropic',
+ AppleAds: 'apple-ads',
Apns: 'apns',
AwsRedshift: 'aws-redshift',
AwsS3: 'aws-s3',
@@ -594,6 +596,7 @@ export interface IntegrationAccessRequestApi {
/** The kind of integration the member is requesting be connected (e.g. 'slack', 'github').
*
* * `anthropic` - Anthropic
+ * * `apple-ads` - Apple Ads
* * `apns` - Apple Push
* * `aws-redshift` - Aws Redshift
* * `aws-s3` - Aws S3
@@ -759,6 +762,7 @@ export type RoleExternalReferencesLookupRetrieveParams = {
export type IntegrationsListParams = {
/**
* * `anthropic` - Anthropic
+ * * `apple-ads` - Apple Ads
* * `apns` - Apple Push
* * `aws-redshift` - Aws Redshift
* * `aws-s3` - Aws S3
@@ -824,6 +828,7 @@ export type IntegrationsListKind = (typeof IntegrationsListKind)[keyof typeof In
export const IntegrationsListKind = {
Anthropic: 'anthropic',
Apns: 'apns',
+ AppleAds: 'apple-ads',
AwsRedshift: 'aws-redshift',
AwsS3: 'aws-s3',
AzureBlob: 'azure-blob',
diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.ts
index 876302b4bbbf..a4e1ca6b826c 100644
--- a/products/integrations/frontend/generated/api.zod.ts
+++ b/products/integrations/frontend/generated/api.zod.ts
@@ -63,6 +63,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
kind: zod
.enum([
'anthropic',
+ 'apple-ads',
'apns',
'aws-redshift',
'aws-s3',
@@ -113,7 +114,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -124,6 +125,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
kind: zod
.enum([
'anthropic',
+ 'apple-ads',
'apns',
'aws-redshift',
'aws-s3',
@@ -175,7 +177,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -186,6 +188,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
kind: zod
.enum([
'anthropic',
+ 'apple-ads',
'apns',
'aws-redshift',
'aws-s3',
@@ -236,7 +239,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -254,6 +257,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
kind: zod
.enum([
'anthropic',
+ 'apple-ads',
'apns',
'aws-redshift',
'aws-s3',
@@ -304,7 +308,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -370,6 +374,7 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
kind: zod
.enum([
'anthropic',
+ 'apple-ads',
'apns',
'aws-redshift',
'aws-s3',
@@ -420,10 +425,10 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
)
.describe(
- "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics"
+ "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics"
),
reason: zod
.string()
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 84fb533f3618..49f566ccd46b 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -4357,6 +4357,7 @@ export const IntegrationKindApi = {
CustomerioWebhook: 'customerio-webhook',
CustomerioTrack: 'customerio-track',
Apns: 'apns',
+ AppleAds: 'apple-ads',
Postgresql: 'postgresql',
AwsS3: 'aws-s3',
AwsRedshift: 'aws-redshift',
diff --git a/products/warehouse_sources/backend/facade/source_config.py b/products/warehouse_sources/backend/facade/source_config.py
index 8c3badae8fcf..763a820de27d 100644
--- a/products/warehouse_sources/backend/facade/source_config.py
+++ b/products/warehouse_sources/backend/facade/source_config.py
@@ -163,6 +163,15 @@ class SourceFieldCredentialAccountSelectConfig(BaseModel):
" exactly these, and the listing endpoint accepts exactly these."
),
)
+ integrationField: str | None = Field(
+ default=None,
+ description=(
+ "Name of an OAuth integration id field that lists the same accounts, for a source"
+ " offering both a typed-in credential and a connected account. The form sends this"
+ " instead of `credentialFields` when it holds a value, and the listing endpoint"
+ " accepts it on the same allowlist."
+ ),
+ )
label: str
name: str
placeholder: str | None = None
diff --git a/products/warehouse_sources/backend/migrations/0172_migrate_apple_search_ads_job_inputs_to_auth_method.py b/products/warehouse_sources/backend/migrations/0172_migrate_apple_search_ads_job_inputs_to_auth_method.py
new file mode 100644
index 000000000000..93b3620eaa0e
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0172_migrate_apple_search_ads_job_inputs_to_auth_method.py
@@ -0,0 +1,78 @@
+from typing import Any, Optional
+
+from django.db import migrations
+
+# The key pair fields, which are copied from the top level into the `auth_method` branch when the
+# source gained the Sign in with Apple option. They remain flat for old workers during rollout.
+# Everything else on an Apple Ads source
+# (`ad_account_id`, `org_id`, `start_date`) stays at the top level and must not move.
+KEY_PAIR_FIELDS = ("client_id", "apple_team_id", "key_id", "private_key")
+
+
+def nest_key_pair_under_auth_method(job_inputs: dict[str, Any]) -> Optional[dict[str, Any]]:
+ """The migrated `job_inputs`, or None when the source already carries a branch.
+
+ Every Apple Ads source that exists today authenticates with its own key pair, because that
+ was the only option. Naming the branch explicitly keeps the edit form on it: the branch
+ defaults to the sign-in option, so a source left flat renders with its key fields hidden.
+ Keeping the flat fields lets workers from the previous release continue syncing during rollout.
+ """
+ if "auth_method" in job_inputs:
+ return None
+
+ migrated = dict(job_inputs)
+ auth_method: dict[str, Any] = {"selection": "key_pair"}
+ for field in KEY_PAIR_FIELDS:
+ auth_method[field] = migrated.get(field, "")
+ migrated["auth_method"] = auth_method
+ return migrated
+
+
+def flatten_auth_method_to_key_pair(job_inputs: dict[str, Any]) -> Optional[dict[str, Any]]:
+ """The pre-branch `job_inputs`, or None when there is nothing the previous release can read.
+
+ A source connected through Sign in with Apple has no flat shape to go back to, because its
+ credential is an integration id the previous release has no field for. Leaving it alone makes
+ it report a config error on a rollback, which is honest: that release cannot sync it either.
+ """
+ auth_method = job_inputs.get("auth_method")
+ if not isinstance(auth_method, dict) or auth_method.get("selection") != "key_pair":
+ return None
+
+ flattened = dict(job_inputs)
+ flattened.pop("auth_method", None)
+ for field in KEY_PAIR_FIELDS:
+ flattened[field] = auth_method.get(field, "")
+ return flattened
+
+
+def _rewrite_job_inputs(apps, rewrite) -> None:
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ for source in ExternalDataSource.objects.filter(source_type="AppleSearchAds"):
+ if not isinstance(source.job_inputs, dict):
+ continue
+
+ rewritten = rewrite(source.job_inputs)
+ if rewritten is None:
+ continue
+
+ ExternalDataSource.objects.filter(pk=source.pk, job_inputs=source.job_inputs).update(job_inputs=rewritten)
+
+
+def migrate_apple_search_ads_job_inputs(apps, schema_editor):
+ _rewrite_job_inputs(apps, nest_key_pair_under_auth_method)
+
+
+def reverse_migrate_apple_search_ads_job_inputs(apps, schema_editor):
+ _rewrite_job_inputs(apps, flatten_auth_method_to_key_pair)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources", "0171_externaldatajob_pipeline_created_idx"),
+ ]
+
+ operations = [
+ migrations.RunPython(migrate_apple_search_ads_job_inputs, reverse_migrate_apple_search_ads_job_inputs),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 7dfba46caede..d50e841ea32f 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0171_externaldatajob_pipeline_created_idx
+0172_migrate_apple_search_ads_job_inputs_to_auth_method
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
index 8811572c9291..bc3122efc15b 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
@@ -194,6 +194,8 @@ def get_credential_account_field_names(fields: list[FieldType]) -> set[str]:
for field in fields:
if isinstance(field, SourceFieldCredentialAccountSelectConfig):
names.update(field.credentialFields)
+ if field.integrationField:
+ names.add(field.integrationField)
elif isinstance(field, SourceFieldSwitchGroupConfig):
names.update(get_credential_account_field_names(field.fields))
elif isinstance(field, SourceFieldSelectConfig):
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
index 89a5f97dc738..3908e2750695 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
@@ -587,7 +587,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
apply_sql_warehouse_schema_clear_migration(instance, old_schema)
source_config: Config = source.parse_config(new_job_inputs)
- validated_job_inputs = source_config.to_dict()
+ validated_job_inputs = source.serialize_config(source_config)
# The settings form resubmits the whole connection config on every save, so changing an
# unrelated setting (auto-syncing new tables, the prefix, the description) re-probed the
@@ -596,7 +596,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
# probe below only runs when the connection actually changed. Direct query sources still
# probe on every save: the same call refreshes their schemas and connection metadata.
try:
- stored_job_inputs = source.parse_config(existing_job_inputs).to_dict()
+ stored_job_inputs = source.serialize_config(source.parse_config(existing_job_inputs))
except Exception:
# A stored config that no longer parses can't be compared, so treat it as changed and
# let the probe run rather than skipping validation on a config we can't read.
@@ -656,7 +656,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
# Credential validation adopts re-entered OAuth2 secrets into the integration row and
# rewrites the config (pointer set, static secrets cleared) — re-serialize so job_inputs
# stores the pointer and never the raw secrets.
- validated_job_inputs = source_config.to_dict()
+ validated_job_inputs = source.serialize_config(source_config)
for key in helpers._CDC_EXPOSED_JOB_INPUT_KEYS:
if key in existing_job_inputs:
validated_job_inputs[key] = existing_job_inputs[key]
@@ -1199,7 +1199,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
status="Running",
source_type=source_type_model,
api_version=source.default_version,
- job_inputs=source_config.to_dict(),
+ job_inputs=source.serialize_config(source_config),
prefix=prefix,
description=description,
access_method=access_method,
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.py
index 437a5d101cb3..e7ba23441154 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
@@ -86,11 +86,14 @@ def token_exchange_error_message(error: requests.RequestException) -> str:
@dataclasses.dataclass(frozen=True)
class AppleSearchAdsCredentials:
- client_id: str
- team_id: str
- key_id: str
+ # Empty on the OAuth path, where PostHog's own service provider registration holds the key
+ # material and the client is handed a bearer token instead of minting one. Only the
+ # customer-supplied key pair path fills these in.
+ client_id: str = ""
+ team_id: str = ""
+ key_id: str = ""
# repr=False: keep the PEM out of tracebacks, logs, and pytest assertion diffs.
- private_key: str = dataclasses.field(repr=False)
+ private_key: str = dataclasses.field(default="", repr=False)
# v5 scopes every request to an organization, the Platform API to an ad account, and the
# two are different identifiers. Which one a source needs follows its version pin, which
# the connect form cannot express — so both are optional here and `validate_credentials`
@@ -195,21 +198,27 @@ class AppleSearchAdsClient:
credentials: AppleSearchAdsCredentials,
api_version: str,
request_logger: Optional[FilteringBoundLogger] = None,
+ token_provider: Optional[Callable[[], str]] = None,
) -> None:
self._credentials = credentials
self._api_version = api_version
self._base_url = base_url_for_version(api_version)
self._logger: FilteringBoundLogger = request_logger or logger
self._access_token: Optional[str] = None
+ # On the OAuth path the caller supplies the bearer token, because the grant belongs to
+ # PostHog's service provider registration rather than to credentials stored on the source.
+ # Called on every (re-)authentication, so it can refresh an expired token in place.
+ self._token_provider = token_provider or self._mint_access_token
+ redact_values = (credentials.private_key,) if credentials.private_key else ()
self._session = make_tracked_session(
retry=APPLE_SEARCH_ADS_RETRY,
- redact_values=(credentials.private_key,),
+ redact_values=redact_values,
)
# The token exchange body carries the signed assertion and the response the bearer
# token, neither of which the name-based sample scrubbers would recognise.
self._token_session = make_tracked_session(
retry=APPLE_SEARCH_ADS_RETRY,
- redact_values=(credentials.private_key,),
+ redact_values=redact_values,
capture=False,
)
@@ -218,7 +227,7 @@ class AppleSearchAdsClient:
return self._base_url
def authenticate(self) -> str:
- self._access_token = self._mint_access_token()
+ self._access_token = self._token_provider()
return self._access_token
def _mint_access_token(self) -> str:
@@ -320,6 +329,7 @@ def validate_credentials(
credentials: AppleSearchAdsCredentials,
api_version: str,
schema_name: Optional[str] = None,
+ token_provider: Optional[Callable[[], str]] = None,
) -> tuple[bool, str | None]:
"""Mint a token and probe one account-scoped endpoint.
@@ -327,7 +337,7 @@ def validate_credentials(
source-create (``schema_name is None``) so a user who only granted a subset of access can
still connect, and reported per-table otherwise.
"""
- client = AppleSearchAdsClient(credentials, api_version)
+ client = AppleSearchAdsClient(credentials, api_version, token_provider=token_provider)
try:
client.authenticate()
except AppleSearchAdsAuthError as e:
@@ -812,9 +822,10 @@ def get_rows(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
start_date: Optional[str] = None,
+ token_provider: Optional[Callable[[], str]] = None,
) -> Iterator[list[dict[str, Any]]]:
config = endpoints_for_version(api_version)[endpoint]
- client = AppleSearchAdsClient(credentials, api_version, request_logger)
+ client = AppleSearchAdsClient(credentials, api_version, request_logger, token_provider=token_provider)
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
# Listed once, up front: the scope stream is lazy and rebuilt on a missed checkpoint, so
@@ -857,6 +868,7 @@ def apple_search_ads_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
start_date: Optional[str] = None,
+ token_provider: Optional[Callable[[], str]] = None,
) -> SourceResponse:
config = endpoints_for_version(api_version)[endpoint]
@@ -871,6 +883,7 @@ def apple_search_ads_source(
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
start_date=start_date,
+ token_provider=token_provider,
),
primary_keys=list(config.primary_keys),
# Reporting windows are walked oldest-first, so `date` only ever moves forward across
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/oauth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/oauth.py
new file mode 100644
index 000000000000..5acc1f83685c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/oauth.py
@@ -0,0 +1,33 @@
+"""Bearer tokens for the Apple Ads service provider OAuth path.
+
+The customer grants PostHog access from the connect form, and the grant is stored as an
+`apple-ads` integration. Apple's access tokens live one hour, which a backfill routinely outlives,
+so the token is resolved per authentication rather than once per run.
+"""
+
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
+ AppleSearchAdsAuthError,
+)
+
+# Both are matched by `get_non_retryable_errors`, so keep the wording in step with the source.
+TOKEN_REFRESH_FAILED_MESSAGE = "Failed to refresh the Apple Ads connection. Please reconnect your Apple Ads account."
+MISSING_TOKEN_MESSAGE = "The connected Apple Ads account has no access token. Please reconnect it."
+
+
+class AppleAdsOauthError(AppleSearchAdsAuthError):
+ """Raised where the client expects an auth failure, so `validate_credentials` reports it."""
+
+
+def apple_ads_access_token(integration: Integration) -> str:
+ """Current bearer token for an Apple Ads grant, refreshing it when it has expired."""
+ oauth_integration = OauthIntegration(integration)
+ if oauth_integration.access_token_expired():
+ oauth_integration.refresh_access_token()
+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED:
+ raise AppleAdsOauthError(TOKEN_REFRESH_FAILED_MESSAGE)
+
+ if not integration.access_token:
+ raise AppleAdsOauthError(MISSING_TOKEN_MESSAGE)
+ return integration.access_token
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.py
index fc96d4720b84..ccdc6fbfacb4 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
@@ -1,5 +1,6 @@
+from collections.abc import Callable
from datetime import date
-from typing import Optional, cast
+from typing import Any, Optional, cast
import requests
@@ -10,6 +11,9 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldCredentialAccountSelectConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
+ SourceFieldOauthConfig,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
AppleSearchAdsAuthError,
@@ -21,6 +25,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.apple_sear
token_exchange_error_message,
validate_credentials as validate_apple_search_ads_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.oauth import (
+ apple_ads_access_token,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (
APPLE_ADS_API_VERSION_V1,
APPLE_SEARCH_ADS_API_VERSION_V5,
@@ -43,7 +50,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.int
IntegrationAccount,
IntegrationAccountListingError,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import CredentialAccountsMixin
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ CredentialAccountsMixin,
+ OAuthMixin,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
@@ -61,6 +71,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
class AppleSearchAdsSource(
ResumableSource[AppleSearchAdsSourceConfig, AppleSearchAdsResumeConfig],
CredentialAccountsMixin[AppleSearchAdsSourceConfig],
+ OAuthMixin,
):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
@@ -123,24 +134,22 @@ class AppleSearchAdsSource(
name=ExternalDataSourceType.APPLESEARCHADS,
category=DataWarehouseSourceCategory.ADVERTISING,
label="Apple Ads",
- # Two actors, in this order, because Apple splits the job: an account admin grants the
- # API role in User Management, and only the user holding that role sees the public key
- # field on the API tab. Collapsing this into one "an admin creates a client" step reads
- # tidier and strands every reader who is an admin without an API role.
caption="""Connect your Apple Ads account, formerly Apple Search Ads, to pull campaigns, ad groups, keywords and daily performance into the PostHog Data warehouse.
-Apple does not generate an API key for you. You supply your own key pair, and only a user with an API role can register it. An account admin who holds no API role will not see the public key field.
+Choose **Sign in with Apple** and authorize PostHog. Apple sends you back here, and the **Ad account** list fills with the accounts you can read.
+
+Either way, your Apple Ads user needs an API role first, or the connection reads nothing. An account admin grants one in [Apple Ads](https://ads.apple.com) under **Account settings > User management**.
-1. In [Apple Ads](https://ads.apple.com), an account admin opens **Account settings > User management** and gives the person setting this up the **API Account Read Only** role.
-2. 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. Pick your **Ad account ID** from the list, which fills in once the four fields above are complete. Apple shows this ID nowhere in its UI, and it is not the same value as your organization ID. 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. [Apple's OAuth guide](https://developer.apple.com/documentation/apple_ads/implementing-oauth-for-the-apple-search-ads-api) covers that exchange.
+The **API key pair** option is for accounts that run their own API client, and for sources still on Apple's Campaign Management API 5. It needs a key pair you generate and register yourself:
-PostHog stores the private key encrypted and uses it to sign a short-lived token on every sync. The token itself is never stored.
+1. 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`.
+2. Signed in as a user with an API role, open **Account settings > API**, paste the contents of `public-key.pem` into the public key field and save. Saving the key creates the client. An account admin who holds no API role will not see that field.
+3. 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`.
+
+PostHog stores every credential encrypted. With a key pair, PostHog signs a short-lived token on each sync and never stores that token.
Reporting tables use daily granularity, which Apple serves for the last 90 days only.""",
- permissionsCaption="""Assign the **API Account Read Only** role to the user who sets up the connection, under **Account settings > User management**. Apple attaches API roles to users, not to clients. That role grants read access to the campaign data these tables are built from. Pick it rather than the campaign group **API Read Only**, which covers a single campaign group. The **API Account Manager** role also works if you already use it.""",
+ permissionsCaption="""Assign the **API Account Read Only** role to the Apple Ads user who sets up the connection, under **Account settings > User management**. Apple attaches API roles to users, not to clients, so this applies to both authentication types. That role grants read access to the campaign data these tables are built from. Pick it rather than the campaign group **API Read Only**, which covers a single campaign group. The **API Account Manager** role also works if you already use it.""",
iconPath="/static/services/apple_search_ads.png",
docsUrl="https://posthog.com/docs/cdp/sources/apple-search-ads",
releaseStatus=ReleaseStatus.BETA,
@@ -150,41 +159,79 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
fields=cast(
list[FieldType],
[
- SourceFieldInputConfig(
- name="client_id",
- label="Client ID",
- type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="SEARCHADS.27478e17-...",
- caption="Apple shows this after you save the public key for your API client.",
- secret=False,
- ),
- SourceFieldInputConfig(
- name="apple_team_id",
- label="Team ID",
- type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="SEARCHADS.6f0a1b2c-...",
- caption="Apple shows this next to the client ID. It often matches the client ID.",
- secret=False,
- ),
- SourceFieldInputConfig(
- name="key_id",
- label="Key ID",
- type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="a1b2c3d4-...",
- caption="Apple shows this next to the client ID.",
- secret=False,
- ),
- SourceFieldInputConfig(
- name="private_key",
- label="Private key",
- type=SourceFieldInputConfigType.TEXTAREA,
+ SourceFieldSelectConfig(
+ name="auth_method",
+ label="Authentication type",
required=True,
- placeholder="-----BEGIN EC PRIVATE KEY-----",
- caption="The unencrypted EC P-256 private key matching the public key you uploaded to Apple.",
- secret=True,
+ # Signing in is the default because it asks the customer for nothing: Apple
+ # grants the token to PostHog's own service provider registration.
+ defaultValue="oauth",
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Sign in with Apple",
+ value="oauth",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldOauthConfig(
+ name="apple_ads_integration_id",
+ label="Apple Ads account",
+ required=False,
+ kind="apple-ads",
+ ),
+ ],
+ ),
+ ),
+ SourceFieldSelectConfigOption(
+ label="API key pair",
+ value="key_pair",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ # The branch fields are optional at the form level
+ # because the other branch leaves them empty.
+ # `validate_credentials` requires the set the chosen
+ # branch needs.
+ required=False,
+ placeholder="SEARCHADS.27478e17-...",
+ caption="Apple shows this after you save the public key for your API client.",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="apple_team_id",
+ label="Team ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="SEARCHADS.6f0a1b2c-...",
+ caption="Apple shows this next to the client ID. It often matches the client ID.",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="key_id",
+ label="Key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="a1b2c3d4-...",
+ caption="Apple shows this next to the client ID.",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="private_key",
+ label="Private key",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=False,
+ placeholder="-----BEGIN EC PRIVATE KEY-----",
+ caption="The unencrypted EC P-256 private key matching the public key you uploaded to Apple.",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ ],
),
SourceFieldCredentialAccountSelectConfig(
name="ad_account_id",
@@ -198,7 +245,10 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
# with them. Apple exposes the ad account id nowhere in its UI, so without
# this the only way to read one is to call the ACL endpoint by hand.
credentialFields=["client_id", "apple_team_id", "key_id", "private_key"],
- caption="Fill in the credentials above and this lists the ad accounts they can read. You can also type one in: it is `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, and it is not the same as your organization ID.",
+ # Both auth branches reach the same ACL endpoint, so one picker serves both:
+ # the grant when the user signed in, the typed-in key pair otherwise.
+ integrationField="apple_ads_integration_id",
+ caption="Connect your account above, or fill in the credentials, and this lists the ad accounts they can read. You can also type one in: it is `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, and it is not the same as your organization ID.",
),
SourceFieldInputConfig(
name="start_date",
@@ -215,7 +265,7 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
type=SourceFieldInputConfigType.TEXT,
required=False,
placeholder="123456",
- caption="Only for sources still on Apple's Campaign Management API 5, which Apple stops serving on 26 January 2027. Leave this empty and enter an ad account ID instead.",
+ caption="Only for sources still on Apple's Campaign Management API 5, which Apple stops serving on 26 January 2027. Those use the API key pair option. Leave this empty and pick an ad account instead.",
secret=False,
),
],
@@ -258,6 +308,39 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
return schemas
+ @staticmethod
+ def _normalize_job_inputs(job_inputs: dict) -> dict:
+ """Make pre-auth-selector key-pair rows readable during a rolling deployment."""
+ if "auth_method" in job_inputs:
+ return job_inputs
+
+ normalized = dict(job_inputs)
+ normalized["auth_method"] = {
+ "selection": "key_pair",
+ "client_id": job_inputs.get("client_id"),
+ "apple_team_id": job_inputs.get("apple_team_id"),
+ "key_id": job_inputs.get("key_id"),
+ "private_key": job_inputs.get("private_key"),
+ }
+ return normalized
+
+ def parse_config(self, job_inputs: dict) -> AppleSearchAdsSourceConfig:
+ return self._config_class.from_dict(self._normalize_job_inputs(job_inputs))
+
+ def validate_config(self, job_inputs: dict) -> tuple[bool, list[str]]:
+ return self._config_class.validate_dict(self._normalize_job_inputs(job_inputs))
+
+ def serialize_config(self, config: AppleSearchAdsSourceConfig) -> dict[str, Any]:
+ serialized = config.to_dict()
+ if config.auth_method.selection == "key_pair":
+ serialized.update(
+ client_id=config.auth_method.client_id,
+ apple_team_id=config.auth_method.apple_team_id,
+ key_id=config.auth_method.key_id,
+ private_key=config.auth_method.private_key,
+ )
+ return serialized
+
def validate_credentials(
self,
config: AppleSearchAdsSourceConfig,
@@ -265,20 +348,39 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
+ resolved_version = self.resolve_api_version(api_version)
+ if self._uses_oauth(config):
+ if resolved_version != APPLE_ADS_API_VERSION_V1:
+ return False, (
+ "Signing in with Apple only works with the Apple Ads Platform API. Reconnect "
+ "this source with an API key pair, or move it off Campaign Management API 5."
+ )
+ elif not config.auth_method.private_key:
+ if config.auth_method.selection == "oauth":
+ return False, "Connect your Apple Ads account, or switch to the API key pair option."
+ return False, "Enter the client ID, team ID, key ID and private key from your Apple Ads API client."
+
+ try:
+ token_provider = self._token_provider(config, team_id)
+ except ValueError:
+ return False, "The connected Apple Ads account no longer exists. Connect it again."
+
return validate_apple_search_ads_credentials(
self._credentials(config),
- self.resolve_api_version(api_version),
+ resolved_version,
schema_name,
+ token_provider=token_provider,
)
def get_credential_accounts(
self, config: AppleSearchAdsSourceConfig, team_id: int, api_version: str | None = None
) -> list[IntegrationAccount]:
- """The ad accounts the entered credentials can read.
+ """The ad accounts this source's credentials can read.
- Only the Platform API scopes on an ad account; a source pinned to the older Campaign
- Management API takes an organization ID, which Apple does show in its UI, so there is
- nothing to list.
+ Serves both auth branches: a connected Apple Ads account reaches the ACL endpoint with its
+ own bearer token, a typed-in key pair signs one. Only the Platform API scopes on an ad
+ account; a source pinned to the older Campaign Management API takes an organization ID,
+ which Apple does show in its UI, so there is nothing to list.
"""
resolved_version = self.resolve_api_version(api_version)
# Checked before authenticating: a token exchange to then list nothing still spends the
@@ -286,7 +388,14 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
if resolved_version != APPLE_ADS_API_VERSION_V1:
return []
- client = AppleSearchAdsClient(self._credentials(config), resolved_version)
+ try:
+ token_provider = self._token_provider(config, team_id)
+ except ValueError as e:
+ raise IntegrationAccountListingError(
+ "The connected Apple Ads account no longer exists. Connect it again."
+ ) from e
+
+ client = AppleSearchAdsClient(self._credentials(config), resolved_version, token_provider=token_provider)
try:
client.authenticate()
except AppleSearchAdsAuthError as e:
@@ -321,15 +430,41 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value,
start_date=config.start_date,
+ token_provider=self._token_provider(config, inputs.team_id),
)
+ @staticmethod
+ def _uses_oauth(config: AppleSearchAdsSourceConfig) -> bool:
+ """Whether this source authenticates through an Apple Ads grant rather than a key pair.
+
+ The stored integration id is the test, not `auth_method.selection`. Migration 0172 names
+ the branch on every source that predates the sign-in path, but a source holds its key
+ material flat until that migration runs, and a flat source parses with the branch's
+ generated default, which is the sign-in option.
+ """
+ return bool(config.auth_method.apple_ads_integration_id)
+
+ def _token_provider(self, config: AppleSearchAdsSourceConfig, team_id: int) -> Optional[Callable[[], str]]:
+ """Bearer-token source for the client, or None to let it sign one from the key pair."""
+ if not self._uses_oauth(config):
+ return None
+
+ integration_id = config.auth_method.apple_ads_integration_id
+ assert integration_id is not None
+ integration = self.get_oauth_integration(integration_id, team_id)
+ if integration.kind != "apple-ads":
+ raise ValueError(f"Integration {integration_id} is not an Apple Ads integration")
+ # Resolved per call, not once: Apple's access tokens live an hour, which a backfill
+ # routinely outlives, and the client re-authenticates on a 401.
+ return lambda: apple_ads_access_token(integration)
+
@staticmethod
def _credentials(config: AppleSearchAdsSourceConfig) -> AppleSearchAdsCredentials:
return AppleSearchAdsCredentials(
- client_id=config.client_id,
- team_id=config.apple_team_id,
- key_id=config.key_id,
- private_key=config.private_key,
+ client_id=config.auth_method.client_id or "",
+ team_id=config.auth_method.apple_team_id or "",
+ key_id=config.auth_method.key_id or "",
+ private_key=config.auth_method.private_key or "",
org_id=config.org_id,
ad_account_id=config.ad_account_id,
)
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.py
index 9cafca86706a..4fe8eb59add7 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
@@ -9,7 +9,7 @@ from parameterized import parameterized
from products.warehouse_sources.backend.facade.source_config import (
SourceFieldCredentialAccountSelectConfig,
- SourceFieldInputConfig,
+ SourceFieldSelectConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
AppleAdAccount,
@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.int
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applesearchads import (
+ AppleSearchAdsAuthMethodConfig,
AppleSearchAdsSourceConfig,
)
@@ -45,18 +46,30 @@ REPORT_ENDPOINTS = tuple(name for name, config in _PLATFORM_ENDPOINTS.items() if
ENTITY_ENDPOINTS = tuple(name for name, config in _PLATFORM_ENDPOINTS.items() if not config.partition_key)
+def key_pair_config(**overrides: Any) -> AppleSearchAdsSourceConfig:
+ fields: dict[str, Any] = {"ad_account_id": "123456789", "start_date": "2026-06-01", **overrides}
+ auth_method = fields.pop("auth_method", None) or AppleSearchAdsAuthMethodConfig(
+ selection="key_pair",
+ client_id="SEARCHADS.client",
+ apple_team_id="SEARCHADS.team",
+ key_id="key-1",
+ private_key="-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----",
+ )
+ return AppleSearchAdsSourceConfig(auth_method=auth_method, **fields)
+
+
+def oauth_config(integration_id: int = 77, **overrides: Any) -> AppleSearchAdsSourceConfig:
+ return key_pair_config(
+ auth_method=AppleSearchAdsAuthMethodConfig(selection="oauth", apple_ads_integration_id=integration_id),
+ **overrides,
+ )
+
+
class TestAppleSearchAdsSource:
def setup_method(self) -> None:
self.source = AppleSearchAdsSource()
self.team_id = 123
- self.config = AppleSearchAdsSourceConfig(
- client_id="SEARCHADS.client",
- apple_team_id="SEARCHADS.team",
- key_id="key-1",
- private_key="-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----",
- ad_account_id="123456789",
- start_date="2026-06-01",
- )
+ self.config = key_pair_config()
def test_api_version_metadata(self) -> None:
assert self.source.supported_versions == (APPLE_SEARCH_ADS_API_VERSION_V5, APPLE_ADS_API_VERSION_V1)
@@ -183,51 +196,158 @@ class TestAppleSearchAdsSource:
def test_both_context_ids_reach_the_credentials(self) -> None:
# Which one a sync needs follows the version pin, so the form collects either and the
# request layer picks.
- config = AppleSearchAdsSourceConfig(
- client_id="SEARCHADS.client",
- apple_team_id="SEARCHADS.team",
- key_id="key-1",
- private_key="pem",
- ad_account_id="123456789",
- org_id="555",
- )
+ config = key_pair_config(org_id="555")
credentials = self.source._credentials(config)
assert (credentials.ad_account_id, credentials.org_id) == ("123456789", "555")
- def test_the_field_caption_and_step_five_describe_the_same_flow(self) -> None:
+ def test_the_field_caption_and_the_setup_steps_describe_the_same_flow(self) -> None:
# Two surfaces describe how someone gets their ad account id, and nothing renders them
# together, so one can be rewritten while the other keeps naming a flow that is gone.
config = self.source.get_source_config
- field_caption = next(
- field.caption
- for field in config.fields
- if isinstance(field, SourceFieldCredentialAccountSelectConfig) and field.name == "ad_account_id"
- )
- assert field_caption is not None
+ field = next(f for f in config.fields if f.name == "ad_account_id")
+ assert isinstance(field, SourceFieldCredentialAccountSelectConfig)
+ 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):
- # Both name the picker and the manual fallback, and neither still tells anyone to
- # connect with the field blank.
- assert "list" in text
- assert "v1/acls" in text
- assert "blank" not in text
+ # The field names both ways of filling it, the manual fallback, and never tells anyone to
+ # connect with it blank.
+ assert "Connect your account" in field.caption
+ assert "fill in the credentials" in field.caption
+ assert "v1/acls" in field.caption
+ assert "blank" not in field.caption
+ # The setup steps still name the signed-in path as the one that fills the list.
+ assert "Sign in with Apple" in config.caption
+ assert "**Ad account** list" in config.caption
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.
- fields = {
- field.name: field
- for field in self.source.get_source_config.fields
- if isinstance(field, SourceFieldInputConfig | SourceFieldCredentialAccountSelectConfig)
- }
+ fields: dict[str, Any] = {field.name: field for field in self.source.get_source_config.fields}
assert fields["ad_account_id"].required is False
assert fields["org_id"].required is False
+ def test_the_connect_form_defaults_to_signing_in_with_apple(self) -> None:
+ # Signing in is the path that asks a customer for nothing, so a reordering or a changed
+ # default must not quietly put everyone back on generating a key pair.
+ fields: dict[str, Any] = {field.name: field for field in self.source.get_source_config.fields}
+ auth_method = fields["auth_method"]
+
+ assert isinstance(auth_method, SourceFieldSelectConfig)
+ assert auth_method.defaultValue == "oauth"
+ assert [option.value for option in auth_method.options] == ["oauth", "key_pair"]
+ assert [field.name for field in auth_method.options[0].fields or []] == ["apple_ads_integration_id"]
+
+ def test_the_ad_account_picker_serves_both_auth_branches(self) -> None:
+ # The picker fills from whichever branch the form holds. Dropping either source leaves
+ # that branch's users typing an ad account id Apple shows nowhere in its UI.
+ field = next(f for f in self.source.get_source_config.fields if f.name == "ad_account_id")
+
+ assert isinstance(field, SourceFieldCredentialAccountSelectConfig)
+ assert field.integrationField == "apple_ads_integration_id"
+ assert field.credentialFields == ["client_id", "apple_team_id", "key_id", "private_key"]
+
+ @parameterized.expand([("generated_default", "oauth"), ("stored_branch", "key_pair")])
+ def test_a_source_holding_key_material_keeps_using_it(self, _name: str, selection: Any) -> None:
+ # Migration 0172 names the branch, but a source holds its key material flat until that
+ # migration runs, and a flat source parses with the branch's generated default. Routing it
+ # down the OAuth path on that default alone would break every pre-existing Apple Ads sync.
+ config = key_pair_config(
+ auth_method=AppleSearchAdsAuthMethodConfig(
+ selection=selection,
+ client_id="SEARCHADS.client",
+ apple_team_id="SEARCHADS.team",
+ key_id="key-1",
+ private_key="pem",
+ )
+ )
+
+ assert self.source._token_provider(config, self.team_id) is None
+ assert self.source._credentials(config).private_key == "pem"
+
+ def test_source_for_pipeline_hands_the_grants_token_to_the_client(self) -> None:
+ # Without a token provider the client falls back to signing an assertion from key
+ # material a signed-in source never holds, and every request 400s at Apple's token endpoint.
+ inputs = mock.MagicMock()
+ inputs.schema_name = "campaigns"
+ inputs.api_version = None
+ inputs.team_id = self.team_id
+ integration = mock.MagicMock()
+ integration.kind = "apple-ads"
+
+ with (
+ mock.patch.object(AppleSearchAdsSource, "get_oauth_integration", return_value=integration),
+ mock.patch(f"{SOURCE_MODULE}.apple_ads_access_token", return_value="bearer-1") as mock_token,
+ mock.patch(f"{SOURCE_MODULE}.apple_search_ads_source") as mock_source,
+ ):
+ self.source.source_for_pipeline(oauth_config(), mock.MagicMock(), inputs)
+ provider = cast("dict[str, Any]", mock_source.call_args.kwargs)["token_provider"]
+ assert provider is not None
+ assert provider() == "bearer-1"
+
+ mock_token.assert_called_once_with(integration)
+
+ def test_credential_accounts_list_through_the_connected_account(self) -> None:
+ # The picker is the only place an ad account id comes from, and a signed-in source has no
+ # key pair to sign an assertion with, so it has to reach Apple with the grant's own token.
+ integration = mock.MagicMock()
+ integration.kind = "apple-ads"
+ with (
+ mock.patch.object(AppleSearchAdsSource, "get_oauth_integration", return_value=integration),
+ mock.patch(f"{SOURCE_MODULE}.apple_ads_access_token", return_value="bearer-1"),
+ mock.patch(f"{SOURCE_MODULE}.AppleSearchAdsClient") as mock_client,
+ mock.patch(f"{SOURCE_MODULE}.readable_ad_accounts") as mock_accounts,
+ ):
+ mock_accounts.return_value = [AppleAdAccount(id="1111111", name="Example Retail")]
+
+ accounts = self.source.get_credential_accounts(oauth_config(), self.team_id)
+ assert mock_client.call_args.kwargs["token_provider"]() == "bearer-1"
+
+ assert [(account.value, account.display_name) for account in accounts] == [("1111111", "Example Retail")]
+
+ def test_token_provider_rejects_an_integration_from_another_provider(self) -> None:
+ integration = mock.MagicMock(kind="slack")
+ with mock.patch.object(AppleSearchAdsSource, "get_oauth_integration", return_value=integration):
+ with pytest.raises(ValueError, match="not an Apple Ads integration"):
+ self.source._token_provider(oauth_config(), self.team_id)
+
+ def test_flat_key_pair_config_remains_readable_during_migration(self) -> None:
+ job_inputs = {
+ "client_id": "SEARCHADS.client",
+ "apple_team_id": "SEARCHADS.team",
+ "key_id": "key-1",
+ "private_key": "pem",
+ "ad_account_id": "123456789",
+ }
+
+ valid, errors = self.source.validate_config(job_inputs)
+ config = self.source.parse_config(job_inputs)
+
+ assert valid, errors
+ assert config.auth_method.selection == "key_pair"
+ assert config.auth_method.private_key == "pem"
+ assert self.source.serialize_config(config)["private_key"] == "pem"
+
+ def test_validate_credentials_rejects_a_grant_against_the_retired_api_version(self) -> None:
+ # Apple issues a service provider grant for the Platform API only. A v5-pinned source has
+ # to stay on its own key pair, so accepting one here would connect and then fail on sync.
+ ok, error = self.source.validate_credentials(
+ oauth_config(), self.team_id, api_version=APPLE_SEARCH_ADS_API_VERSION_V5
+ )
+
+ assert ok is False
+ assert error is not None and "Platform API" in error
+
+ def test_validate_credentials_asks_an_unconnected_user_to_sign_in(self) -> None:
+ config = key_pair_config(auth_method=AppleSearchAdsAuthMethodConfig(selection="oauth"))
+
+ ok, error = self.source.validate_credentials(config, self.team_id)
+
+ assert ok is False
+ assert error == "Connect your Apple Ads account, or switch to the API key pair option."
+
def test_credential_accounts_map_apples_acl_onto_the_shared_picker_shape(self) -> None:
# Apple shows the ad account id nowhere in its UI, so the ACL read is the only way a user
# gets one. An account with no name falls back to its id rather than rendering "None".
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index adf1e12bd7c9..92e6e303bd0d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -388,6 +388,10 @@ class _BaseSource(ABC, Generic[ConfigType]):
def validate_config(self, job_inputs: dict) -> tuple[bool, list[str]]:
return self._config_class.validate_dict(job_inputs)
+ def serialize_config(self, config: ConfigType) -> dict[str, Any]:
+ """Serialize parsed config for storage. Sources may retain rollout-compatible fields."""
+ return config.to_dict()
+
@property
def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py
index 6124c5e413f8..2806c3d60ac9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py
@@ -1,15 +1,26 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
+class AppleSearchAdsAuthMethodConfig(config.Config):
+ apple_ads_integration_id: int | None = config.value(
+ converter=config.str_to_optional_int, default_factory=lambda: None
+ )
+ selection: Literal["oauth", "key_pair"] = "oauth"
+ client_id: str | None = None
+ apple_team_id: str | None = None
+ key_id: str | None = None
+ private_key: str | None = None
+
+
@config.config
class AppleSearchAdsSourceConfig(config.Config):
- client_id: str
- apple_team_id: str
- key_id: str
- private_key: str
+ auth_method: AppleSearchAdsAuthMethodConfig
ad_account_id: str | None = None
start_date: str | None = None
org_id: str | None = None
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index edc4f55c0745..026aa4312bd0 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -145,7 +145,14 @@ def _configure_source_mock_versioning(mock_get_source) -> None:
The update path also asks the source whether an edit introduces a new connection host or leaves
row-backed credentials preserved; a bare MagicMock returns truthy for both, which would wrongly
- trip the credential-reentry gate. Stub them to their real (falsy) defaults."""
+ trip the credential-reentry gate. Stub them to their real (falsy) defaults.
+
+ Both the create and update paths persist `source.serialize_config(source_config)` rather than
+ `source_config.to_dict()` directly, so a source stays able to retain rollout-compatible fields
+ (see `AppleSearchAdsSource.serialize_config`). A bare MagicMock's `serialize_config` otherwise
+ returns an unconfigured MagicMock, which Django's ORM then tries to treat as a query expression
+ and rejects. Delegate it to the parsed config's own `to_dict()`, matching the base class's
+ default implementation, so a test that only sets up `parse_config` keeps working."""
mock_get_source.return_value.default_version = "v1"
mock_get_source.return_value.get_version_deprecation.return_value = None
mock_get_source.return_value.max_instances_per_team = None
@@ -154,6 +161,7 @@ def _configure_source_mock_versioning(mock_get_source) -> None:
mock_get_source.return_value.server_managed_job_input_fields.return_value = []
mock_get_source.return_value.job_inputs_add_connection_host.return_value = False
mock_get_source.return_value.has_preserved_row_backed_credentials.return_value = False
+ mock_get_source.return_value.serialize_config.side_effect = lambda config: config.to_dict()
class TestExternalDataSource(APIBaseTest):
@@ -6980,6 +6988,54 @@ class TestExternalDataSource(APIBaseTest):
assert source.job_inputs[secret_field] == stored_job_inputs[secret_field]
assert source.auto_sync_new_schemas is True
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.source.AppleSearchAdsSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_update_apple_ads_key_pair_unrelated_field_does_not_reprobe(self, mock_validate_credentials):
+ # Apple Ads' serialize_config adds the four key-pair fields back onto the flat dict for a
+ # key_pair source, which parse_config().to_dict() alone does not. Comparing those two shapes
+ # always disagreed, so every save re-probed Apple's API — even one that only flips an
+ # unrelated setting. Compare like for like instead: serialize_config on both sides.
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="AppleSearchAds",
+ created_by=self.user,
+ prefix="test_apple_ads_no_reprobe",
+ job_inputs={
+ "source_type": "AppleSearchAds",
+ "org_id": "4242",
+ "ad_account_id": "acct-1",
+ "client_id": "cid",
+ "apple_team_id": "tid",
+ "key_id": "kid",
+ "private_key": "pem",
+ },
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "org_id": "4242",
+ "ad_account_id": "acct-1",
+ "client_id": "cid",
+ "apple_team_id": "tid",
+ "key_id": "kid",
+ "private_key": "pem",
+ },
+ "auto_sync_new_schemas": True,
+ },
+ )
+
+ assert response.status_code == 200, response.json()
+ source.refresh_from_db()
+ assert source.auto_sync_new_schemas is True
+ mock_validate_credentials.assert_not_called()
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.freshdesk.source.FreshdeskSource.validate_credentials",
return_value=(True, None),
diff --git a/products/warehouse_sources/backend/tests/test_migrate_apple_search_ads_job_inputs_to_auth_method.py b/products/warehouse_sources/backend/tests/test_migrate_apple_search_ads_job_inputs_to_auth_method.py
new file mode 100644
index 000000000000..f72643854416
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_migrate_apple_search_ads_job_inputs_to_auth_method.py
@@ -0,0 +1,80 @@
+import importlib
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applesearchads import (
+ AppleSearchAdsSourceConfig,
+)
+
+# The module name starts with a digit, so it cannot be imported with a normal import statement.
+migration = importlib.import_module(
+ "products.warehouse_sources.backend.migrations.0172_migrate_apple_search_ads_job_inputs_to_auth_method"
+)
+
+_KEY_PAIR = {
+ "client_id": "SEARCHADS.client",
+ "apple_team_id": "SEARCHADS.team",
+ "key_id": "key-1",
+ "private_key": "-----BEGIN EC PRIVATE KEY-----\nabc\n-----END EC PRIVATE KEY-----",
+}
+
+
+def test_a_migrated_source_still_reaches_its_key_pair_and_its_ad_account():
+ """A flat source parses either way, because the config parser falls back to a flat read. What
+ the migration changes is the branch: left unset, `selection` lands on its generated default and
+ the edit form opens on Sign in with Apple with the key fields hidden."""
+ migrated = migration.nest_key_pair_under_auth_method(
+ {**_KEY_PAIR, "ad_account_id": "123456789", "start_date": "2026-06-01", "org_id": "555"}
+ )
+ assert migrated is not None
+
+ config = AppleSearchAdsSourceConfig.from_dict(migrated)
+
+ assert config.auth_method.selection == "key_pair"
+ assert config.auth_method.client_id == "SEARCHADS.client"
+ assert config.auth_method.private_key == _KEY_PAIR["private_key"]
+ assert config.auth_method.apple_ads_integration_id is None
+ # Everything outside the credential must stay at the top level. Moving `ad_account_id` into
+ # the branch would leave every existing sync without the id it scopes every request by.
+ assert (config.ad_account_id, config.start_date, config.org_id) == ("123456789", "2026-06-01", "555")
+
+
+def test_the_migration_nests_the_key_pair_without_breaking_old_workers():
+ migrated = migration.nest_key_pair_under_auth_method({**_KEY_PAIR, "ad_account_id": "123456789"})
+
+ assert migrated == {
+ **_KEY_PAIR,
+ "ad_account_id": "123456789",
+ "auth_method": {"selection": "key_pair", **_KEY_PAIR},
+ }
+
+
+ "job_inputs",
+ [
+ {"auth_method": {"selection": "key_pair", **_KEY_PAIR}},
+ {"auth_method": {"selection": "oauth", "apple_ads_integration_id": 77}},
+ ],
+)
+def test_the_migration_leaves_an_already_migrated_source_alone(job_inputs):
+ """The migration can be re-run by a retry, and a second pass must not wrap the branch in
+ another one or overwrite a connected account's credential with empty strings."""
+ assert migration.nest_key_pair_under_auth_method(job_inputs) is None
+
+
+def test_reverse_restores_the_shape_the_previous_release_reads():
+ """A rollback runs the previous release against these rows, and that code reads the four key
+ pair fields from the top level."""
+ flattened = migration.flatten_auth_method_to_key_pair(
+ {**_KEY_PAIR, "auth_method": {"selection": "key_pair", **_KEY_PAIR}, "ad_account_id": "123456789"}
+ )
+
+ assert flattened == {**_KEY_PAIR, "ad_account_id": "123456789"}
+
+
+def test_reverse_leaves_a_connected_account_alone():
+ """Flattening a grant would write an `apple_ads_integration_id` the previous release has no
+ field for, and drop the branch that the next roll-forward needs."""
+ job_inputs = {"auth_method": {"selection": "oauth", "apple_ads_integration_id": 77}}
+
+ assert migration.flatten_auth_method_to_key_pair(job_inputs) is None
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index ef3ba63e57e2..dea45e57b591 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -13946,6 +13946,8 @@ export interface SourceFieldCredentialAccountSelectConfigApi {
caption?: string | null
/** Names of the sibling fields whose values the account listing needs. The form sends exactly these, and the listing endpoint accepts exactly these. */
credentialFields: string[]
+ /** Name of an OAuth integration id field that lists the same accounts, for a source offering both a typed-in credential and a connected account. The form sends this instead of `credentialFields` when it holds a value, and the listing endpoint accepts it on the same allowlist. */
+ integrationField?: string | null
label: string
name: string
placeholder?: string | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1720d2c60dd1..c2860951bc41 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8507,6 +8507,7 @@ export namespace Schemas {
CustomerioWebhook: 'customerio-webhook',
CustomerioTrack: 'customerio-track',
Apns: 'apns',
+ AppleAds: 'apple-ads',
Postgresql: 'postgresql',
AwsS3: 'aws-s3',
AwsRedshift: 'aws-redshift',
@@ -57906,6 +57907,7 @@ export namespace Schemas {
/**
* * `anthropic` - Anthropic
+ * * `apple-ads` - Apple Ads
* * `apns` - Apple Push
* * `aws-redshift` - Aws Redshift
* * `aws-s3` - Aws S3
@@ -57960,6 +57962,7 @@ export namespace Schemas {
export const IntegrationKindEnum = {
Anthropic: 'anthropic',
+ AppleAds: 'apple-ads',
Apns: 'apns',
AwsRedshift: 'aws-redshift',
AwsS3: 'aws-s3',
@@ -58014,6 +58017,7 @@ export namespace Schemas {
/** The kind of integration the member is requesting be connected (e.g. 'slack', 'github').
*
* * `anthropic` - Anthropic
+ * * `apple-ads` - Apple Ads
* * `apns` - Apple Push
* * `aws-redshift` - Aws Redshift
* * `aws-s3` - Aws S3
@@ -97393,6 +97397,8 @@ export namespace Schemas {
caption?: string | null;
/** Names of the sibling fields whose values the account listing needs. The form sends exactly these, and the listing endpoint accepts exactly these. */
credentialFields: string[];
+ /** Name of an OAuth integration id field that lists the same accounts, for a source offering both a typed-in credential and a connected account. The form sends this instead of `credentialFields` when it holds a value, and the listing endpoint accepts it on the same allowlist. */
+ integrationField?: string | null;
label: string;
name: string;
placeholder?: string | null;
@@ -120477,6 +120483,7 @@ export namespace Schemas {
export type IntegrationsListParams = {
/**
* * `anthropic` - Anthropic
+ * * `apple-ads` - Apple Ads
* * `apns` - Apple Push
* * `aws-redshift` - Aws Redshift
* * `aws-s3` - Aws S3
@@ -120543,6 +120550,7 @@ export namespace Schemas {
export const IntegrationsListKind = {
Anthropic: 'anthropic',
Apns: 'apns',
+ AppleAds: 'apple-ads',
AwsRedshift: 'aws-redshift',
AwsS3: 'aws-s3',
AzureBlob: 'azure-blob',
diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.ts
index d6d2eb2c3f56..89932c5bc6dc 100644
--- a/services/mcp/src/generated/integrations/api.ts
+++ b/services/mcp/src/generated/integrations/api.ts
@@ -21,6 +21,7 @@ export const IntegrationsListQueryParams = () => zod.object({
.enum([
'anthropic',
'apns',
+ 'apple-ads',
'aws-redshift',
'aws-s3',
'azure-blob',
@@ -71,7 +72,7 @@ export const IntegrationsListQueryParams = () => zod.object({
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
index b761489d13a0..7edc5805c45d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
@@ -2,10 +2,11 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"kind": {
- "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `helpscout` - Helpscout\n* `hubspot` - Hubspot\n* `instagram` - Instagram\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `twitter-ads` - Twitter Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel\n* `youtube-analytics` - Youtube Analytics",
+ "description": "* `anthropic` - Anthropic\n* `apple-ads` - Apple Ads\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `helpscout` - Helpscout\n* `hubspot` - Hubspot\n* `instagram` - Instagram\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `twitter-ads` - Twitter Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel\n* `youtube-analytics` - Youtube Analytics",
"enum": [
"anthropic",
"apns",
+ "apple-ads",
"aws-redshift",
"aws-s3",
"azure-blob",
diff --git a/share/share b/share/share
new file mode 120000
index 000000000000..ab003ed58404
--- /dev/null
+++ b/share/share
@@ -0,0 +1 @@
+/Users/tomowers/dev/posthog/posthog/share
\ No newline at end of file