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-imports): surface direct-query host rejection as a user error (#98114)

Tom Owersd496adae3fe5
diff --git a/posthog/hogql/direct_sql/postgres_adapter.py b/posthog/hogql/direct_sql/postgres_adapter.py
index fbdbeb2ed4da..b23f862a5c6c 100644
--- a/posthog/hogql/direct_sql/postgres_adapter.py
+++ b/posthog/hogql/direct_sql/postgres_adapter.py
@@ -158,6 +158,7 @@ class PostgresAdapter:
with request.timings.measure("postgres_source_validation"):
with request.timings.measure("postgres_source_helpers_import"):
from products.warehouse_sources.backend.facade.source_management import (
+ HostNotAllowedError,
_get_sslmode,
source_requires_ssl,
)
@@ -179,7 +180,13 @@ class PostgresAdapter:
with request.timings.measure("postgres_execute"):
with ExitStack() as tunnel_stack:
with request.timings.measure("postgres_tunnel_open", emit_span=True):
- host, port = tunnel_stack.enter_context(postgres_source.with_ssh_tunnel(source_config))
+ try:
+ host, port = tunnel_stack.enter_context(postgres_source.with_ssh_tunnel(source_config))
+ except HostNotAllowedError as error:
+ # `validate_source_config` already ran the host check, but a short-TTL
+ # record can pass there and resolve private on this second lookup. Surface
+ # it as a user query error, matching the validation-time rejection.
+ raise ExposedHogQLError(str(error)) from error
connection_kwargs: PostgresConnectionKwargs = {
"host": host,
"port": port,
diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.py
index f8a876438f72..9ffb5aaf4e56 100644
--- a/posthog/hogql/test/test_direct_postgres_query.py
+++ b/posthog/hogql/test/test_direct_postgres_query.py
@@ -1459,6 +1459,68 @@ class TestDirectPostgresQuery(APIBaseTest):
)
mock_connect.assert_not_called()
+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")
+ def test_execute_direct_postgres_query_surfaces_connect_time_host_rejection_as_user_error(self, mock_connect):
+ # A host can pass the validation-layer check and still be rejected at connect time, because
+ # each check resolves the host again and a short-TTL record can answer public then private.
+ # That connect-time rejection must reach the user as an ExposedHogQLError (a 4xx that the
+ # query runner does not capture), not a bare Exception captured as a platform failure.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ HostNotAllowedError,
+ HostResolution,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
+
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="source_id",
+ connection_id="connection_id",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type="Postgres",
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ prefix="ph3",
+ job_inputs={
+ "host": "db.example.com",
+ "port": 5432,
+ "database": "postgres",
+ "user": "postgres",
+ "password": "postgres",
+ "schema": "ph3",
+ },
+ )
+ DataWarehouseTable.objects.create(
+ name="posthog_dashboard",
+ format="Parquet",
+ team=self.team,
+ external_data_source=source,
+ url_pattern="direct://postgres",
+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True}},
+ )
+
+ executor = HogQLQueryExecutor(
+ query="SELECT id FROM posthog_dashboard LIMIT 1",
+ team=self.team,
+ connection_id=str(source.id),
+ )
+
+ host_rejection = HostNotAllowedError(
+ "Database host not allowed: This host points to an internal or private IP address, "
+ "which PostHog can't reach. Use a host that's reachable from the public internet."
+ )
+ # Validation passes (host resolves public); the connect-time tunnel open rejects it.
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.resolve_safe_host",
+ return_value=HostResolution(connect_host="db.example.com", error=None),
+ ),
+ patch.object(PostgresSource, "with_ssh_tunnel", side_effect=host_rejection),
+ ):
+ with self.assertRaises(ExposedHogQLError) as error:
+ executor.execute()
+
+ self.assertEqual(str(error.exception), str(host_rejection))
+ mock_connect.assert_not_called()
+
@patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")
def test_execute_direct_postgres_query_exposes_database_errors(self, mock_connect):
source = ExternalDataSource.objects.create(
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 7d2617c074d5..5f3d90dac643 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -35,6 +35,7 @@ _LAZY = {
"Config": "sources.common.config",
"IntegrationAccountListingError": "sources.common.integration_accounts",
"filter_integration_accounts": "sources.common.integration_accounts",
+ "HostNotAllowedError": "sources.common.mixins",
"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/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
index 1ab80368d93b..f2bd5184d8b3 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
@@ -13,6 +13,7 @@ import structlog
from posthog.cloud_utils import is_cloud
from posthog.models.integration import Integration
from posthog.psycopg_helpers import prefer_routable_addresses
+from posthog.temporal.common.errors import NonReportableError
from posthog.utils import get_instance_region
from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel
@@ -30,6 +31,24 @@ _INTERNAL_IP_ERROR = (
_DNS_FAILURE_ERROR = "Host could not be resolved"
+class HostNotAllowedError(NonReportableError):
+ """A direct database or SSH tunnel host resolved to an address PostHog won't connect to.
+
+ Raised at connect time by `_check_direct_host` and `_pinned_ssh_host`. A host can pass the
+ validation-layer check and still land here, because each check resolves the host again and a
+ short-TTL record can answer public for one lookup and private for the next. It is always the
+ customer's own DNS or network config, never a PostHog defect, and retrying re-hits the same
+ rejection, so it must fail the work without minting an error tracking issue.
+
+ Two connect paths reach it, and each suppresses reporting its own way:
+ - Import pipeline (Temporal): `NonReportableError` makes the activity interceptor fail the
+ activity without capturing. The message is unchanged so `Any_Source_Errors` still matches it
+ and pauses the schema.
+ - Direct query (HogQL): the direct-source adapter catches this and re-raises `ExposedHogQLError`
+ so the query runner returns a 4xx instead of capturing a platform failure.
+ """
+
+
def is_team_allowlisted_for_internal_hosts(team_id: int) -> bool:
"""Whether this team may point warehouse sources at PostHog-internal hosts.
@@ -259,7 +278,7 @@ def _pinned_ssh_host(ssh_config, team_id: int | None) -> str:
"""
resolution = resolve_safe_host(ssh_config.host, team_id)
if resolution.connect_host is None:
- raise Exception(f"SSH tunnel host not allowed: {resolution.error}")
+ raise HostNotAllowedError(f"SSH tunnel host not allowed: {resolution.error}")
return resolution.connect_host
@@ -293,7 +312,7 @@ def _check_direct_host(config, team_id: int | None) -> None:
"""
resolution = resolve_safe_host(config.host, team_id)
if resolution.connect_host is None:
- raise Exception(f"Database host not allowed: {resolution.error}")
+ raise HostNotAllowedError(f"Database host not allowed: {resolution.error}")
@contextmanager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
index a36b0ba796c8..7a11f8090df9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
@@ -11,10 +11,12 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from posthog.models.integration import Integration
+from posthog.temporal.common.errors import NonReportableError
from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ HostNotAllowedError,
OAuthMixin,
SSHTunnelMixin,
ValidateDatabaseHostMixin,
@@ -528,7 +530,7 @@ class TestDirectHostIsCheckedAtConnect(SimpleTestCase):
patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=self._resolves_to("169.254.169.254")),
patch(f"{_MIXINS_MODULE}.logger"),
):
- with pytest.raises(Exception, match="Database host not allowed"):
+ with pytest.raises(HostNotAllowedError, match="Database host not allowed"):
with self._connection_cm(entrypoint, config, 999):
pass
@@ -536,7 +538,9 @@ class TestDirectHostIsCheckedAtConnect(SimpleTestCase):
class TestDirectHostRejectionIsNonRetryable(SimpleTestCase):
# The rejection is a config problem only the customer can fix, so it has to stop the schedule
# the way its SSH counterpart does. Raising it through the real path couples the wording to the
- # registered pattern: reword one without the other and this fails.
+ # registered pattern: reword one without the other and this fails. It is also a
+ # `NonReportableError`, the marker the Temporal activity interceptor honors to fail the activity
+ # without opening an error tracking issue nobody on our side can act on.
@override_settings(CLOUD_DEPLOYMENT="US")
def test_rejection_message_matches_a_registered_non_retryable_error(self):
config = FakeConfig(host="db.example.com", ssh_tunnel=None)
@@ -545,8 +549,9 @@ class TestDirectHostRejectionIsNonRetryable(SimpleTestCase):
patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=addrinfo),
patch(f"{_MIXINS_MODULE}.logger"),
):
- with pytest.raises(Exception) as exc:
+ with pytest.raises(HostNotAllowedError) as exc:
with open_ssh_tunnel(config, 999):
pass
+ assert isinstance(exc.value, NonReportableError)
assert error_message_matches(str(exc.value), Any_Source_Errors.keys())