:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse): make TikTok Ads OAuth failures visible (#79561)
posthog[bot]0b62b7e0ca5b
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 12f5ff700183..eee69aa95022 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -1197,6 +1197,15 @@ class IntegrationViewSet(auth_url = OauthIntegration.authorize_url(kind, next=next, token=token, region=region, scopes=scopes, team_id=self.team_id)+ # Capture the hand-off to the provider's authorize page. A rejection there (e.g.+ # TikTok's "app has been blocked") never returns to us, so this is the only leg we+ # can record — an authorize start with no matching completion is now countable.+ report_user_action(+ request.user,+ "integration authorize started",+ {"integration_kind": kind},+ team=self.team,+ )response = redirect(auth_url)# nosemgrep: python.django.security.audit.secure-cookies.django-secure-set-cookie (OAuth state, short-lived, needed for cross-site redirect)response.set_cookie("ph_oauth_state", token, max_age=60 * 5)diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 4f8d626fb93d..bf976c1c56c1 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -2191,6 +2191,24 @@ class TestGitHubIntegrationStateValidation:assert response.status_code == status.HTTP_400_BAD_REQUESTassert "next must be a relative path" in response.json()["detail"]+ @override_settings(TIKTOK_ADS_CLIENT_ID="tiktok-app-id", TIKTOK_ADS_CLIENT_SECRET="tiktok-secret")+ @patch("posthog.api.integration.report_user_action")+ def test_oauth_authorize_captures_handoff(self, mock_report, client: HttpClient):+ # An authorize-page rejection (e.g. TikTok's "app has been blocked") never returns to us, so+ # this hand-off event is the only leg we can record for the OAuth-start funnel.+ client.force_login(self.user)++ response = client.get(+ f"/api/environments/{self.team.pk}/integrations/authorize/",+ {"kind": "tiktok-ads"},+ )++ assert response.status_code == status.HTTP_302_FOUND+ assert response["Location"].startswith("https://business-api.tiktok.com/portal/auth")+ mock_report.assert_called_once()+ assert mock_report.call_args.args[1] == "integration authorize started"+ assert mock_report.call_args.args[2] == {"integration_kind": "tiktok-ads"}+@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex a15a28862362..2fda85a85e9d 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -1886,15 +1886,19 @@ class OauthIntegration:timeout=10,)elif kind == "tiktok-ads":+ # Refresh against the Business API app we authorized against, using its app_id/secret and+ # JSON body (mirroring the token exchange). The open.tiktokapis.com/v2 endpoint with+ # client_key belongs to Login Kit — a different TikTok app family whose credentials this+ # integration never holds.return requests.post(- "https://open.tiktokapis.com/v2/oauth/token/",- data={- "client_key": client_id, # TikTok uses client_key instead of client_id- "client_secret": client_secret,+ "https://business-api.tiktok.com/open_api/v1.3/oauth2/refresh_token/",+ json={+ "app_id": client_id,+ "secret": client_secret,"refresh_token": refresh_token,"grant_type": "refresh_token",},- headers={"Content-Type": "application/x-www-form-urlencoded"},+ headers={"Content-Type": "application/json"},timeout=10,)elif kind == "bing-ads":@@ -1943,13 +1947,17 @@ class OauthIntegration:allow_redirects=False,)- @staticmethod- def _parse_token_refresh_response(res: requests.Response) -> dict:+ def _parse_token_refresh_response(self, res: requests.Response) -> dict:try:- return res.json()+ config = res.json()except ValueError:# e.g. an HTML error page from a proxy/5xx - still a failed refresh, not an exceptionreturn {}+ # TikTok Business API nests the refreshed tokens under `data`, same as the token exchange.+ # Lift them to the top level so the generic access_token/refresh_token/expires_in handling reads them.+ if self.integration.kind == "tiktok-ads" and isinstance(config.get("data"), dict):+ config = {**config, **config["data"]}+ return configdef _record_terminal_unreadable_secret(self) -> None:logger.error(diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 73410cd1a228..7a49e5b75c1e 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -311,6 +311,8 @@ class TestOauthIntegrationModel(BaseTest):"GOOGLE_CALENDAR_APP_CLIENT_SECRET": "google-calendar-client-secret","LINKEDIN_APP_CLIENT_ID": "linkedin-client-id","LINKEDIN_APP_CLIENT_SECRET": "linkedin-client-secret",+ "TIKTOK_ADS_CLIENT_ID": "tiktok-app-id",+ "TIKTOK_ADS_CLIENT_SECRET": "tiktok-secret",}def create_integration(@@ -715,6 +717,37 @@ class TestOauthIntegrationModel(BaseTest):assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"assert integration.sensitive_config["refresh_token"] == expected_refresh_token+ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_tiktok_ads_refresh_uses_business_api_and_unwraps_data(self, mock_post, mock_reload):+ # TikTok Business API refreshes against its own endpoint with app_id/secret (JSON) and nests+ # the refreshed tokens under `data` — not the Login Kit client_key/open.tiktokapis.com flow.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "code": 0,+ "data": {"access_token": "REFRESHED_ACCESS_TOKEN", "refresh_token": "ROTATED_REFRESH_TOKEN"},+ }++ integration = self.create_integration(kind="tiktok-ads", config={"expires_in": 1000})++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ mock_post.assert_called_with(+ "https://business-api.tiktok.com/open_api/v1.3/oauth2/refresh_token/",+ json={+ "app_id": "tiktok-app-id",+ "secret": "tiktok-secret",+ "refresh_token": "REFRESH",+ "grant_type": "refresh_token",+ },+ headers={"Content-Type": "application/json"},+ timeout=10,+ )+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"+ assert integration.sensitive_config["refresh_token"] == "ROTATED_REFRESH_TOKEN"+@patch("posthog.models.integration.reload_integrations_on_workers")@patch("posthog.models.integration.requests.post")def test_refresh_access_token_handles_errors(self, mock_post, mock_reload):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.pyindex f50b7281e6b8..72c2b0a56812 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py@@ -99,7 +99,15 @@ class TikTokAdsSource(ResumableSource[TikTokAdsSourceConfig, TikTokAdsResumeConfname=SchemaExternalDataSourceType.TIK_TOK_ADS,category=DataWarehouseSourceCategory.ADVERTISING,label="TikTok Ads",- caption="Collect campaign data, ad performance, and advertising metrics from TikTok Ads. Ensure you have granted PostHog access to your TikTok Ads account, learn how to do this in [the documentation](https://posthog.com/docs/cdp/sources/tiktok-ads).",+ caption=(+ "Collect campaign data, ad performance, and advertising metrics from TikTok Ads. "+ "Ensure you have granted PostHog access to your TikTok Ads account, learn how to do this in "+ "[the documentation](https://posthog.com/docs/cdp/sources/tiktok-ads).\n\n"+ "If TikTok's authorization page rejects the connection before returning to PostHog, this is "+ "usually an account or region restriction on TikTok's side. Check that you have an admin role "+ "in the TikTok Business Center you're connecting, and that TikTok Ads is available in your region. "+ "If it still fails, copy the Log ID from TikTok's error page and contact support."+ ),releaseStatus=ReleaseStatus.GA,iconPath="/static/services/tiktok.png",docsUrl="https://posthog.com/docs/cdp/sources/tiktok-ads",