:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement elasticsearch import source (#62936)
Tom Owerse5ce5026ffb9
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 07d0ed668d38..7c3a71f668a3 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -80,6 +80,7 @@ the row lists both.| drip | HTTP | requests | ✅ || freshdesk | HTTP | requests | ✅ || freshsales | HTTP | requests | ✅ |+| elasticsearch | HTTP | requests | ✅ || eventbrite | HTTP | requests | ✅ || front | HTTP | requests | ✅ || github | HTTP | requests | ✅ |@@ -242,7 +243,6 @@ doesn't conflict with concurrent PRs.- dynamics365- dynamodb- ebay-- elasticsearch- eloqua- expensify- facebook_pagesdiff --git a/posthog/temporal/data_imports/sources/elasticsearch/elasticsearch.py b/posthog/temporal/data_imports/sources/elasticsearch/elasticsearch.pynew file mode 100644index 000000000000..c8ec39e79950--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticsearch/elasticsearch.py@@ -0,0 +1,164 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import quote, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session++# Scroll pages cap at 1000 docs to stay well under the pipeline's buffering thresholds.+PAGE_SIZE = 1000+# Scroll contexts are kept alive between page fetches for this long.+SCROLL_KEEPALIVE = "5m"+REQUEST_TIMEOUT_SECONDS = 120+MAX_RETRY_ATTEMPTS = 5+++class ElasticsearchRetryableError(Exception):+ pass+++class ElasticsearchAuth:+ username: Optional[str] = None+ password: Optional[str] = None+ api_key: Optional[str] = None+++def normalize_host(host: str) -> str:+ """Normalize the cluster URL and reject anything that isn't plain http(s)."""+ host = host.strip()+ if not host:+ raise ValueError("Elasticsearch host is required")+ if "://" not in host:+ host = f"https://{host}"+ host = host.rstrip("/")+ parsed = urlparse(host)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError(f"Invalid Elasticsearch host: {host}")+ return host+++def hostname_of(host: str) -> str:+ return urlparse(normalize_host(host)).hostname or ""+++def _get_session(auth: ElasticsearchAuth) -> requests.Session:+ secrets = tuple(value for value in (auth.password, auth.api_key) if value)+ session = make_tracked_session(redact_values=secrets, allow_redirects=False)+ if auth.api_key:+ session.headers["Authorization"] = f"ApiKey {auth.api_key}"+ elif auth.username is not None:+ session.auth = (auth.username, auth.password or "")+ return session+++def validate_credentials(host: str, auth: ElasticsearchAuth) -> bool:+ """Confirm the cluster is reachable and the credentials are valid via the root info endpoint."""+ try:+ response = _get_session(auth).get(f"{normalize_host(host)}/", timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def list_indices(host: str, auth: ElasticsearchAuth) -> list[str]:+ """List non-system indices (system indices start with a dot)."""+ session = _get_session(auth)+ response = session.get(+ f"{normalize_host(host)}/_cat/indices?format=json&h=index",+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ body = response.json()+ indices = [row.get("index", "") for row in body if isinstance(row, dict)]+ return sorted(index for index in indices if index and not index.startswith("."))+++def get_rows(+ host: str,+ auth: ElasticsearchAuth,+ index: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ session = _get_session(auth)+ base_url = normalize_host(host)++ @retry(+ retry=retry_if_exception_type((ElasticsearchRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def post(url: str, body: dict[str, Any]) -> dict[str, Any]:+ response = session.post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise ElasticsearchRetryableError(+ f"Elasticsearch error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ logger.error(f"Elasticsearch error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ # The scroll API gives a stable snapshot of the index for the duration of+ # the walk; scroll ids expire after SCROLL_KEEPALIVE of inactivity, so the+ # walk restarts from scratch on retry rather than persisting state.+ data = post(+ f"{base_url}/{quote(index)}/_search?scroll={SCROLL_KEEPALIVE}",+ {"size": PAGE_SIZE, "sort": ["_doc"], "query": {"match_all": {}}},+ )+ scroll_id: Optional[str] = data.get("_scroll_id")++ try:+ while True:+ hits = ((data.get("hits") or {}).get("hits")) or []+ items = [{**(hit.get("_source") or {}), "_id": hit["_id"]} for hit in hits]++ if items:+ yield items++ if len(hits) < PAGE_SIZE or not scroll_id:+ break++ data = post(f"{base_url}/_search/scroll", {"scroll": SCROLL_KEEPALIVE, "scroll_id": scroll_id})+ scroll_id = data.get("_scroll_id", scroll_id)+ finally:+ if scroll_id:+ # Best-effort: free the server-side scroll context early.+ try:+ session.delete(+ f"{base_url}/_search/scroll",+ json={"scroll_id": [scroll_id]},+ timeout=10,+ )+ except Exception:+ pass+++def elasticsearch_source(+ host: str,+ auth: ElasticsearchAuth,+ index: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ return SourceResponse(+ name=index,+ items=lambda: get_rows(+ host=host,+ auth=auth,+ index=index,+ logger=logger,+ ),+ primary_keys=["_id"],+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/elasticsearch/source.py b/posthog/temporal/data_imports/sources/elasticsearch/source.pyindex 85baf0be0764..f1bdb120781d 100644--- a/posthog/temporal/data_imports/sources/elasticsearch/source.py+++ b/posthog/temporal/data_imports/sources/elasticsearch/source.py@@ -1,29 +1,177 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponsefrom posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.schema import SourceSchema+from posthog.temporal.data_imports.sources.elasticsearch.elasticsearch import (+ ElasticsearchAuth,+ elasticsearch_source,+ hostname_of,+ list_indices,+ validate_credentials as validate_elasticsearch_credentials,+)from posthog.temporal.data_imports.sources.generated_configs import ElasticsearchSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType+def _auth_from_config(config: ElasticsearchSourceConfig) -> ElasticsearchAuth:+ if config.auth_method.selection == "api_key":+ return ElasticsearchAuth(api_key=config.auth_method.api_key)+ return ElasticsearchAuth(username=config.auth_method.username, password=config.auth_method.password)++@SourceRegistry.register-class ElasticsearchSource(SimpleSource[ElasticsearchSourceConfig]):+class ElasticsearchSource(SimpleSource[ElasticsearchSourceConfig], ValidateDatabaseHostMixin):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ELASTICSEARCH+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Elasticsearch authentication failed. Please check your credentials.",+ "403 Client Error: Forbidden for url": "Elasticsearch denied access. Please check that your credentials can read this index.",+ "404 Client Error: Not Found for url": "Elasticsearch index not found. It may have been deleted or renamed.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ELASTICSEARCH,label="Elasticsearch",+ caption="""Connect your Elasticsearch cluster to pull index documents into the PostHog Data warehouse.++Enter the full cluster URL (e.g. `https://my-deployment.es.us-east-1.aws.found.io:9243`) and credentials with read access to the indices you want to sync. Each non-system index appears as a separate table.""",iconPath="/static/services/elasticsearch.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/elasticsearch",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Cluster URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://my-cluster.example.com:9243",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication method",+ required=True,+ defaultValue="basic",+ options=[+ SourceFieldSelectConfigOption(+ label="Username and password",+ value="basic",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="elastic",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="API key",+ value="api_key",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: ElasticsearchSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every non-system index is a schema. Generic Elasticsearch has no+ # knowable timestamp field per index, so syncs are full refresh.+ indices = list_indices(config.host, _auth_from_config(config))+ if names is not None:+ names_set = set(names)+ indices = [index for index in indices if index in names_set]++ return [+ SourceSchema(+ name=index,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for index in indices+ ]++ def validate_credentials(+ self, config: ElasticsearchSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), team_id)+ except ValueError:+ return False, "Invalid Elasticsearch cluster URL"+ if not host_valid:+ return False, host_error++ if validate_elasticsearch_credentials(config.host, _auth_from_config(config)):+ return True, None++ return False, "Could not connect to Elasticsearch with the provided credentials"++ def source_for_pipeline(self, config: ElasticsearchSourceConfig, inputs: SourceInputs) -> SourceResponse:+ # Re-check at sync time so a PATCHed host can't be retargeted at+ # internal infrastructure.+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), inputs.team_id)+ if not host_valid:+ raise ValueError(host_error or "Invalid Elasticsearch host")++ return elasticsearch_source(+ host=config.host,+ auth=_auth_from_config(config),+ index=inputs.schema_name,+ logger=inputs.logger,)diff --git a/posthog/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py b/posthog/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.pynew file mode 100644index 000000000000..a8ea8ac58337--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py@@ -0,0 +1,173 @@+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.elasticsearch.elasticsearch import (+ PAGE_SIZE,+ ElasticsearchAuth,+ elasticsearch_source,+ get_rows,+ hostname_of,+ list_indices,+ normalize_host,+ validate_credentials,+)++_MODULE = "posthog.temporal.data_imports.sources.elasticsearch.elasticsearch"+++def _response(body: Any, status: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status+ resp.ok = status < 400+ return resp+++def _scroll_page(hits: list[dict[str, Any]], scroll_id: str | None = "scroll-1") -> dict[str, Any]:+ body: dict[str, Any] = {"hits": {"hits": hits}}+ if scroll_id:+ body["_scroll_id"] = scroll_id+ return body+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("https://es.example.com:9243", "https://es.example.com:9243"),+ ("https://es.example.com/", "https://es.example.com"),+ ("es.example.com:9200", "https://es.example.com:9200"),+ (" http://es.internal:9200 ", "http://es.internal:9200"),+ ],+ )+ def test_valid_hosts(self, value, expected):+ assert normalize_host(value) == expected++ @pytest.mark.parametrize("value", ["", "ftp://es.example.com", "https://"])+ def test_invalid_hosts_raise(self, value):+ with pytest.raises(ValueError):+ normalize_host(value)++ def test_hostname_of(self):+ assert hostname_of("https://es.example.com:9243/") == "es.example.com"+++class TestAuthWiring:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_api_key_auth_sets_header(self, mock_session):+ mock_session.return_value.headers = {}+ mock_session.return_value.get.return_value = _response({})++ validate_credentials("https://es.example.com", ElasticsearchAuth(api_key="key123"))++ assert mock_session.return_value.headers["Authorization"] == "ApiKey key123"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_basic_auth_sets_session_auth(self, mock_session):+ mock_session.return_value.headers = {}+ mock_session.return_value.get.return_value = _response({})++ validate_credentials("https://es.example.com", ElasticsearchAuth(username="elastic", password="pw"))++ assert mock_session.return_value.auth == ("elastic", "pw")+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ mock_session.return_value.headers = {}+ mock_session.return_value.get.return_value = _response({}, status=status_code)++ assert validate_credentials("https://es.example.com", ElasticsearchAuth(api_key="k")) is expected++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_credentials_swallows_exceptions(self, mock_session):+ mock_session.return_value.headers = {}+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("https://es.example.com", ElasticsearchAuth(api_key="k")) is False+++class TestListIndices:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_filters_system_indices_and_sorts(self, mock_session):+ mock_session.return_value.headers = {}+ mock_session.return_value.get.return_value = _response(+ [{"index": "orders"}, {"index": ".kibana"}, {"index": "accounts"}, {"index": ""}]+ )++ assert list_indices("https://es.example.com", ElasticsearchAuth(api_key="k")) == ["accounts", "orders"]+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_scrolls_until_short_page(self, mock_session):+ mock_session.return_value.headers = {}+ full_hits = [{"_id": str(i), "_source": {"value": i}} for i in range(PAGE_SIZE)]+ mock_session.return_value.post.side_effect = [+ _response(_scroll_page(full_hits)),+ _response(_scroll_page([{"_id": "last", "_source": {"value": -1}}])),+ ]++ batches = list(get_rows("https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock()))++ assert len(batches) == 2+ assert batches[1] == [{"value": -1, "_id": "last"}]+ urls = [call.args[0] for call in mock_session.return_value.post.call_args_list]+ assert urls[0].endswith("/orders/_search?scroll=5m")+ assert urls[1].endswith("/_search/scroll")+ body = mock_session.return_value.post.call_args_list[1].kwargs["json"]+ assert body == {"scroll": "5m", "scroll_id": "scroll-1"}++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_scroll_context_is_cleared_after_walk(self, mock_session):+ mock_session.return_value.headers = {}+ mock_session.return_value.post.return_value = _response(_scroll_page([{"_id": "1", "_source": {}}]))++ list(get_rows("https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock()))++ mock_session.return_value.delete.assert_called_once()+ assert mock_session.return_value.delete.call_args.kwargs["json"] == {"scroll_id": ["scroll-1"]}++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_rows_hoist_source_and_id(self, mock_session):+ mock_session.return_value.headers = {}+ mock_session.return_value.post.return_value = _response(+ _scroll_page([{"_id": "doc-1", "_source": {"name": "x"}}])+ )++ batches = list(get_rows("https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock()))++ assert batches == [[{"name": "x", "_id": "doc-1"}]]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_index_yields_nothing(self, mock_session):+ mock_session.return_value.headers = {}+ mock_session.return_value.post.return_value = _response(_scroll_page([]))++ assert (+ list(get_rows("https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock())) == []+ )+++class TestElasticsearchSourceResponse:+ def test_response_metadata(self):+ response = elasticsearch_source(+ "https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock()+ )++ assert response.name == "orders"+ assert response.primary_keys == ["_id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py b/posthog/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.pynew file mode 100644index 000000000000..8b74c12ee8c6--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py@@ -0,0 +1,170 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from posthog.temporal.data_imports.sources.elasticsearch.source import ElasticsearchSource, _auth_from_config+from posthog.temporal.data_imports.sources.generated_configs import (+ ElasticsearchAuthMethodConfig,+ ElasticsearchSourceConfig,+)++from products.data_warehouse.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "posthog.temporal.data_imports.sources.elasticsearch.source"+++def _config(selection: str = "basic") -> ElasticsearchSourceConfig:+ return ElasticsearchSourceConfig(+ host="https://es.example.com:9243",+ auth_method=ElasticsearchAuthMethodConfig(+ selection=selection, # type: ignore[arg-type]+ username="elastic",+ password="pw",+ api_key="key123",+ ),+ )+++class TestAuthFromConfig:+ def test_basic_selection(self):+ auth = _auth_from_config(_config("basic"))+ assert auth.username == "elastic"+ assert auth.password == "pw"+ assert auth.api_key is None++ def test_api_key_selection(self):+ auth = _auth_from_config(_config("api_key"))+ assert auth.api_key == "key123"+ assert auth.username is None+++class TestElasticsearchSource:+ def setup_method(self):+ self.source = ElasticsearchSource()+ self.team_id = 123+ self.config = _config()++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.ELASTICSEARCH++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Elasticsearch"+ assert config.label == "Elasticsearch"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/elasticsearch.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["host", "auth_method"]++ def test_auth_method_is_a_select_with_basic_and_api_key(self):+ config = self.source.get_source_config+ auth_field = next(f for f in config.fields if f.name == "auth_method")+ assert isinstance(auth_field, SourceFieldSelectConfig)+ assert {option.value for option in auth_field.options} == {"basic", "api_key"}++ def test_secret_subfields_are_marked_secret(self):+ config = self.source.get_source_config+ auth_field = next(f for f in config.fields if f.name == "auth_method")+ assert isinstance(auth_field, SourceFieldSelectConfig)+ subfields = [f for option in auth_field.options for f in (option.fields or [])]+ secret_names = {f.name for f in subfields if isinstance(f, SourceFieldInputConfig) and f.secret}+ assert secret_names == {"password", "api_key"}++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://es.example.com:9243/orders/_search",+ "403 Client Error: Forbidden for url: https://es.example.com:9243/_cat/indices",+ "404 Client Error: Not Found for url: https://es.example.com:9243/gone/_search",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ def test_non_retryable_errors_does_not_match_server_errors(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(+ key in "500 Server Error for url: https://es.example.com:9243/orders/_search"+ for key in non_retryable_errors+ )++ @mock.patch(f"{_SOURCE_MODULE}.list_indices")+ def test_get_schemas_lists_indices_full_refresh_only(self, mock_list):+ mock_list.return_value = ["accounts", "orders"]++ schemas = self.source.get_schemas(self.config, self.team_id)++ assert [s.name for s in schemas] == ["accounts", "orders"]+ assert all(not s.supports_incremental for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ @mock.patch(f"{_SOURCE_MODULE}.list_indices")+ def test_get_schemas_filtered_by_names(self, mock_list):+ mock_list.return_value = ["accounts", "orders"]++ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])++ assert [s.name for s in schemas] == ["orders"]++ @mock.patch(f"{_SOURCE_MODULE}.validate_elasticsearch_credentials")+ @mock.patch.object(ElasticsearchSource, "is_database_host_valid")+ def test_validate_credentials_checks_host_then_connection(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = True++ is_valid, error = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error is None+ mock_host_valid.assert_called_once_with("es.example.com", self.team_id)++ @mock.patch.object(ElasticsearchSource, "is_database_host_valid")+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")++ is_valid, error = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error == "Host is not allowed"++ def test_validate_credentials_rejects_malformed_host(self):+ config = _config()+ config.host = "ftp://nope"++ is_valid, error = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error == "Invalid Elasticsearch cluster URL"++ @mock.patch(f"{_SOURCE_MODULE}.elasticsearch_source")+ @mock.patch.object(ElasticsearchSource, "is_database_host_valid")+ def test_source_for_pipeline_rechecks_host(self, mock_host_valid, mock_es_source):+ mock_host_valid.return_value = (False, "Host is not allowed")+ inputs = mock.MagicMock()+ inputs.team_id = self.team_id++ with pytest.raises(ValueError, match="Host is not allowed"):+ self.source.source_for_pipeline(self.config, inputs)++ mock_es_source.assert_not_called()++ @mock.patch(f"{_SOURCE_MODULE}.elasticsearch_source")+ @mock.patch.object(ElasticsearchSource, "is_database_host_valid")+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_es_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.team_id = self.team_id+ inputs.schema_name = "orders"++ self.source.source_for_pipeline(self.config, inputs)++ mock_es_source.assert_called_once()+ kwargs = mock_es_source.call_args.kwargs+ assert kwargs["host"] == "https://es.example.com:9243"+ assert kwargs["index"] == "orders"+ assert kwargs["auth"].username == "elastic"diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex d8199c2eb6cd..e93ab0437312 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -36,6 +36,14 @@ class BigQueryUseCustomRegionConfig(config.Config):enabled: bool = config.value(converter=config.str_to_bool, default=False)+class ElasticsearchAuthMethodConfig(config.Config):+ selection: Literal["basic", "api_key"] = "basic"+ username: str | None = None+ password: str | None = None+ api_key: str | None = None++@config.configclass GithubAuthMethodConfig(config.Config):github_integration_id: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)@@ -530,7 +538,8 @@ class EbaySourceConfig(config.Config):@config.configclass ElasticsearchSourceConfig(config.Config):- pass+ host: str+ auth_method: ElasticsearchAuthMethodConfig@config.config