Skip to content

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

feat(data-warehouse): server-side search for the OAuth account picker (#70506)

Tom Owerse237229062bd
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index ac2d62aaa1c9..5d7f60fd551e 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -159,6 +159,7 @@ from products.warehouse_sources.backend.facade.source_management import (
draft_manifest_sync,
fetch_docs_text,
filter_dwh_columns_by_enabled_columns,
+ filter_integration_accounts,
get_cdc_adapter,
get_primary_key_columns,
manifest_request_hosts,
@@ -1807,6 +1808,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
required=True,
description="The OAuth integration id whose accounts should be listed.",
),
+ OpenApiParameter(
+ name="search",
+ type=str,
+ required=False,
+ description="Optional case-insensitive filter over account name/value, for sources whose "
+ "resource list is large (e.g. GitHub repositories).",
+ ),
],
responses={200: IntegrationAccountsResponseSerializer},
)
@@ -1814,9 +1822,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
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."""
+ this endpoint just routes by source type, applies the optional search filter, and serializes."""
source_type = request.query_params.get("source_type")
integration_id = request.query_params.get("integration_id")
+ search = request.query_params.get("search") or None
if not source_type or not integration_id:
raise ValidationError("source_type and integration_id are required")
@@ -1833,13 +1842,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
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}"
+ cache_key = f"oauth_accounts/{self.team_id}/{source_type}/{integration_id_int}/{search or ''}"
cached = cache.get(cache_key)
if cached is not None:
return Response(cached)
try:
- accounts = source.get_oauth_accounts(integration_id_int, self.team_id)
+ accounts = source.get_oauth_accounts(integration_id_int, self.team_id, search=search)
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")
@@ -1849,6 +1858,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# ValueError from an internal bug) stays uncaught and becomes a 500 so monitors see it.
raise ValidationError(str(e))
+ # Belt-and-suspenders: sources that support server-side search already return matching results;
+ # this filters sources that returned a full list and ignored `search`.
+ accounts = filter_integration_accounts(accounts, search)
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.
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 460708c12868..49ffef391e3a 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
@@ -10941,6 +10941,42 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
}
]
+ def test_search_filters_returned_accounts(self):
+ # GSC ignores `search`, so the endpoint filters its returned list generically.
+ 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"},
+ {"siteUrl": "https://other.org/", "permissionLevel": "siteOwner"},
+ ],
+ ),
+ ):
+ response = self.client.get(self._url("GoogleSearchConsole", integration.id) + "&search=other")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert [a["value"] for a in response.json()["accounts"]] == ["https://other.org/"]
+
+ def test_github_lists_repositories_with_search(self):
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="github",
+ config={},
+ sensitive_config={"access_token": "gho_test"},
+ integration_id="gh_test",
+ created_by=self.user,
+ )
+ gh_path = "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.GitHubIntegration"
+ with patch(gh_path) as mock_gh:
+ mock_gh.return_value.list_cached_repositories.return_value = ([{"full_name": "PostHog/posthog"}], False)
+ response = self.client.get(self._url("Github", integration.id) + "&search=posthog")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert [a["value"] for a in response.json()["accounts"]] == ["PostHog/posthog"]
+ mock_gh.return_value.list_cached_repositories.assert_called_once_with(search="posthog", limit=100, offset=0)
+
@parameterized.expand([(401,), (403,)])
def test_gsc_auth_error_returns_actionable_400(self, status_code: int):
integration = self._gsc_integration()
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 1ebc2ada84a6..212feb81c07d 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -32,6 +32,7 @@ _LAZY = {
"WebhookSyncResult": "sources.common.base",
"Config": "sources.common.config",
"IntegrationAccountListingError": "sources.common.integration_accounts",
+ "filter_integration_accounts": "sources.common.integration_accounts",
"OAuthMixin": "sources.common.mixins",
"SourceSchema": "sources.common.schema",
"build_default_schemas": "sources.common.schema",
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.py
index 515e7e4c6530..96f4ceb81709 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
@@ -207,7 +207,10 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], O
return friendly
return None
- def get_oauth_accounts(self, integration_id: int, team_id: int) -> list[IntegrationAccount]:
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> list[IntegrationAccount]:
+ # Bing accounts are few, so `search` is ignored here and the endpoint filters the returned list.
try:
integration = self.get_oauth_integration(integration_id, team_id)
except ValueError as e:
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.py
index e9d9fd7e408f..2d08064824d7 100644
--- 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.py
@@ -26,3 +26,20 @@ class IntegrationAccount:
"""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."""
+
+
+def filter_integration_accounts(accounts: list[IntegrationAccount], search: str | None) -> list[IntegrationAccount]:
+ """Case-insensitive substring filter across the fields a user would search by. Applied generically by
+ the OAuth accounts endpoint so sources returning a full list still get search; sources whose provider
+ supports server-side search (e.g. GitHub repositories) additionally push the query down for scale, and
+ this filter is then a no-op on their already-matching results."""
+ query = (search or "").strip().lower()
+ if not query:
+ return accounts
+ return [
+ account
+ for account in accounts
+ if query in account.display_name.lower()
+ or query in account.value.lower()
+ or (account.secondary_text is not None and query in account.secondary_text.lower())
+ ]
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 11926152e016..c4cfa388e520 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
@@ -283,9 +283,13 @@ class OAuthMixin:
close_old_connections()
_integration_fetch_backoff_sleep(attempt)
- def get_oauth_accounts(self, integration_id: int, team_id: int) -> list[IntegrationAccount]:
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> 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.
+ # the shared IntegrationAccount contract, served by one generic endpoint. `search` is an optional
+ # query for sources whose account/resource list is large enough to filter server-side (e.g. GitHub
+ # repositories); small-list sources may ignore it and let the endpoint filter the result.
raise NotImplementedError(f"{type(self).__name__} does not support listing OAuth accounts")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_integration_accounts.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_integration_accounts.py
new file mode 100644
index 000000000000..5b3c7f4b80cf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_integration_accounts.py
@@ -0,0 +1,36 @@
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ filter_integration_accounts,
+)
+
+_ACCOUNTS = [
+ IntegrationAccount(value="PostHog/posthog", display_name="PostHog/posthog"),
+ IntegrationAccount(value="PostHog/code", display_name="PostHog/code"),
+ IntegrationAccount(value="123", display_name="Acme Ads", secondary_text="ACC-987"),
+]
+
+
+class TestFilterIntegrationAccounts:
+ @pytest.mark.parametrize("search", [None, "", " "])
+ def test_empty_search_returns_all(self, search):
+ assert filter_integration_accounts(_ACCOUNTS, search) == _ACCOUNTS
+
+ def test_matches_value_case_insensitively(self):
+ result = filter_integration_accounts(_ACCOUNTS, "CODE")
+ assert [a.value for a in result] == ["PostHog/code"]
+
+ def test_matches_display_name(self):
+ result = filter_integration_accounts(_ACCOUNTS, "acme")
+ assert [a.value for a in result] == ["123"]
+
+ def test_matches_secondary_text(self):
+ result = filter_integration_accounts(_ACCOUNTS, "acc-987")
+ assert [a.value for a in result] == ["123"]
+
+ def test_no_match_returns_empty(self):
+ assert filter_integration_accounts(_ACCOUNTS, "nonexistent") == []
+
+ def test_trims_whitespace(self):
+ assert [a.value for a in filter_integration_accounts(_ACCOUNTS, " code ")] == ["PostHog/code"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
index 5230b5b6f478..e78a4fbc3c9a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
@@ -34,6 +34,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -218,6 +222,30 @@ If automatic creation failed, your token needs webhook permissions — the **adm
"Missing integration ID": "Integration ID is not configured. Please reconnect your GitHub account.",
}
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> 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 (disconnected/deleted), not a server bug.
+ raise IntegrationAccountListingError(
+ "The linked GitHub integration could not be found. Please reconnect your GitHub account."
+ ) from e
+
+ # `repository` is `owner/repo`. Repo lists can be large, so push the search down to the cache
+ # query (server-side) and cap the page — the picker searches as the user types rather than
+ # loading every repo at once.
+ repositories, _has_more = GitHubIntegration(integration).list_cached_repositories(
+ search=search or "", limit=100, offset=0
+ )
+ return [
+ IntegrationAccount(value=repo["full_name"], display_name=repo["full_name"])
+ for repo in repositories
+ if repo.get("full_name")
+ ]
+
def _get_access_token(self, config: GithubSourceConfig, team_id: int) -> str:
if config.auth_method.selection == "pat":
if not config.auth_method.personal_access_token:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py
index 991ee93eb401..7e6341421beb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py
@@ -1,6 +1,9 @@
import pytest
from unittest import mock
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
GithubAuthMethodConfig,
GithubSourceConfig,
@@ -8,6 +11,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.github.source import GithubSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_GITHUB_INTEGRATION_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.GitHubIntegration"
+)
+
class TestGithubSource:
def setup_method(self):
@@ -17,6 +24,52 @@ class TestGithubSource:
def test_source_type(self):
assert self.source.source_type == ExternalDataSourceType.GITHUB
+ @mock.patch(_GITHUB_INTEGRATION_PATH)
+ @mock.patch.object(GithubSource, "get_oauth_integration")
+ def test_get_oauth_accounts_maps_repositories(self, mock_get_oauth, mock_github_integration):
+ mock_get_oauth.return_value = mock.MagicMock()
+ mock_github_integration.return_value.list_cached_repositories.return_value = (
+ [{"full_name": "PostHog/posthog"}, {"full_name": "PostHog/code"}],
+ False,
+ )
+
+ accounts = self.source.get_oauth_accounts(1, self.team_id)
+
+ assert [a.value for a in accounts] == ["PostHog/posthog", "PostHog/code"]
+ assert [a.display_name for a in accounts] == ["PostHog/posthog", "PostHog/code"]
+ mock_get_oauth.assert_called_once_with(1, self.team_id)
+
+ @mock.patch(_GITHUB_INTEGRATION_PATH)
+ @mock.patch.object(GithubSource, "get_oauth_integration")
+ def test_get_oauth_accounts_pushes_search_down(self, mock_get_oauth, mock_github_integration):
+ mock_get_oauth.return_value = mock.MagicMock()
+ list_repos = mock_github_integration.return_value.list_cached_repositories
+ list_repos.return_value = ([], False)
+
+ self.source.get_oauth_accounts(1, self.team_id, search="posthog")
+
+ list_repos.assert_called_once_with(search="posthog", limit=100, offset=0)
+
+ @mock.patch(_GITHUB_INTEGRATION_PATH)
+ @mock.patch.object(GithubSource, "get_oauth_integration")
+ def test_get_oauth_accounts_skips_repos_without_full_name(self, mock_get_oauth, mock_github_integration):
+ mock_get_oauth.return_value = mock.MagicMock()
+ mock_github_integration.return_value.list_cached_repositories.return_value = (
+ [{"full_name": "PostHog/posthog"}, {"full_name": ""}, {"id": 1}],
+ False,
+ )
+
+ accounts = self.source.get_oauth_accounts(1, self.team_id)
+
+ assert [a.value for a in accounts] == ["PostHog/posthog"]
+
+ @mock.patch.object(GithubSource, "get_oauth_integration")
+ def test_get_oauth_accounts_missing_integration_raises(self, mock_get_oauth):
+ mock_get_oauth.side_effect = ValueError("Integration not found")
+
+ with pytest.raises(IntegrationAccountListingError):
+ self.source.get_oauth_accounts(999, self.team_id)
+
@pytest.mark.parametrize(
"expected_key",
[
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.py
index 106ba6894ac0..1b11b6116347 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
@@ -71,7 +71,10 @@ 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]:
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> list[IntegrationAccount]:
+ # Search Console sites are few, so `search` is ignored here and the endpoint filters the list.
try:
session = google_search_console_session(integration_id, team_id)
except Integration.DoesNotExist:
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 7a3f9a8f4c0f..5f4f43d19070 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -7138,6 +7138,10 @@ export type ExternalDataSourcesOauthAccountsRetrieveParams = {
* The OAuth integration id whose accounts should be listed.
*/
integration_id: number
+ /**
+ * Optional case-insensitive filter over account name/value, for sources whose resource list is large (e.g. GitHub repositories).
+ */
+ search?: string
/**
* The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').
*/
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index 26e920e95a71..abbc3054e816 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -951,7 +951,7 @@ export const getExternalDataSourcesOauthAccountsRetrieveUrl = (
/**
* 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.
+ * this endpoint just routes by source type, applies the optional search filter, and serializes.
*/
export const externalDataSourcesOauthAccountsRetrieve = async (
projectId: string,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 72c591b5c64c..9b0a95bab19f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -62912,6 +62912,10 @@ export namespace Schemas {
* The OAuth integration id whose accounts should be listed.
*/
integration_id: number;
+ /**
+ * Optional case-insensitive filter over account name/value, for sources whose resource list is large (e.g. GitHub repositories).
+ */
+ search?: string;
/**
* The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').
*/
@@ -69978,6 +69982,10 @@ export namespace Schemas {
* The OAuth integration id whose accounts should be listed.
*/
integration_id: number;
+ /**
+ * Optional case-insensitive filter over account name/value, for sources whose resource list is large (e.g. GitHub repositories).
+ */
+ search?: string;
/**
* The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').
*/