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(elasticsearch): name the real reason a connection check failed (#96370)

Tom Owers30b1d799a862
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
index 30df00f822e9..19fdc2dfe7cc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
@@ -32,6 +32,33 @@ NON_JSON_RESPONSE_ERROR = "Elasticsearch returned a non-JSON response"
_ES_FLOAT_TYPES = frozenset({"float", "double", "half_float", "scaled_float"})
+# Setup-time copy, one message per failure the root-info probe can tell apart. Collapsing them
+# into one blames the credentials for a cluster that was never reached, so someone re-enters a
+# key that was correct all along.
+CREDENTIALS_REJECTED_ERROR = (
+ "Elasticsearch rejected your credentials. Check the username and password, or the API key, then try again."
+)
+FORBIDDEN_ERROR = (
+ "Your Elasticsearch credentials can't read this cluster. Grant the user or API key read access "
+ "to the indices you want to sync, then try again."
+)
+UNREACHABLE_ERROR = (
+ "Couldn't reach your Elasticsearch cluster. Check the cluster URL and port, and that the "
+ "cluster accepts connections from PostHog's IP addresses."
+)
+TLS_ERROR = (
+ "Couldn't open a secure connection to your Elasticsearch cluster. Check that the URL starts "
+ "with https and that the cluster's TLS certificate is valid."
+)
+CLUSTER_UNAVAILABLE_ERROR = (
+ "Your Elasticsearch cluster didn't answer the connection check. Check the cluster's health, then try again."
+)
+UNEXPECTED_RESPONSE_ERROR = (
+ "Elasticsearch didn't accept the connection check. Check that the cluster URL points at the "
+ "Elasticsearch HTTP API, not Kibana or a proxy in front of it."
+)
+
+
class ElasticsearchRetryableError(Exception):
pass
@@ -71,13 +98,26 @@ def _get_session(auth: ElasticsearchAuth) -> requests.Session:
return session
-def validate_credentials(host: str, auth: ElasticsearchAuth) -> bool:
+def validate_credentials(host: str, auth: ElasticsearchAuth) -> tuple[bool, str | None]:
"""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 requests.exceptions.SSLError:
+ return False, TLS_ERROR
except Exception:
- return False
+ return False, UNREACHABLE_ERROR
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, CREDENTIALS_REJECTED_ERROR
+ if response.status_code == 403:
+ return False, FORBIDDEN_ERROR
+ # A 429 or 5xx means the cluster is busy or unhealthy, not that the URL or the credentials
+ # are wrong, so neither is worth re-checking.
+ if response.status_code == 429 or response.status_code >= 500:
+ return False, CLUSTER_UNAVAILABLE_ERROR
+ return False, UNEXPECTED_RESPONSE_ERROR
def list_indices(host: str, auth: ElasticsearchAuth) -> list[str]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py
index abd97619118f..00f3f29f549d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py
@@ -167,10 +167,7 @@ Enter the full cluster URL (e.g. `https://my-deployment.es.us-east-1.aws.found.i
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"
+ return validate_elasticsearch_credentials(config.host, _auth_from_config(config))
def source_for_pipeline(self, config: ElasticsearchSourceConfig, inputs: SourceInputs) -> SourceResponse:
# Re-check at sync time so a PATCHed host can't be retargeted at
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
index f2bdc737105e..994747e8806b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
@@ -6,7 +6,13 @@ from unittest import mock
import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.elasticsearch.elasticsearch import (
+ CLUSTER_UNAVAILABLE_ERROR,
+ CREDENTIALS_REJECTED_ERROR,
+ FORBIDDEN_ERROR,
PAGE_SIZE,
+ TLS_ERROR,
+ UNEXPECTED_RESPONSE_ERROR,
+ UNREACHABLE_ERROR,
ElasticsearchAuth,
coerce_float_fields,
elasticsearch_source,
@@ -80,26 +86,43 @@ class TestAuthWiring:
class TestValidateCredentials:
@pytest.mark.parametrize(
- "status_code, expected",
+ "status_code, expected_valid, expected_error",
[
- (200, True),
- (401, False),
- (403, False),
- (500, False),
+ (200, True, None),
+ (401, False, CREDENTIALS_REJECTED_ERROR),
+ (403, False, FORBIDDEN_ERROR),
+ (404, False, UNEXPECTED_RESPONSE_ERROR),
+ (429, False, CLUSTER_UNAVAILABLE_ERROR),
+ (500, False, CLUSTER_UNAVAILABLE_ERROR),
],
)
@mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected_valid, expected_error):
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
+ is_valid, error = validate_credentials("https://es.example.com", ElasticsearchAuth(api_key="k"))
+ assert is_valid is expected_valid
+ assert error == expected_error
+
+ @pytest.mark.parametrize(
+ "raised, expected_error",
+ [
+ (Exception("boom"), UNREACHABLE_ERROR),
+ (requests.exceptions.ConnectionError("refused"), UNREACHABLE_ERROR),
+ (requests.exceptions.SSLError("bad cert"), TLS_ERROR),
+ ],
+ )
@mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_credentials_swallows_exceptions(self, mock_session):
+ def test_validate_credentials_transport_failure_mapping(self, mock_session, raised, expected_error):
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
+ mock_session.return_value.get.side_effect = raised
+
+ assert validate_credentials("https://es.example.com", ElasticsearchAuth(api_key="k")) == (
+ False,
+ expected_error,
+ )
class TestListIndices:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py
index 52787b642815..108f50a6d389 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py
@@ -1,6 +1,9 @@
import pytest
from unittest import mock
+from products.warehouse_sources.backend.temporal.data_imports.sources.elasticsearch.elasticsearch import (
+ CREDENTIALS_REJECTED_ERROR,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.elasticsearch.source import (
ElasticsearchSource,
_auth_from_config,
@@ -86,7 +89,7 @@ class TestElasticsearchSource:
@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
+ mock_validate.return_value = (True, None)
is_valid, error = self.source.validate_credentials(self.config, self.team_id)
@@ -94,6 +97,17 @@ class TestElasticsearchSource:
assert error is None
mock_host_valid.assert_called_once_with("es.example.com", self.team_id)
+ @mock.patch(f"{_SOURCE_MODULE}.validate_elasticsearch_credentials")
+ @mock.patch.object(ElasticsearchSource, "is_database_host_valid")
+ def test_validate_credentials_surfaces_the_probe_reason(self, mock_host_valid, mock_validate):
+ mock_host_valid.return_value = (True, None)
+ mock_validate.return_value = (False, CREDENTIALS_REJECTED_ERROR)
+
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error == CREDENTIALS_REJECTED_ERROR
+
@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")