Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-warehouse): pick the Apple Ads ad account from a list (#104291)

Tom Owers0ecf7c6e28dd
diff --git a/frontend/src/lib/integrations/credentialAccountsLogic.ts b/frontend/src/lib/integrations/credentialAccountsLogic.ts
new file mode 100644
index 000000000000..2ec8c4fc114a
--- /dev/null
+++ b/frontend/src/lib/integrations/credentialAccountsLogic.ts
@@ -0,0 +1,125 @@
+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+
+import { externalDataSourcesCredentialAccountsCreate } from 'products/warehouse_sources/frontend/generated/api'
+import type { IntegrationAccountApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+const CREDENTIALS_DEBOUNCE_MS = 500
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface credentialAccountsLogicValues {
+ accounts: IntegrationAccountApi[]
+ accountsError: string | null
+ accountsLoaded: boolean
+ accountsLoading: boolean
+ credentials: Record<string, string>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface credentialAccountsLogicActions {
+ loadAccounts: () => any
+ loadAccountsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAccountsSuccess: (
+ accounts: IntegrationAccountApi[],
+ payload?: any
+ ) => {
+ accounts: IntegrationAccountApi[]
+ payload?: any
+ }
+ setCredentials: (credentials: Record<string, string>) => {
+ credentials: Record<string, string>
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface credentialAccountsLogicProps {
+ sourceType: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface credentialAccountsLogicMeta {
+ key: string
+}
+
+export type credentialAccountsLogicType = MakeLogicType<
+ credentialAccountsLogicValues,
+ credentialAccountsLogicActions,
+ credentialAccountsLogicProps,
+ credentialAccountsLogicMeta
+>
+
+/**
+ * Accounts listed from credentials still sitting in the connect form, for a source that has no
+ * OAuth integration to read them from. The OAuth twin is `integrationAccountsLogic`.
+ *
+ * Keyed on source type alone: the credentials change as the user types, and keying on them would
+ * mount a fresh logic per keystroke.
+ */
+export const credentialAccountsLogic = kea<credentialAccountsLogicType>([
+ props({} as { sourceType: string }),
+ key((props) => props.sourceType),
+ path((key) => ['lib', 'integrations', 'credentialAccountsLogic', key]),
+
+ actions({
+ setCredentials: (credentials: Record<string, string>) => ({ credentials }),
+ }),
+
+ loaders(({ props, values }) => ({
+ accounts: [
+ [] as IntegrationAccountApi[],
+ {
+ loadAccounts: async () => {
+ const response = await externalDataSourcesCredentialAccountsCreate(
+ String(ApiConfig.getCurrentProjectId()),
+ {
+ source_type: props.sourceType,
+ credentials: values.credentials,
+ }
+ )
+ return response.accounts
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ credentials: [{} as Record<string, string>, { setCredentials: (_, { credentials }) => credentials }],
+ // Distinguishes "not fetched yet" from "fetched and genuinely empty", so the picker doesn't
+ // flash an empty state before the first response.
+ accountsLoaded: [
+ false,
+ {
+ loadAccountsSuccess: () => true,
+ loadAccountsFailure: () => true,
+ },
+ ],
+ // The backend turns a provider rejection into an actionable 400 (a key it won't accept, a
+ // role that can read nothing). Surface that rather than a generic empty state.
+ accountsError: [
+ null as string | null,
+ {
+ loadAccounts: () => null,
+ loadAccountsSuccess: () => null,
+ loadAccountsFailure: (_, { error, errorObject }) =>
+ errorObject?.data?.detail ?? errorObject?.detail ?? error ?? null,
+ },
+ ],
+ }),
+
+ listeners(({ actions }) => ({
+ setCredentials: async (_, breakpoint) => {
+ // Longer than the OAuth logic's search debounce: this fires while the user is still
+ // typing credentials, and each attempt costs a token exchange against the provider.
+ await breakpoint(CREDENTIALS_DEBOUNCE_MS)
+ actions.loadAccounts()
+ },
+ })),
+])
diff --git a/products/data_warehouse/frontend/shared/components/forms/CredentialAccountSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/CredentialAccountSelector.tsx
new file mode 100644
index 000000000000..6f5fbaee1b1f
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/forms/CredentialAccountSelector.tsx
@@ -0,0 +1,164 @@
+import { useActions, useValues } from 'kea'
+import { FormContext } from 'kea-forms'
+import { useContext, useEffect, useMemo } from 'react'
+
+import { LemonInput } from '@posthog/lemon-ui'
+
+import { credentialAccountsLogic } from 'lib/integrations/credentialAccountsLogic'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+
+import { InputSuggestion, InputWithSuggestionsDropdown } from './InputWithSuggestionsDropdown'
+
+export interface CredentialAccountSelectorProps {
+ fieldName: string
+ fieldLabel: string
+ /** Sibling payload fields whose values the listing needs, named by the field config. */
+ credentialFields: string[]
+ /** Data warehouse source type used to route the listing endpoint, e.g. "AppleSearchAds". */
+ sourceType: string
+ placeholder?: string
+ /** Optional format guidance rendered under the field label. */
+ caption?: string
+}
+
+/** Pull the named credential fields out of a (possibly nested) form payload.
+ *
+ * Returns undefined until every one of them has a value: the listing calls the provider, and a
+ * request built from a half-filled form can only fail. */
+export function collectCredentials(payload: unknown, credentialFields: string[]): Record<string, string> | undefined {
+ const collected: Record<string, string> = {}
+ for (const name of credentialFields) {
+ const value = findFieldValue(payload, name)
+ if (value === undefined || value === null || String(value).trim() === '') {
+ return undefined
+ }
+ collected[name] = String(value)
+ }
+ return collected
+}
+
+/** Find the value stored under `key` anywhere in a (possibly nested) payload object. Mirrors the
+ * OAuth picker's lookup: a credential can sit inside a select group rather than at the top level. */
+function findFieldValue(obj: unknown, key: string): unknown {
+ if (!obj || typeof obj !== 'object') {
+ return undefined
+ }
+ const record = obj as Record<string, unknown>
+ if (key in record) {
+ return record[key]
+ }
+ for (const nested of Object.values(record)) {
+ const found = findFieldValue(nested, key)
+ if (found !== undefined) {
+ return found
+ }
+ }
+ return undefined
+}
+
+/** Account picker for a source whose credentials are typed into the connect form rather than held
+ * by an OAuth integration. The OAuth twin is `IntegrationAccountSelector`; both render the same
+ * free-text-with-suggestions input, so a user who cannot list accounts can always type one. */
+export function CredentialAccountSelector(props: CredentialAccountSelectorProps): JSX.Element {
+ // Only mount the hook-using inner component inside a kea <Form>, to avoid a null logic.
+ const formContext = useContext(FormContext)
+ if (!formContext.logic) {
+ return <AccountTextField {...props} />
+ }
+ return <CredentialAccountSelectorInner {...props} formLogic={formContext.logic} formKey={formContext.formKey} />
+}
+
+function CredentialAccountSelectorInner({
+ formLogic,
+ formKey,
+ ...props
+}: CredentialAccountSelectorProps & { formLogic: any; formKey: string }): JSX.Element {
+ const { sourceType, credentialFields, fieldName, fieldLabel, placeholder, caption } = props
+ const values = useValues(formLogic) as Record<string, any> | null
+ const credentials = collectCredentials(values?.[formKey]?.payload, credentialFields)
+
+ const { accounts, accountsLoading, accountsLoaded, accountsError } = useValues(
+ credentialAccountsLogic({ sourceType })
+ )
+ const { setCredentials } = useActions(credentialAccountsLogic({ sourceType }))
+
+ // Serialized so the effect fires on a changed credential rather than on every render.
+ const credentialsKey = credentials ? JSON.stringify(credentials) : ''
+ useEffect(() => {
+ if (credentialsKey) {
+ setCredentials(JSON.parse(credentialsKey))
+ }
+ }, [credentialsKey, setCredentials])
+
+ const suggestions = useMemo<InputSuggestion[]>(
+ () =>
+ accounts.map((account) => ({
+ value: account.value,
+ label:
+ account.display_name === account.value
+ ? account.display_name
+ : `${account.display_name} (${account.value})`,
+ searchText: [account.display_name, account.value].join(' '),
+ })),
+ [accounts]
+ )
+
+ return (
+ <LemonField name={fieldName} label={fieldLabel} help={captionHelp(caption)}>
+ {({ value, onChange }) => (
+ <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={
+ credentials
+ ? "Couldn't load your accounts. Type the value in above."
+ : 'Fill in the credentials above to list accounts.'
+ }
+ noMatchMessage={() => 'No accounts match your filter.'}
+ loadingMessage="Loading accounts…"
+ />
+ {accountsError && <p className="m-0 text-xs text-warning">{accountsError}</p>}
+ {accountsLoaded && !accountsLoading && !accountsError && accounts.length === 0 && (
+ <p className="m-0 text-xs text-warning">
+ These credentials can't read any {fieldLabel} yet. Check the API user's role, or enter the
+ value above if you know it.
+ </p>
+ )}
+ </div>
+ )}
+ </LemonField>
+ )
+}
+
+function captionHelp(caption?: string): JSX.Element | undefined {
+ return caption ? <LemonMarkdown className="text-xs">{caption}</LemonMarkdown> : undefined
+}
+
+function AccountTextField({
+ fieldName,
+ fieldLabel,
+ placeholder,
+ caption,
+}: CredentialAccountSelectorProps): 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>
+ )
+}
diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
index 55af54dcec5f..93882b0af3cc 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
@@ -36,6 +36,7 @@ import {
sourceWizardLogic,
} from '../../../scenes/NewSourceScene/sourceWizardLogic'
import { CDC_SOURCE_TYPES } from '../../cdc'
+import { CredentialAccountSelector } from './CredentialAccountSelector'
import { isCustomSourceAiBuilderEnabled } from './customSourceManifest'
import { CustomSourceManifestBuilder } from './CustomSourceManifestBuilder'
import { customSourceManifestBuilderLogic } from './customSourceManifestBuilderLogic'
@@ -403,6 +404,22 @@ export const sourceFieldToElement = (
)
}
+ // Sources whose credentials live in the form rather than in an OAuth integration: the account
+ // field lists what those credentials can reach, while staying a free-text input.
+ if (field.type === 'credential-account-select') {
+ return (
+ <CredentialAccountSelector
+ key={field.name}
+ fieldName={field.name}
+ fieldLabel={field.label}
+ credentialFields={field.credentialFields}
+ sourceType={sourceConfig.name}
+ placeholder={field.placeholder ?? undefined}
+ caption={field.caption ?? undefined}
+ />
+ )
+ }
+
if (field.type === 'file-upload') {
return (
<LemonField key={field.name} name={field.name} label={field.label}>
diff --git a/products/data_warehouse/frontend/shared/components/forms/collectCredentials.test.ts b/products/data_warehouse/frontend/shared/components/forms/collectCredentials.test.ts
new file mode 100644
index 000000000000..e49705e837f5
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/forms/collectCredentials.test.ts
@@ -0,0 +1,41 @@
+import { collectCredentials } from './CredentialAccountSelector'
+
+describe('collectCredentials', () => {
+ const FIELDS = ['client_id', 'private_key']
+
+ it('collects the named fields from a flat payload', () => {
+ expect(collectCredentials({ client_id: 'abc', private_key: 'pem', unrelated: 'x' }, FIELDS)).toEqual({
+ client_id: 'abc',
+ private_key: 'pem',
+ })
+ })
+
+ it('finds a field nested under a select group', () => {
+ // Mirrors how a source with two auth methods stores its fields, the shape the OAuth picker's
+ // own lookup exists to handle.
+ expect(collectCredentials({ auth_method: { client_id: 'abc', private_key: 'pem' } }, FIELDS)).toEqual({
+ client_id: 'abc',
+ private_key: 'pem',
+ })
+ })
+
+ // Every listing attempt costs a token exchange against the provider, and one built from a
+ // half-filled form can only fail — so an incomplete payload must not produce a request.
+ it.each([
+ ['a missing field', { client_id: 'abc' }],
+ ['an empty string', { client_id: 'abc', private_key: '' }],
+ ['whitespace only', { client_id: 'abc', private_key: ' ' }],
+ ['a null', { client_id: 'abc', private_key: null }],
+ ['an empty payload', {}],
+ ['a non-object payload', undefined],
+ ])('returns undefined for %s', (_label, payload) => {
+ expect(collectCredentials(payload, FIELDS)).toBeUndefined()
+ })
+
+ it('stringifies non-string values', () => {
+ expect(collectCredentials({ client_id: 123, private_key: 'pem' }, FIELDS)).toEqual({
+ client_id: '123',
+ private_key: 'pem',
+ })
+ })
+})
diff --git a/products/warehouse_sources/backend/facade/source_config.py b/products/warehouse_sources/backend/facade/source_config.py
index 72a355eb401e..8c3badae8fcf 100644
--- a/products/warehouse_sources/backend/facade/source_config.py
+++ b/products/warehouse_sources/backend/facade/source_config.py
@@ -24,6 +24,7 @@ __all__ = [
"SourceConfigResponse",
"SourceDocumentedTable",
"SourceFieldConfig",
+ "SourceFieldCredentialAccountSelectConfig",
"SourceFieldFileUploadConfig",
"SourceFieldFileUploadJsonFormatConfig",
"SourceFieldInputConfig",
@@ -143,6 +144,32 @@ class SourceFieldOauthAccountSelectConfig(BaseModel):
type: Literal["oauth-account-select"] = "oauth-account-select"
+class SourceFieldCredentialAccountSelectConfig(BaseModel):
+ """Account picker for a source whose credentials are typed into the form, not held by an
+ `Integration` row. Same `IntegrationAccount` shape and same picker as `oauth-account-select`;
+ only where the credentials come from differs.
+
+ `credentialFields` is the security boundary. The listing endpoint accepts those field names and
+ no others, so the picker cannot be used to push arbitrary connection details into a source's
+ client.
+ """
+
+ model_config = _WIRE_MODEL_CONFIG
+ caption: str | None = None
+ credentialFields: list[str] = Field(
+ ...,
+ description=(
+ "Names of the sibling fields whose values the account listing needs. The form sends"
+ " exactly these, and the listing endpoint accepts exactly these."
+ ),
+ )
+ label: str
+ name: str
+ placeholder: str | None = None
+ required: bool | None = None
+ type: Literal["credential-account-select"] = "credential-account-select"
+
+
class SourceFieldInputConfig(BaseModel):
model_config = _WIRE_MODEL_CONFIG
caption: str | None = None
@@ -232,6 +259,7 @@ SourceFieldConfig = Annotated[
SourceFieldSelectConfig,
SourceFieldOauthConfig,
SourceFieldOauthAccountSelectConfig,
+ SourceFieldCredentialAccountSelectConfig,
SourceFieldFileUploadConfig,
SourceFieldSSHTunnelConfig,
],
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 4136bcbc35fa..4b7758c48774 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -41,6 +41,7 @@ _LAZY = {
"Config": "sources.common.config",
"IntegrationAccountListingError": "sources.common.integration_accounts",
"filter_integration_accounts": "sources.common.integration_accounts",
+ "CredentialAccountsMixin": "sources.common.mixins",
"DATABASE_HOST_NOT_ALLOWED_GUIDANCE": "sources.common.mixins",
"HostNotAllowedError": "sources.common.mixins",
"OAuthMixin": "sources.common.mixins",
diff --git a/products/warehouse_sources/backend/management/commands/generate_source_configs.py b/products/warehouse_sources/backend/management/commands/generate_source_configs.py
index 1a01733e8c04..5b2f48fd2f8d 100644
--- a/products/warehouse_sources/backend/management/commands/generate_source_configs.py
+++ b/products/warehouse_sources/backend/management/commands/generate_source_configs.py
@@ -9,6 +9,7 @@ from structlog import get_logger
from products.warehouse_sources.backend.facade.source_config import (
SourceConfig,
+ SourceFieldCredentialAccountSelectConfig,
SourceFieldFileUploadConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
@@ -126,6 +127,10 @@ class SourceConfigGenerator:
field_def = self._process_oauth_account_select_field(field)
return [field_def] if field_def else [], []
+ elif isinstance(field, SourceFieldCredentialAccountSelectConfig):
+ field_def = self._process_credential_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]
@@ -344,6 +349,20 @@ class SourceConfigGenerator:
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_credential_account_select_field(self, field: SourceFieldCredentialAccountSelectConfig) -> str:
+ # Persisted exactly like a text field — the picker only changes how the value is chosen, so a
+ # source can switch a field to this type without reshaping configs already stored.
+ 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/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
index b9331c30c691..e0b55fc79bd1 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
@@ -19,6 +19,7 @@ from products.data_warehouse.backend.facade.api import (
)
from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SOURCE_PREFIX, ExternalDataSource
from products.warehouse_sources.backend.facade.source_config import (
+ SourceFieldCredentialAccountSelectConfig,
SourceFieldFileUploadConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
@@ -179,6 +180,26 @@ def get_oauth_integration_kinds(fields: list[FieldType]) -> set[str]:
return kinds
+def get_credential_account_field_names(fields: list[FieldType]) -> set[str]:
+ """The field names a source's credential account pickers are allowed to be handed.
+
+ The listing endpoint takes connection details straight from a form that has not been submitted,
+ so without this it would accept any key the caller invented and hand it to `parse_config`.
+ Collecting the names the source itself declared holds the endpoint to the credentials a picker
+ genuinely needs, and leaves a source that declares no such picker unable to reach it at all."""
+ names: set[str] = set()
+ for field in fields:
+ if isinstance(field, SourceFieldCredentialAccountSelectConfig):
+ names.update(field.credentialFields)
+ elif isinstance(field, SourceFieldSwitchGroupConfig):
+ names.update(get_credential_account_field_names(field.fields))
+ elif isinstance(field, SourceFieldSelectConfig):
+ for option in field.options:
+ if option.fields:
+ names.update(get_credential_account_field_names(option.fields))
+ return names
+
+
def _name_variants(name: str) -> tuple[str, ...]:
"""The spellings a declared field name can be stored under, declared spelling first.
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/oauth_accounts.py b/products/warehouse_sources/backend/presentation/views/external_data_source/oauth_accounts.py
index afee63f30774..a412cd155f19 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/oauth_accounts.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/oauth_accounts.py
@@ -17,6 +17,7 @@ from posthog.models.integration import Integration
from posthog.permissions import TeamMemberAdminManagementPermission
from products.warehouse_sources.backend.facade.source_management import (
+ CredentialAccountsMixin,
IntegrationAccountListingError,
OAuthMixin,
filter_integration_accounts,
@@ -59,6 +60,23 @@ class IntegrationAccountsResponseSerializer(serializers.Serializer):
)
+class CredentialAccountsRequestSerializer(serializers.Serializer):
+ """Body for listing accounts from credentials the user has typed but not yet submitted."""
+
+ source_type = serializers.CharField(
+ help_text="The data warehouse source type whose picker is asking (e.g. 'AppleSearchAds')."
+ )
+ credentials = serializers.DictField(
+ child=serializers.CharField(allow_blank=True, trim_whitespace=False),
+ help_text=("Values of the sibling fields named by the picker's `credentialFields`. Any other key is rejected."),
+ )
+ api_version = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Vendor API version the source is pinned to. Defaults to the source's current default.",
+ )
+
+
class AccountPickerManagementPermission(TeamMemberAdminManagementPermission):
"""Admin gate for the account picker, with a message the customer can act on.
@@ -163,3 +181,59 @@ class ExternalDataSourceOAuthAccountsMixin(base.ExternalDataSourceViewSetBase):
if accounts:
cache.set(cache_key, response_data, 60)
return Response(response_data)
+
+ @extend_schema(
+ request=CredentialAccountsRequestSerializer,
+ responses={200: IntegrationAccountsResponseSerializer},
+ )
+ @action(methods=["POST"], detail=False, url_path="credential_accounts")
+ def credential_accounts(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """List the accounts a source's typed-in credentials can reach, in the shared
+ IntegrationAccount shape.
+
+ The OAuth twin takes an integration id because the token already lives on the server. Here
+ the credentials are still in the form, so they arrive in the body — POST, not GET, to keep a
+ private key out of the URL and out of anything that logs one. Nothing is cached for the same
+ reason: the cache key would have to include the credentials.
+ """
+ serializer = CredentialAccountsRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+
+ source_type = data["source_type"]
+ try:
+ source = base.SourceRegistry.get_source(cast(ExternalDataSourceType, source_type))
+ except ValueError:
+ raise ValidationError(f"Unknown source type: {source_type}")
+
+ if not isinstance(source, CredentialAccountsMixin):
+ raise ValidationError(f"Source type {source_type} does not support listing accounts from credentials")
+
+ # The declared names are the whole allowlist. A source with no credential picker has an empty
+ # set, which fails here rather than reaching `parse_config` with caller-chosen keys.
+ allowed = helpers.get_credential_account_field_names(source.get_source_config.fields)
+ if not allowed:
+ raise ValidationError(f"Source type {source_type} does not support listing accounts from credentials")
+
+ credentials = data["credentials"]
+ unexpected = set(credentials) - allowed
+ if unexpected:
+ raise ValidationError(f"Unexpected credential fields: {', '.join(sorted(unexpected))}")
+
+ try:
+ config = source.parse_config(credentials)
+ except Exception:
+ # A half-filled form is the normal case here — the picker fires as soon as the user
+ # stops typing — so this is not worth capturing.
+ raise ValidationError("Fill in the credentials above to list accounts.")
+
+ try:
+ accounts = source.get_credential_accounts(config, self.team_id, api_version=data.get("api_version"))
+ except NotImplementedError:
+ raise ValidationError(f"Source type {source_type} does not support listing accounts from credentials")
+ except IntegrationAccountListingError as e:
+ # Same split as the OAuth path: an actionable customer-side failure (a key the provider
+ # rejects) is a 400 carrying its message; anything else stays uncaught as a 500.
+ raise ValidationError(str(e))
+
+ return Response(IntegrationAccountsResponseSerializer({"accounts": accounts}).data)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/viewset.py b/products/warehouse_sources/backend/presentation/views/external_data_source/viewset.py
index e6f444b5e18d..ff2785da5072 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/viewset.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/viewset.py
@@ -89,6 +89,9 @@ class ExternalDataSourceViewSet(
# 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",
+ # Same disclosure concern as `oauth_accounts`, plus it makes an outbound call with
+ # credentials taken from the request body.
+ "credential_accounts",
# Live outbound HTTP to a caller-supplied manifest (including POSTs) — a
# side-effecting action, so it needs write scope, not read.
"preview_resource",
@@ -131,7 +134,7 @@ class ExternalDataSourceViewSet(
# 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":
+ if self.action in ("oauth_accounts", "credential_accounts"):
return [
IsAuthenticated(),
APIScopePermission(),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py
index 7830acdcbcab..31c7aed81f49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py
@@ -84,6 +84,18 @@ class AppleSearchAdsCredentials:
ad_account_id: Optional[str] = None
+@frozen
+class AppleAdAccount:
+ """One ad account the configured API client can read, for the connect form's picker."""
+
+ id: str
+ name: Optional[str] = None
+
+ @property
+ def label(self) -> str:
+ return f"{self.id} ({self.name})" if self.name else self.id
+
+
@dataclasses.dataclass(frozen=True)
class AppleSearchAdsResumeConfig:
# Offset into the current page set.
@@ -306,7 +318,7 @@ def validate_credentials(
missing = missing_context_id(credentials, api_version)
if missing is not None:
if api_version == APPLE_ADS_API_VERSION_V1:
- return False, _blank_ad_account_message(_readable_ad_accounts(client, api_version))
+ return False, _blank_ad_account_message(readable_ad_accounts(client, api_version))
return False, missing
# The campaign list is the cheapest account-scoped read: it exercises the access token
@@ -332,10 +344,13 @@ def validate_credentials(
return False, f"The Apple Ads API returned an unexpected status code: {status}"
-def _readable_ad_accounts(client: AppleSearchAdsClient, api_version: str) -> Optional[list[tuple[str, Optional[str]]]]:
- """Ad accounts these credentials can read as ``(id, name)`` pairs, or None when the lookup fails.
+def readable_ad_accounts(client: AppleSearchAdsClient, api_version: str) -> Optional[list[AppleAdAccount]]:
+ """The ad accounts these credentials can read, or None when the lookup itself failed.
- Best effort. The ACL lookup carries no context id, so it works before one is entered.
+ Best effort, and never raises: the ACL lookup carries no context id, so it works before one
+ is entered. Both callers have something better to say than the lookup's own error, and both
+ need to tell "the lookup failed" apart from "it found nothing" — the connect message names a
+ different next step for each, and the picker keeps its free-text field either way.
"""
if api_version != APPLE_ADS_API_VERSION_V1:
return None
@@ -349,13 +364,13 @@ def _readable_ad_accounts(client: AppleSearchAdsClient, api_version: str) -> Opt
except (requests.RequestException, ValueError):
return None
- accounts: list[tuple[str, Optional[str]]] = []
+ accounts: list[AppleAdAccount] = []
for account in flatten_acl_rows(page_rows(payload, config, api_version)):
account_id = account.get("id")
if account_id is None:
continue
name = account.get("name")
- accounts.append((str(account_id), str(name) if name else None))
+ accounts.append(AppleAdAccount(id=str(account_id), name=str(name) if name else None))
return accounts
@@ -364,7 +379,7 @@ _AD_ACCOUNT_SCOPING = (
)
-def _blank_ad_account_message(accounts: Optional[list[tuple[str, Optional[str]]]]) -> str:
+def _blank_ad_account_message(accounts: Optional[list[AppleAdAccount]]) -> str:
if accounts is None:
return (
"Enter the ad account ID. PostHog could not list the ad accounts these credentials can "
@@ -376,10 +391,10 @@ def _blank_ad_account_message(accounts: Optional[list[tuple[str, Optional[str]]]
"These credentials cannot read any ad account yet. Give the API user the API Account "
"Read Only role for the ad account in Apple Ads, then connect again."
)
- named = ", ".join(f"{account_id} ({name})" if name else account_id for account_id, name in accounts)
+ named = ", ".join(account.label for account in accounts)
if len(accounts) == 1:
return (
- f"These credentials can read one ad account: {named}. Enter {accounts[0][0]} in Ad "
+ f"These credentials can read one ad account: {named}. Enter {accounts[0].id} in Ad "
f"account ID and connect again. {_AD_ACCOUNT_SCOPING}"
)
return (
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py
index 399c11455e4e..b2a73e86daa6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py
@@ -1,17 +1,23 @@
from datetime import date
from typing import Optional, cast
+import requests
+
from products.warehouse_sources.backend.facade.source_config import (
DataWarehouseSourceCategory,
ReleaseStatus,
SourceConfig,
+ SourceFieldCredentialAccountSelectConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
+ AppleSearchAdsAuthError,
+ AppleSearchAdsClient,
AppleSearchAdsCredentials,
AppleSearchAdsResumeConfig,
apple_search_ads_source,
+ readable_ad_accounts,
validate_credentials as validate_apple_search_ads_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (
@@ -32,6 +38,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ IntegrationAccountListingError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import CredentialAccountsMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
@@ -46,7 +57,10 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AppleSearchAdsSource(ResumableSource[AppleSearchAdsSourceConfig, AppleSearchAdsResumeConfig]):
+class AppleSearchAdsSource(
+ ResumableSource[AppleSearchAdsSourceConfig, AppleSearchAdsResumeConfig],
+ CredentialAccountsMixin[AppleSearchAdsSourceConfig],
+):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
supported_versions = (APPLE_SEARCH_ADS_API_VERSION_V5, APPLE_ADS_API_VERSION_V1)
@@ -120,7 +134,7 @@ Apple does not generate an API key for you. You supply your own key pair, and on
2. Generate an EC P-256 key pair. On macOS or Linux, run `openssl ecparam -genkey -name prime256v1 -noout -out private-key.pem` and then `openssl ec -in private-key.pem -pubout -out public-key.pem`.
3. Signed in as that user, open **Account settings > API**, paste the contents of `public-key.pem` into the public key field and save. Saving the key creates the client.
4. Apple then shows the client ID, team ID and key ID above the field. Enter those below, along with the contents of `private-key.pem`.
-5. Leave **Ad account ID** blank on the first connect. PostHog stops and shows the ad account IDs your credentials can read. That stop is the expected result of the first connect, not a credential failure. Enter one of the IDs and connect again. To look it up yourself, read `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, with an access token signed by the credentials from step 4 — follow [Apple's OAuth guide](https://developer.apple.com/documentation/apple_ads/implementing-oauth-for-the-apple-search-ads-api) to exchange them for one. The ad account ID is not the same value as your organization ID.
+5. Pick your **Ad account ID** from the list, which fills in once the four fields above are complete. Apple shows this ID nowhere in its UI, and it is not the same value as your organization ID. To look it up yourself, read `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, with an access token signed by the credentials from step 4. [Apple's OAuth guide](https://developer.apple.com/documentation/apple_ads/implementing-oauth-for-the-apple-search-ads-api) covers that exchange.
PostHog stores the private key encrypted and uses it to sign a short-lived token on every sync. The token itself is never stored.
@@ -135,18 +149,6 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
fields=cast(
list[FieldType],
[
- SourceFieldInputConfig(
- name="ad_account_id",
- label="Ad account ID",
- type=SourceFieldInputConfigType.TEXT,
- # Optional at the form level because a source pinned to Apple's older
- # API needs the organization ID below instead. `validate_credentials`
- # requires whichever one the source's API version uses.
- required=False,
- placeholder="123456789",
- caption="Leave this blank on the first connect. PostHog stops and shows the ad account IDs your credentials can read. That stop is the expected result, not a credential failure. Enter one of the IDs and connect again. To look it up yourself, read `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, with an access token signed by the credentials above.",
- secret=False,
- ),
SourceFieldInputConfig(
name="client_id",
label="Client ID",
@@ -183,6 +185,20 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
caption="The unencrypted EC P-256 private key matching the public key you uploaded to Apple.",
secret=True,
),
+ SourceFieldCredentialAccountSelectConfig(
+ name="ad_account_id",
+ label="Ad account ID",
+ # Optional at the form level because a source pinned to Apple's older API
+ # needs the organization ID below instead. `validate_credentials` requires
+ # whichever one the source's API version uses.
+ required=False,
+ placeholder="123456789",
+ # Ordered after the four fields it names, because the lookup signs a token
+ # with them. Apple exposes the ad account id nowhere in its UI, so without
+ # this the only way to read one is to call the ACL endpoint by hand.
+ credentialFields=["client_id", "apple_team_id", "key_id", "private_key"],
+ caption="Fill in the credentials above and this lists the ad accounts they can read. You can also type one in: it is `adAccount.id` from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, and it is not the same as your organization ID.",
+ ),
SourceFieldInputConfig(
name="start_date",
label="Report start date",
@@ -254,6 +270,36 @@ Reporting tables use daily granularity, which Apple serves for the last 90 days
schema_name,
)
+ def get_credential_accounts(
+ self, config: AppleSearchAdsSourceConfig, team_id: int, api_version: str | None = None
+ ) -> list[IntegrationAccount]:
+ """The ad accounts the entered credentials can read.
+
+ Only the Platform API scopes on an ad account; a source pinned to the older Campaign
+ Management API takes an organization ID, which Apple does show in its UI, so there is
+ nothing to list.
+ """
+ resolved_version = self.resolve_api_version(api_version)
+ # Checked before authenticating: a token exchange to then list nothing still spends the
+ # customer's Apple rate-limit budget on every keystroke that completes the form.
+ if resolved_version != APPLE_ADS_API_VERSION_V1:
+ return []
+
+ client = AppleSearchAdsClient(self._credentials(config), resolved_version)
+ try:
+ client.authenticate()
+ except AppleSearchAdsAuthError as e:
+ raise IntegrationAccountListingError(str(e)) from e
+ except requests.RequestException as e:
+ raise IntegrationAccountListingError(
+ f"Could not exchange the Apple Ads credentials for an access token: {e}"
+ ) from e
+
+ # None means the ACL lookup itself failed. The picker has no better answer than an empty
+ # list either way, and its field stays free text, so the user can still type an id.
+ accounts = readable_ad_accounts(client, resolved_version) or []
+ return [IntegrationAccount(value=account.id, display_name=account.name or account.id) for account in accounts]
+
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppleSearchAdsResumeConfig]:
# Entity and report endpoints store incompatible checkpoint shapes, so keep each
# endpoint's state in its own Redis slot.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py
index a59555ddcdfd..e0f0d8aea71a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py
@@ -1,12 +1,19 @@
from datetime import date
from typing import Any, cast
+import pytest
from unittest import mock
+import requests
from parameterized import parameterized
-from products.warehouse_sources.backend.facade.source_config import SourceFieldInputConfig
+from products.warehouse_sources.backend.facade.source_config import (
+ SourceFieldCredentialAccountSelectConfig,
+ SourceFieldInputConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
+ AppleAdAccount,
+ AppleSearchAdsAuthError,
AppleSearchAdsResumeConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (
@@ -23,6 +30,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
VersionDeprecation,
error_message_matches,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applesearchads import (
AppleSearchAdsSourceConfig,
@@ -186,20 +196,25 @@ class TestAppleSearchAdsSource:
assert (credentials.ad_account_id, credentials.org_id) == ("123456789", "555")
- def test_the_field_caption_and_step_five_describe_the_same_blank_connect_flow(self) -> None:
+ def test_the_field_caption_and_step_five_describe_the_same_flow(self) -> None:
+ # Two surfaces describe how someone gets their ad account id, and nothing renders them
+ # together, so one can be rewritten while the other keeps naming a flow that is gone.
config = self.source.get_source_config
field_caption = next(
field.caption
for field in config.fields
- if isinstance(field, SourceFieldInputConfig) and field.name == "ad_account_id"
+ if isinstance(field, SourceFieldCredentialAccountSelectConfig) and field.name == "ad_account_id"
)
assert field_caption is not None
assert config.caption is not None
step_five = next(line for line in config.caption.splitlines() if line.startswith("5."))
for text in (field_caption, step_five):
- assert "connect again" in text
- assert "expected" in text
+ # Both name the picker and the manual fallback, and neither still tells anyone to
+ # connect with the field blank.
+ assert "list" in text
+ assert "v1/acls" in text
+ assert "blank" not in text
def test_the_connect_form_does_not_require_either_context_id(self) -> None:
# `required` cannot express "depends on the version pin", so `validate_credentials`
@@ -207,8 +222,68 @@ class TestAppleSearchAdsSource:
fields = {
field.name: field
for field in self.source.get_source_config.fields
- if isinstance(field, SourceFieldInputConfig)
+ if isinstance(field, SourceFieldInputConfig | SourceFieldCredentialAccountSelectConfig)
}
assert fields["ad_account_id"].required is False
assert fields["org_id"].required is False
+
+ def test_credential_accounts_map_apples_acl_onto_the_shared_picker_shape(self) -> None:
+ # Apple shows the ad account id nowhere in its UI, so the ACL read is the only way a user
+ # gets one. An account with no name falls back to its id rather than rendering "None".
+ with (
+ mock.patch(f"{SOURCE_MODULE}.AppleSearchAdsClient") as mock_client,
+ mock.patch(f"{SOURCE_MODULE}.readable_ad_accounts") as mock_accounts,
+ ):
+ mock_accounts.return_value = [
+ AppleAdAccount(id="1111111", name="Example Retail"),
+ AppleAdAccount(id="2222222", name=None),
+ ]
+
+ accounts = self.source.get_credential_accounts(self.config, self.team_id)
+
+ mock_client.return_value.authenticate.assert_called_once()
+ assert [(account.value, account.display_name) for account in accounts] == [
+ ("1111111", "Example Retail"),
+ ("2222222", "2222222"),
+ ]
+
+ @parameterized.expand(
+ [
+ (
+ "a key apple will not accept",
+ AppleSearchAdsAuthError("Could not sign the Apple Ads client secret."),
+ "Could not sign the Apple Ads client secret.",
+ ),
+ (
+ "apple being unreachable",
+ requests.ConnectionError("connection refused"),
+ "Could not exchange the Apple Ads credentials for an access token",
+ ),
+ ]
+ )
+ def test_a_failed_token_exchange_becomes_a_listing_error(
+ self, _name: str, raised: Exception, expected: str
+ ) -> None:
+ # The endpoint turns `IntegrationAccountListingError` into a 400 carrying its message and
+ # lets everything else 500, so an auth failure that escapes as its own type shows someone
+ # mid-setup an opaque server error instead of the reason their key was refused.
+ with mock.patch(f"{SOURCE_MODULE}.AppleSearchAdsClient") as mock_client:
+ mock_client.return_value.authenticate.side_effect = raised
+
+ with pytest.raises(IntegrationAccountListingError) as error:
+ self.source.get_credential_accounts(self.config, self.team_id)
+
+ assert expected in str(error.value)
+
+ def test_the_older_api_version_lists_nothing_without_calling_apple(self) -> None:
+ # v5 scopes on an organization id, which Apple does show in its UI, so there is nothing to
+ # list. The picker fires on every completed edit, so spending a token exchange to return an
+ # empty list would burn the customer's Apple rate-limit budget for nothing.
+ with mock.patch(f"{SOURCE_MODULE}.AppleSearchAdsClient") as mock_client:
+ accounts = self.source.get_credential_accounts(
+ self.config, self.team_id, api_version=APPLE_SEARCH_ADS_API_VERSION_V5
+ )
+
+ assert accounts == []
+ mock_client.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index b2b667e2ee69..736aa7fa28aa 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
@@ -17,6 +17,7 @@ if TYPE_CHECKING:
from products.warehouse_sources.backend.facade.source_config import (
SourceConfig,
+ SourceFieldCredentialAccountSelectConfig,
SourceFieldFileUploadConfig,
SourceFieldInputConfig,
SourceFieldOauthAccountSelectConfig,
@@ -88,6 +89,7 @@ FieldType = Union[
SourceFieldSelectConfig,
SourceFieldOauthConfig,
SourceFieldOauthAccountSelectConfig,
+ SourceFieldCredentialAccountSelectConfig,
SourceFieldFileUploadConfig,
SourceFieldSSHTunnelConfig,
]
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.py
index 62981210b5eb..320938a98a32 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
@@ -5,7 +5,7 @@ import ipaddress
import dataclasses
from collections.abc import Callable, Generator, Sequence
from contextlib import _GeneratorContextManager, contextmanager
-from typing import Any
+from typing import Any, Generic, TypeVar
from django.conf import settings
from django.db import OperationalError, close_old_connections
@@ -26,6 +26,7 @@ from posthog.utils import get_instance_region
from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel
from products.warehouse_sources.backend.models.util import _is_safe_public_ip
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.config import Config
from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
IntegrationAccount,
)
@@ -740,6 +741,29 @@ class OAuthMixin:
raise NotImplementedError(f"{type(self).__name__} does not support listing OAuth accounts")
+# Contravariant because the config only ever appears as a parameter: a source narrows it to its
+# own generated config class, which a plain `Config` annotation would reject as unsubstitutable.
+_CredentialConfig = TypeVar("_CredentialConfig", bound=Config, contravariant=True)
+
+
+class CredentialAccountsMixin(Generic[_CredentialConfig]):
+ """Account listing for a source whose credentials are typed into the connect form.
+
+ The OAuth twin above reads its credentials from an `Integration` row, so the caller passes an id
+ and the token never leaves the server. Here the credentials are still in the form — the user has
+ not submitted them yet, which is the point: the account id they need is only discoverable by
+ calling the provider with the rest of what they typed.
+
+ Implementations take an already-parsed source config, so a half-filled form fails the same way it
+ would on connect rather than somewhere inside provider code.
+ """
+
+ def get_credential_accounts(
+ self, config: _CredentialConfig, team_id: int, api_version: str | None = None
+ ) -> list[IntegrationAccount]:
+ raise NotImplementedError(f"{type(self).__name__} does not support listing accounts from credentials")
+
+
class ValidateDatabaseHostMixin:
"""Mixin for database-based sources to validate connection host"""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py
index 4a6758685b05..972c373dce70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py
@@ -2,14 +2,9 @@ from products.warehouse_sources.backend.facade.source_config import (
DataWarehouseSourceCategory,
ReleaseStatus,
SourceConfig,
- SourceFieldFileUploadConfig,
SourceFieldInputConfig,
- SourceFieldOauthAccountSelectConfig,
- SourceFieldOauthConfig,
- SourceFieldSelectConfig,
- SourceFieldSSHTunnelConfig,
- SourceFieldSwitchGroupConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (
PostgresSourceConfig,
@@ -17,16 +12,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
-_SourceField = (
- SourceFieldInputConfig
- | SourceFieldSwitchGroupConfig
- | SourceFieldSelectConfig
- | SourceFieldOauthConfig
- | SourceFieldOauthAccountSelectConfig
- | SourceFieldFileUploadConfig
- | SourceFieldSSHTunnelConfig
-)
-
_NEON_POOLED_HOST_CDC_ERROR = (
"This is Neon's pooled endpoint, which doesn't support logical replication. For CDC, use the "
"direct host instead — remove the '-pooler' suffix (e.g. "
@@ -60,7 +45,7 @@ class NeonSource(PostgresSource):
return ExternalDataSourceType.NEON
@staticmethod
- def _adjust_field(field: _SourceField) -> _SourceField:
+ def _adjust_field(field: FieldType) -> FieldType:
if isinstance(field, SourceFieldInputConfig):
if field.name == "connection_string":
return field.model_copy(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py
index 5fbb52a9b8f5..a48f7a6e3b52 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py
@@ -4,14 +4,10 @@ from products.warehouse_sources.backend.facade.source_config import (
DataWarehouseSourceCategory,
ReleaseStatus,
SourceConfig,
- SourceFieldFileUploadConfig,
SourceFieldInputConfig,
- SourceFieldOauthAccountSelectConfig,
- SourceFieldOauthConfig,
- SourceFieldSelectConfig,
SourceFieldSSHTunnelConfig,
- SourceFieldSwitchGroupConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (
PostgresSourceConfig,
@@ -19,16 +15,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
-_SourceField = (
- SourceFieldInputConfig
- | SourceFieldSwitchGroupConfig
- | SourceFieldSelectConfig
- | SourceFieldOauthConfig
- | SourceFieldOauthAccountSelectConfig
- | SourceFieldFileUploadConfig
- | SourceFieldSSHTunnelConfig
-)
-
# planetscale.com is the dashboard, never a database endpoint — Postgres hosts live on
# psdb.cloud. Pasting the dashboard address otherwise fails as an opaque connection timeout.
_PLANETSCALE_WEB_HOST_RE = re.compile(r"(^|\.)planetscale\.com$", re.IGNORECASE)
@@ -99,7 +85,7 @@ class PlanetScalePostgresSource(PostgresSource):
return ExternalDataSourceType.PLANETSCALEPOSTGRES
@staticmethod
- def _adjust_field(field: _SourceField) -> _SourceField:
+ def _adjust_field(field: FieldType) -> FieldType:
if not isinstance(field, SourceFieldInputConfig):
return field
if field.name == "connection_string":
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.py
index 616eb693d1ee..ae7ded4cddb5 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
@@ -5,14 +5,9 @@ from products.warehouse_sources.backend.facade.source_config import (
DataWarehouseSourceCategory,
ReleaseStatus,
SourceConfig,
- SourceFieldFileUploadConfig,
SourceFieldInputConfig,
- SourceFieldOauthAccountSelectConfig,
- SourceFieldOauthConfig,
- SourceFieldSelectConfig,
- SourceFieldSSHTunnelConfig,
- SourceFieldSwitchGroupConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
SourceSchema,
@@ -27,16 +22,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.s
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
-_SourceField = (
- SourceFieldInputConfig
- | SourceFieldSwitchGroupConfig
- | SourceFieldSelectConfig
- | SourceFieldOauthConfig
- | SourceFieldOauthAccountSelectConfig
- | SourceFieldFileUploadConfig
- | SourceFieldSSHTunnelConfig
-)
-
# Supabase's direct connection host (`db.<ref>.supabase.co`) is IPv6-only and so is
# unreachable from PostHog's IPv4 egress — by far the biggest cause of Supabase
# connection failures. Users need the connection pooler host instead.
@@ -172,7 +157,7 @@ class SupabaseSource(PostgresSource):
)
@staticmethod
- def _adjust_field(field: _SourceField) -> _SourceField:
+ def _adjust_field(field: FieldType) -> FieldType:
if isinstance(field, SourceFieldInputConfig) and field.name == "host":
return field.model_copy(
update={
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 0d58848e7bde..6a9e001b5135 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -43,6 +43,7 @@ from products.warehouse_sources.backend.facade.models import (
sync_frequency_interval_to_sync_frequency,
)
from products.warehouse_sources.backend.facade.source_config import (
+ SourceFieldCredentialAccountSelectConfig,
SourceFieldFileUploadConfig,
SourceFieldFileUploadJsonFormatConfig,
SourceFieldInputConfig,
@@ -65,6 +66,7 @@ from products.warehouse_sources.backend.presentation.views.external_data_source.
DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE,
INVALID_CREDENTIALS_FALLBACK_MESSAGE,
_classify_refresh_schemas_error,
+ get_credential_account_field_names,
get_declared_field_names,
get_direct_connection_metadata,
get_nonsensitive_and_sensitive_field_names,
@@ -81,6 +83,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
VersionDeprecation,
WebhookCreationResult,
)
+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 (
DATABASE_HOST_NOT_ALLOWED_GUIDANCE,
HostNotAllowedError,
@@ -14041,6 +14047,159 @@ _PREVIEW_MANIFEST = {
}
+class TestGetCredentialAccountFieldNames(SimpleTestCase):
+ """This set is the allowlist the credential accounts endpoint enforces, so a field it fails to
+ find is one the picker can never send, and a field it wrongly includes is one a caller can push
+ into `parse_config`."""
+
+ def test_collects_declared_credential_fields(self):
+ fields = [
+ SourceFieldCredentialAccountSelectConfig(
+ name="ad_account_id",
+ label="Ad account ID",
+ credentialFields=["client_id", "private_key"],
+ required=False,
+ ),
+ SourceFieldInputConfig(
+ name="private_key",
+ label="Private key",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ]
+
+ assert get_credential_account_field_names(cast(list, fields)) == {"client_id", "private_key"}
+
+ def test_finds_fields_nested_under_a_select_option(self):
+ # A source offering two auth methods would otherwise resolve to an empty allowlist, which the
+ # endpoint reads as "no picker" and rejects.
+ fields = [
+ SourceFieldSelectConfig(
+ name="auth_method",
+ label="Auth method",
+ defaultValue="key_pair",
+ required=True,
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Key pair",
+ value="key_pair",
+ fields=[
+ SourceFieldCredentialAccountSelectConfig(
+ name="ad_account_id",
+ label="Ad account ID",
+ credentialFields=["client_id"],
+ required=False,
+ )
+ ],
+ )
+ ],
+ )
+ ]
+
+ assert get_credential_account_field_names(cast(list, fields)) == {"client_id"}
+
+ def test_a_source_with_no_picker_declares_nothing(self):
+ fields = [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ )
+ ]
+
+ assert get_credential_account_field_names(cast(list, fields)) == set()
+
+
+class TestCredentialAccountsEndpoint(APIBaseTest):
+ _APPLE_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.source"
+
+ _CREDENTIALS = {
+ "client_id": "SEARCHADS.27478e17",
+ "apple_team_id": "SEARCHADS.27478e17",
+ "key_id": "a1b2c3d4",
+ "private_key": "-----BEGIN EC PRIVATE KEY-----\nkey\n-----END EC PRIVATE KEY-----",
+ }
+
+ def setUp(self):
+ super().setUp()
+ # Same disclosure concern as the OAuth picker, so the endpoint requires manage access.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ @property
+ def _url(self) -> str:
+ return f"/api/environments/{self.team.pk}/external_data_sources/credential_accounts/"
+
+ def test_lists_the_accounts_the_credentials_can_read(self):
+ with patch(f"{self._APPLE_SOURCE_MODULE}.AppleSearchAdsSource.get_credential_accounts") as mock_accounts:
+ mock_accounts.return_value = [
+ IntegrationAccount(value="1111111", display_name="Example Retail"),
+ IntegrationAccount(value="2222222", display_name="Example Retail Apps"),
+ ]
+ response = self.client.post(
+ self._url, {"source_type": "AppleSearchAds", "credentials": self._CREDENTIALS}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [account["value"] for account in response.json()["accounts"]] == ["1111111", "2222222"]
+
+ def test_a_credential_field_the_source_did_not_declare_is_rejected(self):
+ # The allowlist is the only thing standing between this endpoint and an arbitrary-config
+ # proxy: everything in `credentials` is handed to the source's own `parse_config`.
+ with patch(f"{self._APPLE_SOURCE_MODULE}.AppleSearchAdsSource.get_credential_accounts") as mock_accounts:
+ response = self.client.post(
+ self._url,
+ {
+ "source_type": "AppleSearchAds",
+ "credentials": {**self._CREDENTIALS, "org_id": "555"},
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "org_id" in response.json()["detail"]
+ mock_accounts.assert_not_called()
+
+ def test_a_source_without_a_credential_picker_is_rejected(self):
+ response = self.client.post(
+ self._url, {"source_type": "Stripe", "credentials": {"stripe_secret_key": "sk_test"}}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_unknown_source_type_is_rejected(self):
+ response = self.client.post(self._url, {"source_type": "NotASource", "credentials": {}}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_a_provider_rejection_is_a_400_carrying_its_message(self):
+ # Without the `IntegrationAccountListingError` catch this 500s, and the user setting the
+ # source up sees an opaque server error instead of the reason their key was refused.
+ with patch(f"{self._APPLE_SOURCE_MODULE}.AppleSearchAdsSource.get_credential_accounts") as mock_accounts:
+ mock_accounts.side_effect = IntegrationAccountListingError("Apple rejected the signed client secret.")
+ response = self.client.post(
+ self._url, {"source_type": "AppleSearchAds", "credentials": self._CREDENTIALS}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Apple rejected the signed client secret." in response.json()["detail"]
+
+ def test_regular_member_is_forbidden(self):
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.post(
+ self._url, {"source_type": "AppleSearchAds", "credentials": self._CREDENTIALS}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+
class TestExternalDataSourcePreviewAndCustomPayload(APIBaseTest):
def _url(self, action: str) -> str:
return f"/api/environments/{self.team.pk}/external_data_sources/{action}/"
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 122eceac3f45..2795fc54488a 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -6700,6 +6700,57 @@ export interface ExternalDataSourceConnectionOptionApi {
readonly description: string | null
}
+/**
+ * Values of the sibling fields named by the picker's `credentialFields`. Any other key is rejected.
+ */
+export type CredentialAccountsRequestApiCredentials = { [key: string]: string }
+
+/**
+ * Body for listing accounts from credentials the user has typed but not yet submitted.
+ */
+export interface CredentialAccountsRequestApi {
+ /** The data warehouse source type whose picker is asking (e.g. 'AppleSearchAds'). */
+ source_type: string
+ /** Values of the sibling fields named by the picker's `credentialFields`. Any other key is rejected. */
+ credentials: CredentialAccountsRequestApiCredentials
+ /**
+ * Vendor API version the source is pinned to. Defaults to the source's current default.
+ * @nullable
+ */
+ api_version?: 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[]
+}
+
/**
* Validate credentials and preview available tables from a remote database.
*
@@ -9477,37 +9528,6 @@ 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.
*/
@@ -13752,6 +13772,26 @@ export interface SourceFieldOauthAccountSelectConfigApi {
type: 'oauth-account-select'
}
+/**
+ * Account picker for a source whose credentials are typed into the form, not held by an
+ * `Integration` row. Same `IntegrationAccount` shape and same picker as `oauth-account-select`;
+ * only where the credentials come from differs.
+ *
+ * `credentialFields` is the security boundary. The listing endpoint accepts those field names and
+ * no others, so the picker cannot be used to push arbitrary connection details into a source's
+ * client.
+ */
+export interface SourceFieldCredentialAccountSelectConfigApi {
+ caption?: string | null
+ /** Names of the sibling fields whose values the account listing needs. The form sends exactly these, and the listing endpoint accepts exactly these. */
+ credentialFields: string[]
+ label: string
+ name: string
+ placeholder?: string | null
+ required?: boolean | null
+ type: 'credential-account-select'
+}
+
export interface SourceFieldFileUploadJsonFormatConfigApi {
format?: '.json'
keys: '*' | string[]
@@ -13779,6 +13819,7 @@ export interface SourceFieldSelectConfigOptionApi {
| SourceFieldSelectConfigApi
| SourceFieldOauthConfigApi
| SourceFieldOauthAccountSelectConfigApi
+ | SourceFieldCredentialAccountSelectConfigApi
| SourceFieldFileUploadConfigApi
| SourceFieldSSHTunnelConfigApi
)[]
@@ -13809,6 +13850,7 @@ export interface SourceFieldSwitchGroupConfigApi {
| SourceFieldSelectConfigApi
| SourceFieldOauthConfigApi
| SourceFieldOauthAccountSelectConfigApi
+ | SourceFieldCredentialAccountSelectConfigApi
| SourceFieldFileUploadConfigApi
| SourceFieldSSHTunnelConfigApi
)[]
@@ -13864,6 +13906,7 @@ export interface SourceConfigResponseApi {
| SourceFieldSelectConfigApi
| SourceFieldOauthConfigApi
| SourceFieldOauthAccountSelectConfigApi
+ | SourceFieldCredentialAccountSelectConfigApi
| SourceFieldFileUploadConfigApi
| SourceFieldSSHTunnelConfigApi
)[]
@@ -13887,6 +13930,7 @@ export interface SourceConfigResponseApi {
| SourceFieldSelectConfigApi
| SourceFieldOauthConfigApi
| SourceFieldOauthAccountSelectConfigApi
+ | SourceFieldCredentialAccountSelectConfigApi
| SourceFieldFileUploadConfigApi
| SourceFieldSSHTunnelConfigApi
)[]
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index 5235ab64d314..6213ea147c0f 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
CdcPrerequisitesResponseApi,
CdcStatusApi,
CreateWebhookResponseApi,
+ CredentialAccountsRequestApi,
DatabaseSchemaRequestApi,
DeleteWebhookResponseApi,
DirectConnectionSourceOptionApi,
@@ -1117,6 +1118,32 @@ export const externalDataSourcesConnectionsList = async (
})
}
+export const getExternalDataSourcesCredentialAccountsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/external_data_sources/credential_accounts/`
+}
+
+/**
+ * List the accounts a source's typed-in credentials can reach, in the shared
+ * IntegrationAccount shape.
+ *
+ * The OAuth twin takes an integration id because the token already lives on the server. Here
+ * the credentials are still in the form, so they arrive in the body — POST, not GET, to keep a
+ * private key out of the URL and out of anything that logs one. Nothing is cached for the same
+ * reason: the cache key would have to include the credentials.
+ */
+export const externalDataSourcesCredentialAccountsCreate = async (
+ projectId: string,
+ credentialAccountsRequestApi: CredentialAccountsRequestApi,
+ options?: RequestInit
+): Promise<IntegrationAccountsResponseApi> => {
+ return apiMutator<IntegrationAccountsResponseApi>(getExternalDataSourcesCredentialAccountsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(credentialAccountsRequestApi),
+ })
+}
+
export const getExternalDataSourcesDatabaseSchemaCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/external_data_sources/database_schema/`
}
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index d1824e5b6e5d..e505564288ae 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -572,6 +572,32 @@ export const ExternalDataSourcesUpdateWebhookInputsCreateBody = /* @__PURE__ */
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+/**
+ * List the accounts a source's typed-in credentials can reach, in the shared
+ * IntegrationAccount shape.
+ *
+ * The OAuth twin takes an integration id because the token already lives on the server. Here
+ * the credentials are still in the form, so they arrive in the body — POST, not GET, to keep a
+ * private key out of the URL and out of anything that logs one. Nothing is cached for the same
+ * reason: the cache key would have to include the credentials.
+ */
+export const ExternalDataSourcesCredentialAccountsCreateBody = /* @__PURE__ */ zod
+ .object({
+ source_type: zod
+ .string()
+ .describe("The data warehouse source type whose picker is asking (e.g. 'AppleSearchAds')."),
+ credentials: zod
+ .record(zod.string(), zod.string())
+ .describe(
+ "Values of the sibling fields named by the picker's `credentialFields`. Any other key is rejected."
+ ),
+ api_version: zod
+ .string()
+ .nullish()
+ .describe("Vendor API version the source is pinned to. Defaults to the source's current default."),
+ })
+ .describe('Body for listing accounts from credentials the user has typed but not yet submitted.')
+
/**
* Create, Read, Update and Delete External data Sources.
*/
diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yaml
index 7bcc33f9d9eb..f951a12722a7 100644
--- a/products/warehouse_sources/mcp/tools.yaml
+++ b/products/warehouse_sources/mcp/tools.yaml
@@ -409,6 +409,9 @@ tools:
only re-call if `exists: false`. For Stripe the signing_secret is auto-captured from the Stripe API response
and stored securely; if auto-registration fails (e.g. the API key lacks webhook permissions), the user must
create the webhook manually in Stripe and submit the signing_secret via update-webhook-inputs.
+ external-data-sources-credential-accounts-create:
+ operation: external_data_sources_credential_accounts_create
+ enabled: false
external-data-sources-db-schema:
operation: external_data_sources_database_schema_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 02a32f836f1f..2a83cf04902d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23815,6 +23815,26 @@ export namespace Schemas {
access_secret: string;
}
+ /**
+ * Values of the sibling fields named by the picker's `credentialFields`. Any other key is rejected.
+ */
+ export type CredentialAccountsRequestCredentials = {[key: string]: string};
+
+ /**
+ * Body for listing accounts from credentials the user has typed but not yet submitted.
+ */
+ export interface CredentialAccountsRequest {
+ /** The data warehouse source type whose picker is asking (e.g. 'AppleSearchAds'). */
+ source_type: string;
+ /** Values of the sibling fields named by the picker's `credentialFields`. Any other key is rejected. */
+ credentials: CredentialAccountsRequestCredentials;
+ /**
+ * Vendor API version the source is pinned to. Defaults to the source's current default.
+ * @nullable
+ */
+ api_version?: string | null;
+ }
+
export interface CurrentBranchHealth {
/** Detected default branch ('master' or 'main') from runs in the same 24-hour window. */
default_branch: string;
@@ -91173,6 +91193,26 @@ export namespace Schemas {
type: 'oauth-account-select';
}
+ /**
+ * Account picker for a source whose credentials are typed into the form, not held by an
+ * `Integration` row. Same `IntegrationAccount` shape and same picker as `oauth-account-select`;
+ * only where the credentials come from differs.
+ *
+ * `credentialFields` is the security boundary. The listing endpoint accepts those field names and
+ * no others, so the picker cannot be used to push arbitrary connection details into a source's
+ * client.
+ */
+ export interface SourceFieldCredentialAccountSelectConfig {
+ caption?: string | null;
+ /** Names of the sibling fields whose values the account listing needs. The form sends exactly these, and the listing endpoint accepts exactly these. */
+ credentialFields: string[];
+ label: string;
+ name: string;
+ placeholder?: string | null;
+ required?: boolean | null;
+ type: 'credential-account-select';
+ }
+
export interface SourceFieldFileUploadJsonFormatConfig {
format?: '.json';
keys: '*' | string[];
@@ -91193,7 +91233,7 @@ export namespace Schemas {
}
export interface SourceFieldSelectConfigOption {
- fields?: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[] | null;
+ fields?: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldCredentialAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[] | null;
label: string;
value: string;
}
@@ -91214,7 +91254,7 @@ export namespace Schemas {
export interface SourceFieldSwitchGroupConfig {
caption?: string | null;
default: string | number | boolean;
- fields: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[];
+ fields: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldCredentialAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[];
label: string;
name: string;
type: 'switch-group';
@@ -91253,7 +91293,7 @@ export namespace Schemas {
featureFlag?: string | null;
/** Whether this source should be prominently displayed in onboarding flows */
featured?: boolean | null;
- fields: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[];
+ fields: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldCredentialAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[];
iconClassName?: string | null;
iconPath: string;
/** Extra search terms (alternate spellings, acronyms) for the catalog search, e.g. GoogleAnalytics → ["ga4", "ga"]. Matched alongside name/label/category. */
@@ -91267,7 +91307,7 @@ export namespace Schemas {
/** Whether the source-creation wizard should expose the per-column projection picker. Mirrors `SQLSource.supports_column_selection` so the wizard doesn't show a picker for drivers that ignore `enabled_columns` at sync time. */
supportsColumnSelection: boolean;
unreleasedSource?: boolean | null;
- webhookFields?: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[] | null;
+ webhookFields?: (SourceFieldInputConfig | SourceFieldSwitchGroupConfig | SourceFieldSelectConfig | SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig | SourceFieldCredentialAccountSelectConfig | SourceFieldFileUploadConfig | SourceFieldSSHTunnelConfig)[] | null;
/** If true, the source does not support automatic webhook registration via API (e.g. Slack, where the user must paste the URL into the source's app settings). Adjusts the setup UI copy to avoid promising automatic registration. */
webhookManualOnly?: boolean | null;
webhookSetupCaption?: string | null;