: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 ad sources (#65692)
Javier Bahamondesb884f603cead
diff --git a/frontend/src/lib/integrations/googleSearchConsoleIntegrationLogic.ts b/frontend/src/lib/integrations/googleSearchConsoleIntegrationLogic.tsdeleted file mode 100644index 94efde16d564..000000000000--- a/frontend/src/lib/integrations/googleSearchConsoleIntegrationLogic.ts+++ /dev/null@@ -1,67 +0,0 @@-import { actions, isBreakpoint, kea, key, listeners, path, props, reducers } from 'kea'--import api from 'lib/api'--import type { googleSearchConsoleIntegrationLogicType } from './googleSearchConsoleIntegrationLogicType'--export interface GoogleSearchConsoleSite {- // Canonical Google format: `https://example.com/` (URL-prefix, trailing slash required)- // or `sc-domain:example.com` (Domain property). We surface the string verbatim so the- // backend comparison in `validate_credentials` matches without normalization.- siteUrl: string- permissionLevel: 'siteOwner' | 'siteFullUser' | 'siteRestrictedUser' | 'siteUnverifiedUser'-}--interface SitesResponse {- sites: GoogleSearchConsoleSite[]-}--export const googleSearchConsoleIntegrationLogic = kea<googleSearchConsoleIntegrationLogicType>([- props({} as { id: number }),- key((props) => props.id),- path((key) => ['lib', 'integrations', 'googleSearchConsoleIntegrationLogic', key]),-- actions({- loadSites: true,- loadSitesSuccess: (sites: GoogleSearchConsoleSite[]) => ({ sites }),- loadSitesFailure: true,- }),-- reducers({- sites: [- [] as GoogleSearchConsoleSite[],- {- loadSites: () => [],- loadSitesSuccess: (_, { sites }) => sites,- },- ],- sitesLoading: [- false,- {- loadSites: () => true,- loadSitesSuccess: () => false,- loadSitesFailure: () => false,- },- ],- }),-- listeners(({ actions, props }) => ({- loadSites: async (_, breakpoint) => {- try {- // Manual typing for now — the autogenerated `api.integrations.googleSearchConsoleSites`- // will replace this once `hogli build:openapi` succeeds. Path mirrors the @action- // decorator on `IntegrationViewSet.google_search_console_sites`.- const response = (await api.get(- `api/projects/@current/integrations/${props.id}/google_search_console_sites/`- )) as SitesResponse- await breakpoint()- actions.loadSitesSuccess(response.sites)- } catch (e: any) {- if (isBreakpoint(e)) {- throw e- }- actions.loadSitesFailure()- }- },- })),-])diff --git a/frontend/src/lib/integrations/integrationAccountsLogic.ts b/frontend/src/lib/integrations/integrationAccountsLogic.tsnew file mode 100644index 000000000000..92ed3dbef92d--- /dev/null+++ b/frontend/src/lib/integrations/integrationAccountsLogic.ts@@ -0,0 +1,47 @@+import { kea, key, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiConfig } from 'lib/api'++import { externalDataSourcesOauthAccountsRetrieve } from 'products/warehouse_sources/frontend/generated/api'+import type { IntegrationAccountApi } from 'products/warehouse_sources/frontend/generated/api.schemas'++import type { integrationAccountsLogicType } from './integrationAccountsLogicType'++export const integrationAccountsLogic = kea<integrationAccountsLogicType>([+ props({} as { id: number; sourceType: string }),+ key((props) => `${props.sourceType}/${props.id}`),+ path((key) => ['lib', 'integrations', 'integrationAccountsLogic', key]),++ loaders(({ props }) => ({+ accounts: [+ [] as IntegrationAccountApi[],+ {+ loadAccounts: async () => {+ const response = await externalDataSourcesOauthAccountsRetrieve(+ String(ApiConfig.getCurrentProjectId()),+ {+ source_type: props.sourceType,+ integration_id: props.id,+ }+ )+ return response.accounts+ },+ },+ ],+ })),++ reducers({+ // Surface the backend's actionable 400 message (e.g. "reconnect the integration") instead of+ // falling back to a generic "no accounts" empty state. Cleared when a fresh load starts or succeeds.+ accountsError: [+ null as string | null,+ {+ loadAccounts: () => null,+ loadAccountsSuccess: () => null,+ loadAccountsFailure: (_, { error, errorObject }) =>+ errorObject?.data?.detail ?? errorObject?.detail ?? error ?? null,+ },+ ],+ }),+])diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 179c251c3db0..4f2c4663e564 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -42594,6 +42594,9 @@{"$ref": "#/definitions/SourceFieldOauthConfig"},+ {+ "$ref": "#/definitions/SourceFieldOauthAccountSelectConfig"+ },{"$ref": "#/definitions/SourceFieldFileUploadConfig"},@@ -42683,6 +42686,40 @@"enum": ["text", "email", "search", "url", "password", "time", "number", "textarea"],"type": "string"},+ "SourceFieldOauthAccountSelectConfig": {+ "additionalProperties": false,+ "properties": {+ "caption": {+ "type": "string"+ },+ "integrationField": {+ "description": "Name of the OAuth integration id field this account selector reads from.",+ "type": "string"+ },+ "integrationKind": {+ "description": "Integration kind to validate and route the account fetch through.",+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "placeholder": {+ "type": "string"+ },+ "required": {+ "type": "boolean"+ },+ "type": {+ "const": "oauth-account-select",+ "type": "string"+ }+ },+ "required": ["type", "name", "label", "integrationField", "integrationKind"],+ "type": "object"+ },"SourceFieldOauthConfig": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex ebb6c9f06c0f..3cb7f75cc757 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -6477,6 +6477,19 @@ export interface SourceFieldInputConfig {secret: boolean}+export interface SourceFieldOauthAccountSelectConfig {+ type: 'oauth-account-select'+ name: string+ label: string+ /** Name of the OAuth integration id field this account selector reads from. */+ integrationField: string+ /** Integration kind to validate and route the account fetch through. */+ integrationKind: string+ placeholder?: string+ caption?: string+ required?: boolean+}+export type SourceFieldSelectConfigConverter = 'str_to_int' | 'str_to_bool' | 'str_to_optional_int'export interface SourceFieldSelectConfigOption {@@ -6522,6 +6535,7 @@ export type SourceFieldConfig =| SourceFieldSwitchGroupConfig| SourceFieldSelectConfig| SourceFieldOauthConfig+ | SourceFieldOauthAccountSelectConfig| SourceFieldFileUploadConfig| SourceFieldSSHTunnelConfigdiff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 7b87374e49b5..c1a0da75ede6 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -11,7 +11,6 @@ from django.http import HttpResponsefrom django.shortcuts import redirectfrom django.utils import timezone-import requestsimport structlogfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema, extend_schema_serializer@@ -99,9 +98,6 @@ logger = structlog.get_logger(__name__)GITHUB_REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9_.\-]+")-# Short TTL for the Search Console sites dropdown — just enough to dedupe repeated UI loads.-GSC_AUTOCOMPLETE_CACHE_TTL_SECONDS = 60-def validate_github_repository_name(repo: str) -> str:"""Validate repository paths accepted by GitHub integration endpoints."""@@ -355,25 +351,6 @@ class SlackChannelsResponseSerializer(serializers.Serializer):)-class GoogleSearchConsoleSiteSerializer(serializers.Serializer):- siteUrl = serializers.CharField(- help_text=(- "Site URL in canonical Google format — `https://example.com/` for URL-prefix "- "properties (trailing slash mandatory) or `sc-domain:example.com` for Domain properties."- )- )- permissionLevel = serializers.CharField(- help_text=(- "The connected user's permission level for this site. One of `siteOwner`, "- "`siteFullUser`, `siteRestrictedUser`, `siteUnverifiedUser`."- )- )---class GoogleSearchConsoleSitesResponseSerializer(serializers.Serializer):- sites = GoogleSearchConsoleSiteSerializer(many=True)--class IntegrationAccessRequestSerializer(serializers.Serializer):kind = serializers.ChoiceField(choices=Integration.IntegrationKind.choices,@@ -899,9 +876,6 @@ class IntegrationViewSet("github_oauth_authorize",# Side-effecting POST (emails admins) — a read-only token must not be able to trigger it."request_access",- # Enumerates every Search Console property on the connected Google account — gate behind- # manage access so read-only members can't discover unrelated domains (info disclosure).- "google_search_console_sites",]permission_classes = [TeamMemberStrictManagementPermission]queryset = defer_repository_cache_fields(Integration.objects.all())@@ -1191,47 +1165,6 @@ class IntegrationViewSet(cache.set(key, response_data, 60)return Response(response_data)- @extend_schema(responses={200: GoogleSearchConsoleSitesResponseSerializer})- @action(methods=["GET"], detail=True, url_path="google_search_console_sites")- def google_search_console_sites(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """List the Search Console properties the connected Google account has access to."""- # Lazy import — keeps the Google data-imports SDK dependency off the api/ module- # import path, mirroring how other ad-platform endpoints stay self-contained.- from products.warehouse_sources.backend.facade.source_management import ( # noqa: PLC0415 — keeps the heavy dep off the import path- google_search_console_session,- list_sites,- )-- instance = self.get_object()- if instance.kind != "google-search-console":- raise ValidationError(- "google_search_console_sites endpoint is only supported for Google Search Console integrations"- )- _ensure_oauth_token_valid(instance)-- cache_key = f"google_search_console/{instance.id}/sites"- cached = cache.get(cache_key)- if cached is not None:- return Response(cached)-- session = google_search_console_session(instance.id, instance.team_id)- try:- sites = list_sites(session)- except requests.HTTPError as e:- status_code = e.response.status_code if e.response is not None else None- if status_code in (401, 403):- # The token refreshed fine but the connected Google account isn't authorized to- # read Search Console — a customer-side connection issue, not a PostHog bug. Return- # an actionable 400 rather than letting the HTTPError surface as an unhandled 500.- raise ValidationError(- "Google Search Console rejected the credentials. Please reconnect your account "- "and ensure it has read access to the property."- )- raise- response_data = {"sites": sites}- cache.set(cache_key, response_data, GSC_AUTOCOMPLETE_CACHE_TTL_SECONDS)- return Response(response_data)-@action(methods=["GET"], detail=True, url_path="linkedin_ads_conversion_rules")def linkedin_ad_conversion_rules(self, request: Request, *args: Any, **kwargs: Any) -> Response:instance = self.get_object()diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 29787c5a7cb1..aadbd3d6d42c 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -14,7 +14,6 @@ from django.test import override_settingsfrom django.test.client import Client as HttpClientfrom django.utils import timezone-import requestsfrom parameterized import parameterizedfrom rest_framework import status@@ -4456,80 +4455,3 @@ class TestIntegrationMembershipPermissions(APIBaseTest):existing.refresh_from_db()assert existing.config["project_id"] == "original-project"assert Integration.objects.filter(team=self.team, kind="google-cloud-service-account").count() == 1---class TestGoogleSearchConsoleSitesEndpoint:- _SESSION_PATH = (- "products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console."- "google_search_console.google_search_console_session"- )- _LIST_SITES_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.google_search_console.list_sites"-- @pytest.fixture(autouse=True)- def setup_integration(self, db):- self.organization = Organization.objects.create(name="Test Org")- self.team = Team.objects.create(organization=self.organization, name="Test Team")- self.user = User.objects.create_and_join(- self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN- )-- def _create_gsc_integration(self) -> Integration:- # No refresh_token → `_ensure_oauth_token_valid` treats the access token as valid and skips refresh.- return Integration.objects.create(- team=self.team,- kind="google-search-console",- config={},- sensitive_config={"access_token": "ya29.test"},- integration_id="gsc_test",- created_by=self.user,- )-- def _url(self, integration_id: int) -> str:- return f"/api/environments/{self.team.pk}/integrations/{integration_id}/google_search_console_sites/"-- @staticmethod- def _http_error(status_code: int) -> requests.HTTPError:- response = requests.Response()- response.status_code = status_code- return requests.HTTPError(f"{status_code} Client Error", response=response)-- @patch(_LIST_SITES_PATH)- @patch(_SESSION_PATH)- def test_auth_error_returns_actionable_400(self, mock_session, mock_list_sites, client: HttpClient):- # 401 and 403 both mean the connected account can't read Search Console — the endpoint should- # turn either into an actionable 400 rather than letting it surface as an unhandled 500.- integration = self._create_gsc_integration()- client.force_login(self.user)-- for status_code in (401, 403):- mock_list_sites.side_effect = self._http_error(status_code)-- response = client.get(self._url(integration.id))-- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content- assert "reconnect your account" in str(response.json()).lower()-- @patch(_LIST_SITES_PATH)- @patch(_SESSION_PATH)- def test_success_returns_sites(self, mock_session, mock_list_sites, client: HttpClient):- integration = self._create_gsc_integration()- mock_list_sites.return_value = [{"siteUrl": "https://example.com/", "permissionLevel": "siteOwner"}]-- client.force_login(self.user)- response = client.get(self._url(integration.id))-- assert response.status_code == status.HTTP_200_OK, response.content- assert response.json()["sites"] == [{"siteUrl": "https://example.com/", "permissionLevel": "siteOwner"}]-- @patch(_LIST_SITES_PATH)- @patch(_SESSION_PATH)- def test_non_auth_http_error_is_not_swallowed(self, mock_session, mock_list_sites, client: HttpClient):- # Only 401/403 are converted to a 400 — any other status keeps surfacing as a server error so- # a genuine bug isn't masked by the auth handling.- integration = self._create_gsc_integration()- mock_list_sites.side_effect = self._http_error(500)-- client.force_login(self.user)- response = client.get(self._url(integration.id))-- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.contentdiff --git a/posthog/permissions.py b/posthog/permissions.pyindex 10aa9d4f3fa9..8516ca49ffe2 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -304,6 +304,20 @@ class TeamMemberStrictManagementPermission(BasePermission):return requesting_level >= minimum_level+class TeamMemberAdminManagementPermission(BasePermission):+ """+ Require at least admin effective project access level for ALL methods, including reads.+ """++ message = "You don't have sufficient permissions in the project."++ def has_permission(self, request, view) -> bool:+ requesting_level = view.user_permissions.current_team.effective_membership_level+ if requesting_level is None:+ return False+ return requesting_level >= OrganizationMembership.Level.ADMIN++class IsStaffUser(IsAdminUser):message = "You are not a staff user, contact your instance admin."diff --git a/posthog/schema.py b/posthog/schema.pyindex 4b13eb51543c..be5f514e6df9 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -2418,6 +2418,26 @@ class SourceFieldFileUploadJsonFormatConfig(BaseModel):keys: str | list[str]+class SourceFieldOauthAccountSelectConfig(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ caption: str | None = None+ integrationField: str = Field(+ ...,+ description=("Name of the OAuth integration id field this account selector reads from."),+ )+ integrationKind: str = Field(+ ...,+ description="Integration kind to validate and route the account fetch through.",+ )+ label: str+ name: str+ placeholder: str | None = None+ required: bool | None = None+ type: Literal["oauth-account-select"] = "oauth-account-select"++class SourceFieldOauthConfig(BaseModel):model_config = ConfigDict(extra="forbid",@@ -28177,6 +28197,7 @@ class SourceConfig(BaseModel):| SourceFieldSwitchGroupConfig| SourceFieldSelectConfig| SourceFieldOauthConfig+ | SourceFieldOauthAccountSelectConfig| SourceFieldFileUploadConfig| SourceFieldSSHTunnelConfig]@@ -28214,6 +28235,7 @@ class SourceConfig(BaseModel):| SourceFieldSwitchGroupConfig| SourceFieldSelectConfig| SourceFieldOauthConfig+ | SourceFieldOauthAccountSelectConfig| SourceFieldFileUploadConfig| SourceFieldSSHTunnelConfig]@@ -28254,6 +28276,7 @@ class SourceFieldSelectConfigOption(BaseModel):| SourceFieldSwitchGroupConfig| SourceFieldSelectConfig| SourceFieldOauthConfig+ | SourceFieldOauthAccountSelectConfig| SourceFieldFileUploadConfig| SourceFieldSSHTunnelConfig]@@ -28274,6 +28297,7 @@ class SourceFieldSwitchGroupConfig(BaseModel):| SourceFieldSwitchGroupConfig| SourceFieldSelectConfig| SourceFieldOauthConfig+ | SourceFieldOauthAccountSelectConfig| SourceFieldFileUploadConfig| SourceFieldSSHTunnelConfig]diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 7bc46cc05999..5989eff3fb21 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -8,6 +8,7 @@ from typing import Any, castfrom urllib.parse import quotefrom django.conf import settings+from django.core.cache import cachefrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import connection, transactionfrom django.db.models import Prefetch, Q@@ -21,6 +22,7 @@ from openai import APIConnectionErrorfrom psycopg import OperationalErrorfrom rest_framework import filters, serializers, status, viewsetsfrom rest_framework.exceptions import APIException, ValidationError+from rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom sshtunnel import BaseSSHTunnelForwarderError@@ -29,6 +31,7 @@ from posthog.schema import (SourceFieldFileUploadConfig,SourceFieldInputConfig,SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SourceFieldSelectConfig,SourceFieldSSHTunnelConfig,@@ -43,6 +46,12 @@ from posthog.api.utils import actionfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.user import User+from posthog.permissions import (+ AccessControlPermission,+ APIScopePermission,+ TeamMemberAccessPermission,+ TeamMemberAdminManagementPermission,+)from posthog.rate_limit import (CustomSourceAIBuilderBurstThrottle,CustomSourceAIBuilderDailyThrottle,@@ -132,7 +141,9 @@ from products.warehouse_sources.backend.facade.source_management import (DocsFetchError,ExternalWebhookInfo,FieldType,+ IntegrationAccountListingError,MySQLSource,+ OAuthMixin,PostgresSource,RowFilterValidationError,SourceRegistry,@@ -266,7 +277,9 @@ def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> tuplens, s = get_nonsensitive_and_sensitive_field_names(field.fields)nonsensitive.update(ns)sensitive.update(s)- elif isinstance(field, SourceFieldOauthConfig):+ elif isinstance(field, SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig):+ # The selected account/property is a plain identifier (e.g. Bing Ads account_id,+ # GSC site_url), not a secret — keep it so the form can prefill on edit._add_name_variants(nonsensitive, field.name)elif isinstance(field, SourceFieldSSHTunnelConfig):_add_name_variants(nonsensitive, field.name)@@ -1531,6 +1544,39 @@ class SimpleExternalDataSourceSerializers(serializers.ModelSerializer):read_only_fields = ["id", "created_by", "created_at", "status", "source_type"]+class IntegrationAccountSerializer(serializers.Serializer):+ """A selectable account/resource exposed by an OAuth integration, in the shared shape every ad+ platform produces (see ``IntegrationAccount`` in the data-imports common module). One serializer+ and one frontend selector work across all platforms."""++ value = serializers.CharField(+ help_text="The identifier stored in the source config and used for API calls (numeric account id as a string, a site url, etc.)."+ )+ display_name = serializers.CharField(help_text="Primary human-readable label for the account.")+ is_primary = serializers.BooleanField(+ help_text="True when this account belongs to the connected user's own (primary) account context, rather than one they merely have access to. Sorted/marked first."+ )+ badges = serializers.ListField(+ child=serializers.CharField(),+ help_text="Short status chips for the account, e.g. ['Active'] or ['Pause'].",+ )+ group = serializers.CharField(+ allow_null=True,+ help_text="Optional grouping label for hierarchical platforms (e.g. the owning customer/manager name).",+ )+ secondary_text = serializers.CharField(+ allow_null=True,+ help_text="Extra identifier shown in parentheses and searchable, e.g. the alphanumeric account number.",+ )+++class IntegrationAccountsResponseSerializer(serializers.Serializer):+ accounts = IntegrationAccountSerializer(+ many=True,+ help_text="All accounts the connected integration can access.",+ )++@extend_schema(extensions={"x-product": "warehouse_sources"})class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):"""@@ -1560,6 +1606,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"disable_cdc","repair_cdc","update_cdc_settings",+ # Enumerates the connected provider's accounts/sites — write-scoped so a read-only token can't+ # list them (info disclosure); also gated behind admin in dangerously_get_permissions.+ "oauth_accounts",# Live outbound HTTP to a caller-supplied manifest (including POSTs) — a# side-effecting action, so it needs write scope, not read."preview_resource",@@ -1586,6 +1635,20 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisearch_fields = ["source_type", "prefix"]ordering = "-created_at"+ def dangerously_get_permissions(self):+ # The account picker enumerates every account/site the connected provider exposes, so require+ # manage access even though it's a GET — a read-only member shouldn't discover unrelated+ # accounts (info disclosure). Other actions fall back to the viewset defaults.+ if self.action == "oauth_accounts":+ return [+ IsAuthenticated(),+ APIScopePermission(),+ AccessControlPermission(),+ TeamMemberAccessPermission(),+ TeamMemberAdminManagementPermission(),+ ]+ raise NotImplementedError()+def get_throttles(self):# The AI manifest builder fans out to several Opus calls per request and isn't billed to the# customer, so cap it per team: a burst guard against double-submits/retries, an hourly window@@ -1670,6 +1733,69 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidirect_query_enabled=serializer.validated_data.get("direct_query_enabled", True),)+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="source_type",+ type=str,+ required=True,+ description="The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').",+ ),+ OpenApiParameter(+ name="integration_id",+ type=int,+ required=True,+ description="The OAuth integration id whose accounts should be listed.",+ ),+ ],+ responses={200: IntegrationAccountsResponseSerializer},+ )+ @action(methods=["GET"], detail=False, url_path="oauth_accounts")+ def oauth_accounts(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """List the accounts/properties a connected OAuth integration exposes, in the shared+ IntegrationAccount shape. The logic lives in each source (via OAuthMixin.get_oauth_accounts);+ this endpoint just routes by source type and serializes the result."""+ source_type = request.query_params.get("source_type")+ integration_id = request.query_params.get("integration_id")+ if not source_type or not integration_id:+ raise ValidationError("source_type and integration_id are required")++ try:+ integration_id_int = int(integration_id)+ except ValueError:+ raise ValidationError("integration_id must be an integer")++ try:+ source = SourceRegistry.get_source(cast(ExternalDataSourceType, source_type))+ except ValueError:+ raise ValidationError(f"Unknown source type: {source_type}")++ if not isinstance(source, OAuthMixin):+ raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")++ cache_key = f"oauth_accounts/{self.team_id}/{source_type}/{integration_id_int}"+ cached = cache.get(cache_key)+ if cached is not None:+ return Response(cached)++ try:+ accounts = source.get_oauth_accounts(integration_id_int, self.team_id)+ except NotImplementedError:+ # An OAuth source that hasn't implemented account listing yet (passes the isinstance check).+ raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")+ except IntegrationAccountListingError as e:+ # Actionable, customer-side failure (revoked/expired token, deleted integration, the provider+ # rejecting the credentials) — surface the message as a 400. Anything else (e.g. a bare+ # ValueError from an internal bug) stays uncaught and becomes a 500 so monitors see it.+ raise ValidationError(str(e))++ response_data = {"accounts": IntegrationAccountSerializer(accounts, many=True).data}+ # Don't cache an empty result: a transient provider hiccup that returns [] without raising would+ # otherwise poison the picker for 60s for every admin on the team.+ if accounts:+ cache.set(cache_key, response_data, 60)+ return Response(response_data)+def perform_update(self, serializer: serializers.BaseSerializer) -> None:# Runs for both PUT and PATCH (DRF's partial_update delegates to update -> perform_update).# `created_via` is write-once and reflects original creation origin; the edit's own origindiff --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 e6371f1c1fe4..3da08f1cd283 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@@ -14,6 +14,8 @@ from django.test import SimpleTestCase, override_settingsfrom django.utils import timezoneimport psycopg+import requests+from google.auth.exceptions import RefreshErrorfrom parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.exceptions import ValidationError@@ -30,7 +32,8 @@ from posthog.schema import (SourceFieldSwitchGroupConfig,)-from posthog.models import Team+from posthog.models import OrganizationMembership, Team+from posthog.models.integration import Integrationfrom posthog.models.project import Projectfrom products.data_tools.backend.models.join import DataWarehouseJoin@@ -10733,6 +10736,205 @@ class TestExternalDataSourceStoreCredentials(APIBaseTest):assert [result["credential_id"] for result in response.json()] == [str(newer.pk), str(older.pk)]+class TestOAuthAccountsEndpoint(APIBaseTest):+ _GSC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.source"+ _BING_LIST_ACCOUNTS = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.BingAdsClient.list_accounts"+ )++ def setUp(self):+ super().setUp()+ # The endpoint requires manage access (it enumerates the provider's accounts), so default the+ # user to admin; the forbidden-member test drops back to MEMBER explicitly.+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ def _url(self, source_type: str, integration_id: int) -> str:+ return (+ f"/api/environments/{self.team.pk}/external_data_sources/oauth_accounts/"+ f"?source_type={source_type}&integration_id={integration_id}"+ )++ def _bing_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="bing-ads",+ config={},+ sensitive_config={"access_token": "token", "refresh_token": "refresh"},+ integration_id="bing_test",+ created_by=self.user,+ )++ def _gsc_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="google-search-console",+ config={},+ sensitive_config={"access_token": "ya29.test"},+ integration_id="gsc_test",+ created_by=self.user,+ )++ @staticmethod+ def _http_error(status_code: int) -> requests.HTTPError:+ response = requests.Response()+ response.status_code = status_code+ return requests.HTTPError(f"{status_code} Client Error", response=response)++ def test_regular_member_is_forbidden(self):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ integration = self._gsc_integration()++ response = self.client.get(self._url("GoogleSearchConsole", integration.id))++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content++ def test_missing_params_returns_400(self):+ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/oauth_accounts/?source_type=BingAds"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content++ def test_unknown_source_type_returns_400(self):+ response = self.client.get(self._url("NotARealSource", 1))+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content++ def test_non_oauth_source_returns_400(self):+ response = self.client.get(self._url("Postgres", 1))+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content++ def test_oauth_source_without_listing_returns_400(self):+ # An OAuth source that hasn't implemented get_oauth_accounts passes the isinstance check but+ # raises NotImplementedError — it must surface as a 400, not an unhandled 500.+ response = self.client.get(self._url("Salesforce", 1))+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content++ def test_gsc_success_maps_sites_to_accounts(self):+ integration = self._gsc_integration()+ with (+ patch(f"{self._GSC_MODULE}.google_search_console_session"),+ patch(+ f"{self._GSC_MODULE}.list_sites",+ return_value=[{"siteUrl": "https://example.com/", "permissionLevel": "siteOwner"}],+ ),+ ):+ response = self.client.get(self._url("GoogleSearchConsole", integration.id))++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json()["accounts"] == [+ {+ "value": "https://example.com/",+ "display_name": "https://example.com/",+ "is_primary": False,+ "badges": ["siteOwner"],+ "group": None,+ "secondary_text": None,+ }+ ]++ @parameterized.expand([(401,), (403,)])+ def test_gsc_auth_error_returns_actionable_400(self, status_code: int):+ integration = self._gsc_integration()+ with (+ patch(f"{self._GSC_MODULE}.google_search_console_session"),+ patch(f"{self._GSC_MODULE}.list_sites", side_effect=self._http_error(status_code)),+ ):+ response = self.client.get(self._url("GoogleSearchConsole", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "reconnect your account" in str(response.json()).lower()++ @override_settings(BING_ADS_DEVELOPER_TOKEN="dev_token")+ def test_bing_success_returns_accounts(self):+ integration = self._bing_integration()+ with patch(self._BING_LIST_ACCOUNTS, return_value=[]):+ response = self.client.get(self._url("BingAds", integration.id))++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json() == {"accounts": []}++ def test_gsc_non_auth_http_error_is_not_swallowed(self):+ # Only 401/403 become an actionable 400 — any other status keeps surfacing as a 500 so a+ # genuine bug isn't masked by the auth handling. Restores the parity the old endpoint test had.+ integration = self._gsc_integration()+ with (+ patch(f"{self._GSC_MODULE}.google_search_console_session"),+ patch(f"{self._GSC_MODULE}.list_sites", side_effect=self._http_error(500)),+ ):+ response = self.client.get(self._url("GoogleSearchConsole", integration.id))++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content++ def test_gsc_unexpected_error_is_not_swallowed(self):+ # A non-actionable runtime failure inside listing must surface as a 500, not a 400 — a bare+ # exception is a server bug, not bad user input.+ integration = self._gsc_integration()+ with (+ patch(f"{self._GSC_MODULE}.google_search_console_session"),+ patch(f"{self._GSC_MODULE}.list_sites", side_effect=RuntimeError("boom")),+ ):+ response = self.client.get(self._url("GoogleSearchConsole", integration.id))++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content++ def test_gsc_revoked_token_returns_actionable_400(self):+ # The lazy OAuth refresh raises RefreshError when the stored token is revoked/expired; it must+ # become an actionable 400, not an unhandled 500.+ integration = self._gsc_integration()+ with (+ patch(f"{self._GSC_MODULE}.google_search_console_session"),+ patch(f"{self._GSC_MODULE}.list_sites", side_effect=RefreshError("invalid_grant")),+ ):+ response = self.client.get(self._url("GoogleSearchConsole", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "reconnect the integration" in str(response.json()).lower()++ def test_gsc_missing_integration_returns_400(self):+ # google_search_console_session raises Integration.DoesNotExist for a missing/foreign id — it+ # must surface as an actionable 400, not a 500. (Mocked rather than hitting the real session,+ # whose lazy credential load calls close_old_connections and would drop the test connection.)+ integration = self._gsc_integration()+ with patch(+ f"{self._GSC_MODULE}.google_search_console_session",+ side_effect=Integration.DoesNotExist(),+ ):+ response = self.client.get(self._url("GoogleSearchConsole", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "reconnect" in str(response.json()).lower()++ @override_settings(BING_ADS_DEVELOPER_TOKEN="dev_token")+ def test_bing_auth_error_returns_actionable_400(self):+ # list_accounts funnels SDK auth failures through _wrap_with_fault_detail as a ValueError whose+ # message carries the original error type; the source maps the known auth substrings to a 400.+ integration = self._bing_integration()+ wrapped = ValueError("Failed to list Bing Ads accounts: OAuthTokenRequestException: invalid_grant The grant")+ with patch(self._BING_LIST_ACCOUNTS, side_effect=wrapped):+ response = self.client.get(self._url("BingAds", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "reconnect" in str(response.json()).lower()++ @override_settings(BING_ADS_DEVELOPER_TOKEN="dev_token")+ def test_bing_unexpected_error_is_not_swallowed(self):+ # A non-actionable failure inside list_accounts must surface as a 500, not be masked as a 400.+ integration = self._bing_integration()+ with patch(self._BING_LIST_ACCOUNTS, side_effect=RuntimeError("schema parser exploded")):+ response = self.client.get(self._url("BingAds", integration.id))++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content++ @override_settings(BING_ADS_DEVELOPER_TOKEN="dev_token")+ def test_bing_missing_integration_returns_400(self):+ # A missing/foreign integration id must surface as an actionable 400, not a 500.+ response = self.client.get(self._url("BingAds", 99999999))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "reconnect" in str(response.json()).lower()++_PREVIEW_MANIFEST = {"client": {"base_url": "https://api.example.com",diff --git a/products/data_warehouse/frontend/shared/components/forms/GoogleSearchConsoleSiteSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/GoogleSearchConsoleSiteSelector.tsxdeleted file mode 100644index 3849af08794b..000000000000--- a/products/data_warehouse/frontend/shared/components/forms/GoogleSearchConsoleSiteSelector.tsx+++ /dev/null@@ -1,139 +0,0 @@-import { useActions, useValues } from 'kea'-import { FormContext } from 'kea-forms'-import { useContext, useEffect, useMemo } from 'react'--import { LemonInput } from '@posthog/lemon-ui'--import { googleSearchConsoleIntegrationLogic } from 'lib/integrations/googleSearchConsoleIntegrationLogic'-import { integrationsLogic } from 'lib/integrations/integrationsLogic'-import { LemonField } from 'lib/lemon-ui/LemonField'--import { InputWithSuggestionsDropdown } from './InputWithSuggestionsDropdown'--const SITE_URL_PLACEHOLDER = 'https://example.com/ or sc-domain:example.com'--/**- * Renders the Search Console `site_url` field as a free-text input with a popover- * of the connected integration's verified properties for autocomplete-style picking.- *- * Falls back to a plain text input before the user picks an OAuth account (or when- * the form's stored integration ID points at a stale integration), so the field- * stays usable while the integration choice above is being fixed.- *- * Works in both contexts that render this field:- * - The new-source wizard (`sourceWizardLogic`, form key `sourceConnectionDetails`)- * - The existing-source Config tab (`sourceSettingsLogic`, form key `sourceConfig`)- *- * We read the OAuth integration ID via `FormContext` from kea-forms instead of- * binding directly to a specific logic, so this stays decoupled from which scene- * renders it.- */-export function GoogleSearchConsoleSiteSelector(): JSX.Element {- // FormContext.logic is set whenever this field renders inside a kea <Form> (both the- // new-source wizard and the existing-source config tab do). Only mount the hook-using- // inner component when it's present, so we never pass a null logic into useValues — and- // calling the hook conditionally here would itself violate the rules of hooks.- const formContext = useContext(FormContext)- if (!formContext.logic) {- return <SiteUrlTextField />- }- return <GoogleSearchConsoleSiteSelectorInner formLogic={formContext.logic} formKey={formContext.formKey} />-}--function GoogleSearchConsoleSiteSelectorInner({- formLogic,- formKey,-}: {- formLogic: any- formKey: string-}): JSX.Element {- const integrationId = useFormIntegrationId(formLogic, formKey)- const { integrations, integrationsLoading } = useValues(integrationsLogic)-- const integrationIsValid = useMemo(() => {- if (!integrationId || integrationsLoading || !integrations) {- return false- }- return integrations.some(- (integration) => integration.id === integrationId && integration.kind === 'google-search-console'- )- }, [integrationId, integrations, integrationsLoading])-- if (integrationIsValid && integrationId) {- return <GoogleSearchConsoleSiteFieldWithSuggestions integrationId={integrationId} />- }-- return <SiteUrlTextField />-}--function SiteUrlTextField(): JSX.Element {- return (- <LemonField name="site_url" label="Property URL">- {({ value, onChange }) => (- <LemonInput- className="ph-ignore-input"- data-attr="site_url"- placeholder={SITE_URL_PLACEHOLDER}- type="text"- value={value || ''}- onChange={onChange}- />- )}- </LemonField>- )-}--function useFormIntegrationId(formLogic: any, formKey: string): number | undefined {- // formLogic is guaranteed non-null by the caller, so useValues always runs with a valid logic.- const values = useValues(formLogic) as Record<string, any> | null- if (!values) {- return undefined- }- // Coerce to number — when the form is hydrated from a saved source's `job_inputs`- // the integration ID arrives as a string from JSONB. Without the cast, downstream- // `integration.id === id` lookups in `integrationsLogic` silently miss the match.- const raw = values[formKey]?.payload?.google_search_console_integration_id- const id = raw === undefined || raw === null || raw === '' ? undefined : Number(raw)- return id && Number.isFinite(id) ? id : undefined-}--function GoogleSearchConsoleSiteFieldWithSuggestions({ integrationId }: { integrationId: number }): JSX.Element {- const { sites, sitesLoading } = useValues(googleSearchConsoleIntegrationLogic({ id: integrationId }))- const { loadSites } = useActions(googleSearchConsoleIntegrationLogic({ id: integrationId }))-- useEffect(() => {- loadSites()- }, [loadSites])-- const siteUrls = useMemo(() => sites.map((site) => site.siteUrl), [sites])-- return (- <LemonField name="site_url" label="Property URL">- {({ value, onChange }) => {- const savedValueMissing = !!value && !sitesLoading && sites.length > 0 && !siteUrls.includes(value)- return (- <div className="flex flex-col gap-2">- <InputWithSuggestionsDropdown- data-attr="site_url"- placeholder={SITE_URL_PLACEHOLDER}- value={value || ''}- onChange={onChange}- suggestions={siteUrls}- suggestionsLoading={sitesLoading}- searchPlaceholder="Filter verified properties…"- emptyMessage="No properties found for this Google account. In Google Search Console, grant the connected account access to a verified property, then reconnect."- loadingMessage="Loading from Google…"- />- {savedValueMissing && (- <p className="m-0 text-xs text-warning">- The currently saved property <code>{value}</code> isn't in the verified list for the- connected Google account. Save anyway if you know it's correct, or pick a different one- from the list.- </p>- )}- </div>- )- }}- </LemonField>- )-}diff --git a/products/data_warehouse/frontend/shared/components/forms/InputWithSuggestionsDropdown.tsx b/products/data_warehouse/frontend/shared/components/forms/InputWithSuggestionsDropdown.tsxindex d45e06e40d19..f5e570d88de8 100644--- a/products/data_warehouse/frontend/shared/components/forms/InputWithSuggestionsDropdown.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/InputWithSuggestionsDropdown.tsx@@ -1,18 +1,39 @@-import { useMemo, useState } from 'react'+import { ReactNode, useMemo, useState } from 'react'import { IconCheck } from '@posthog/icons'import { LemonButton, LemonInput, Spinner } from '@posthog/lemon-ui'import { Popover } from 'lib/lemon-ui/Popover/Popover'+/**+ * A suggestion is either a plain string (shown verbatim, and copied into `value` on click) or a+ * rich entry where the value stored differs from what's displayed — e.g. show "Account name (id)"+ * but store just the id. `searchText` is what the filter matches against (defaults to `value`).+ */+export type InputSuggestion = string | { value: string; label: ReactNode; searchText?: string }++interface NormalizedSuggestion {+ value: string+ label: ReactNode+ searchText: string+}++function normalizeSuggestion(suggestion: InputSuggestion): NormalizedSuggestion {+ if (typeof suggestion === 'string') {+ return { value: suggestion, label: suggestion, searchText: suggestion }+ }+ return { value: suggestion.value, label: suggestion.label, searchText: suggestion.searchText ?? suggestion.value }+}+export interface InputWithSuggestionsDropdownProps {/** Current value of the input. Free text — user can type anything, suggestions are only hints. */value: stringonChange: (next: string) => voidplaceholder?: string'data-attr'?: string- /** Suggestions to surface in the popover. Each value is shown verbatim and copied into `value` on click. */- suggestions: string[]+ /** Suggestions to surface in the popover. Plain strings, or `{ value, label, searchText }` when the+ * stored value differs from the displayed label. Clicking one copies its `value` into the input. */+ suggestions: InputSuggestion[]suggestionsLoading?: boolean/** Search input placeholder inside the popover. */searchPlaceholder?: string@@ -50,13 +71,15 @@ export function InputWithSuggestionsDropdown({const [open, setOpen] = useState(false)const [searchTerm, setSearchTerm] = useState('')+ const normalized = useMemo(() => suggestions.map(normalizeSuggestion), [suggestions])+const filtered = useMemo(() => {const needle = searchTerm.trim().toLowerCase()if (!needle) {- return suggestions+ return normalized}- return suggestions.filter((suggestion) => suggestion.toLowerCase().includes(needle))- }, [suggestions, searchTerm])+ return normalized.filter((suggestion) => suggestion.searchText.toLowerCase().includes(needle))+ }, [normalized, searchTerm])return (<Popover@@ -87,21 +110,21 @@ export function InputWithSuggestionsDropdown({) : (<div className="flex flex-col max-h-64 overflow-y-auto">{filtered.map((suggestion) => {- const isCurrent = suggestion === value+ const isCurrent = suggestion.value === valuereturn (<LemonButton- key={suggestion}+ key={suggestion.value}size="small"fullWidthactive={isCurrent}icon={isCurrent ? <IconCheck /> : undefined}onClick={() => {- onChange(suggestion)+ onChange(suggestion.value)setSearchTerm('')setOpen(false)}}>- {suggestion}+ {suggestion.label}</LemonButton>)})}diff --git a/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsxnew file mode 100644index 000000000000..f4c7f2b2bb22--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx@@ -0,0 +1,179 @@+import { useActions, useValues } from 'kea'+import { FormContext } from 'kea-forms'+import { useContext, useEffect, useMemo } from 'react'++import { LemonInput, LemonTag } from '@posthog/lemon-ui'++import { integrationAccountsLogic } from 'lib/integrations/integrationAccountsLogic'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'++import { InputSuggestion, InputWithSuggestionsDropdown } from './InputWithSuggestionsDropdown'++export interface IntegrationAccountSelectorProps {+ fieldName: string+ fieldLabel: string+ /** Which OAuth id field of the form payload to read, e.g. "bing_ads_integration_id". */+ integrationField: string+ /** Integration kind used to validate the connected integration, e.g. "bing-ads". */+ integrationKind: string+ /** Data warehouse source type used to route the generic accounts endpoint, e.g. "BingAds". */+ sourceType: string+ placeholder?: string+ /** Optional format guidance rendered under the field label. */+ caption?: string+}++/** Generic account/resource picker for OAuth ad sources: a dropdown of the connected integration's+ * accounts (shared IntegrationAccount contract), falling back to a text input until one is connected. */+export function IntegrationAccountSelector(props: IntegrationAccountSelectorProps): JSX.Element {+ // Only mount the hook-using inner component once inside a kea <Form>, to avoid a null logic.+ const formContext = useContext(FormContext)+ if (!formContext.logic) {+ return <AccountTextField {...props} />+ }+ return <IntegrationAccountSelectorInner {...props} formLogic={formContext.logic} formKey={formContext.formKey} />+}++function IntegrationAccountSelectorInner({+ formLogic,+ formKey,+ ...props+}: IntegrationAccountSelectorProps & { formLogic: any; formKey: string }): JSX.Element {+ const integrationId = useFormIntegrationId(formLogic, formKey, props.integrationField)+ const { integrations, integrationsLoading } = useValues(integrationsLogic)++ const integrationIsValid = useMemo(() => {+ if (!integrationId || integrationsLoading || !integrations) {+ return false+ }+ return integrations.some(+ (integration) => integration.id === integrationId && integration.kind === props.integrationKind+ )+ }, [integrationId, integrations, integrationsLoading, props.integrationKind])++ if (integrationIsValid && integrationId) {+ return <IntegrationAccountFieldWithDropdown {...props} integrationId={integrationId} />+ }++ return <AccountTextField {...props} />+}++function captionHelp(caption?: string): JSX.Element | undefined {+ return caption ? <LemonMarkdown className="text-xs">{caption}</LemonMarkdown> : undefined+}++function AccountTextField({+ fieldName,+ fieldLabel,+ placeholder,+ caption,+}: IntegrationAccountSelectorProps): JSX.Element {+ return (+ <LemonField name={fieldName} label={fieldLabel} help={captionHelp(caption)}>+ {({ value, onChange }) => (+ <LemonInput+ className="ph-ignore-input"+ data-attr={fieldName}+ placeholder={placeholder}+ type="text"+ value={value || ''}+ onChange={onChange}+ />+ )}+ </LemonField>+ )+}++function useFormIntegrationId(formLogic: any, formKey: string, integrationField: string): number | undefined {+ const values = useValues(formLogic) as Record<string, any> | null+ if (!values) {+ return undefined+ }+ // Saved job_inputs store the id as a JSONB string; coerce so `integration.id === id` matches.+ const raw = values[formKey]?.payload?.[integrationField]+ const id = raw === undefined || raw === null || raw === '' ? undefined : Number(raw)+ return id && Number.isFinite(id) ? id : undefined+}++function IntegrationAccountFieldWithDropdown({+ integrationId,+ sourceType,+ fieldName,+ fieldLabel,+ placeholder,+ caption,+}: IntegrationAccountSelectorProps & { integrationId: number }): JSX.Element {+ const { accounts, accountsLoading, accountsError } = useValues(+ integrationAccountsLogic({ id: integrationId, sourceType })+ )+ const { loadAccounts } = useActions(integrationAccountsLogic({ id: integrationId, sourceType }))++ useEffect(() => {+ loadAccounts()+ }, [loadAccounts])++ const suggestions = useMemo<InputSuggestion[]>(() => {+ const sorted = [...accounts].sort((a, b) => Number(b.is_primary) - Number(a.is_primary))+ return sorted.map((account) => {+ // When display_name === value (e.g. GSC site url), "value (value)" is redundant.+ const labelText =+ account.display_name === account.value+ ? account.display_name+ : `${account.display_name} (${account.value})`+ const searchText =+ account.display_name === account.value+ ? `${account.value} ${account.secondary_text ?? ''}`+ : `${account.display_name} ${account.value} ${account.secondary_text ?? ''}`+ return {+ value: account.value,+ label: (+ <div className="flex items-center gap-2">+ <span>{labelText}</span>+ {account.is_primary && <LemonTag type="primary">Primary</LemonTag>}+ {account.badges.map((badge) => (+ <LemonTag type="muted" key={badge}>+ {badge}+ </LemonTag>+ ))}+ </div>+ ),+ searchText,+ }+ })+ }, [accounts])++ return (+ <LemonField name={fieldName} label={fieldLabel} help={captionHelp(caption)}>+ {({ value, onChange }) => {+ const accountValues = accounts.map((account) => account.value)+ const savedValueMissing =+ !!value && !accountsLoading && accounts.length > 0 && !accountValues.includes(String(value))+ return (+ <div className="flex flex-col gap-2">+ <InputWithSuggestionsDropdown+ data-attr={fieldName}+ placeholder={placeholder}+ value={value || ''}+ onChange={onChange}+ suggestions={suggestions}+ suggestionsLoading={accountsLoading}+ searchPlaceholder="Filter accounts…"+ emptyMessage="No accounts accessible by this integration."+ loadingMessage="Loading accounts…"+ />+ {accountsError && <p className="m-0 text-xs text-warning">{accountsError}</p>}+ {savedValueMissing && (+ <p className="m-0 text-xs text-warning">+ The currently saved {fieldLabel} <code>{value}</code> isn't in the accessible list for+ the connected account. Save anyway if you know it's correct, or pick a different one+ from the list.+ </p>+ )}+ </div>+ )+ }}+ </LemonField>+ )+}diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsxindex 2d47c7c1c2ce..45905c7c5ec5 100644--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx@@ -37,7 +37,7 @@ import { isCustomSourceAiBuilderEnabled } from './customSourceManifest'import { CustomSourceManifestBuilder } from './CustomSourceManifestBuilder'import { customSourceManifestBuilderLogic } from './customSourceManifestBuilderLogic'import { GitHubRepositorySelector } from './GitHubRepositorySelector'-import { GoogleSearchConsoleSiteSelector } from './GoogleSearchConsoleSiteSelector'+import { IntegrationAccountSelector } from './IntegrationAccountSelector'import { SourceIntegrationChoice } from './IntegrationChoice'import { parseConnectionStringForSource } from './parsers'import { supportsDirectQuery } from './schemaGroupingUtils'@@ -279,6 +279,24 @@ export const sourceFieldToElement = ()}+ // Ad/analytics sources whose account/property field is backed by the shared IntegrationAccount+ // contract: once the OAuth integration is picked, the text input becomes a dropdown of the+ // accounts the integration can access (one component, one logic, one endpoint shape for all).+ if (field.type === 'oauth-account-select') {+ return (+ <IntegrationAccountSelector+ key={field.name}+ fieldName={field.name}+ fieldLabel={field.label}+ integrationField={field.integrationField}+ integrationKind={field.integrationKind}+ sourceType={sourceConfig.name}+ placeholder={field.placeholder}+ caption={field.caption}+ />+ )+ }+if (field.type === 'file-upload') {return (<LemonField key={field.name} name={field.name} label={field.label}>@@ -312,13 +330,6 @@ export const sourceFieldToElement = (return <GitHubRepositorySelector key={field.name} />}- if (field.type === 'text' && field.name === 'site_url' && sourceConfig.name === 'GoogleSearchConsole') {- // Special case — once the user picks an OAuth integration the selector swaps the- // text input for a dropdown populated from the Search Console API. Avoids the- // `sc-domain:` vs trailing-slash typos that bounce off `validate_credentials`.- return <GoogleSearchConsoleSiteSelector key={field.name} />- }-return (<LemonFieldkey={field.name}diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex f27e67113afb..1a4f5850b9b3 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -355,17 +355,6 @@ export interface GitHubTeamsResponseApi {has_more: boolean}-export interface GoogleSearchConsoleSiteApi {- /** Site URL in canonical Google format — `https://example.com/` for URL-prefix properties (trailing slash mandatory) or `sc-domain:example.com` for Domain properties. */- siteUrl: string- /** The connected user's permission level for this site. One of `siteOwner`, `siteFullUser`, `siteRestrictedUser`, `siteUnverifiedUser`. */- permissionLevel: string-}--export interface GoogleSearchConsoleSitesResponseApi {- sites: GoogleSearchConsoleSiteApi[]-}-export interface JiraProjectApi {/** Jira project ID. */id: stringdiff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.tsindex c80ea67d99bc..4518df9996b7 100644--- a/products/integrations/frontend/generated/api.ts+++ b/products/integrations/frontend/generated/api.ts@@ -17,7 +17,6 @@ import type {GitHubReposRefreshResponseApi,GitHubReposResponseApi,GitHubTeamsResponseApi,- GoogleSearchConsoleSitesResponseApi,IntegrationAccessRequestApi,IntegrationAccessRequestResponseApi,IntegrationConfigApi,@@ -546,27 +545,6 @@ export const integrationsGoogleConversionActionsRetrieve = async (})}-export const getIntegrationsGoogleSearchConsoleSitesRetrieveUrl = (projectId: string, id: number) => {- return `/api/projects/${projectId}/integrations/${id}/google_search_console_sites/`-}--/**- * List the Search Console properties the connected Google account has access to.- */-export const integrationsGoogleSearchConsoleSitesRetrieve = async (- projectId: string,- id: number,- options?: RequestInit-): Promise<GoogleSearchConsoleSitesResponseApi> => {- return apiMutator<GoogleSearchConsoleSitesResponseApi>(- getIntegrationsGoogleSearchConsoleSitesRetrieveUrl(projectId, id),- {- ...options,- method: 'GET',- }- )-}-export const getIntegrationsJiraProjectsRetrieveUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/integrations/${id}/jira_projects/`}diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yamlindex 8925c5a7fa61..f80cce902825 100644--- a/products/integrations/mcp/tools.yaml+++ b/products/integrations/mcp/tools.yaml@@ -140,9 +140,6 @@ tools:integrations-google-conversion-actions-retrieve:operation: integrations_google_conversion_actions_retrieveenabled: false- integrations-google-search-console-sites-retrieve:- operation: integrations_google_search_console_sites_retrieve- enabled: falseintegrations-jira-projects-retrieve:operation: integrations_jira_projects_retrieveenabled: truediff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex e1f1556e7685..2d52c497fae7 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -31,6 +31,8 @@ _LAZY = {"WebhookSource": "sources.common.base","WebhookSyncResult": "sources.common.base","Config": "sources.common.config",+ "IntegrationAccountListingError": "sources.common.integration_accounts",+ "OAuthMixin": "sources.common.mixins","SourceSchema": "sources.common.schema","build_default_schemas": "sources.common.schema","RowFilterValidationError": "sources.common.sql",diff --git a/products/warehouse_sources/backend/management/commands/generate_source_configs.py b/products/warehouse_sources/backend/management/commands/generate_source_configs.pyindex 09cf142f6d7e..1a0c3a611162 100644--- a/products/warehouse_sources/backend/management/commands/generate_source_configs.py+++ b/products/warehouse_sources/backend/management/commands/generate_source_configs.py@@ -11,6 +11,7 @@ from posthog.schema import (SourceFieldFileUploadConfig,SourceFieldInputConfig,SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SourceFieldSelectConfig,SourceFieldSelectConfigConverter,@@ -107,6 +108,10 @@ class SourceConfigGenerator:field_def = self._process_oauth_field(field)return [field_def] if field_def else [], []+ elif isinstance(field, SourceFieldOauthAccountSelectConfig):+ field_def = self._process_oauth_account_select_field(field)+ return [field_def] if field_def else [], []+elif isinstance(field, SourceFieldFileUploadConfig):field_def, nested_class = self._process_file_upload_field(field, parent_class)return [field_def] if field_def else [], [nested_class]@@ -284,6 +289,20 @@ class SourceConfigGenerator:else:return f" {python_field_name}: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)"+ def _process_oauth_account_select_field(self, field: SourceFieldOauthAccountSelectConfig) -> str:+ # The selected account/property is persisted as a plain string on the config (e.g. Bing Ads+ # account_id, GSC site_url); the OAuth integration it's scoped to lives in its own field.+ python_field_name, should_alias = self._make_python_identifier(field.name)++ if field.required:+ if should_alias:+ return f' {python_field_name}: str = config.value(alias="{field.name}")'+ return f" {python_field_name}: str"++ if should_alias:+ return f' {python_field_name}: str | None = config.value(alias="{field.name}", default_factory=lambda: None)'+ return f" {python_field_name}: str | None = None"+def _process_file_upload_field(self, field: SourceFieldFileUploadConfig, parent_class: str) -> tuple[str, str]:python_field_name, should_alias = self._make_python_identifier(field.name)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.pyindex 9ada63736ad9..8058b08a8eae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py@@ -10,6 +10,10 @@ from suds import WebFaultfrom posthog.settings import integrations+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccount,+)+from .schemas import REPORT_CONFIG, RESOURCE_SCHEMAS, BingAdsResourcefrom .utils import (ENVIRONMENT,@@ -21,6 +25,11 @@ from .utils import (logger = structlog.get_logger(__name__)+# Bing Ads API version pinned across the Customer/Campaign management SOAP services (matches `bingads.v13`).+BING_ADS_API_VERSION = 13+# Microsoft's documented maximum page size for GetCustomersInfo.+GET_CUSTOMERS_INFO_MAX_RESULTS = 1000+def _as_list(value: Any) -> list[Any]:if value is None:@@ -115,7 +124,7 @@ class BingAdsClient:try:service_client = ServiceClient(service="CustomerManagementService",- version=13,+ version=BING_ADS_API_VERSION,authorization_data=self.authorization_data,environment=ENVIRONMENT,)@@ -127,6 +136,48 @@ class BingAdsClient:return self._customer_id+ def list_accounts(self) -> list[IntegrationAccount]:+ """Every account the user can access, across all their customers, as ``IntegrationAccount``.++ A user can belong to multiple customers (agencies) and ``GetAccountsInfo`` is per-customer,+ so enumerate customers first (``GetCustomersInfo``) and collect each one's accounts.+ """+ primary_customer_id = self.get_customer_id()+ original_customer_id = self.authorization_data.customer_id+ try:+ service_client = ServiceClient(+ service="CustomerManagementService",+ version=BING_ADS_API_VERSION,+ authorization_data=self.authorization_data,+ environment=ENVIRONMENT,+ )+ customers = service_client.GetCustomersInfo(CustomerNameFilter="", TopN=GET_CUSTOMERS_INFO_MAX_RESULTS)++ accounts: list[IntegrationAccount] = []+ for customer in getattr(customers, "CustomerInfo", None) or []:+ # GetAccountsInfo reads the customer from authorization_data, so scope it per customer.+ self.authorization_data.customer_id = customer.Id+ result = service_client.GetAccountsInfo(CustomerId=customer.Id, OnlyParentAccounts=False)+ for account in getattr(result, "AccountInfo", None) or []:+ status = getattr(account, "AccountLifeCycleStatus", None) or "Unknown"+ accounts.append(+ IntegrationAccount(+ value=str(account.Id),+ display_name=getattr(account, "Name", None) or "Unnamed account",+ is_primary=customer.Id == primary_customer_id,+ badges=(status,),+ group=getattr(customer, "Name", None),+ secondary_text=getattr(account, "Number", None),+ )+ )+ except Exception as e:+ raise _wrap_with_fault_detail(e, "Failed to list Bing Ads accounts") from e+ finally:+ # Restore the shared scope so a later sync on this client isn't left pointed at the last customer.+ self.authorization_data.customer_id = original_customer_id++ return accounts+def get_campaigns(self, account_id: int, customer_id: int) -> Generator[list[dict[str, Any]]]:self.authorization_data.account_id = account_idself.authorization_data.customer_id = customer_id@@ -134,7 +185,7 @@ class BingAdsClient:try:service_client = ServiceClient(service="CampaignManagementService",- version=13,+ version=BING_ADS_API_VERSION,authorization_data=self.authorization_data,environment=ENVIRONMENT,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.pyindex 02be923684c4..515e7e4c6530 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py@@ -1,11 +1,12 @@from typing import Optional, cast+from django.conf import settings+from posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,SourceConfig,- SourceFieldInputConfig,- SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SuggestedTable,)@@ -24,6 +25,10 @@ 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 ResumableSourceManager@@ -32,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.types import ExternalDataSourceTypefrom .bing_ads import bing_ads_source, get_incremental_fields, get_schemas+from .client import BingAdsClientfrom .utils import BingAdsResumeConfig@@ -140,20 +146,20 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], Ofields=cast(list[FieldType],[- SourceFieldInputConfig(- name="account_id",- label="Account ID",- type=SourceFieldInputConfigType.TEXT,- required=True,- placeholder="",- secret=False,- ),+ # OAuth first: the account dropdown below is populated from this integration.SourceFieldOauthConfig(name="bing_ads_integration_id",label="Bing Ads account",required=True,kind="bing-ads",),+ SourceFieldOauthAccountSelectConfig(+ name="account_id",+ label="Account ID",+ integrationField="bing_ads_integration_id",+ integrationKind="bing-ads",+ required=True,+ ),],),suggestedTables=[@@ -192,6 +198,53 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], Ocapture_exception(e)return False, f"Failed to validate Bing Ads credentials: {str(e)}"+ def _actionable_listing_message(self, error: str) -> str | None:+ """Map a wrapped list_accounts error to the friendly, customer-actionable message for it, or+ None if it isn't a known auth/credential failure (so it stays a 500). Reuses the non-retryable+ catalog — entries with a None friendly message are internal config issues, not user-actionable."""+ for substring, friendly in self.get_non_retryable_errors().items():+ if friendly is not None and substring in error:+ return friendly+ return None++ def get_oauth_accounts(self, integration_id: int, team_id: int) -> list[IntegrationAccount]:+ try:+ integration = self.get_oauth_integration(integration_id, team_id)+ except ValueError as e:+ # get_oauth_integration raises ValueError for a missing/foreign integration id — an+ # actionable customer-side state (deleted/disconnected), not a server bug.+ raise IntegrationAccountListingError(+ "The linked Bing Ads integration could not be found. Please reconnect your Bing Ads integration."+ ) from e++ if not settings.BING_ADS_DEVELOPER_TOKEN:+ raise ValueError("Bing Ads developer token not configured")+ if not integration.access_token:+ raise IntegrationAccountListingError(+ "Bing Ads access token not found. Please reconnect your Bing Ads integration."+ )+ if not integration.refresh_token:+ raise IntegrationAccountListingError(+ "Bing Ads refresh token not found. Please reconnect your Bing Ads integration."+ )++ client = BingAdsClient(+ access_token=integration.access_token,+ refresh_token=integration.refresh_token,+ developer_token=settings.BING_ADS_DEVELOPER_TOKEN,+ )+ try:+ return client.list_accounts()+ except ValueError as e:+ # list_accounts funnels SDK errors through _wrap_with_fault_detail, which preserves the+ # underlying type/message inside a ValueError. Match the known auth/credential failures+ # (same substrings the retry classifier uses) and surface them as an actionable 400; let+ # anything else propagate as a 500 so genuine bugs aren't masked as bad user input.+ friendly = self._actionable_listing_message(str(e))+ if friendly is not None:+ raise IntegrationAccountListingError(friendly) from e+ raise+def get_schemas(self,config: BingAdsSourceConfig,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.pyindex c3c9eeab4004..64ac46b057f5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py@@ -14,6 +14,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.c)from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.schemas import BingAdsResourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.source import BingAdsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccount,+)def _make_webfault(faultstring: str, detail: object | None) -> WebFault:@@ -100,6 +103,62 @@ class TestBingAdsClient:assert client._customer_id == self.customer_idmock_client_instance.GetUser.assert_called_once_with(UserId=None)+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.ServiceClient")+ def test_list_accounts_across_customers_flags_primary(self, mock_service_client):+ instance = mock_service_client.return_value+ instance.GetUser.return_value = mock.MagicMock(User=mock.MagicMock(CustomerId=111))+ instance.GetCustomersInfo.return_value = mock.MagicMock(+ CustomerInfo=[+ mock.MagicMock(Id=111, Name="Primary Co"),+ mock.MagicMock(Id=222, Name="Other Co"),+ ]+ )++ def accounts_for(CustomerId, OnlyParentAccounts):+ if CustomerId == 111:+ account = mock.MagicMock(Id=1, Number="A1", Name="Acc 1", AccountLifeCycleStatus="Active")+ else:+ # A missing status falls back to "Unknown" rather than the literal string "None".+ account = mock.MagicMock(Id=2, Number="B2", Name="Acc 2", AccountLifeCycleStatus=None)+ return mock.MagicMock(AccountInfo=[account])++ instance.GetAccountsInfo.side_effect = accounts_for++ client = BingAdsClient(self.access_token, self.refresh_token, self.developer_token)+ result = client.list_accounts()++ assert result == [+ IntegrationAccount(+ value="1",+ display_name="Acc 1",+ is_primary=True,+ badges=("Active",),+ group="Primary Co",+ secondary_text="A1",+ ),+ # A missing status falls back to "Unknown" rather than the literal string "None".+ IntegrationAccount(+ value="2",+ display_name="Acc 2",+ is_primary=False,+ badges=("Unknown",),+ group="Other Co",+ secondary_text="B2",+ ),+ ]+ # Per-customer scoping must not leak onto the shared authorization_data after the call.+ assert client.authorization_data.customer_id is None++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.ServiceClient")+ def test_list_accounts_wraps_soap_fault(self, mock_service_client):+ instance = mock_service_client.return_value+ instance.GetUser.return_value = mock.MagicMock(User=mock.MagicMock(CustomerId=111))+ instance.GetCustomersInfo.side_effect = _make_webfault("Server raised fault: 'Invalid client data.'", None)++ client = BingAdsClient(self.access_token, self.refresh_token, self.developer_token)+ with pytest.raises(ValueError, match="Failed to list Bing Ads accounts"):+ client.list_accounts()+@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.ServiceClient")def test_get_customer_id_preserves_underlying_exception_details(self, mock_service_client):"""Underlying exception's class name and message must be embedded in the raised ValueError sodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.pyindex 23c87b992fd3..3de4a656c364 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py@@ -1,7 +1,7 @@import pytestfrom unittest import mock-from posthog.schema import SourceFieldInputConfig, SourceFieldOauthConfig+from posthog.schema import SourceFieldOauthAccountSelectConfig, SourceFieldOauthConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.source import BingAdsSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.utils import BingAdsResumeConfig@@ -36,17 +36,19 @@ class TestBingAdsSource:assert config.iconPath == "/static/services/bing-ads.svg"assert len(config.fields) == 2- account_id_field = config.fields[0]- assert isinstance(account_id_field, SourceFieldInputConfig)- assert account_id_field.name == "account_id"- assert account_id_field.required is True-- oauth_field = config.fields[1]+ oauth_field = config.fields[0]assert isinstance(oauth_field, SourceFieldOauthConfig)assert oauth_field.name == "bing_ads_integration_id"assert oauth_field.required is Trueassert oauth_field.kind == "bing-ads"+ account_id_field = config.fields[1]+ assert isinstance(account_id_field, SourceFieldOauthAccountSelectConfig)+ assert account_id_field.name == "account_id"+ assert account_id_field.required is True+ assert account_id_field.integrationField == "bing_ads_integration_id"+ assert account_id_field.integrationKind == "bing-ads"+@pytest.mark.parametrize("account_id,integration_id,expected_error_fragment",[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.pyindex b57b65f1026d..ac2e319fb4c7 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@@ -16,6 +16,7 @@ from posthog.schema import (SourceConfig,SourceFieldFileUploadConfig,SourceFieldInputConfig,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SourceFieldSelectConfig,SourceFieldSSHTunnelConfig,@@ -84,6 +85,7 @@ FieldType = Union[SourceFieldSwitchGroupConfig,SourceFieldSelectConfig,SourceFieldOauthConfig,+ SourceFieldOauthAccountSelectConfig,SourceFieldFileUploadConfig,SourceFieldSSHTunnelConfig,]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_accounts.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_accounts.pynew file mode 100644index 000000000000..e9d9fd7e408f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_accounts.py@@ -0,0 +1,28 @@+import dataclasses+++class IntegrationAccountListingError(Exception):+ """Actionable, customer-side failure while listing an integration's accounts (missing config,+ revoked/expired credentials, a deleted integration). The OAuth accounts endpoint maps it to a 400+ so the user gets the message; non-actionable failures stay uncaught and surface as a 500."""++[email protected](frozen=True)+class IntegrationAccount:+ """A selectable account/resource an OAuth integration exposes (a Bing account, a Search Console+ site, ...). Each platform's client maps its API onto this shape so one frontend selector and one+ serializer cover all of them; platform-specific richness flattens into ``badges`` / ``group``.+ """++ value: str+ """Stored in the source config (numeric account id as a string, site url, etc.)."""+ display_name: str+ is_primary: bool = False+ """Marks the user's own/primary account context. The client (IntegrationAccountSelector) applies the+ ordering — this flag carries no server-side ordering guarantee."""+ badges: tuple[str, ...] = ()+ """Status chips, e.g. ("Active",)."""+ group: str | None = None+ """Grouping for hierarchical platforms (e.g. the owning customer name)."""+ secondary_text: str | None = None+ """Extra searchable identifier shown in parentheses, e.g. the account number."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.pyindex 218f1b822677..11926152e016 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py@@ -14,6 +14,9 @@ from posthog.utils import get_instance_regionfrom products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnelfrom products.warehouse_sources.backend.models.util import _is_safe_public_ip+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccount,+)logger = structlog.get_logger(__name__)@@ -280,6 +283,11 @@ class OAuthMixin:close_old_connections()_integration_fetch_backoff_sleep(attempt)+ def get_oauth_accounts(self, integration_id: int, team_id: int) -> list[IntegrationAccount]:+ # The account picker lives in the source: each OAuth source maps its provider's accounts onto+ # the shared IntegrationAccount contract, served by one generic endpoint.+ raise NotImplementedError(f"{type(self).__name__} does not support listing OAuth accounts")+class ValidateDatabaseHostMixin:"""Mixin for database-based sources to validate connection host"""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.pyindex 141628a9f420..106ba6894ac0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py@@ -8,8 +8,7 @@ from posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,ReleaseStatus,SourceConfig,- SourceFieldInputConfig,- SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,)@@ -20,6 +19,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSourceResponse,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+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 ResumableSourceManager@@ -68,6 +71,44 @@ class GoogleSearchConsoleSource("invalid_grant": "Your Google Search Console connection has expired or been revoked. Please reconnect your account.",}+ def get_oauth_accounts(self, integration_id: int, team_id: int) -> list[IntegrationAccount]:+ try:+ session = google_search_console_session(integration_id, team_id)+ except Integration.DoesNotExist:+ raise IntegrationAccountListingError(+ "The Google Search Console connection for this source no longer exists. "+ "Please reconnect your Google account."+ )+ try:+ sites = list_sites(session)+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status in (401, 403):+ # The token refreshed fine but the connected Google account isn't authorized to read+ # Search Console — a customer-side connection issue. Surface an actionable message the+ # endpoint turns into a 400 rather than an unhandled 500.+ raise IntegrationAccountListingError(+ "Google Search Console rejected the credentials. Please reconnect your account "+ "and ensure it has read access to the property."+ )+ raise+ except RefreshError:+ # The stored OAuth token is revoked/expired/missing scopes — raised while AuthorizedSession+ # refreshes it. Not a server bug, so surface an actionable reconnect message (400) rather+ # than letting the raw RefreshError escape as a 500.+ raise IntegrationAccountListingError(+ "Could not authenticate with Google Search Console. Please reconnect the integration."+ )+ # GSC has no name distinct from the site url, so value and display_name are the same.+ return [+ IntegrationAccount(+ value=site["siteUrl"],+ display_name=site["siteUrl"],+ badges=(site["permissionLevel"],) if site.get("permissionLevel") else (),+ )+ for site in sites+ ]+def get_schemas(self,config: GoogleSearchConsoleSourceConfig,@@ -209,17 +250,17 @@ class GoogleSearchConsoleSource(required=True,kind="google-search-console",),- SourceFieldInputConfig(+ SourceFieldOauthAccountSelectConfig(name="site_url",label="Property URL",- type=SourceFieldInputConfigType.TEXT,- required=True,+ integrationField="google_search_console_integration_id",+ integrationKind="google-search-console",placeholder="https://example.com/ or sc-domain:example.com",caption=("The exact verified property URL as it appears in Google Search Console. ""Use the trailing slash for URL prefix properties or the `sc-domain:` prefix for domain properties."),- secret=False,+ required=True,),],),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.pyindex ec8e439daf67..c112fd779ff5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py@@ -8,6 +8,7 @@ from posthog.schema import (SourceConfig,SourceFieldFileUploadConfig,SourceFieldInputConfig,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SourceFieldSelectConfig,SourceFieldSSHTunnelConfig,@@ -24,6 +25,7 @@ _SourceField = (| SourceFieldSwitchGroupConfig| SourceFieldSelectConfig| SourceFieldOauthConfig+ | SourceFieldOauthAccountSelectConfig| SourceFieldFileUploadConfig| SourceFieldSSHTunnelConfig)diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 973d948c1182..8f59c23c035b 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -3500,6 +3500,37 @@ export interface DraftCustomManifestResponseApi {error: string | null}+/**+ * A selectable account/resource exposed by an OAuth integration, in the shared shape every ad+ * platform produces (see ``IntegrationAccount`` in the data-imports common module). One serializer+ * and one frontend selector work across all platforms.+ */+export interface IntegrationAccountApi {+ /** The identifier stored in the source config and used for API calls (numeric account id as a string, a site url, etc.). */+ value: string+ /** Primary human-readable label for the account. */+ display_name: string+ /** True when this account belongs to the connected user's own (primary) account context, rather than one they merely have access to. Sorted/marked first. */+ is_primary: boolean+ /** Short status chips for the account, e.g. ['Active'] or ['Pause']. */+ badges: string[]+ /**+ * Optional grouping label for hierarchical platforms (e.g. the owning customer/manager name).+ * @nullable+ */+ group: string | null+ /**+ * Extra identifier shown in parentheses and searchable, e.g. the alphanumeric account number.+ * @nullable+ */+ secondary_text: string | null+}++export interface IntegrationAccountsResponseApi {+ /** All accounts the connected integration can access. */+ accounts: IntegrationAccountApi[]+}+/*** Source config as flat keys. For source_type 'Custom': 'manifest_json' (a stringified RESTAPIConfig describing client.base_url, auth, and resources) plus the credential for the manifest's declared auth type — 'auth_token' (bearer), 'auth_api_key' (api_key), or 'auth_password' (http_basic). Secrets stay in these auth_* keys, never inline in the manifest.*/@@ -5789,6 +5820,17 @@ export type ExternalDataSourcesConnectionsListParams = {search?: string}+export type ExternalDataSourcesOauthAccountsRetrieveParams = {+ /**+ * The OAuth integration id whose accounts should be listed.+ */+ integration_id: number+ /**+ * The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').+ */+ source_type: string+}+export type ExternalDataSourcesStoredCredentialsListParams = {/*** A search term.diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.tsindex 3f16b052b55b..26e920e95a71 100644--- a/products/warehouse_sources/frontend/generated/api.ts+++ b/products/warehouse_sources/frontend/generated/api.ts@@ -22,9 +22,11 @@ import type {ExternalDataSourcesConnectLinkRetrieveParams,ExternalDataSourcesConnectionsListParams,ExternalDataSourcesListParams,+ ExternalDataSourcesOauthAccountsRetrieveParams,ExternalDataSourcesRepairCdcCreate200,ExternalDataSourcesStoredCredentialsListParams,ExternalDataSourcesWizardRetrieveParams,+ IntegrationAccountsResponseApi,PaginatedExternalDataSchemaListApi,PaginatedExternalDataSourceConnectionOptionListApi,PaginatedExternalDataSourceSerializersListApi,@@ -927,6 +929,44 @@ export const externalDataSourcesDraftCustomManifestCreate = async (})}+export const getExternalDataSourcesOauthAccountsRetrieveUrl = (+ projectId: string,+ params: ExternalDataSourcesOauthAccountsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/external_data_sources/oauth_accounts/?${stringifiedParams}`+ : `/api/projects/${projectId}/external_data_sources/oauth_accounts/`+}++/**+ * List the accounts/properties a connected OAuth integration exposes, in the shared+ * IntegrationAccount shape. The logic lives in each source (via OAuthMixin.get_oauth_accounts);+ * this endpoint just routes by source type and serializes the result.+ */+export const externalDataSourcesOauthAccountsRetrieve = async (+ projectId: string,+ params: ExternalDataSourcesOauthAccountsRetrieveParams,+ options?: RequestInit+): Promise<IntegrationAccountsResponseApi> => {+ return apiMutator<IntegrationAccountsResponseApi>(+ getExternalDataSourcesOauthAccountsRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getExternalDataSourcesPreviewResourceCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/external_data_sources/preview_resource/`}diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yamlindex 63a848c65a40..ef914cfcbd51 100644--- a/products/warehouse_sources/mcp/tools.yaml+++ b/products/warehouse_sources/mcp/tools.yaml@@ -379,6 +379,9 @@ tools:exclude:- schemas.*.table.columns- schemas.*.available_columns+ external-data-sources-oauth-accounts-retrieve:+ operation: external_data_sources_oauth_accounts_retrieve+ enabled: falseexternal-data-sources-partial-update:operation: external_data_sources_partial_updateenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c76fc1a528a5..23acd4ffeabe 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -25689,17 +25689,6 @@ export namespace Schemas {notes: string[];}- export interface GoogleSearchConsoleSite {- /** Site URL in canonical Google format — `https://example.com/` for URL-prefix properties (trailing slash mandatory) or `sc-domain:example.com` for Domain properties. */- siteUrl: string;- /** The connected user's permission level for this site. One of `siteOwner`, `siteFullUser`, `siteRestrictedUser`, `siteUnverifiedUser`. */- permissionLevel: string;- }-- export interface GoogleSearchConsoleSitesResponse {- sites: GoogleSearchConsoleSite[];- }-/*** * `line` - line* * `symbol` - symbol@@ -29182,6 +29171,37 @@ export namespace Schemas {success: boolean;}+ /**+ * A selectable account/resource exposed by an OAuth integration, in the shared shape every ad+ * platform produces (see ``IntegrationAccount`` in the data-imports common module). One serializer+ * and one frontend selector work across all platforms.+ */+ export interface IntegrationAccount {+ /** The identifier stored in the source config and used for API calls (numeric account id as a string, a site url, etc.). */+ value: string;+ /** Primary human-readable label for the account. */+ display_name: string;+ /** True when this account belongs to the connected user's own (primary) account context, rather than one they merely have access to. Sorted/marked first. */+ is_primary: boolean;+ /** Short status chips for the account, e.g. ['Active'] or ['Pause']. */+ badges: string[];+ /**+ * Optional grouping label for hierarchical platforms (e.g. the owning customer/manager name).+ * @nullable+ */+ group: string | null;+ /**+ * Extra identifier shown in parentheses and searchable, e.g. the alphanumeric account number.+ * @nullable+ */+ secondary_text: string | null;+ }++ export interface IntegrationAccountsResponse {+ /** All accounts the connected integration can access. */+ accounts: IntegrationAccount[];+ }+/*** Standard Integration serializer.*/@@ -60003,6 +60023,17 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsExternalDataSourcesOauthAccountsRetrieveParams = {+ /**+ * The OAuth integration id whose accounts should be listed.+ */+ integration_id: number;+ /**+ * The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').+ */+ source_type: string;+ };+export type EnvironmentsExternalDataSourcesStoredCredentialsListParams = {/*** A search term.@@ -66882,6 +66913,17 @@ export namespace Schemas {search?: string;};+ export type ExternalDataSourcesOauthAccountsRetrieveParams = {+ /**+ * The OAuth integration id whose accounts should be listed.+ */+ integration_id: number;+ /**+ * The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').+ */+ source_type: string;+ };+export type ExternalDataSourcesStoredCredentialsListParams = {/*** A search term.