: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
fix(batch-exports): harden databricks host validation and connect hang (#67058)
Ross0df3a07b0df9
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 6529cfe471ce..07edcb53cb03 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -477,13 +477,12 @@ class TestDatabricksIntegration:self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN)- @patch("posthog.models.integration.socket.socket")+ @patch("posthog.models.integration.is_url_allowed", return_value=(True, None))def test_integration_from_config_with_valid_config(self,- mock_socket,+ mock_is_url_allowed,client: HttpClient,):- mock_socket.return_value.connect.return_value = Noneclient.force_login(self.user)response = client.post(@@ -539,15 +538,12 @@ class TestDatabricksIntegration:),],)- @patch("posthog.models.integration.socket.socket")def test_integration_from_config_with_invalid_config(self,- mock_socket,invalid_config,expected_error_message,client: HttpClient,):- mock_socket.return_value.connect.return_value = Noneclient.force_login(self.user)response = client.post(@@ -562,6 +558,43 @@ class TestDatabricksIntegration:assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json()["detail"] == expected_error_message+ @pytest.mark.parametrize(+ "host",+ [+ "169.254.169.254",+ "127.0.0.1",+ "10.0.0.1",+ "192.168.1.1",+ ],+ )+ # FORCE_URL_VALIDATION exercises the real SSRF guard; otherwise is_url_allowed short-circuits+ # in dev/DEBUG, which is on under tests.+ @override_settings(FORCE_URL_VALIDATION=True)+ def test_integration_from_config_rejects_internal_host(+ self,+ host,+ client: HttpClient,+ ):+ """Member-supplied Databricks hosts that resolve to internal IPs must be rejected (SSRF guard)."""+ client.force_login(self.user)++ response = client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {+ "kind": "databricks",+ "config": {+ "server_hostname": host,+ "client_id": "client_id",+ "client_secret": "client_secret",+ },+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert host in response.json()["detail"]+ assert not Integration.objects.filter(team=self.team, kind="databricks").exists()+class TestAwsS3Integration:@pytest.fixture(autouse=True)diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex c2c1cfee3a3e..272a0f8e1516 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -3,7 +3,6 @@ import hmacimport jsonimport timeimport base64-import socketimport hashlibfrom collections.abc import Iterablefrom dataclasses import dataclass@@ -3449,30 +3448,23 @@ class DatabricksIntegration:def validate_host(server_hostname: str):"""Validate the Databricks host.- This is a quick check to ensure the host is valid and that we can connect to it (testing connectivity to a SQL- warehouse requires a warehouse http_path in addition to these parameters so it not possible to perform a full- test here)+ We check the value is a bare hostname (not a full URL) and that it passes our shared SSRF+ guard (rejects unresolvable hosts, internal IPs, cloud-metadata hosts, and internal domain+ patterns). This is a quick check (testing connectivity to a SQL warehouse requires a+ warehouse http_path in addition to these parameters so it not possible to perform a full+ test here)."""# we expect a hostname, not a full URLif server_hostname.startswith("http"):raise DatabricksIntegrationError(f"Databricks integration is not valid: 'server_hostname' should not be a full URL")- # TCP connectivity check- try:- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- sock.settimeout(3.0)- # we only support https- port = 443- sock.connect((server_hostname, port))- sock.close()- except OSError:- raise DatabricksIntegrationError(- f"Databricks integration error: could not connect to hostname '{server_hostname}'"- )- except Exception:++ # Databricks is always https, so reuse the shared URL allowlist as the SSRF guard.+ allowed, _reason = is_url_allowed(f"https://{server_hostname}")+ if not allowed:raise DatabricksIntegrationError(- f"Databricks integration error: could not connect to hostname '{server_hostname}'"+ f"Databricks integration error: could not validate hostname '{server_hostname}'")diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 8a7e34e2530a..209c43f7a399 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -1,6 +1,5 @@import timeimport base64-import socketfrom datetime import UTC, datetime, timedeltafrom typing import Optional@@ -2049,9 +2048,8 @@ class TestGitHubIntegrationGhApiGet(BaseTest):class TestDatabricksIntegrationModel(BaseTest):- @patch("posthog.models.integration.socket.socket")- def test_integration_from_config_with_valid_config(self, mock_socket):- mock_socket.return_value.connect.return_value = None+ @patch("posthog.models.integration.is_url_allowed", return_value=(True, None))+ def test_integration_from_config_with_valid_config(self, mock_is_url_allowed):integration = DatabricksIntegration.integration_from_config(team_id=self.team.pk,server_hostname="databricks.com",@@ -2064,14 +2062,10 @@ class TestDatabricksIntegrationModel(BaseTest):assert integration.config == {"server_hostname": "databricks.com"}assert integration.sensitive_config == {"client_id": "client_id", "client_secret": "client_secret"}- @patch("posthog.models.integration.socket.socket")- def test_integration_from_config_with_invalid_server_hostname(self, mock_socket):- # this is the error raised when the server hostname is invalid- mock_socket.return_value.connect.side_effect = socket.gaierror(- 8, "nodename nor servname provided, or not known"- )+ @patch("posthog.models.integration.is_url_allowed", return_value=(False, "Could not resolve host"))+ def test_integration_from_config_with_invalid_server_hostname(self, mock_is_url_allowed):with pytest.raises(- DatabricksIntegrationError, match="Databricks integration error: could not connect to hostname 'invalid'"+ DatabricksIntegrationError, match="Databricks integration error: could not validate hostname 'invalid'"):DatabricksIntegration.integration_from_config(team_id=self.team.pk,diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.pyindex 4873136028ca..8cc1fb9ee97b 100644--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py@@ -1,6 +1,7 @@import ioimport jsonimport time+import socketimport typing as timport asyncioimport datetime as dt@@ -213,6 +214,9 @@ class DatabricksClient:# queries we make to Databricks. 1 second has been chosen rather arbitrarily.DEFAULT_POLL_INTERVAL = 1.0+ # Timeout (seconds) for the TCP reachability preflight in `_check_host_reachable`.+ DEFAULT_CONNECT_TIMEOUT = 30.0+def __init__(self,server_hostname: str,@@ -222,6 +226,7 @@ class DatabricksClient:catalog: str,schema: str,statement_timeout_seconds: float | None = None,+ connect_timeout_seconds: float = DEFAULT_CONNECT_TIMEOUT,):self.server_hostname = server_hostnameself.http_path = http_path@@ -233,6 +238,7 @@ class DatabricksClient:# to be longer than the client-side per-call timeouts so the client fires first and the# server only kicks in as a last resort.self.statement_timeout_seconds = statement_timeout_seconds+ self.connect_timeout_seconds = connect_timeout_secondsself._connection: None | Connection = None@@ -245,6 +251,7 @@ class DatabricksClient:inputs: DatabricksInsertInputs,integration: DatabricksIntegration,statement_timeout_seconds: float | None = None,+ connect_timeout_seconds: float = DEFAULT_CONNECT_TIMEOUT,) -> t.Self:"""Initialize a DatabricksClient from `DatabricksInsertInputs` and `DatabricksIntegration`.@@ -260,6 +267,7 @@ class DatabricksClient:catalog=inputs.catalog,schema=inputs.schema,statement_timeout_seconds=statement_timeout_seconds,+ connect_timeout_seconds=connect_timeout_seconds,)@property@@ -271,16 +279,34 @@ class DatabricksClient:raise Exception("Not connected, open a connection by calling `connect`")return self._connection- async def _connect(self):- """Establish a raw Databricks connection in a separate thread.+ async def _check_host_reachable(self) -> None:+ """Fail fast on an unreachable/invalid host before calling ``sql.connect``.- Known hang risk: ``oauth_service_principal(config)`` triggers an OIDC endpoint discovery- HTTP call inside ``sql.connect``. That call uses the Databricks SDK's own client timeout- (~5 minutes, not configurable here), and doesn't respect the ``_socket_timeout`` / ``_retry_stop_after_*``- settings. So if the host is unreachable or DNS hangs, this method can block for- up to ~5 minutes before raising. See https://github.com/databricks/databricks-sdk-py/issues/1046.+ ``sql.connect`` triggers an OIDC endpoint discovery HTTP call (via ``oauth_service_principal``)+ whose client retries for ~5 minutes and ignores the ``_socket_timeout`` / ``_retry_stop_after_*``+ settings we pass, so an invalid host blocks the worker thread for the full ~5 minutes before+ raising (https://github.com/databricks/databricks-sdk-py/issues/1046). A short TCP probe catches+ that case in ``connect_timeout_seconds`` and, unlike wrapping ``sql.connect`` in a timeout,+ leaves no stranded thread — the socket terminates on its own timeout and the SDK call is never+ started."""+ def probe() -> None:+ with socket.create_connection((self.server_hostname, 443), timeout=self.connect_timeout_seconds):+ pass++ try:+ await asyncio.to_thread(probe)+ except OSError as err:+ self.logger.info("Could not reach Databricks host '%s': %s", self.server_hostname, err)+ raise DatabricksConnectionError(+ "Failed to connect to Databricks. Please check that your connection details are valid."+ ) from err++ async def _connect(self):+ """Establish a raw Databricks connection in a separate thread."""+ await self._check_host_reachable()+def get_credential_provider():config = Config(host=f"https://{self.server_hostname}",diff --git a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.pyindex 24b28149ce8c..04a1146734d0 100644--- a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py+++ b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py@@ -124,6 +124,7 @@ class TestConnect:use_catalog_mock = AsyncMock()with (+ patch.object(client, "_check_host_reachable", new=AsyncMock()),patch("products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect",return_value=MagicMock(),@@ -137,11 +138,29 @@ class TestConnect:use_catalog_mock.assert_not_called()- async def test_when_invalid_host(self, client: DatabricksClient):+ async def test_when_invalid_host(self):+ """An invalid/unreachable host must fail fast rather than hang for ~5 minutes in the SDK's+ OIDC discovery (https://github.com/databricks/databricks-sdk-py/issues/1046).++ The TCP reachability preflight must fail the connection — using the configurable+ ``connect_timeout_seconds`` — *before* ``sql.connect`` is ever called, so no worker thread+ is left blocking on the hang-prone SDK call.+ """+ # 192.0.2.1 is reserved as non-routable (RFC 5737 TEST-NET-1), so the preflight connect fails+ # fast (no DNS, no real host).+ client = DatabricksClient(+ server_hostname="192.0.2.1",+ http_path="test",+ client_id="test",+ client_secret="test",+ catalog="test",+ schema="test",+ connect_timeout_seconds=0.01,+ )+with patch(- "products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect",- side_effect=ValueError("invalid host"),- ):+ "products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect"+ ) as mock_sql_connect:with pytest.raises(DatabricksConnectionError,match="Failed to connect to Databricks. Please check that your connection details are valid.",@@ -149,6 +168,8 @@ class TestConnect:async with client.connect():pass+ mock_sql_connect.assert_not_called()+class TestQueryBuilders:async def test_merge_query_with_schema_evolution(self, client: DatabricksClient):diff --git a/pyproject.toml b/pyproject.tomlindex ea566a12f268..170af7083d29 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -178,8 +178,8 @@ dependencies = ["linkedin-api-client~=0.3.0","glom~=24.11.0","modal~=1.5.0",- "databricks-sql-connector~=4.2.5",- "databricks-sdk~=0.102.0",+ "databricks-sql-connector~=4.3.0",+ "databricks-sdk~=0.118.0","free-email-domains~=1.0.1","disposable-email-domains~=0.0.140","pymediainfo~=7.0.1",diff --git a/uv.lock b/uv.lockindex c20b39a15c97..c9def98f945a 100644--- a/uv.lock+++ b/uv.lock@@ -1554,21 +1554,22 @@ wheels = [[[package]]name = "databricks-sdk"-version = "0.102.0"+version = "0.118.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "google-auth" },{ name = "protobuf" },{ name = "requests" },+ { name = "urllib3" },]-sdist = { url = "https://files.pythonhosted.org/packages/ab/b3/41ff1c3afe092df9085e084e0dc81c45bca5ed65f7b60dc59df0ade43c76/databricks_sdk-0.102.0.tar.gz", hash = "sha256:8fa5f82317ee27cc46323c6e2543d2cfefb4468653f92ba558271043c6f72fb9", size = 887450, upload-time = "2026-03-19T08:15:54.428Z" }+sdist = { url = "https://files.pythonhosted.org/packages/57/55/776f868cfe97821aafdee3a387badf4468c6205be97d18144738cfc94f66/databricks_sdk-0.118.0.tar.gz", hash = "sha256:cd049b7a9612d957e53d842631800f1974406fc3bec78bc51d429387046a0287", size = 992804, upload-time = "2026-06-18T14:09:35.16Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/02/8c/d082bd5f72d7613524d5b35dfe1f71732b2246be2704fad68cd0e3fdd020/databricks_sdk-0.102.0-py3-none-any.whl", hash = "sha256:75d1253276ee8f3dd5e7b00d62594b7051838435e618f74a8570a6dbd723ec12", size = 838533, upload-time = "2026-03-19T08:15:52.248Z" },+ { url = "https://files.pythonhosted.org/packages/8c/7b/b0ce4a5d544d28df9b86d63305bfad7f09409c0a0ce52f4ad29d2098d9fd/databricks_sdk-0.118.0-py3-none-any.whl", hash = "sha256:7931c7147315902e4347863074c2e2bc1d389338e15d1b60bbf49bc5ebabcbe0", size = 939666, upload-time = "2026-06-18T14:09:33.064Z" },][[package]]name = "databricks-sql-connector"-version = "4.2.5"+version = "4.3.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "lz4" },@@ -1582,9 +1583,9 @@ dependencies = [{ name = "thrift" },{ name = "urllib3" },]-sdist = { url = "https://files.pythonhosted.org/packages/42/0c/1e8179f427044a0c769e279b2c45b72a20cff902f4e92ca1bcca50549435/databricks_sql_connector-4.2.5.tar.gz", hash = "sha256:762df7568ef1998540f96b20cad6f1aaae87d1aad54e40e528f87e4524397291", size = 187223, upload-time = "2026-02-09T11:26:29.762Z" }+sdist = { url = "https://files.pythonhosted.org/packages/dd/e3/16d6f15f0456f6abd35406ddadd651b7579ed2f7c2ffda2722b263529427/databricks_sql_connector-4.3.0.tar.gz", hash = "sha256:047a56d31a61a04bd7eaa33a29e2c899b177f5b9089c127e9ae88c261e635cd1", size = 222828, upload-time = "2026-06-15T07:04:54.098Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/67/a7/0d6dd8323cb2249a979cf4c6a45694e975668c53b19d52d7e15490bafb4c/databricks_sql_connector-4.2.5-py3-none-any.whl", hash = "sha256:31cee10552ce77a830318ce9488fc5e67daca7abbcdf0d8d34f12a180bc55039", size = 213906, upload-time = "2026-02-09T11:26:28.566Z" },+ { url = "https://files.pythonhosted.org/packages/d6/e5/4473f714f24d408a34c8a35f7b1e9b49d4e1c3fb2759166cee0ee23042c2/databricks_sql_connector-4.3.0-py3-none-any.whl", hash = "sha256:a48f33ab246e42950d12da0c12d7b82eae616f18e3103a4f5801ceeae8861f30", size = 251500, upload-time = "2026-06-15T07:04:52.628Z" },][[package]]@@ -5835,8 +5836,8 @@ requires-dist = [{ name = "dagster-postgres", specifier = "==0.26.18" },{ name = "dagster-slack", specifier = "==0.26.18" },{ name = "dagster-webserver", specifier = "==1.10.18" },- { name = "databricks-sdk", specifier = "~=0.102.0" },- { name = "databricks-sql-connector", specifier = "~=4.2.5" },+ { name = "databricks-sdk", specifier = "~=0.118.0" },+ { name = "databricks-sql-connector", specifier = "~=4.3.0" },{ name = "defusedxml", specifier = "~=0.7.1" },{ name = "deltalake", extras = ["pyarrow"], specifier = "==1.4.0" },{ name = "disposable-email-domains", specifier = "~=0.0.140" },@@ -8166,12 +8167,9 @@ wheels = [[[package]]name = "thrift"-version = "0.20.0"+version = "0.22.0"source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "six" },-]-sdist = { url = "https://files.pythonhosted.org/packages/3c/2d/8946864f716ac82dcc88d290ed613cba7a80ec75df4f553ec3ff275f486e/thrift-0.20.0.tar.gz", hash = "sha256:4dd662eadf6b8aebe8a41729527bd69adf6ceaa2a8681cbef64d1273b3e8feba", size = 62295, upload-time = "2024-03-22T22:53:08.228Z" }+sdist = { url = "https://files.pythonhosted.org/packages/b2/c2/db648cc10dd7d15560f2eafd92a27cd280811924696e0b4a87175fb28c94/thrift-0.22.0.tar.gz", hash = "sha256:42e8276afbd5f54fe1d364858b6877bc5e5a4a5ed69f6a005b94ca4918fe1466", size = 62303, upload-time = "2025-05-23T20:49:33.309Z" }[[package]]name = "tiktoken"