: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(data-warehouse): backend-driven account picker for linkedin ads (#69817)
Javier Bahamondes2f61ff44d48e
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 6cb78d0dc8ff..680fdb3da997 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -45,6 +45,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.event_usage import EventSource, get_event_source, report_user_actionfrom posthog.exceptions_capture import capture_exception+from posthog.models.integration import Integrationfrom posthog.models.user import Userfrom posthog.permissions import (AccessControlPermission,@@ -240,6 +241,30 @@ def get_sensitive_field_names(fields: list[FieldType]) -> set[str]:return sensitive+def get_oauth_integration_kinds(fields: list[FieldType]) -> set[str]:+ """The integration kinds a source connects with, declared by its `oauth` fields (`kind`) and its+ `oauth-account-select` fields (`integrationKind`). Every OAuth account listing is served by one+ endpoint that takes an integration id from the caller, so this is what the endpoint checks that id+ against — a Google integration id must not be able to route its token into the LinkedIn Ads client+ just because both rows belong to the caller's team.++ Both field types are read because a source can list accounts without rendering a picker: GitHub+ serves repositories to its own component off a plain `oauth` field."""+ kinds: set[str] = set()+ for field in fields:+ if isinstance(field, SourceFieldOauthAccountSelectConfig):+ kinds.add(field.integrationKind)+ elif isinstance(field, SourceFieldOauthConfig):+ kinds.add(field.kind)+ elif isinstance(field, SourceFieldSwitchGroupConfig):+ kinds.update(get_oauth_integration_kinds(field.fields))+ elif isinstance(field, SourceFieldSelectConfig):+ for option in field.options:+ if option.fields:+ kinds.update(get_oauth_integration_kinds(option.fields))+ return kinds++def _add_name_variants(target: set[str], name: str) -> None:"""Add a field name and its underscore variant to a set.@@ -1844,6 +1869,23 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif not isinstance(source, OAuthMixin):raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")+ # The integration id is caller-supplied and each source looks it up by (id, team_id) only, so+ # without this a same-team integration of a different provider would be accepted here and its+ # OAuth token handed to this source's provider. Pin it to the kind(s) the source's picker+ # declares before any of that runs.+ expected_kinds = get_oauth_integration_kinds(source.get_source_config.fields)+ if not expected_kinds:+ raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")+ if not Integration.objects.filter(+ id=integration_id_int, team_id=self.team_id, kind__in=expected_kinds+ ).exists():+ # One message for "gone" and "wrong kind" alike: from the UI both mean the picker is holding+ # a connection this source can't use, and neither tells the caller anything about ids it+ # isn't already allowed to see.+ raise ValidationError(+ f"No {source_type} connection was found for this integration. Please reconnect the integration."+ )+cache_key = f"oauth_accounts/{self.team_id}/{source_type}/{integration_id_int}/{search or ''}"cached = cache.get(cache_key)if cached is not None: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.pyindex 01902688c8de..1a5587f3179d 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@@ -70,6 +70,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.custom.souManifestValidationError,PreviewResult,)+from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client import LinkedinAdsApiErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (PostgresDiscoveredSchema,@@ -10866,6 +10867,7 @@ class TestOAuthAccountsEndpoint(APIBaseTest):_BING_LIST_ACCOUNTS = ("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.BingAdsClient.list_accounts")+ _LINKEDIN_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source"def setUp(self):super().setUp()@@ -10890,6 +10892,16 @@ class TestOAuthAccountsEndpoint(APIBaseTest):created_by=self.user,)+ def _linkedin_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="linkedin-ads",+ config={},+ sensitive_config={"access_token": "token"},+ integration_id="linkedin_test",+ created_by=self.user,+ )+def _gsc_integration(self) -> Integration:return Integration.objects.create(team=self.team,@@ -11006,6 +11018,70 @@ class TestOAuthAccountsEndpoint(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUEST, response.contentassert "reconnect your account" in str(response.json()).lower()+ def test_linkedin_success_maps_ad_accounts_to_accounts(self):+ integration = self._linkedin_integration()+ client = MagicMock()+ client.get_accounts.return_value = [{"id": 5123, "name": "Acme Ads", "status": "ACTIVE"}]+ with patch(f"{self._LINKEDIN_MODULE}.linkedin_ads_client_for_integration", return_value=client):+ response = self.client.get(self._url("LinkedinAds", integration.id))++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json()["accounts"] == [+ {+ "value": "5123",+ "display_name": "Acme Ads",+ "is_primary": False,+ "badges": ["ACTIVE"],+ "group": None,+ "secondary_text": None,+ }+ ]++ @parameterized.expand([(401,), (403,)])+ def test_linkedin_auth_error_returns_actionable_400(self, status_code: int):+ integration = self._linkedin_integration()+ client = MagicMock()+ client.get_accounts.side_effect = LinkedinAdsApiError(f"LinkedIn API error ({status_code}): nope", status_code)+ with patch(f"{self._LINKEDIN_MODULE}.linkedin_ads_client_for_integration", return_value=client):+ response = self.client.get(self._url("LinkedinAds", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "re-authorize" in str(response.json()).lower()++ def test_linkedin_non_auth_api_error_is_not_swallowed(self):+ integration = self._linkedin_integration()+ client = MagicMock()+ client.get_accounts.side_effect = LinkedinAdsApiError("LinkedIn API error (400): bad", 400)+ with patch(f"{self._LINKEDIN_MODULE}.linkedin_ads_client_for_integration", return_value=client):+ response = self.client.get(self._url("LinkedinAds", integration.id))++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content++ def test_integration_of_another_kind_is_rejected(self):+ # Same team, so the (id, team_id) lookup each source does would accept it: only the kind check+ # stops this Bing token from being sent to LinkedIn's API.+ integration = self._bing_integration()+ with patch(f"{self._LINKEDIN_MODULE}.linkedin_ads_client_for_integration") as client_for_integration:+ response = self.client.get(self._url("LinkedinAds", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ client_for_integration.assert_not_called()++ def test_integration_from_another_team_is_rejected(self):+ other_team = Team.objects.create(organization=self.organization)+ integration = Integration.objects.create(+ team=other_team,+ kind="linkedin-ads",+ config={},+ sensitive_config={"access_token": "token"},+ integration_id="linkedin_other_team",+ )+ with patch(f"{self._LINKEDIN_MODULE}.linkedin_ads_client_for_integration") as client_for_integration:+ response = self.client.get(self._url("LinkedinAds", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ client_for_integration.assert_not_called()+@override_settings(BING_ADS_DEVELOPER_TOKEN="dev_token")def test_bing_success_returns_accounts(self):integration = self._bing_integration()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.pyindex 4e7b0aba5b6a..5db76680f1bd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py@@ -69,6 +69,18 @@ class LinkedinAdsDailyRateLimitError(Exception):"""+class LinkedinAdsApiError(Exception):+ """A non-retryable LinkedIn API response.++ Not named `status_code`: drf-exceptions-hog reads that attribute off any escaping exception and+ would render LinkedIn's status as PostHog's HTTP response status.+ """++ def __init__(self, message: str, api_status_code: int) -> None:+ super().__init__(message)+ self.api_status_code = api_status_code++def _parse_retry_after(response: Any) -> float | None:"""Pull a numeric Retry-After (seconds) off the underlying requests.Response, if present.LinkedIn sends integer seconds; HTTP-date forms and negative/garbage values are ignored@@ -115,8 +127,15 @@ class LinkedinAdsClient:self.api_version = API_VERSIONdef get_accounts(self) -> list[dict[str, Any]]:- """Get ad accounts."""- return self._make_request(endpoint=LinkedinAdsResource.Accounts, finder="search")+ """Every ad account the authorized member can access. `q=search` is paginated, so a single+ request returns only the first page."""+ accounts: list[dict[str, Any]] = []+ for elements, _ in self._make_paginated_request(+ endpoint=LinkedinAdsResource.Accounts,+ path=f"/{LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Accounts]}",+ ):+ accounts.extend(elements)+ return accountsdef get_campaigns(self, account_id: str, starting_page_token: Optional[str] = None@@ -314,7 +333,9 @@ class LinkedinAdsClient:f"LinkedIn API error (retryable, {response.status_code}): {response.response.text}")if response.status_code != 200:- raise Exception(f"LinkedIn API error ({response.status_code}): {response.response.text}")+ raise LinkedinAdsApiError(+ f"LinkedIn API error ({response.status_code}): {response.response.text}", response.status_code+ )return responsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.pyindex 256c6cb62458..e8cc96cb3e33 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py@@ -35,6 +35,15 @@ module_logger = structlog.get_logger(__name__)INITIAL_ANALYTICS_LOOKBACK_DAYS = 365 * 5+class LinkedinAdsTokenRefreshError(Exception):+ """The stored OAuth token expired and could not be refreshed. Its message is already user-facing+ (see `get_non_retryable_errors`)."""+++class LinkedinAdsMissingTokenError(ValueError):+ """Subclasses ValueError so callers that only expect a ValueError here keep working."""++@dataclassclass LinkedInAdsResumeConfig:"""Resume state for LinkedIn Ads sync — `nextPageToken` from the entity@@ -143,9 +152,9 @@ def _get_integration(integration_id: int, team_id: int) -> Integration:_backoff_sleep(attempt)-def linkedin_ads_client(config: LinkedinAdsSourceConfig, team_id: int) -> LinkedinAdsClient:- """Initialize a LinkedIn Ads client with provided config."""- integration = _get_integration(config.linkedin_ads_integration_id, team_id)+def linkedin_ads_client_for_integration(integration_id: int, team_id: int) -> LinkedinAdsClient:+ """Initialize a LinkedIn Ads client from an OAuth integration id."""+ integration = _get_integration(integration_id, team_id)# LinkedIn access tokens expire (~60 days). Refresh a stale-but-refreshable token here so it gets# renewed instead of 401ing into a forced re-authorization. `access_token_expired` is a no-op when@@ -154,15 +163,20 @@ def linkedin_ads_client(config: LinkedinAdsSourceConfig, team_id: int) -> Linkedif oauth_integration.access_token_expired():oauth_integration.refresh_access_token()if integration.errors == ERROR_TOKEN_REFRESH_FAILED:- raise Exception(+ raise LinkedinAdsTokenRefreshError("Failed to refresh token for LinkedIn Ads integration. Please re-authorize the integration.")if not integration.access_token:- raise ValueError("LinkedIn Ads integration does not have an access token")+ raise LinkedinAdsMissingTokenError("LinkedIn Ads integration does not have an access token")return LinkedinAdsClient(integration.access_token)+def linkedin_ads_client(config: LinkedinAdsSourceConfig, team_id: int) -> LinkedinAdsClient:+ """Initialize a LinkedIn Ads client with provided config."""+ return linkedin_ads_client_for_integration(config.linkedin_ads_integration_id, team_id)++def linkedin_ads_source(config: LinkedinAdsSourceConfig,resource_name: str,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.pyindex db493aa9b4ec..95ebf5b23fdd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py@@ -5,8 +5,7 @@ from posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,ReleaseStatus,SourceConfig,- SourceFieldInputConfig,- SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SuggestedTable,)@@ -26,22 +25,31 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basfrom 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 OAuthMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+from .client import LinkedinAdsApiError, LinkedinAdsDailyRateLimitErrorfrom .linkedin_ads import (+ LinkedinAdsMissingTokenError,LinkedInAdsResumeConfig,+ LinkedinAdsTokenRefreshError,get_incremental_fields as get_linkedin_ads_incremental_fields,get_schemas as get_linkedin_ads_schemas,+ linkedin_ads_client_for_integration,linkedin_ads_source,)@SourceRegistry.register-class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResumeConfig]):+class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResumeConfig], OAuthMixin):lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@property@@ -104,20 +112,19 @@ class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResufields=cast(list[FieldType],[- SourceFieldInputConfig(- name="account_id",- label="Account ID",- type=SourceFieldInputConfigType.TEXT,- required=True,- placeholder="",- secret=False,- ),SourceFieldOauthConfig(name="linkedin_ads_integration_id",label="LinkedIn Ads account",required=True,kind="linkedin-ads",),+ SourceFieldOauthAccountSelectConfig(+ name="account_id",+ label="Account ID",+ integrationField="linkedin_ads_integration_id",+ integrationKind="linkedin-ads",+ required=True,+ ),],),suggestedTables=[@@ -132,6 +139,49 @@ class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResu],)+ def get_oauth_accounts(+ self, integration_id: int, team_id: int, search: str | None = None+ ) -> list[IntegrationAccount]:+ # A member's ad accounts are few, so `search` is ignored here and the endpoint filters the list.+ try:+ client = linkedin_ads_client_for_integration(integration_id, team_id)+ except Integration.DoesNotExist as e:+ raise IntegrationAccountListingError(+ "Your LinkedIn Ads connection is no longer available — it may have been disconnected. "+ "Please re-authorize the LinkedIn Ads integration."+ ) from e+ except LinkedinAdsTokenRefreshError as e:+ raise IntegrationAccountListingError(str(e)) from e+ except LinkedinAdsMissingTokenError as e:+ raise IntegrationAccountListingError(+ "The LinkedIn Ads integration has no access token. Please re-authorize the integration."+ ) from e++ try:+ accounts = client.get_accounts()+ except LinkedinAdsApiError as e:+ if e.api_status_code not in (401, 403):+ # Any other status means we built a bad request, which the user cannot fix.+ raise+ raise IntegrationAccountListingError(+ "LinkedIn rejected the credentials for this integration. Please re-authorize the "+ "LinkedIn Ads integration and make sure the signed-in member can access your ad accounts."+ ) from e+ except LinkedinAdsDailyRateLimitError as e:+ raise IntegrationAccountListingError(+ "LinkedIn's daily API limit for this connection has been reached. "+ "Please try again after it resets at midnight UTC."+ ) from e++ return [+ IntegrationAccount(+ value=str(account["id"]),+ display_name=account.get("name") or "Unnamed account",+ badges=(account["status"],) if account.get("status") else (),+ )+ for account in accounts+ ]+def validate_credentials(self, config: LinkedinAdsSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.pyindex dce68b04711a..02b5cfc03387 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py@@ -45,6 +45,28 @@ class TestLinkedinAdsClient:assert result == [{"id": "123", "name": "Test Account"}]mock_client_instance.finder.assert_called_once()+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")+ def test_get_accounts_collects_every_page(self, mock_restli_client):+ page_one = mock.MagicMock()+ page_one.status_code = 200+ page_one.elements = [{"id": "1", "name": "Account 1"}]+ page_one.response.text = json.dumps({"metadata": {"nextPageToken": "token123"}})++ page_two = mock.MagicMock()+ page_two.status_code = 200+ page_two.elements = [{"id": "2", "name": "Account 2"}]+ page_two.response.text = json.dumps({"metadata": {}})++ mock_client_instance = mock_restli_client.return_value+ mock_client_instance.finder.side_effect = [page_one, page_two]++ client = LinkedinAdsClient(self.access_token)+ result = client.get_accounts()++ assert result == [{"id": "1", "name": "Account 1"}, {"id": "2", "name": "Account 2"}]+ assert mock_client_instance.finder.call_count == 2+ assert mock_client_instance.finder.call_args_list[1][1]["query_params"]["pageToken"] == "token123"+@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")def test_get_accounts_api_error(self, mock_restli_client):"""Test accounts retrieval with API error."""