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): backend-driven account picker for snapchat ads (#70197)

Javier Bahamondesf9e8ae0673a1
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 19ae33655227..14409ce9f3cf 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -11520,6 +11520,7 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
)
_REDDIT_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.source"
_LINKEDIN_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source"
+ _SNAPCHAT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.source"
_META_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.source"
def setUp(self):
@@ -11610,6 +11611,73 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
response = self.client.get(self._url("Salesforce", 1))
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ def _snapchat_integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="snapchat",
+ config={},
+ sensitive_config={"access_token": "token"},
+ integration_id="snapchat_test",
+ created_by=self.user,
+ )
+
+ def test_snapchat_maps_accounts_grouped_by_organization(self):
+ integration = self._snapchat_integration()
+ listed = [
+ ({"id": "acc-1", "name": "PostHog Self Service", "status": "PENDING"}, "PostHog"),
+ ({"id": "acc-2", "name": "PostHog", "status": "ACTIVE"}, "PostHog"),
+ ]
+ with (
+ patch(f"{self._SNAPCHAT_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._SNAPCHAT_MODULE}.list_ad_accounts", return_value=listed),
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = False
+ response = self.client.get(self._url("SnapchatAds", integration.id))
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["accounts"] == [
+ {
+ "value": "acc-1",
+ "display_name": "PostHog Self Service",
+ "is_primary": False,
+ "badges": ["Pending"],
+ "group": "PostHog",
+ "secondary_text": None,
+ },
+ {
+ "value": "acc-2",
+ "display_name": "PostHog",
+ "is_primary": False,
+ "badges": ["Active"],
+ "group": "PostHog",
+ "secondary_text": None,
+ },
+ ]
+
+ @parameterized.expand([(401,), (403,)])
+ def test_snapchat_auth_error_returns_actionable_400(self, status_code: int):
+ integration = self._snapchat_integration()
+ with (
+ patch(f"{self._SNAPCHAT_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._SNAPCHAT_MODULE}.list_ad_accounts", side_effect=self._http_error(status_code)),
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = False
+ response = self.client.get(self._url("SnapchatAds", integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "reconnect your snapchat ads" in str(response.json()).lower()
+
+ def test_snapchat_non_auth_api_error_is_not_swallowed(self):
+ integration = self._snapchat_integration()
+ with (
+ patch(f"{self._SNAPCHAT_MODULE}.OauthIntegration") as mock_oauth,
+ patch(f"{self._SNAPCHAT_MODULE}.list_ad_accounts", side_effect=self._http_error(500)),
+ ):
+ mock_oauth.return_value.access_token_expired.return_value = False
+ response = self.client.get(self._url("SnapchatAds", integration.id))
+
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content
+
def _reddit_integration(self, **kwargs) -> Integration:
return Integration.objects.create(
**{
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py
index f75cfcd0256c..f0749368d857 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py
@@ -1,17 +1,19 @@
from typing import Optional, cast
+import requests
+
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
ReleaseStatus,
SourceConfig,
- SourceFieldInputConfig,
- SourceFieldInputConfigType,
+ SourceFieldOauthAccountSelectConfig,
SourceFieldOauthConfig,
SuggestedTable,
)
from posthog.exceptions_capture import capture_exception
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, OauthIntegration
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
SourceInputs,
@@ -25,6 +27,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import 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
@@ -35,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_a
SnapchatResumeConfig,
snapchat_ads_source,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.utils import list_ad_accounts
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -80,20 +87,19 @@ class SnapchatAdsSource(ResumableSource[SnapchatAdsSourceConfig, SnapchatResumeC
fields=cast(
list[FieldType],
[
- SourceFieldInputConfig(
- name="ad_account_id",
- label="Snapchat Ads Ad Account ID",
- type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="Your Snapchat Ads ad account ID",
- secret=False,
- ),
SourceFieldOauthConfig(
name="snapchat_integration_id",
label="Snapchat Ads account",
required=True,
kind="snapchat",
),
+ SourceFieldOauthAccountSelectConfig(
+ name="ad_account_id",
+ label="Snapchat Ads Ad Account ID",
+ integrationField="snapchat_integration_id",
+ integrationKind="snapchat",
+ required=True,
+ ),
],
),
suggestedTables=[
@@ -108,6 +114,48 @@ class SnapchatAdsSource(ResumableSource[SnapchatAdsSourceConfig, SnapchatResumeC
],
)
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> list[IntegrationAccount]:
+ # Snapchat ad accounts are few, so `search` is ignored here and the endpoint filters the list.
+ try:
+ integration = self.get_oauth_integration(integration_id, team_id)
+ except ValueError as e:
+ raise IntegrationAccountListingError(
+ "The linked Snapchat Ads integration could not be found. "
+ "Please reconnect your Snapchat Ads integration."
+ ) from e
+
+ oauth = OauthIntegration(integration)
+ if integration.errors != ERROR_TOKEN_REFRESH_FAILED and oauth.access_token_expired():
+ oauth.refresh_access_token()
+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED or not integration.access_token:
+ raise IntegrationAccountListingError(
+ "Could not refresh the Snapchat Ads credentials. Please reconnect your Snapchat Ads integration."
+ )
+
+ try:
+ accounts = list_ad_accounts(integration.access_token)
+ except requests.HTTPError as e:
+ status_code = e.response.status_code if e.response is not None else None
+ if status_code not in (401, 403):
+ # Not a credential problem the user can fix — surface it.
+ raise
+ raise IntegrationAccountListingError(
+ "Snapchat rejected the credentials for this integration. Please reconnect your Snapchat Ads "
+ "integration and make sure the connected account can access your ad accounts."
+ ) from e
+
+ return [
+ IntegrationAccount(
+ value=account["id"],
+ display_name=account.get("name") or "Unnamed account",
+ badges=(account["status"].capitalize(),) if account.get("status") else (),
+ group=organization_name,
+ )
+ for account, organization_name in accounts
+ ]
+
def validate_credentials(
self, config: SnapchatAdsSourceConfig, team_id: int, schema_name: Optional[str] = None
) -> tuple[bool, str | None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py
index caf1ae1d3e2c..3f201bca003d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py
@@ -2,10 +2,14 @@ from collections.abc import Callable, Iterator
from datetime import datetime
from typing import Any, Optional
+import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.snapchat_ads import (
SnapchatResumeConfig,
@@ -13,8 +17,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_a
)
from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.source import SnapchatAdsSource
from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.utils import (
+ AD_ACCOUNTS_PAGE_LIMIT,
+ MAX_AD_ACCOUNT_PAGES,
SnapchatDateRangeManager,
format_stats_day_boundary,
+ list_ad_accounts,
)
@@ -408,3 +415,165 @@ class TestNonRetryableErrors:
assert not any(pattern in error_msg for pattern in self._patterns), (
f"Snapchat error '{error_msg}' should remain retryable"
)
+
+
+class TestListAdAccounts:
+ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.utils"
+
+ def test_flattens_accounts_and_pairs_with_organization_name(self) -> None:
+ body = {
+ "organizations": [
+ {
+ "sub_request_status": "SUCCESS",
+ "organization": {
+ "name": "PostHog",
+ "ad_accounts": [
+ {"id": "acc-1", "name": "PostHog Self Service", "status": "PENDING"},
+ {"id": "acc-2", "name": "PostHog", "status": "ACTIVE"},
+ ],
+ },
+ },
+ # A failed sub-request contributes no accounts.
+ {"sub_request_status": "ERROR", "organization": {"name": "Broken", "ad_accounts": [{"id": "x"}]}},
+ ]
+ }
+ response = MagicMock()
+ response.json.return_value = body
+ session = MagicMock()
+ session.get.return_value = response
+
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ result = list_ad_accounts("token")
+
+ assert [(account["id"], org_name) for account, org_name in result] == [
+ ("acc-1", "PostHog"),
+ ("acc-2", "PostHog"),
+ ]
+ assert session.get.call_args.kwargs["params"] == {
+ "with_ad_accounts": "true",
+ "limit": AD_ACCOUNTS_PAGE_LIMIT,
+ }
+
+ @staticmethod
+ def _organizations_page(name: str, account_id: str, next_link: str | None = None) -> dict:
+ page: dict = {
+ "request_status": "SUCCESS",
+ "organizations": [
+ {
+ "sub_request_status": "SUCCESS",
+ "organization": {"name": name, "ad_accounts": [{"id": account_id, "name": account_id}]},
+ }
+ ],
+ }
+ if next_link:
+ page["paging"] = {"next_link": next_link}
+ return page
+
+ def _session_returning(self, *bodies: dict) -> MagicMock:
+ responses = []
+ for body in bodies:
+ response = MagicMock()
+ response.json.return_value = body
+ responses.append(response)
+ session = MagicMock()
+ session.get.side_effect = responses
+ return session
+
+ def test_follows_next_link_until_exhausted(self) -> None:
+ # A single page would silently truncate the picker for an org with more accounts than fit
+ # in one page — the user's account just wouldn't be there, with no error.
+ next_link = "https://adsapi.snapchat.com/v1/me/organizations?with_ad_accounts=true&cursor=page-2"
+ session = self._session_returning(
+ self._organizations_page("PostHog", "acc-1", next_link=next_link),
+ self._organizations_page("Agency", "acc-2"),
+ )
+
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ result = list_ad_accounts("token")
+
+ assert [(account["id"], org_name) for account, org_name in result] == [
+ ("acc-1", "PostHog"),
+ ("acc-2", "Agency"),
+ ]
+ assert session.get.call_count == 2
+ # The second request follows next_link verbatim: it already carries the cursor and the query.
+ assert session.get.call_args_list[1].args[0] == next_link
+ assert session.get.call_args_list[1].kwargs["params"] is None
+
+ def test_in_body_failure_raises_actionable_error(self) -> None:
+ # A 200 whose body reports failure would otherwise fall through to an empty picker.
+ session = self._session_returning(
+ {"request_status": "ERROR", "debug_message": "Invalid scope", "display_message": "Something went wrong"}
+ )
+
+ with (
+ patch(f"{self._MODULE}.make_tracked_session", return_value=session),
+ pytest.raises(IntegrationAccountListingError, match="Invalid scope"),
+ ):
+ list_ad_accounts("token")
+
+ def test_all_organizations_failing_raises_instead_of_returning_empty(self) -> None:
+ session = self._session_returning(
+ {
+ "request_status": "SUCCESS",
+ "organizations": [
+ {"sub_request_status": "ERROR", "organization": {"name": "Broken", "ad_accounts": []}}
+ ],
+ }
+ )
+
+ with (
+ patch(f"{self._MODULE}.make_tracked_session", return_value=session),
+ pytest.raises(IntegrationAccountListingError),
+ ):
+ list_ad_accounts("token")
+
+ def test_no_organizations_returns_empty_list(self) -> None:
+ session = self._session_returning({"request_status": "SUCCESS", "organizations": []})
+
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ assert list_ad_accounts("token") == []
+
+ def test_page_cap_raises_instead_of_returning_partial(self) -> None:
+ # A looping/oversized next_link must fail closed rather than return the accounts collected so
+ # far as if complete — that would silently present a truncated (or cursor-duplicated) picker.
+ response = MagicMock()
+ response.json.return_value = self._organizations_page(
+ "PostHog", "acc-1", next_link="https://adsapi.snapchat.com/v1/me/organizations?cursor=loop"
+ )
+ session = MagicMock()
+ session.get.return_value = response
+
+ with (
+ patch(f"{self._MODULE}.make_tracked_session", return_value=session),
+ pytest.raises(IntegrationAccountListingError, match="too many pages"),
+ ):
+ list_ad_accounts("token")
+
+ assert session.get.call_count == MAX_AD_ACCOUNT_PAGES
+
+ @parameterized.expand(
+ [
+ ("cross_origin_host", "https://evil.example.com/v1/me/organizations?with_ad_accounts=true&cursor=page-2"),
+ (
+ "non_https_same_host",
+ "http://adsapi.snapchat.com/v1/me/organizations?with_ad_accounts=true&cursor=page-2",
+ ),
+ ]
+ )
+ def test_rejects_untrusted_pagination_link_without_following_it(self, _name: str, next_link: str) -> None:
+ # The bearer token rides on each pagination request, so a next_link off Snapchat's HTTPS API
+ # host must be rejected before we re-attach the token to it.
+ session = self._session_returning(
+ self._organizations_page("PostHog", "acc-1", next_link=next_link),
+ self._organizations_page("Agency", "acc-2"),
+ )
+
+ with (
+ patch(f"{self._MODULE}.make_tracked_session", return_value=session),
+ pytest.raises(IntegrationAccountListingError),
+ ):
+ list_ad_accounts("token")
+
+ # The token-bearing request to the untrusted host is never made.
+ assert session.get.call_count == 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py
index 411e76ed6f11..7eda176f2985 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py
@@ -2,6 +2,7 @@ import copy
from collections.abc import Iterable
from datetime import date, datetime, timedelta
from typing import Any, Optional
+from urllib.parse import urlsplit
from zoneinfo import ZoneInfo
import structlog
@@ -10,6 +11,9 @@ from requests import Request, Response
from requests.exceptions import HTTPError, RequestException, Timeout
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.settings import (
BASE_URL,
@@ -26,6 +30,96 @@ SNAPCHAT_DATE_FORMAT = "%Y-%m-%dT00:00:00"
RETRYABLE_STATUS_CODES = [429, 500, 503]
+AD_ACCOUNTS_PAGE_LIMIT = 50
+# Guards against a malformed/looping `next_link`; far above any real org count.
+MAX_AD_ACCOUNT_PAGES = 100
+
+# Every pagination request carries the bearer token, so we only ever follow a `next_link`
+# that stays on Snapchat's API host over HTTPS.
+_EXPECTED_API_HOST = urlsplit(BASE_URL).hostname
+
+
+def _validate_pagination_url(url: str) -> None:
+ """Reject a `next_link` that isn't HTTPS on Snapchat's API host.
+
+ Each pagination request attaches the OAuth bearer token, so a cross-origin
+ `next_link` would leak it to another host. Defense-in-depth behind the egress
+ proxy: fail closed rather than follow an unexpected origin.
+ """
+ parts = urlsplit(url)
+ if parts.scheme != "https" or parts.hostname != _EXPECTED_API_HOST:
+ raise IntegrationAccountListingError(
+ "Snapchat returned an unexpected pagination link while listing ad accounts. Please try again."
+ )
+
+
+def _raise_for_in_body_failure(body: dict) -> None:
+ """Snapchat can report failure in a 200 body via `request_status`, so `raise_for_status()` alone
+ would let it through and leave the user with a silently empty picker."""
+ request_status = body.get("request_status")
+ if request_status is None or request_status == "SUCCESS":
+ return
+ message = body.get("debug_message") or body.get("display_message") or "Unknown API error"
+ raise IntegrationAccountListingError(f"Snapchat could not list your ad accounts: {message}")
+
+
+def list_ad_accounts(access_token: str) -> list[tuple[dict, str | None]]:
+ """Snapchat nests them: `organizations[].organization.ad_accounts[]`, with a per-organization
+ `sub_request_status` we skip unless it succeeded.
+ """
+ session = make_tracked_session(allow_redirects=False)
+ url = f"{BASE_URL}/me/organizations"
+ params: dict | None = {"with_ad_accounts": "true", "limit": AD_ACCOUNTS_PAGE_LIMIT}
+
+ accounts: list[tuple[dict, str | None]] = []
+ saw_organization = False
+ saw_successful_organization = False
+
+ for _ in range(MAX_AD_ACCOUNT_PAGES):
+ response = session.get(
+ url,
+ headers={"Authorization": f"Bearer {access_token}"},
+ params=params,
+ timeout=30,
+ )
+ response.raise_for_status()
+ body = response.json()
+ _raise_for_in_body_failure(body)
+
+ for wrapper in body.get("organizations") or []:
+ saw_organization = True
+ if wrapper.get("sub_request_status") != "SUCCESS":
+ continue
+ saw_successful_organization = True
+ organization = wrapper.get("organization") or {}
+ organization_name = organization.get("name")
+ for account in organization.get("ad_accounts") or []:
+ accounts.append((account, organization_name))
+
+ next_link = (body.get("paging") or {}).get("next_link")
+ if not next_link:
+ break
+ # next_link is an absolute URL that already carries the cursor and the original query.
+ # Validate its origin before re-attaching the bearer token to it.
+ _validate_pagination_url(next_link)
+ url, params = next_link, None
+ else:
+ # Hitting the cap means a looping/oversized result set; returning the accounts gathered so
+ # far would silently present a truncated (or cursor-duplicated) picker as complete.
+ raise IntegrationAccountListingError(
+ "Snapchat returned too many pages while listing ad accounts. Please try again."
+ )
+
+ if saw_organization and not saw_successful_organization:
+ # Every org failed, so an empty list here means "we couldn't read them", not "you have none".
+ raise IntegrationAccountListingError(
+ "Snapchat could not return the ad accounts for any of your organizations. "
+ "Please make sure the connected account can access them and try again."
+ )
+
+ return accounts
+
+
def fetch_account_metadata(ad_account_id: str, access_token: str) -> tuple[str | None, str | None]:
"""Fetch the currency and timezone configured on the Snapchat ad account.