: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(warehouse-sources): pin postgres connects to validated addresses (#95376)
Tom Piccirelloc178a6b8cee5
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex fcfe370a0f57..6ef9921d8d84 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -737,14 +737,16 @@ preserved (omitted) secret is reused — exfiltrating the credential. `host` andalready handled separately, so only sources whose connection target lives in a differently named field (e.g.Okta's `okta_domain`) need to override this. The default is `[]` (no extra fields).-Pair this with `_is_host_safe` (`common/mixins.py`) at both-source-create and sync time to block hosts resolving to internal/private IPs.+Pair this with `is_database_host_valid` (`common/mixins.py`) at source-create time to block hosts+resolving to internal/private IPs. At connect time, open every direct database connection through+`with_ssh_tunnel()`, which re-checks the host on each open, and pin the validated addresses in the+client where the driver allows it (see `pinned_host_kwargs` in `common/mixins.py`).## MixinsFrom `products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py`:-- `SSHTunnelMixin` — `with_ssh_tunnel()` context plus `make_ssh_tunnel_func()` for deferred tunnel opening.+- `SSHTunnelMixin` — `with_ssh_tunnel()` context plus `make_ssh_tunnel_func()` for deferred tunnel opening. Both re-check the SSH host and the database host on every open.- `OAuthMixin` — `get_oauth_integration()` to pull `Integration` from the DB.- `ValidateDatabaseHostMixin` — `is_database_host_valid()` to block internal VPC IPs (unless SSH tunnel is used).diff --git a/posthog/hogql/direct_sql/clickhouse_adapter.py b/posthog/hogql/direct_sql/clickhouse_adapter.pyindex 441f94a66737..2714ade2c4c2 100644--- a/posthog/hogql/direct_sql/clickhouse_adapter.py+++ b/posthog/hogql/direct_sql/clickhouse_adapter.py@@ -279,7 +279,11 @@ class ClickHouseAdapter:def execute(self, request: DirectQueryRequest) -> DirectQueryResult:from clickhouse_connect.driver.exceptions import ClickHouseError- from products.warehouse_sources.backend.facade.source_management import ClickHouseConnectionError+ from products.warehouse_sources.backend.facade.source_management import (+ ClickHouseConnectionError,+ HostNotAllowedError,+ TemporaryHostResolutionError,+ )source = request.sourceclickhouse_source, config = self.validate_source_config(source, request.team)@@ -319,6 +323,8 @@ class ClickHouseAdapter:OSError,BaseSSHTunnelForwarderError,ExposedHogQLError,+ HostNotAllowedError,+ TemporaryHostResolutionError,) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:diff --git a/posthog/hogql/direct_sql/mysql_adapter.py b/posthog/hogql/direct_sql/mysql_adapter.pyindex 77486f620717..5bfdb1abf140 100644--- a/posthog/hogql/direct_sql/mysql_adapter.py+++ b/posthog/hogql/direct_sql/mysql_adapter.py@@ -150,6 +150,11 @@ class MySQLAdapter:def execute(self, request: DirectQueryRequest) -> DirectQueryResult:source = request.source+ from products.warehouse_sources.backend.facade.source_management import (+ HostNotAllowedError,+ TemporaryHostResolutionError,+ )+mysql_implementation, source_config = self.validate_source_config(source, request.team)settings = request.settingsstatement_timeout_seconds = max(@@ -177,7 +182,13 @@ class MySQLAdapter:)results = cursor.fetchall()description = cursor.description or []- except (pymysql.MySQLError, BaseSSHTunnelForwarderError, ExposedHogQLError) as error:+ except (+ pymysql.MySQLError,+ BaseSSHTunnelForwarderError,+ ExposedHogQLError,+ HostNotAllowedError,+ TemporaryHostResolutionError,+ ) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:return DirectQueryResult(results=[], types=[], print_columns=[], error=mysql_error_to_message(error))diff --git a/posthog/hogql/direct_sql/postgres_adapter.py b/posthog/hogql/direct_sql/postgres_adapter.pyindex b23f862a5c6c..4982157933e3 100644--- a/posthog/hogql/direct_sql/postgres_adapter.py+++ b/posthog/hogql/direct_sql/postgres_adapter.py@@ -44,6 +44,7 @@ class PostgresConnectionKwargs(TypedDict, total=False):sslcert: strsslkey: strsslrootcert: str+ hostaddr: strdef is_postwh_host(host: str | None) -> bool:@@ -159,7 +160,9 @@ class PostgresAdapter:with request.timings.measure("postgres_source_helpers_import"):from products.warehouse_sources.backend.facade.source_management import (HostNotAllowedError,+ TemporaryHostResolutionError,_get_sslmode,+ pinned_host_kwargs,source_requires_ssl,)@@ -181,7 +184,9 @@ class PostgresAdapter:with ExitStack() as tunnel_stack:with request.timings.measure("postgres_tunnel_open", emit_span=True):try:- host, port = tunnel_stack.enter_context(postgres_source.with_ssh_tunnel(source_config))+ host, port = tunnel_stack.enter_context(+ postgres_source.with_ssh_tunnel(source_config, request.team.pk)+ )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@@ -207,6 +212,18 @@ class PostgresAdapter:# DuckLake hosts (any region: .us/.eu/.dev.postwh.com) require SSL# but do not use certificate-based auth.connection_kwargs["sslmode"] = "require"+ # Dial only the addresses the host policy validated, the same way a sync does.+ connection_kwargs.update(+ cast(+ PostgresConnectionKwargs,+ pinned_host_kwargs(+ host,+ port=port,+ connect_timeout=DIRECT_POSTGRES_CONNECT_TIMEOUT_SECONDS,+ team_id=request.team.pk,+ ),+ )+ )with request.timings.measure("postgres_connect", emit_span=True):try:@@ -247,7 +264,13 @@ class PostgresAdapter:description = cursor.description or []with request.timings.measure("postgres_query_fetch"):results = cursor.fetchall() if description else []- except (psycopg.Error, BaseSSHTunnelForwarderError, ExposedHogQLError) as error:+ except (+ psycopg.Error,+ BaseSSHTunnelForwarderError,+ ExposedHogQLError,+ HostNotAllowedError,+ TemporaryHostResolutionError,+ ) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:return DirectQueryResult(results=[], types=[], print_columns=[], error=postgres_error_to_message(error))diff --git a/posthog/hogql/direct_sql/redshift_adapter.py b/posthog/hogql/direct_sql/redshift_adapter.pyindex f1f39272bc50..618f13ac00a4 100644--- a/posthog/hogql/direct_sql/redshift_adapter.py+++ b/posthog/hogql/direct_sql/redshift_adapter.py@@ -131,6 +131,11 @@ class RedshiftAdapter:def execute(self, request: DirectQueryRequest) -> DirectQueryResult:source = request.source+ from products.warehouse_sources.backend.facade.source_management import (+ HostNotAllowedError,+ TemporaryHostResolutionError,+ )+redshift_implementation, source_config = self.validate_source_config(source, request.team)source_schema = source_config.schemasettings = request.settings@@ -163,7 +168,13 @@ class RedshiftAdapter:# as an empty result instead of raising on fetch, mirroring Postgres.description = cursor.description or []results = _fetch_capped_redshift_rows(cursor) if description else []- except (psycopg.Error, BaseSSHTunnelForwarderError, ExposedHogQLError) as error:+ except (+ psycopg.Error,+ BaseSSHTunnelForwarderError,+ ExposedHogQLError,+ HostNotAllowedError,+ TemporaryHostResolutionError,+ ) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:return DirectQueryResult(results=[], types=[], print_columns=[], error=postgres_error_to_message(error))diff --git a/posthog/hogql/test/test_direct_clickhouse_query.py b/posthog/hogql/test/test_direct_clickhouse_query.pyindex 19043f2c79d1..588758871d43 100644--- a/posthog/hogql/test/test_direct_clickhouse_query.py+++ b/posthog/hogql/test/test_direct_clickhouse_query.py@@ -1,7 +1,14 @@+import socketfrom uuid import uuid4from posthog.test.base import APIBaseTest+from unittest.mock import patch+from django.test import override_settings++from parameterized import parameterized++from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.query import HogQLQueryExecutorfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource@@ -13,9 +20,15 @@ DIRECT_CLICKHOUSE_URL_PATTERN = "direct://clickhouse"DIRECT_CLICKHOUSE_DATABASE_OPTION = "direct_clickhouse_database"DIRECT_CLICKHOUSE_TABLE_OPTION = "direct_clickhouse_table"+_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"+++def _answers_with(address: str) -> list[tuple]:+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (address, 0))]+class TestDirectClickHouseQuery(APIBaseTest):- def _create_source(self, *, database: str) -> ExternalDataSource:+ def _create_source(self, *, database: str, host: str = "localhost") -> ExternalDataSource:return ExternalDataSource.objects.create(team=self.team,source_id=str(uuid4()),@@ -25,7 +38,7 @@ class TestDirectClickHouseQuery(APIBaseTest):access_method=ExternalDataSource.AccessMethod.DIRECT,prefix="ch",job_inputs={- "host": "localhost",+ "host": host,"port": 8443,"database": database,"user": "readonly_direct_connect",@@ -67,6 +80,39 @@ class TestDirectClickHouseQuery(APIBaseTest):# Normalize away identifier backticks so the assertion is agnostic to escaping.return sql.replace("`", "")+ @parameterized.expand(+ [+ (+ "flips_to_an_internal_address",+ _answers_with("10.0.0.5"),+ "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.",+ ),+ (+ "resolver_asks_to_try_again",+ socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution"),+ "Temporary failure resolving the host 'db.example.com'. Try again in a moment.",+ ),+ ]+ )+ @override_settings(CLOUD_DEPLOYMENT="DEV")+ def test_a_host_refused_at_connect_is_exposed(+ self, _name: str, connect_time_answer: object, expected_message: str+ ) -> None:+ source = self._create_source(database="posthog", host="db.example.com")+ self._create_table(source)++ executor = HogQLQueryExecutor(query="SELECT id FROM events", team=self.team, connection_id=str(source.id))++ with (+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=[_answers_with("52.1.2.3"), connect_time_answer]),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ with self.assertRaises(ExposedHogQLError) as error:+ executor.execute()++ self.assertEqual(str(error.exception), expected_message)+def test_uses_the_sources_configured_database(self):source = self._create_source(database="posthog")self._create_table(source)diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex 9ffb5aaf4e56..007bcc0a5593 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -1,3 +1,4 @@+import socketfrom datetime import date, timedeltafrom typing import Any, castfrom uuid import uuid4@@ -35,7 +36,9 @@ from posthog.hogql.query import HogQLQueryExecutorfrom posthog.models import Teamfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource-from products.warehouse_sources.backend.facade.source_management import SSL_REQUIRED_AFTER_DATE+from products.warehouse_sources.backend.facade.source_management import SSL_REQUIRED_AFTER_DATE, HostNotAllowedError++_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"class TestDirectPostgresQuery(APIBaseTest):@@ -1459,6 +1462,113 @@ class TestDirectPostgresQuery(APIBaseTest):)mock_connect.assert_not_called()+ # Staging rather than US or EU, because the internal-host allowlist there exempts one team id+ # per region and this test cannot choose the team it gets.+ @override_settings(CLOUD_DEPLOYMENT="DEV")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")+ def test_execute_direct_postgres_query_exposes_a_resolver_blip_at_connect(self, mock_connect):+ # The host check before the query resolves the host, then the resolver answers "try again"+ # on the connect-time check a moment later. Nothing is wrong with the source, so the query+ # must come back as a query error telling the user to retry, not an unexpected server error.+ 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),+ )+ resolved = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("52.1.2.3", 0))]+ blip = socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")++ with (+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=[resolved, blip]),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ with self.assertRaises(ExposedHogQLError) as error:+ executor.execute()++ self.assertIn("Try again in a moment", str(error.exception))+ mock_connect.assert_not_called()++ # The host check before the connect passes here, and the pin's own lookup refuses the host a+ # moment later — the two answers disagreeing is the case the pin exists to catch. The refusal+ # is raised inside the execute block, so it has to reach the same handler a driver error does.+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.pinned_host_kwargs",+ side_effect=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."+ ),+ )+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")+ def test_execute_direct_postgres_query_exposes_host_rejected_at_connect(self, mock_connect, _mock_pinned_host):+ 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),+ )++ with self.assertRaises(ExposedHogQLError) as error:+ executor.execute()++ self.assertEqual(+ str(error.exception),+ "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.",+ )+ 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, becausediff --git a/posthog/psycopg_helpers.py b/posthog/psycopg_helpers.pyindex 8d133689a4fc..90c2ed6ac32d 100644--- a/posthog/psycopg_helpers.py+++ b/posthog/psycopg_helpers.py@@ -53,6 +53,36 @@ def prefer_routable_addresses(addresses: list[str]) -> list[str]:return routable or addresses+# The resolver answers with one of these when the lookup itself failed, rather than reaching a+# verdict on the name: the resolver was unreachable or timed out (EAI_AGAIN), or the lookup could+# not complete locally (EAI_SYSTEM, EAI_MEMORY). A caller that refuses the host on one of these+# blames the customer for a failure on our side, so they stay retryable. Every other code is an+# answer about the name itself.+_TEMPORARY_RESOLUTION_ERRNOS = frozenset({socket.EAI_AGAIN, socket.EAI_SYSTEM, socket.EAI_MEMORY})+++def is_temporary_resolution_failure(error: BaseException) -> bool:+ """Whether a failed lookup is the resolver failing, rather than an answer about the name."""+ return isinstance(error, socket.gaierror) and error.errno in _TEMPORARY_RESOLUTION_ERRNOS+++# The bounded lookup's own transient failures. A classifier that matches on the message reuses+# these strings, so a reword here cannot silently drop the classification.+HOST_RESOLUTION_TIMEOUT_ERROR = "Timed out resolving database host name"+TEMPORARY_HOST_RESOLUTION_ERROR = "Temporary failure resolving database host name"+++def is_resolvable_hostname(host: str) -> bool:+ """Whether `host` is a name a resolver would look up: not empty, not a Unix socket path, not an IP literal."""+ if not host or host.startswith("/"):+ return False+ try:+ ipaddress.ip_address(host.strip("[]"))+ except ValueError:+ return True+ return False++def resolve_psycopg_hostaddr_with_timeout(host: str,port: int,@@ -60,16 +90,16 @@ def resolve_psycopg_hostaddr_with_timeout(*,fail_on_resolution_error: bool = False,abort_check: Callable[[], None] | None = None,+ raise_on_temporary_failure: bool = False,) -> list[str] | None:- """Resolve a hostname before psycopg's unbounded Python-side DNS lookup."""- if not host or host.startswith("/"):- return None+ """Resolve a hostname before psycopg's unbounded Python-side DNS lookup.- try:- ipaddress.ip_address(host.strip("[]"))+ `raise_on_temporary_failure` turns a resolver failure that is not an answer about the name+ (see `is_temporary_resolution_failure`) into a retryable `psycopg.OperationalError` instead of+ `None`, for callers that treat `None` as a name that does not exist.+ """+ if not is_resolvable_hostname(host):return None- except ValueError:- passaddrinfo: list[Any] = []lookup_error: list[BaseException] = []@@ -89,11 +119,13 @@ def resolve_psycopg_hostaddr_with_timeout(abort_check()remaining_seconds = deadline - monotonic()if remaining_seconds <= 0:- raise psycopg.OperationalError(f"Timed out resolving database host name after {timeout}s")+ raise psycopg.OperationalError(f"{HOST_RESOLUTION_TIMEOUT_ERROR} after {timeout}s")thread.join(min(remaining_seconds, 1.0 if abort_check is not None else remaining_seconds))if abort_check is not None:abort_check()if lookup_error:+ if raise_on_temporary_failure and is_temporary_resolution_failure(lookup_error[0]):+ raise psycopg.OperationalError(TEMPORARY_HOST_RESOLUTION_ERROR) from lookup_error[0]if isinstance(lookup_error[0], OSError):if fail_on_resolution_error:raise psycopg.OperationalError("Could not resolve database host name") from lookup_error[0]diff --git a/posthog/test/test_psycopg_helpers.py b/posthog/test/test_psycopg_helpers.pyindex 5fb4f09c7fd3..31181b7a53e4 100644--- a/posthog/test/test_psycopg_helpers.py+++ b/posthog/test/test_psycopg_helpers.py@@ -1,8 +1,12 @@+import socket++import pytestfrom unittest.mock import patch+import psycopgfrom parameterized import parameterized-from posthog.psycopg_helpers import prefer_routable_addresses+from posthog.psycopg_helpers import prefer_routable_addresses, resolve_psycopg_hostaddr_with_timeout_V6 = ["2600:1f16:1c4:661c:d148:b481:5246:e29d", "2600:1f16:1c4:6621:c8f:607d:ea25:4345"]_V4 = ["13.58.18.166", "16.59.10.57"]@@ -36,3 +40,30 @@ class TestPreferRoutableAddresses:def test_anything_that_is_not_an_ipv6_address_survives(self):with patch(f"{_HELPERS}.has_ipv6_route", return_value=False):assert prefer_routable_addresses(["db.example.com", _V6[0]]) == ["db.example.com"]+++class TestResolveTemporaryFailure:+ @parameterized.expand(+ [+ ("try_again", socket.EAI_AGAIN, "Temporary failure in name resolution"),+ ("system_error", socket.EAI_SYSTEM, "System error"),+ ("out_of_memory", socket.EAI_MEMORY, "Memory allocation failure"),+ ]+ )+ def test_a_resolver_failure_raises_a_retryable_error_when_asked(self, _name, errno, message) -> None:+ with patch(f"{_HELPERS}.socket.getaddrinfo", side_effect=socket.gaierror(errno, message)):+ with pytest.raises(psycopg.OperationalError, match="Temporary failure"):+ resolve_psycopg_hostaddr_with_timeout("db.example.com", 5432, 5, raise_on_temporary_failure=True)++ def test_a_name_that_does_not_exist_stays_a_refusal(self) -> None:+ missing = socket.gaierror(socket.EAI_NONAME, "Name or service not known")+ with patch(f"{_HELPERS}.socket.getaddrinfo", side_effect=missing):+ assert (+ resolve_psycopg_hostaddr_with_timeout("db.example.com", 5432, 5, raise_on_temporary_failure=True)+ is None+ )++ def test_a_try_again_answer_is_none_by_default(self) -> None:+ blip = socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")+ with patch(f"{_HELPERS}.socket.getaddrinfo", side_effect=blip):+ assert resolve_psycopg_hostaddr_with_timeout("db.example.com", 5432, 5) is Nonediff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex 5f3d90dac643..1191ceeaa321 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -35,8 +35,11 @@ _LAZY = {"Config": "sources.common.config","IntegrationAccountListingError": "sources.common.integration_accounts","filter_integration_accounts": "sources.common.integration_accounts",+ "DATABASE_HOST_NOT_ALLOWED_GUIDANCE": "sources.common.mixins","HostNotAllowedError": "sources.common.mixins","OAuthMixin": "sources.common.mixins",+ "pinned_host_kwargs": "sources.common.mixins",+ "TemporaryHostResolutionError": "sources.common.mixins","SourceSchema": "sources.common.schema","build_default_schemas": "sources.common.schema","build_default_sync_settings": "sources.common.schema",diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pyindex abc813912416..1a1ad1886f27 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py@@ -120,6 +120,7 @@ from products.warehouse_sources.backend.facade.models import (update_sync_type_config_keys,)from products.warehouse_sources.backend.facade.source_management import (+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,DEFAULT_LAG_CRITICAL_THRESHOLD_MB,DEFAULT_LAG_WARNING_THRESHOLD_MB,PREVIEW_DEFAULT_ROWS,@@ -135,6 +136,7 @@ from products.warehouse_sources.backend.facade.source_management import (DocsFetchError,ExternalWebhookInfo,FieldType,+ HostNotAllowedError,IntegrationAccountListingError,MySQLSource,OAuthMixin,@@ -144,6 +146,7 @@ from products.warehouse_sources.backend.facade.source_management import (SourceSchema,SQLSource,SSLRequiredError,+ TemporaryHostResolutionError,WebhookSource,build_default_schemas,build_default_sync_settings,@@ -238,6 +241,16 @@ def _hide_noncanonical_managed_warehouse_sources(return queryset.exclude(hidden_sources)+# Failures to reach the source database that only the customer can fix. Handlers return them as a+# 400 without capturing, so they stay out of error tracking.+_EXPECTED_CONNECTION_ERRORS = (+ OperationalError,+ BaseSSHTunnelForwarderError,+ SSLRequiredError,+ HostNotAllowedError,+ TemporaryHostResolutionError,+)+REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES = {"timeout": "Connection timed out while fetching schemas from the source.","timed out": "Connection timed out while fetching schemas from the source.",@@ -254,6 +267,9 @@ REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES = {"forbidden": "The source credentials do not have permission to fetch schemas.","ssl/tls connection is required": "SSL/TLS is required to connect to the source.","could not establish session to ssh gateway": "Could not establish an SSH tunnel to the source.",+ # Raised by the connect-time host check of every SQL source; the map is matched on lowercased text.+ "database host not allowed": DATABASE_HOST_NOT_ALLOWED_GUIDANCE,+ "temporary failure resolving": "Could not resolve the source host right now. Try again in a moment.",}@@ -2683,7 +2699,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixischema_name = cdc_schema_name_by_location.get((db_schema, table_name))if schema_name is not None:pk_columns_by_table[schema_name] = primary_key_columns- except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ except _EXPECTED_CONNECTION_ERRORS as e:# Connecting to the user's database to detect CDC primary keys is expected to# fail when the host, port, credentials, or SSH tunnel are wrong, or the server# requires/refuses SSL. Surface it as a 400, but don't capture it — these are@@ -4140,8 +4156,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixitables=tables,slot_name=slot_name,publication_name=publication_name,+ team_id=self.team_id,)- except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ except _EXPECTED_CONNECTION_ERRORS as e:# Probing a user-supplied database to validate it is expected to fail when the host,# credentials, or SSH tunnel are wrong or the server drops the connection. Surface it# to the wizard as a 400, but don't capture it — these are user/upstream connection@@ -4210,7 +4227,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixislot_name=request.data.get("cdc_slot_name") or None,publication_name=request.data.get("cdc_publication_name") or None,)- except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ except _EXPECTED_CONNECTION_ERRORS as e:# Probing the source's database to validate it is expected to fail when the host,# credentials, or SSH tunnel are wrong, the server requires/refuses SSL, or it drops the# connection. Surface it as a 400, but don't capture it — these are user/upstream@@ -4285,7 +4302,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixislot_name=request.data.get("cdc_slot_name") or None,publication_name=request.data.get("cdc_publication_name") or None,)- except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ except _EXPECTED_CONNECTION_ERRORS as e:# Expected user/upstream connection failure (bad host/credentials/SSH tunnel, server# requires/refuses SSL, dropped connection). Surface as a 400 without capturing — see the# check_cdc_prerequisites_for_source handler above.@@ -4489,7 +4506,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixireturn Response(status=status.HTTP_409_CONFLICT, data={"message": str(e)})except CDCRepairError as e:return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})- except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ except _EXPECTED_CONNECTION_ERRORS as e:# Expected user/upstream connection failure — surface as a 400 without capturing,# mirroring the enable_cdc handler.return Response(@@ -4570,7 +4587,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi# back into the same deterministic failure.try:live_status = adapter.get_status(instance)- except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ except _EXPECTED_CONNECTION_ERRORS as e:return Response(status=status.HTTP_400_BAD_REQUEST,data={diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 73175bfa6e49..9b5c8a31efd0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -69,6 +69,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basResumableSource,error_message_matches,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ DATABASE_HOST_NOT_ALLOWED_ERROR,+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,+ SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR,+ TEMPORARY_HOST_RESOLUTION_PREFIX,+)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (AcquireV3LockActivityInputs,CheckPipelineVersionActivityInputs,@@ -122,10 +128,13 @@ Any_Source_Errors: dict[str, str | None] = {# resolve, or resolves to a private/internal address. Mirrors the `SSH tunnel host not allowed`# entry: a config problem only the customer can fix, so retrying just re-hits the same# rejection. Match the stable prefix and exclude the volatile host details that follow it.- "Database host not allowed": (- "PostHog rejected this source's database host because it either couldn't be resolved, or "- "resolves to a private/internal address. Check the host is spelled correctly and reachable "- "from the public internet, then re-enable the sync."+ DATABASE_HOST_NOT_ALLOWED_ERROR: DATABASE_HOST_NOT_ALLOWED_GUIDANCE,+ # Raised by `_pinned_ssh_host` for the bastion, the same class of config problem as the entry+ # above: the tunnel host doesn't resolve, or resolves to a private/internal address.+ SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR: (+ "PostHog rejected this source's SSH tunnel host because it either couldn't be resolved, or "+ "resolves to a private/internal address. Check the tunnel host is spelled correctly and "+ "reachable from the public internet, then re-enable the sync."),# Raised by `SSHTunnel.get_tunnel` when `is_auth_valid()` fails — the SSH tunnel private key# can't be parsed, or password auth is missing a username/password. Shared by every@@ -254,6 +263,13 @@ Transient_Error_Messages: dict[str, str] = {# and again through Temporal, so reaching here means the outage outlasted both and the stored# text is a bare status plus the vendor URL. Only the gateway statuses are mapped: a 500 can be# one request the vendor mishandles every time, which is not an outage that clears on its own.+ # The host policy's own lookup never answered. Every SQL source reaches it through the shared+ # tunnel layer, so it is mapped here rather than per source.+ TEMPORARY_HOST_RESOLUTION_PREFIX: (+ "PostHog couldn't resolve your source's host: the lookup kept failing without an answer. "+ "Check that the host name is correct and that its DNS records are answering; the next sync "+ "runs on schedule."+ ),"502 Server Error": TRANSIENT_VENDOR_UNAVAILABLE_MESSAGE,"503 Server Error": TRANSIENT_VENDOR_UNAVAILABLE_MESSAGE,"504 Server Error": TRANSIENT_VENDOR_UNAVAILABLE_MESSAGE,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/README.md b/products/warehouse_sources/backend/temporal/data_imports/sources/README.mdindex 3360e551b3b8..b48dfe565cac 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/README.md@@ -198,7 +198,7 @@ We have a handful of mixins available for your source classes. Add these to your#### `SSHTunnelMixin`-Provides a `with_ssh_tunnel()` context that opens a tunnel to a target and provides you with a host/port to connect to with your source.+Provides a `with_ssh_tunnel()` context that opens a tunnel to a target and provides you with a host/port to connect to with your source. It checks the SSH host and the database host on every open, not only when the source is created, so a DNS record that changes after setup cannot point a later sync at a private address. The database host is yielded as the hostname, so a client that can dial one address while presenting another name (libpq `host`/`hostaddr`, a pre-opened socket for pymysql) should also pin the addresses it validated, the way the Postgres client does.We also expose a `make_ssh_tunnel_func()` that does the same as the above, but instead returns a function to be passed to open the tunnel at a later time. This is helpful if your source logic doesn't actually live in your source class directly.@@ -208,7 +208,7 @@ Provides a simple `get_oauth_integration()` method to pull the `Integration` obj#### `ValidateDatabaseHostMixin`-Provides `is_database_host_valid()` to validate that the source isn't trying to access local IP addresses in our internal VPC on AWS (unless if the user is using a SSH tunnel).+Provides `is_database_host_valid()` to validate that the source isn't trying to access local IP addresses in our internal VPC on AWS (unless if the user is using a SSH tunnel). This runs when a source is created or updated; the connection-time check lives in `with_ssh_tunnel()` above.## Non-Retryable Errorsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.pyindex f2bd5184d8b3..3dec987c2ec9 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@@ -1,18 +1,25 @@+import reimport timeimport socketimport ipaddressimport dataclasses-from collections.abc import Callable, Generator+from collections.abc import Callable, Generator, Sequencefrom contextlib import _GeneratorContextManager, contextmanagerfrom typing import Any+from django.conf import settingsfrom django.db import OperationalError, close_old_connectionsimport structlogfrom posthog.cloud_utils import is_cloudfrom posthog.models.integration import Integration-from posthog.psycopg_helpers import prefer_routable_addresses+from posthog.psycopg_helpers import (+ is_resolvable_hostname,+ is_temporary_resolution_failure,+ prefer_routable_addresses,+ resolve_psycopg_hostaddr_with_timeout,+)from posthog.temporal.common.errors import NonReportableErrorfrom posthog.utils import get_instance_region@@ -29,6 +36,35 @@ _INTERNAL_IP_ERROR = ("Use a host that's reachable from the public internet.")_DNS_FAILURE_ERROR = "Host could not be resolved"+_MALFORMED_HOST_ERROR = (+ "Enter a single hostname or IP address for the host, without a port, path, comma, space or trailing dot."+)+_NON_ASCII_HOST_ERROR = (+ "This host has characters outside ASCII. Enter its punycode form instead, the spelling that starts with xn--."+)++# The sync registry and the schema-refresh map match this prefix; the rest of the message carries+# the volatile host details.+DATABASE_HOST_NOT_ALLOWED_ERROR = "Database host not allowed"+SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR = "SSH tunnel host not allowed"+TEMPORARY_HOST_RESOLUTION_PREFIX = "Temporary failure resolving the host"+DATABASE_HOST_NOT_ALLOWED_GUIDANCE = (+ "PostHog rejected this source's database host because it either couldn't be resolved, or "+ "resolves to a private/internal address. Check the host is spelled correctly and reachable "+ "from the public internet, then re-enable the sync."+)+++class TemporaryHostResolutionError(NonReportableError):+ """The resolver failed while the policy looked a host up, without answering about the name.++ Not a policy decision, so no non-retryable registry matches its message and the CDC classifier+ leaves it unknown: the work fails and is retried. `NonReportableError` keeps every retry of a+ resolver outage out of error tracking, on the activities that do not classify it themselves.+ """++ def __init__(self, host: str) -> None:+ super().__init__(f"{TEMPORARY_HOST_RESOLUTION_PREFIX} '{host}'. Try again in a moment.")class HostNotAllowedError(NonReportableError):@@ -62,14 +98,19 @@ def is_team_allowlisted_for_internal_hosts(team_id: int) -> bool:@dataclasses.dataclass(frozen=True, kw_only=True)class HostResolution:- """The outcome of `resolve_safe_host`.+ """The outcome of `resolve_safe_host` or `check_resolved_addresses`.`connect_host` is None exactly when the host was rejected, in which case `error` carriesthe user-facing reason.++ `addresses` holds every address the caller may dial, in resolver order. When the check ran,+ each one passed it. When the check was skipped, they are whatever the caller resolved, which+ is nothing for `resolve_safe_host` because it does not look the host up in that case."""connect_host: str | Noneerror: str | None+ addresses: tuple[str, ...] = ()def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:@@ -78,7 +119,10 @@ def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:Callers that go on to open the connection themselves should use `resolve_safe_host` andconnect to the address it returns, so that the address checked is the address used."""- resolution = resolve_safe_host(host, team_id)+ try:+ resolution = resolve_safe_host(host, team_id)+ except TemporaryHostResolutionError as e:+ return False, str(e)return resolution.connect_host is not None, resolution.error@@ -101,81 +145,195 @@ def resolve_safe_host(host: str, team_id: int | None) -> HostResolution:with a public address for this check and a private one for the connect, which defeats thecheck entirely. When the check is skipped there is no resolution to pin, so the hostnamecomes back unchanged.- """- def _log(decision: str, stage: str, reason: str | None, resolved_ips: list[str] | None = None) -> None:- if decision == "block":- log_fn = logger.warning # SSRF attempt — always logged- elif stage in ("not_cloud", "e2e"):- log_fn = logger.debug # never fires on cloud / spammy on self-hosted- else:- log_fn = logger.info-- log_fn(- "data_imports.host_check",- host=host,- team_id=team_id,- decision=decision,- stage=stage,- reason=reason,- resolved_ips=resolved_ips,- )+ A client that cannot dial a bare address, because it needs the name for SNI or dials several+ addresses in turn, resolves the host itself and passes the answer to+ `check_resolved_addresses` instead, so the set it validates is the set it dials.+ """+ if is_cloud() and (guard_error := _single_host_error(host)) is not None:+ _log_host_check(host, team_id, "block", "malformed_host", guard_error)+ return HostResolution(connect_host=None, error=guard_error)- def _allow_unpinned(stage: str) -> HostResolution:- _log("allow", stage, None)+ exempt_stage = _host_check_exemption(host, team_id)+ if exempt_stage is not None:+ _log_host_check(host, team_id, "allow", exempt_stage, None)return HostResolution(connect_host=host, error=None)- def _block(stage: str, error: str, resolved_ips: list[str] | None = None) -> HostResolution:- _log("block", stage, error, resolved_ips)- return HostResolution(connect_host=None, error=error)-- if not is_cloud():- return _allow_unpinned("not_cloud")-- region = get_instance_region()- if region == "E2E":- return _allow_unpinned("e2e")-- if team_id is not None and is_team_allowlisted_for_internal_hosts(team_id):- return _allow_unpinned("team_allowlist")-- normalized = host.lower().strip().rstrip(".")-- # PostHog-managed DuckLake hosts resolve to internal IPs but are safe.- if normalized.endswith(".postwh.com"):- return _allow_unpinned("postwh_managed")+ normalized = _normalize_host(host)if normalized in {"localhost"}:- return _block("localhost", _INTERNAL_IP_ERROR)+ _log_host_check(host, team_id, "block", "localhost", _INTERNAL_IP_ERROR)+ return HostResolution(connect_host=None, error=_INTERNAL_IP_ERROR)try:if not _is_safe_public_ip(host):- return _block("literal_ip", _INTERNAL_IP_ERROR)+ _log_host_check(host, team_id, "block", "literal_ip", _INTERNAL_IP_ERROR)+ return HostResolution(connect_host=None, error=_INTERNAL_IP_ERROR)except ValueError:pass- dns_failure_error = (- f"Couldn't resolve the host '{host}'. Check that it's spelled correctly and reachable from the public internet."- )try:- addrinfo = socket.getaddrinfo(normalized, None, proto=socket.IPPROTO_TCP)+ addrinfo = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)resolved_ips = [str(sockaddr[0]) for *_meta, sockaddr in addrinfo]- except (socket.gaierror, UnicodeError):+ except socket.gaierror as e:+ # A resolver blip is not a verdict on the host; refusing it would disable the schema.+ if is_temporary_resolution_failure(e):+ raise TemporaryHostResolutionError(host) from e+ resolved_ips = []+ except UnicodeError:# getaddrinfo IDNA-encodes the host, so a malformed hostname (e.g. a DNS label over 63# bytes) raises UnicodeError ("label too long") instead of gaierror. Either way the host# can't be resolved — return the actionable message rather than crashing.- _log("block", "dns_failure", _DNS_FAILURE_ERROR)- return HostResolution(connect_host=None, error=dns_failure_error)+ resolved_ips = []- for resolved_ip in resolved_ips:- if not _is_safe_public_ip(resolved_ip):- return _block("resolved_ip", _INTERNAL_IP_ERROR, resolved_ips)+ return _check_resolved_ips(host, team_id, resolved_ips)+++def check_resolved_addresses(host: str, addresses: Sequence[str], team_id: int | None) -> HostResolution:+ """Apply the `resolve_safe_host` policy to addresses the caller resolved itself.++ For a client that looks `host` up on its own and dials that answer. `resolve_safe_host`+ resolves and pins in one step, which a client cannot use when it needs the hostname for SNI+ or wants to try several addresses in turn. Validating the client's own answer here keeps the+ guarantee: the set it validates is the set it dials, so a record that answers public on one+ lookup and private on the next has no second lookup to slip past.++ The same exemptions as `resolve_safe_host` apply, and `addresses` is returned whole so an+ exempt caller still dials what it resolved. An empty `addresses` is a failed lookup and is+ refused, because letting the connection library resolve again would reopen the gap.+ """+ if is_cloud() and (guard_error := _single_host_error(host)) is not None:+ _log_host_check(host, team_id, "block", "malformed_host", guard_error)+ return HostResolution(connect_host=None, error=guard_error)++ exempt_stage = _host_check_exemption(host, team_id)+ if exempt_stage is not None:+ _log_host_check(host, team_id, "allow", exempt_stage, None)+ return HostResolution(connect_host=host, error=None, addresses=tuple(addresses))++ return _check_resolved_ips(host, team_id, list(addresses))+++_resolve_hostaddr_with_timeout = resolve_psycopg_hostaddr_with_timeout+++def pinned_host_kwargs(host: str, *, port: int, connect_timeout: float, team_id: int | None) -> dict[str, str]:+ """Resolve `host` once, validate the answer, and return the libpq `host`/`hostaddr` pair that+ dials exactly those addresses.++ The hostname is repeated once per address because libpq pairs `host` and `hostaddr`+ positionally: the name keeps carrying SNI, which Neon and the Supabase pooler need, and every+ validated address stays in libpq's failover list. A failed lookup is refused rather than left+ to libpq, because that retry would be a second, unvalidated lookup. A lookup that times out,+ or that the resolver answers with "try again", raises `psycopg.OperationalError` so it stays+ retryable; only a name that does not exist is refused.++ An IP literal (the SSH tunnel's loopback bind), a Unix socket path, or an empty host has no+ lookup to race and comes back unchanged. Dev and test connect to local or fake hosts, so the+ lookup is skipped there, as in `_get_sslmode`.+ """+ if settings.TEST or settings.DEBUG or settings.E2E_TESTING:+ return {"host": host}+ if is_cloud() and (guard_error := _single_host_error(host)) is not None:+ raise HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: {guard_error}")++ if not is_resolvable_hostname(host):+ return {"host": host}++ addresses = _resolve_hostaddr_with_timeout(host, port, connect_timeout, raise_on_temporary_failure=True) or []+ resolution = check_resolved_addresses(host, addresses, team_id)+ if resolution.connect_host is None:+ raise HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: {resolution.error or _INTERNAL_IP_ERROR}")+ if not resolution.addresses:+ # An exempt host whose lookup failed. The policy does not apply, and there is nothing to+ # pin, so libpq resolves the name itself as it did before.+ return {"host": host}++ return {+ "host": ",".join([host] * len(resolution.addresses)),+ "hostaddr": ",".join(resolution.addresses),+ }+++def _normalize_host(host: str) -> str:+ return host.lower().strip().rstrip(".")+++_HOST_LABEL = re.compile(r"^(?!-)[a-z0-9_-]{1,63}(?<!-)\Z")+++def _is_single_host(host: str) -> bool:+ """Whether `host` names one endpoint: an IP literal, or one hostname with no separators.++ libpq reads a comma as a host list and a leading slash as a socket directory, so an+ exemption granted on the whole string would let the driver dial a part of it the policy+ never looked at.+ """+ normalized = _normalize_host(host)+ try:+ parsed = ipaddress.ip_address(normalized.strip("[]"))+ except ValueError:+ pass+ else:+ # A scope id ("fe80::1%eth0") selects an interface and is not part of the address. CPython+ # keeps whatever follows the "%" verbatim, commas and spaces included, so a host list can+ # ride through here and be split by the driver.+ return parsed.version != 6 or parsed.scope_id is None+ return 0 < len(normalized) <= 253 and all(_HOST_LABEL.match(label) for label in normalized.split("."))+++def _single_host_error(host: str) -> str | None:+ """Why `host` is not one endpoint the drivers can dial as written, or None when it is.++ The drivers dial `host` as stored, so the string validated has to be that string. A name with+ characters outside ASCII is refused rather than converted, because the drivers hand the host to+ the resolver as raw bytes. Anything `strip()` or `rstrip(".")` would remove is refused too,+ because the resolver would then answer for a different name than the one dialed.+ """+ if not host.isascii():+ return _NON_ASCII_HOST_ERROR+ if host != host.strip() or host.endswith(".") or not _is_single_host(host):+ return _MALFORMED_HOST_ERROR+ return None+++def _host_check_exemption(host: str, team_id: int | None) -> str | None:+ """Return the stage name that exempts this host from the check, or None when it applies."""+ if not is_cloud():+ return "not_cloud"++ if get_instance_region() == "E2E":+ return "e2e"++ if team_id is not None and is_team_allowlisted_for_internal_hosts(team_id):+ return "team_allowlist"++ # PostHog-managed DuckLake hosts resolve to internal IPs but are safe. A suffix test is+ # enough only because callers refuse anything that is not one hostname before asking.+ if _normalize_host(host).endswith(".postwh.com"):+ return "postwh_managed"++ return None+++def _check_resolved_ips(host: str, team_id: int | None, resolved_ips: list[str]) -> HostResolution:if not resolved_ips:- _log("block", "dns_failure", _DNS_FAILURE_ERROR)- return HostResolution(connect_host=None, error=dns_failure_error)+ _log_host_check(host, team_id, "block", "dns_failure", _DNS_FAILURE_ERROR)+ return HostResolution(+ connect_host=None,+ error=(+ f"Couldn't resolve the host '{host}'. "+ "Check that it's spelled correctly and reachable from the public internet."+ ),+ )- _log("allow", "resolved_ip", None, resolved_ips)+ for resolved_ip in resolved_ips:+ if not _is_safe_public_ip(resolved_ip):+ _log_host_check(host, team_id, "block", "resolved_ip", _INTERNAL_IP_ERROR, resolved_ips)+ return HostResolution(connect_host=None, error=_INTERNAL_IP_ERROR)++ _log_host_check(host, team_id, "allow", "resolved_ip", None, resolved_ips)# getaddrinfo returns addresses in the order the resolver prefers, which is the order a# connect would try them in. Pinning the first one gives up that fallback: if it is down,# nothing tries the next. Every address in the list passed the check above, so this costs@@ -184,7 +342,34 @@ def resolve_safe_host(host: str, team_id: int | None) -> HostResolution:# That order is IPv6-first for a dual-stack host (RFC 6724), so on an IPv4-only worker the# pinned address is one nothing can route to and the connection can never succeed. Order by# what this host can actually reach before pinning.- return HostResolution(connect_host=prefer_routable_addresses(resolved_ips)[0], error=None)+ routable = prefer_routable_addresses(resolved_ips)+ return HostResolution(connect_host=routable[0], error=None, addresses=tuple(routable))+++def _log_host_check(+ host: str,+ team_id: int | None,+ decision: str,+ stage: str,+ reason: str | None,+ resolved_ips: list[str] | None = None,+) -> None:+ if decision == "block":+ log_fn = logger.warning # SSRF attempt — always logged+ elif stage in ("not_cloud", "e2e"):+ log_fn = logger.debug # never fires on cloud / spammy on self-hosted+ else:+ log_fn = logger.info++ log_fn(+ "data_imports.host_check",+ host=host,+ team_id=team_id,+ decision=decision,+ stage=stage,+ reason=reason,+ resolved_ips=resolved_ips,+ )def log_connection_open(@@ -278,7 +463,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 HostNotAllowedError(f"SSH tunnel host not allowed: {resolution.error}")+ raise HostNotAllowedError(f"{SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR}: {resolution.error}")return resolution.connect_host@@ -291,28 +476,25 @@ def _check_direct_host(config, team_id: int | None) -> None:re-checked on any later scheduled run. A direct database connection is a raw socket, so theHTTP egress proxy is not in its path either.- Unlike `_pinned_ssh_host` this checks without pinning, so a host that answers public here and- private on the connect is still reachable: this closes the standing exposure, not the- resolve-to-connect race. Pinning belongs in the clients, and for Postgres it costs nothing —- `_connect_to_postgres` already builds libpq's `host`/`hostaddr` pair, so the name still- carries SNI and every validated address stays in the failover list. What stops it living here- is that the address alone is not the decision: `resolve_safe_host` also exempts self-hosted- instances, the internal-analytics teams, and PostHog-managed hosts. Re-checking with the bare- predicate at the connect would refuse all three, so the policy has to travel with the- addresses before the pin can move.+ Unlike `_pinned_ssh_host` this checks without pinning, because the `(host, port)` this+ layer yields has to stay the hostname: the clients need it for SNI and for multi-address+ failover. So on its own this closes the standing exposure, not the resolve-to-connect race.+ The Postgres client closes that race itself: `_open_connection` in `postgres.py` resolves+ the host once, validates that answer with `check_resolved_addresses`, and dials exactly+ those addresses through libpq's `host`/`hostaddr` pair. The Redshift, MySQL and MSSQL+ clients still hand the hostname to their driver, so for them this check is the only one.A `team_id` of None fails closed. It changes nothing for a customer team, whose result is thesame either way; it only costs the internal-host exemption on entry points that don't carry ateam yet (`open_ssh_tunnel(config)` in the Redshift, MySQL and MSSQL clients).- The resolve inside `resolve_safe_host` is unbounded, and for Postgres it now runs ahead of the- bounded `_resolve_hostaddr_with_timeout`. A stalled resolver therefore hangs the activity until- Temporal's `start_to_close_timeout` rather than failing fast and retryably — the failure that- bounded lookup exists to prevent. Bounding this one is the follow-up.+ The resolve inside `resolve_safe_host` is unbounded. A stalled resolver therefore hangs the+ activity until Temporal's `start_to_close_timeout` rather than failing fast and retryably.+ Bounding this one is the follow-up."""resolution = resolve_safe_host(config.host, team_id)if resolution.connect_host is None:- raise HostNotAllowedError(f"Database host not allowed: {resolution.error}")+ raise HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: {resolution.error or _INTERNAL_IP_ERROR}")@contextmanagerdiff --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.pyindex 7a11f8090df9..4b3192abcc14 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@@ -19,8 +19,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixHostNotAllowedError,OAuthMixin,SSHTunnelMixin,+ TemporaryHostResolutionError,ValidateDatabaseHostMixin,_is_host_safe,+ check_resolved_addresses,make_ssh_tunnel_factory,open_ssh_tunnel,resolve_safe_host,@@ -107,6 +109,60 @@ class TestIsHostSafe(SimpleTestCase):valid, _ = _is_host_safe(host, team_id=999)assert valid+ @parameterized.expand(+ [+ ("comma_joined_postwh", "10.0.0.5,x.postwh.com", 999),+ ("comma_joined_allowlisted_team", "10.0.0.5,db.example.com", 2),+ ("space_joined_postwh", "10.0.0.5 x.postwh.com", 999),+ ("socket_path_postwh", "/var/run/x.postwh.com", 999),+ ("port_suffix_postwh", "x.postwh.com:5432", 999),+ ("leading_space_postwh", " x.postwh.com", 999),+ ("trailing_dot_postwh", "x.postwh.com.", 999),+ ("newline_label_postwh", "evil.example.com\n.postwh.com", 999),+ ("ipv6_scope_id_hiding_a_host_list", "fe80::1%x,10.0.0.1,x.postwh.com", 999),+ ("ipv6_scope_id", "fe80::1%eth0", 999),+ ]+ )+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_blocks_hosts_that_are_not_one_name_before_any_exemption(self, _name: str, host: str, team_id: int):+ with patch(f"{_MIXINS_MODULE}.socket.getaddrinfo") as getaddrinfo_mock:+ valid, error = _is_host_safe(host, team_id=team_id)++ assert not valid+ assert error is not None and "single hostname" in error+ getaddrinfo_mock.assert_not_called()++ @parameterized.expand(+ [+ ("try_again", socket.EAI_AGAIN, "Temporary failure in name resolution"),+ ("system_error", socket.EAI_SYSTEM, "System error"),+ ("out_of_memory", socket.EAI_MEMORY, "Memory allocation failure"),+ ]+ )+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_a_resolver_failure_is_reported_as_try_again(self, _name: str, errno: int, message: str) -> None:+ with patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=socket.gaierror(errno, message)):+ valid, error = _is_host_safe("db.example.com", team_id=999)++ assert not valid+ assert error is not None and "Try again" in error++ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_a_host_with_characters_outside_ascii_is_refused_before_any_lookup(self) -> None:+ with patch(f"{_MIXINS_MODULE}.socket.getaddrinfo") as getaddrinfo_mock:+ valid, error = _is_host_safe("täst.example.com", team_id=999)++ assert not valid+ assert error is not None and "punycode" in error+ getaddrinfo_mock.assert_not_called()++ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_allows_the_punycode_form_of_a_hostname(self) -> None:+ with patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=[(None, None, None, None, ("52.1.2.3", 0))]):+ valid, _ = _is_host_safe("xn--tst-qla.example.com", team_id=999)++ assert valid+@override_settings(CLOUD_DEPLOYMENT="US")def test_blocks_fake_postwh_suffix(self):with patch(@@ -155,14 +211,19 @@ class TestIsHostSafe(SimpleTestCase):resolution = resolve_safe_host("dual-stack.example.com", team_id=999)assert resolution.connect_host == "52.1.2.3"+ assert resolution.addresses == ("52.1.2.3",)+ @parameterized.expand(+ [+ ("no_errno", socket.gaierror("Name or service not known")),+ ("name_or_service_not_known", socket.gaierror(socket.EAI_NONAME, "Name or service not known")),+ ]+ )@override_settings(CLOUD_DEPLOYMENT="US")- def test_unresolvable_host_blocked(self):- import socket-+ def test_unresolvable_host_blocked(self, _name: str, lookup_error: socket.gaierror):with patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.socket.getaddrinfo",- side_effect=socket.gaierror("Name or service not known"),+ side_effect=lookup_error,):valid, error = _is_host_safe("nonexistent.invalid", team_id=999)assert not valid@@ -172,12 +233,10 @@ class TestIsHostSafe(SimpleTestCase):@override_settings(CLOUD_DEPLOYMENT="US")def test_malformed_host_label_blocked(self):- # A single DNS label over 63 bytes makes getaddrinfo's IDNA encoding raise UnicodeError,- # not gaierror — this must be handled gracefully instead of crashing.valid, error = _is_host_safe("a" * 92, team_id=999)assert not validassert error is not None- assert "resolve" in error+ assert "single hostname" in error@override_settings(CLOUD_DEPLOYMENT="US")def test_blocked_host_logs_warning(self):@@ -534,6 +593,21 @@ class TestDirectHostIsCheckedAtConnect(SimpleTestCase):with self._connection_cm(entrypoint, config, 999):pass+ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_a_resolver_blip_is_a_retryable_error_not_a_rejection(self, entrypoint: str) -> None:+ config = FakeConfig(host="db.example.com", ssh_tunnel=None)+ blip = socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")+ with (+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=blip),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ with pytest.raises(TemporaryHostResolutionError) as exc:+ with self._connection_cm(entrypoint, config, 999):+ pass++ assert not error_message_matches(str(exc.value), Any_Source_Errors.keys())+class TestDirectHostRejectionIsNonRetryable(SimpleTestCase):# The rejection is a config problem only the customer can fix, so it has to stop the schedule@@ -555,3 +629,76 @@ class TestDirectHostRejectionIsNonRetryable(SimpleTestCase):assert isinstance(exc.value, NonReportableError)assert error_message_matches(str(exc.value), Any_Source_Errors.keys())+++class TestCheckResolvedAddresses(SimpleTestCase):+ @parameterized.expand(+ [+ ("internal_first", ["10.0.0.5", "203.0.113.5"]),+ ("internal_second", ["203.0.113.5", "169.254.169.254"]),+ ("ipv6_mapped_internal", ["::ffff:10.0.0.1"]),+ ("nat64_imds", ["64:ff9b::169.254.169.254"]),+ ]+ )+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_any_internal_address_in_the_set_is_refused(self, _name: str, addresses: list[str]) -> None:+ with patch(f"{_MIXINS_MODULE}.logger"):+ resolution = check_resolved_addresses("db.example.com", addresses, team_id=999)++ assert resolution.connect_host is None+ assert resolution.addresses == ()+ assert resolution.error is not None++ @parameterized.expand(+ [("postwh_suffix", "10.0.0.5,x.postwh.com", 999), ("allowlisted_team", "10.0.0.5,db.example.com", 2)]+ )+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_a_host_that_is_not_one_name_is_refused_despite_an_exemption(+ self, _name: str, host: str, team_id: int+ ) -> None:+ with patch(f"{_MIXINS_MODULE}.logger"):+ resolution = check_resolved_addresses(host, ["10.0.0.5"], team_id=team_id)++ assert resolution.connect_host is None+ assert resolution.addresses == ()++ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_a_public_set_is_returned_whole_in_resolver_order(self) -> None:+ with (+ patch(f"{_MIXINS_MODULE}.logger"),+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=True),+ ):+ resolution = check_resolved_addresses("db.example.com", ["2600:1f18::1", "52.1.2.3"], team_id=999)++ assert resolution.error is None+ assert resolution.connect_host == "2600:1f18::1"+ assert resolution.addresses == ("2600:1f18::1", "52.1.2.3")++ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_an_empty_set_is_a_failed_lookup_and_is_refused(self) -> None:+ with patch(f"{_MIXINS_MODULE}.logger"):+ resolution = check_resolved_addresses("db.example.com", [], team_id=999)++ assert resolution.connect_host is None+ assert resolution.error is not None+ assert "resolve" in resolution.error++ @parameterized.expand(+ [+ ("team_allowlist", "US", "db.internal.example.com", 2),+ ("not_cloud", None, "db.internal.example.com", 999),+ ("posthog_managed", "US", "warehouse.postwh.com", 999),+ ]+ )+ def test_exemptions_skip_the_check_and_keep_the_set(+ self, _name: str, deployment: str | None, host: str, team_id: int+ ) -> None:+ with (+ override_settings(CLOUD_DEPLOYMENT=deployment),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ resolution = check_resolved_addresses(host, ["10.0.0.5"], team_id=team_id)++ assert resolution.error is None+ assert resolution.connect_host == host+ assert resolution.addresses == ("10.0.0.5",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.pyindex ca2fb5879e92..d878b750bc33 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py@@ -106,6 +106,7 @@ class NeonSource(PostgresSource):slot_name: str | None = None,publication_name: str | None = None,require_ssl: bool = True,+ team_id: int | None = None,) -> list[str]:# The pooled endpoint accepts normal connections, so the generic checks would pass —# but logical replication doesn't work through it. Fail fast without connecting.@@ -118,4 +119,5 @@ class NeonSource(PostgresSource):slot_name=slot_name,publication_name=publication_name,require_ssl=require_ssl,+ team_id=team_id,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/test_neon_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/test_neon_source.pyindex ae7a29421917..9182a079b202 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/test_neon_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/test_neon_source.py@@ -115,7 +115,8 @@ def test_cdc_prerequisites_delegate_for_direct_hosts(host):config = mock.MagicMock(host=host)with mock.patch.object(PostgresSource, "check_cdc_prerequisites", return_value=[]) as super_check:- errors = NeonSource().check_cdc_prerequisites(config, management_mode="posthog", tables=["users"])+ errors = NeonSource().check_cdc_prerequisites(config, management_mode="posthog", tables=["users"], team_id=7)super_check.assert_called_once()+ assert super_check.call_args.kwargs["team_id"] == 7assert errors == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.pyindex ea4770fd1eff..22ea3b27634e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py@@ -163,6 +163,7 @@ class PlanetScalePostgresSource(PostgresSource):slot_name: str | None = None,publication_name: str | None = None,require_ssl: bool = True,+ team_id: int | None = None,) -> list[str]:# PSBouncer accepts normal connections, so the generic checks would pass — but logical# replication doesn't work through it. Fail fast without connecting.@@ -175,4 +176,5 @@ class PlanetScalePostgresSource(PostgresSource):slot_name=slot_name,publication_name=publication_name,require_ssl=require_ssl,+ team_id=team_id,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/test_planetscale_postgres_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/test_planetscale_postgres_source.pyindex ffb30f67035c..30fd092a06c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/test_planetscale_postgres_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/test_planetscale_postgres_source.py@@ -151,10 +151,11 @@ def test_a_port_that_is_not_a_number_is_not_treated_as_psbouncer(port):def test_cdc_on_the_direct_port_defers_to_postgres():with mock.patch.object(PostgresSource, "check_cdc_prerequisites", return_value=[]) as super_check:errors = PlanetScalePostgresSource().check_cdc_prerequisites(- _config(), management_mode="managed", tables=["users"]+ _config(), management_mode="managed", tables=["users"], team_id=7)super_check.assert_called_once()+ assert super_check.call_args.kwargs["team_id"] == 7assert errors == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.pyindex 2501f5aca55c..21fe9d683e50 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py@@ -12,6 +12,7 @@ import structlogfrom sshtunnel import BaseSSHTunnelForwarderErrorfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import cdc_error_info+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.errors import (classify_postgres_cdc_error,@@ -163,9 +164,10 @@ class PostgresCDCAdapter:def is_connection_error(self, exc: BaseException) -> bool:# psycopg raises OperationalError for every failure to reach the source DB# (connect timeout, refused, unreachable host, DNS, dropped, auth); sshtunnel- # raises BaseSSHTunnelForwarderError when the tunnel itself can't be established.- # Neither points at a bug in our code.- return isinstance(exc, psycopg.OperationalError | BaseSSHTunnelForwarderError)+ # raises BaseSSHTunnelForwarderError when the tunnel itself can't be established;+ # the host policy raises HostNotAllowedError before any socket opens.+ # None points at a bug in our code.+ return isinstance(exc, psycopg.OperationalError | BaseSSHTunnelForwarderError | HostNotAllowedError)def classify_error(self, exc: BaseException) -> CDCErrorInfo | None:category = classify_postgres_cdc_error(exc)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/errors.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/errors.pyindex c8bdc063d730..e04ffd2e24e7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/errors.py@@ -15,6 +15,10 @@ import psycopg.errorsfrom sshtunnel import BaseSSHTunnelForwarderErrorfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR,+ HostNotAllowedError,+)# Server requires (or rejects) an encrypted connection. Kept specific so a transient# "SSL connection has been closed unexpectedly" stays a retryable connection failure.@@ -67,6 +71,14 @@ def classify_postgres_cdc_error(exc: BaseException) -> CDCErrorCategory | None:return CDCErrorCategory.SSH_TUNNEL_FAILEDreturn None+ # The host policy refused a host before any socket opened. Deterministic for the configured+ # host, so it stops the run like an unroutable address does. One type covers the bastion and+ # the database, and each needs its own guidance, so the prefix picks the category.+ if isinstance(exc, HostNotAllowedError):+ if str(exc).startswith(SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR):+ return CDCErrorCategory.SSH_TUNNEL_FAILED+ return CDCErrorCategory.HOST_UNREACHABLE+# Guard all string-based checks: only psycopg exceptions carry these message patterns.# A non-psycopg exception whose message happens to contain e.g. "does not exist" would# otherwise be misclassified as non-retryable SLOT_MISSING, permanently stopping retries.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.pyindex 1c6aaa883c5e..181771106b93 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.py@@ -45,6 +45,7 @@ def cdc_pg_connection(source: ExternalDataSource, connect_timeout: int = 15) ->password=config.password,require_ssl=require_ssl,connect_timeout=connect_timeout,+ team_id=source.team_id,)try:yield conndiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.pyindex 3f931b19e27c..cce71f669b02 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py@@ -127,6 +127,7 @@ class PgCDCStreamReader:user=self._params.user,password=self._params.password,require_ssl=self._params.require_ssl,+ team_id=self._source.team_id if self._source is not None else None,# statement_timeout (30m) is a server-side ceiling so a stalled WAL decode can't# hang the streaming connection indefinitely; it bounds a single peek, the caller's# soft deadline bounds the whole run. idle_in_transaction_session_timeout=0 stops the@@ -291,6 +292,7 @@ class PgCDCStreamReader:user=self._params.user,password=self._params.password,require_ssl=self._params.require_ssl,+ team_id=self._source.team_id if self._source is not None else None,),logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.pyindex 811bcd74d597..847343d1f26b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py@@ -7,6 +7,7 @@ import psycopg.errorsfrom parameterized import parameterizedfrom sshtunnel import BaseSSHTunnelForwarderError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import (PostgresCDCAdapter,_slot_setup_error_message,@@ -378,6 +379,7 @@ class TestIsConnectionError:("connect_timeout", psycopg.errors.ConnectionTimeout("connection timeout expired"), True),("operational", psycopg.OperationalError("connection refused"), True),("ssh_tunnel", BaseSSHTunnelForwarderError("could not open tunnel"), True),+ ("host_policy", HostNotAllowedError("resolves to a private address"), True),("programming_bug", ValueError("unexpected status shape"), False),])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_errors.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_errors.pyindex 966a9204a67d..52cec67e0c1e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_errors.py@@ -5,6 +5,7 @@ from parameterized import parameterizedfrom sshtunnel import BaseSSHTunnelForwarderErrorfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.errors import (classify_postgres_cdc_error,)@@ -65,6 +66,16 @@ class TestClassifyPostgresCDCError:),CDCErrorCategory.HOST_UNREACHABLE,),+ (+ "database_host_not_allowed_is_non_retryable_host",+ HostNotAllowedError("Database host not allowed: resolves to a private address"),+ CDCErrorCategory.HOST_UNREACHABLE,+ ),+ (+ "ssh_tunnel_host_not_allowed_is_a_tunnel_failure",+ HostNotAllowedError("SSH tunnel host not allowed: resolves to a private address"),+ CDCErrorCategory.SSH_TUNNEL_FAILED,+ ),("slot_missing",psycopg.errors.UndefinedObject('replication slot "posthog_slot" does not exist'),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex d109443281de..235e92c634d4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -34,7 +34,6 @@ from posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_tafrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception-from posthog.psycopg_helpers import resolve_psycopg_hostaddr_with_timeoutfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (@@ -59,7 +58,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpersincremental_type_to_initial_value,incremental_type_to_operator,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import open_ssh_tunnel+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ open_ssh_tunnel,+ pinned_host_kwargs,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (Column,Table,@@ -829,16 +831,22 @@ def _is_invalid_ssl_negotiation_response(error: BaseException) -> bool:return _INVALID_SSL_NEGOTIATION_RESPONSE_SUBSTRING in " ".join(str(arg) for arg in error.args).lower()-_resolve_hostaddr_with_timeout = resolve_psycopg_hostaddr_with_timeout---def _connect_with_options_fallback(**connect_kwargs: Any) -> psycopg.Connection:- """`psycopg.connect` that retries without the libpq `options` startup parameter when the- server rejects it.+def _open_connection(*, team_id: int | None = None, **connect_kwargs: Any) -> psycopg.Connection:+ """The one `psycopg.connect` in this module. Every connection to a source database opens+ here so that `pinned_host_kwargs` decides what gets dialed.- See `_OPTIONS_STARTUP_PARAM_UNSUPPORTED_SUBSTRINGS` for why transaction-mode poolers reject+ Retries without the libpq `options` startup parameter when the server rejects it. See+ `_OPTIONS_STARTUP_PARAM_UNSUPPORTED_SUBSTRINGS` for why transaction-mode poolers reject`options` and why dropping it is safe."""+ connect_kwargs.update(+ pinned_host_kwargs(+ connect_kwargs["host"],+ port=connect_kwargs.get("port", 5432),+ connect_timeout=connect_kwargs.get("connect_timeout", 15),+ team_id=team_id,+ )+ )try:return psycopg.connect(**connect_kwargs)except psycopg.OperationalError as e:@@ -859,6 +867,7 @@ def _connect_to_postgres(password: str,require_ssl: bool = False,connect_timeout: int = 15,+ team_id: int | None = None,**kwargs: Any,) -> psycopg.Connection:sslmode = _get_sslmode(require_ssl)@@ -869,19 +878,9 @@ def _connect_to_postgres(# cleanly. We always force UTF8 and append any caller-supplied `options` after it.caller_options = kwargs.pop("options", None)options = f"{FORCE_UTF8_CLIENT_ENCODING} {caller_options}" if caller_options else FORCE_UTF8_CLIENT_ENCODING- # Bound psycopg's Python-side DNS lookup in production (see `_resolve_hostaddr_with_timeout`).- # Dev/test connect to local or fake hosts, so skip the real lookup there — mirrors `_get_sslmode`.- if not (settings.TEST or settings.DEBUG or settings.E2E_TESTING):- addresses = _resolve_hostaddr_with_timeout(host, port, connect_timeout)- if addresses:- # A comma-separated `host`/`hostaddr` pair of matching length is how psycopg/libpq- # represent multiple attempts (see `split_attempts` in psycopg/_conninfo_utils.py) — this- # keeps its per-address failover intact for a dual-stack host instead of pinning the- # connection to whichever single address `getaddrinfo` happened to return first.- host = ",".join([host] * len(addresses))- kwargs["hostaddr"] = ",".join(addresses)try:- return _connect_with_options_fallback(+ return _open_connection(+ team_id=team_id,host=host,port=port,dbname=database,@@ -922,10 +921,17 @@ def pg_connection(user: str,password: str,require_ssl: bool = False,+ team_id: int | None = None,) -> Iterator[psycopg.Connection]:"""Context manager that opens a postgres connection and ensures it is closed on exit."""conn = _connect_to_postgres(- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl+ host=host,+ port=port,+ database=database,+ user=user,+ password=password,+ require_ssl=require_ssl,+ team_id=team_id,)try:yield conn@@ -1419,13 +1425,20 @@ def get_postgres_row_count(password: str,schema: str | None,require_ssl: bool = False,+ team_id: int | None = None,names: list[str] | None = None,) -> dict[str, int]:if _normalize_selected_schema(schema) is None and not names:return {}try:with pg_connection(- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl+ host=host,+ port=port,+ database=database,+ user=user,+ password=password,+ require_ssl=require_ssl,+ team_id=team_id,) as connection:return _row_counts_from_conn(connection, schema, names)except:@@ -1543,6 +1556,7 @@ def get_schemas(schema: str | None,port: int,require_ssl: bool = False,+ team_id: int | None = None,names: list[str] | None = None,) -> dict[str, PostgresDiscoveredSchema]:"""Get all tables from PostgreSQL source schemas to sync."""@@ -1566,7 +1580,13 @@ def get_schemas(# `_is_dropped_or_connection_limit` matches only these known-transient conditions.def _connect_and_discover() -> dict[str, PostgresDiscoveredSchema]:connection = _connect_to_postgres(- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl+ host=host,+ port=port,+ database=database,+ user=user,+ password=password,+ require_ssl=require_ssl,+ team_id=team_id,)try:return _schemas_from_conn(connection, schema, names)@@ -1590,13 +1610,20 @@ def get_primary_keys_for_schemas(port: int,table_names: list[str],require_ssl: bool = False,+ team_id: int | None = None,) -> dict[str, list[str] | None]:"""Detect primary keys for all tables in a single query."""result: dict[str, list[str] | None] = dict.fromkeys(table_names)try:with pg_connection(- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl+ host=host,+ port=port,+ database=database,+ user=user,+ password=password,+ require_ssl=require_ssl,+ team_id=team_id,) as connection:pks = get_primary_key_columns(connection, schema, table_names)for table_name, pk_cols in pks.items():@@ -1683,11 +1710,18 @@ def get_foreign_keys(schema: str | None,port: int,require_ssl: bool = False,+ team_id: int | None = None,names: list[str] | None = None,) -> dict[str, list[tuple[str, str, str]]]:"""Get foreign keys for tables in the selected PostgreSQL schema."""with pg_connection(- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl+ host=host,+ port=port,+ database=database,+ user=user,+ password=password,+ require_ssl=require_ssl,+ team_id=team_id,) as connection:return _foreign_keys_from_conn(connection, schema, names)@@ -1699,9 +1733,16 @@ def get_connection_metadata(password: str,port: int,require_ssl: bool = False,+ team_id: int | None = None,) -> dict[str, Any]:with pg_connection(- host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl+ host=host,+ port=port,+ database=database,+ user=user,+ password=password,+ require_ssl=require_ssl,+ team_id=team_id,) as connection:with connection.cursor() as cursor:cursor.execute("SELECT current_database(), version()")@@ -3314,7 +3355,8 @@ def postgres_source(def _open_setup_connection() -> psycopg.Connection:try:- conn = _connect_with_options_fallback(+ conn = _open_connection(+ team_id=team_id,host=host,port=port,dbname=database,@@ -3684,7 +3726,8 @@ def postgres_source(def get_connection():try:- connection = _connect_with_options_fallback(+ connection = _open_connection(+ team_id=team_id,host=host,port=port,dbname=database,@@ -4308,9 +4351,10 @@ class PostgresImplementation(SQLSourceImplementation[PostgresSourceConfig, psycoconfig: PostgresSourceConfig,*,require_ssl: bool = False,+ team_id: int | None = None,) -> Iterator[psycopg.Connection]:"""Open a single psycopg connection (through the SSH tunnel if configured)."""- with open_ssh_tunnel(config) as (host, port):+ with open_ssh_tunnel(config, team_id) as (host, port):with pg_connection(host=host,port=port,@@ -4318,6 +4362,7 @@ class PostgresImplementation(SQLSourceImplementation[PostgresSourceConfig, psycouser=config.user,password=config.password,require_ssl=require_ssl,+ team_id=team_id,) as conn:yield conndiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex 65b16dda9320..6df1a933f965 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -20,6 +20,7 @@ from posthog.schema import ()from posthog.exceptions_capture import capture_exception+from posthog.psycopg_helpers import HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERRORfrom products.data_warehouse.backend.facade.api import reconcile_postgres_schemasfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention@@ -28,7 +29,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basFieldType,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ HostNotAllowedError,SSHTunnelMixin,+ TemporaryHostResolutionError,ValidateDatabaseHostMixin,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry@@ -118,8 +121,17 @@ _INVALID_CREDENTIALS_VALIDATION_ERROR = ("The database rejected the username or password. Check the user and password for this source and try again.")+_HOST_RESOLUTION_RETRY_MESSAGE = (+ "PostHog couldn't resolve your database host right now. Check the host name, then try again in a moment."+)+PostgresErrors = {"password authentication failed for user": _INVALID_CREDENTIALS_VALIDATION_ERROR,+ # The bounded lookup in front of the connect reports a stalled resolver and a "try again"+ # answer as psycopg errors. Neither is a verdict on the host, so validation asks for a retry+ # rather than capturing a self-recovering failure.+ HOST_RESOLUTION_TIMEOUT_ERROR: _HOST_RESOLUTION_RETRY_MESSAGE,+ TEMPORARY_HOST_RESOLUTION_ERROR: _HOST_RESOLUTION_RETRY_MESSAGE,# libpq reports a bad password via SCRAM with a different wording than the line above."error received from server in SCRAM exchange: Wrong password": _INVALID_CREDENTIALS_VALIDATION_ERROR,# Supabase/Supavisor poolers report a missing tenant/user during credential validation with@@ -282,6 +294,11 @@ _CONNECTION_LIMIT_EXHAUSTED_MESSAGE = ("schedule.")+_HOST_RESOLUTION_EXHAUSTED_MESSAGE = (+ "PostHog could not resolve your database host: the DNS lookup timed out or the resolver asked "+ "to try again on every attempt. Check that the host name is correct and that its DNS records "+ "are answering. This sync is still enabled and will run again on its next schedule."+)_RECOVERY_CONFLICT_EXHAUSTED_MESSAGE = ("Your read replica kept canceling PostHog's reads because it had to apply changes from the ""primary that removed rows the sync was still reading, and the conflict outlasted every retry. "@@ -1030,12 +1047,17 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa# `using_read_replica` is False. The single-conflict message reaching here (as opposed to the# "kept canceling reads..."/"no key that can resume..." messages above, which are the# exhausted-retry abort and stay non-retryable) is the same self-recovering condition.+ # The bounded lookup in front of every connect raises these two when the resolver does not+ # answer in time or answers "try again". Neither is a verdict on the host, and a fresh+ # attempt recovers, so they belong with the other self-recovering connect failures.return {*_CONNECTION_DROPPED_ERROR_SUBSTRINGS,*_POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS,*_SERVER_STARTING_UP_ERROR_SUBSTRINGS,*_CONNECTION_LIMIT_ERROR_SUBSTRINGS,"conflict with recovery",+ HOST_RESOLUTION_TIMEOUT_ERROR,+ TEMPORARY_HOST_RESOLUTION_ERROR,}def get_retry_exhausted_errors(self) -> dict[str, str]:@@ -1054,6 +1076,8 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa**dict.fromkeys(_SERVER_STARTING_UP_ERROR_SUBSTRINGS, _SERVER_UNAVAILABLE_EXHAUSTED_MESSAGE),**dict.fromkeys(_CONNECTION_LIMIT_ERROR_SUBSTRINGS, _CONNECTION_LIMIT_EXHAUSTED_MESSAGE),"conflict with recovery": _RECOVERY_CONFLICT_EXHAUSTED_MESSAGE,+ HOST_RESOLUTION_TIMEOUT_ERROR: _HOST_RESOLUTION_EXHAUSTED_MESSAGE,+ TEMPORARY_HOST_RESOLUTION_ERROR: _HOST_RESOLUTION_EXHAUSTED_MESSAGE,}def reconcile_schema_metadata(@@ -1120,6 +1144,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaschema=config.schema,names=names,require_ssl=require_ssl,+ team_id=team_id,)# Foreign keys are advisory metadata (they pre-populate relationship hints in the# table picker). The discovery query joins three `information_schema` views, which@@ -1136,6 +1161,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaschema=config.schema,names=names,require_ssl=require_ssl,+ team_id=team_id,)except Exception as e:structlog.get_logger().warning("Failed to detect foreign keys for Postgres schemas", exc_info=e)@@ -1151,6 +1177,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaschema=config.schema,names=names,require_ssl=require_ssl,+ team_id=team_id,)else:row_counts = {}@@ -1184,6 +1211,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDapassword=config.password,database=config.database,require_ssl=require_ssl,+ team_id=team_id,) as conn:# PK lookup powers `supports_cdc`. Wrap in try/except so a permissions# quirk on `pg_catalog` (rare) only disables CDC advertising for this@@ -1371,6 +1399,10 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaif require_ssl:return False, _SSL_UNSUPPORTED_ERRORreturn False, str(e)+ except HostNotAllowedError as e:+ return False, str(e)+ except TemporaryHostResolutionError as e:+ return False, str(e)except OperationalError as e:error_msg = " ".join(str(n) for n in e.args)for key, value in PostgresErrors.items():@@ -1418,6 +1450,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDapassword=config.password,database=config.database,require_ssl=require_ssl,+ team_id=team_id,)def check_cdc_prerequisites(@@ -1428,6 +1461,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaslot_name: str | None = None,publication_name: str | None = None,require_ssl: bool = True,+ team_id: int | None = None,) -> list[str]:"""Validate Postgres CDC prerequisites against a live connection.@@ -1441,7 +1475,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa_connect_to_postgres,)- with self.with_ssh_tunnel(config) as (host, port):+ with self.with_ssh_tunnel(config, team_id) as (host, port):conn = _connect_to_postgres(host=host,port=port,@@ -1449,6 +1483,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDauser=config.user,password=config.password,require_ssl=require_ssl,+ team_id=team_id,)try:schema = config.schema.strip() if isinstance(config.schema, str) and config.schema.strip() else "public"@@ -1501,7 +1536,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDarow_filters=inputs.row_filters,)require_ssl = source_requires_ssl(schema.source, config)- with self.get_implementation.connect(config, require_ssl=require_ssl) as conn:+ with self.get_implementation.connect(config, require_ssl=require_ssl, team_id=inputs.team_id) as conn:# Autocommit so a rejected SET (engines without statement_timeout support) is its# own statement and cannot poison the probe query's transaction.conn.autocommit = Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex 0a66d3b67085..10188b05a012 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -16,6 +16,7 @@ from django.db import (OperationalError as DjangoOperationalError,connection as django_connection,)+from django.test import override_settingsimport psycopgimport pyarrow as pa@@ -24,6 +25,9 @@ from parameterized import parameterizedfrom psycopg import sqlfrom sshtunnel import BaseSSHTunnelForwarderError+from posthog.dataclasses import frozen+from posthog.psycopg_helpers import HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERROR+import products.warehouse_sources.backend.temporal.data_imports.sources.postgres.partitioned_tables as partitioned_tables_pkgfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (DEFAULT_NUMERIC_SCALE,@@ -37,11 +41,17 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.con)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import table_payload_bytesfrom 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,+ TemporaryHostResolutionError,+ _resolve_hostaddr_with_timeout,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import batchingfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (ColumnTypeCategory,ValidatedRowFilter,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (ForeignServerUnreachableError,XminUnsupportedError,@@ -92,7 +102,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_capture_xmin_ceiling,_connect_to_postgres,_connect_with_dropped_retry,- _connect_with_options_fallback,_fetch_rows_for,_get_estimated_row_count_for_partitioned_table,_get_partition_settings,@@ -115,10 +124,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_is_unsupported_statement_timeout_error,_next_recovery_conflict_chunk_size,_normalize_function_names,+ _open_connection,_pk_uniqueness_probe_timeout_error,_raise_if_setup_connection_broken,_recovery_conflict_abort_error,- _resolve_hostaddr_with_timeout,_rls_active_from_conn,_role_subject_to_rls,_safe_close_connection,@@ -639,6 +648,22 @@ class TestPostgresSourceNonRetryableErrors:# so one missing here would silently fall back to storing the raw driver text.assert source.get_retryable_errors() == set(source.get_retry_exhausted_errors().keys())+ @pytest.mark.parametrize(+ "error_msg",+ [+ f"{HOST_RESOLUTION_TIMEOUT_ERROR} after 15.0s",+ TEMPORARY_HOST_RESOLUTION_ERROR,+ ],+ )+ def test_resolver_failures_before_the_connect_are_classified_retryable(self, source, error_msg):+ # The bounded lookup in front of every connect raises these when the resolver stalls or+ # answers "try again". Neither is a verdict on the host, so a fresh attempt recovers. Without+ # the classification, `_handle_import_error` reports a self-recovering failure on every one+ # of the activity's retries. They must stay out of get_non_retryable_errors too, which is+ # checked first and would disable the schema.+ assert error_message_matches(error_msg, source.get_retryable_errors())+ assert not error_message_matches(error_msg, source.get_non_retryable_errors().keys())+@pytest.mark.parametrize("error_msg",[@@ -2533,7 +2558,7 @@ class TestConnectToPostgresMultiAddressFailover:]with (patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.settings"+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.settings") as mock_settings,patch("posthog.psycopg_helpers.socket.getaddrinfo",@@ -2562,7 +2587,7 @@ class TestConnectToPostgresMultiAddressFailover:addrinfo = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("203.0.113.5", 5432))]with (patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.settings"+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.settings") as mock_settings,patch("posthog.psycopg_helpers.socket.getaddrinfo",@@ -2587,6 +2612,217 @@ class TestConnectToPostgresMultiAddressFailover:assert connect_mock.call_args.kwargs["hostaddr"] == "203.0.113.5"+@frozen+class _ProductionCloud:+ getaddrinfo: MagicMock+ connect: MagicMock+++class TestConnectToPostgresDialsOnlyValidatedAddresses:+ @staticmethod+ # nosemgrep: semgrep.rules.devex.tuple-return-prefer-dataclass -- mirrors socket.getaddrinfo's positional result+ def _addrinfo(*addresses: str) -> list[tuple[int, int, int, str, tuple[str, int]]]:+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (address, 5432)) for address in addresses]++ @contextmanager+ def _production_cloud(self, resolver_result: Any) -> Iterator[_ProductionCloud]:+ resolver_kwargs = (+ {"side_effect": resolver_result}+ if isinstance(resolver_result, BaseException) or callable(resolver_result)+ else {"return_value": resolver_result}+ )+ with (+ override_settings(CLOUD_DEPLOYMENT="US"),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.settings"+ ) as mock_settings,+ patch("posthog.psycopg_helpers.socket.getaddrinfo", **resolver_kwargs) as getaddrinfo_mock,+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=True),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect"+ ) as connect_mock,+ ):+ mock_settings.TEST = False+ mock_settings.DEBUG = False+ mock_settings.E2E_TESTING = False+ yield _ProductionCloud(getaddrinfo=getaddrinfo_mock, connect=connect_mock)++ @staticmethod+ def _connect(host: str = "db.example.com", **kwargs: Any) -> psycopg.Connection:+ return _connect_to_postgres(+ host=host, port=5432, database="postgres", user="user", password="password", **kwargs+ )++ @pytest.mark.parametrize(+ "addresses",+ [+ ("10.0.0.5", "52.1.2.3"),+ ("52.1.2.3", "169.254.169.254"),+ ("64:ff9b::169.254.169.254",),+ ],+ )+ def test_an_internal_address_anywhere_in_the_resolved_set_refuses_the_connect(+ self, addresses: tuple[str, ...]+ ) -> None:+ with self._production_cloud(self._addrinfo(*addresses)) as cloud:+ with pytest.raises(Exception, match="Database host not allowed"):+ self._connect(team_id=999)++ cloud.connect.assert_not_called()++ @pytest.mark.parametrize(+ "resolver_result",+ [+ socket.gaierror(-2, "Name or service not known"),+ [],+ ],+ )+ def test_a_failed_lookup_refuses_the_connect_rather_than_letting_libpq_resolve(self, resolver_result: Any) -> None:+ with self._production_cloud(resolver_result) as cloud:+ with pytest.raises(Exception, match="Database host not allowed"):+ self._connect(team_id=999)++ cloud.connect.assert_not_called()++ def test_a_public_set_is_dialed_whole_with_the_hostname_kept_for_sni(self) -> None:+ with self._production_cloud(self._addrinfo("2600:1f18::1", "52.1.2.3")) as cloud:+ self._connect(team_id=999)++ assert cloud.connect.call_args.kwargs["host"] == "db.example.com,db.example.com"+ assert cloud.connect.call_args.kwargs["hostaddr"] == "2600:1f18::1,52.1.2.3"++ def test_an_allowlisted_team_dials_its_internal_addresses_pinned(self) -> None:+ with self._production_cloud(self._addrinfo("10.0.0.5")) as cloud:+ self._connect(team_id=2)++ assert cloud.connect.call_args.kwargs["host"] == "db.example.com"+ assert cloud.connect.call_args.kwargs["hostaddr"] == "10.0.0.5"++ def test_a_missing_team_fails_closed(self) -> None:+ with self._production_cloud(self._addrinfo("10.0.0.5")) as cloud:+ with pytest.raises(Exception, match="Database host not allowed"):+ self._connect()++ cloud.connect.assert_not_called()++ def test_an_exempt_host_whose_lookup_failed_is_left_for_libpq_to_resolve(self) -> None:+ with self._production_cloud(socket.gaierror(-2, "Name or service not known")) as cloud:+ self._connect(team_id=2)++ assert cloud.connect.call_args.kwargs["host"] == "db.example.com"+ assert "hostaddr" not in cloud.connect.call_args.kwargs++ def test_a_resolver_blip_stays_retryable(self) -> None:+ with self._production_cloud(socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")) as cloud:+ with pytest.raises(psycopg.OperationalError, match="Temporary failure") as exc_info:+ self._connect(team_id=999)++ assert "Database host not allowed" not in str(exc_info.value)+ cloud.connect.assert_not_called()++ def test_a_comma_joined_host_is_refused_before_libpq_sees_it(self) -> None:+ with self._production_cloud(self._addrinfo("10.0.0.5")) as cloud:+ with pytest.raises(HostNotAllowedError, match="single hostname"):+ self._connect(host="10.0.0.5,x.postwh.com", team_id=999)++ cloud.getaddrinfo.assert_not_called()+ cloud.connect.assert_not_called()++ def test_an_ip_literal_host_is_dialed_as_is_without_a_lookup(self) -> None:+ with self._production_cloud(self._addrinfo("127.0.0.1")) as cloud:+ self._connect(host="127.0.0.1", team_id=999)++ cloud.getaddrinfo.assert_not_called()+ assert cloud.connect.call_args.kwargs["host"] == "127.0.0.1"+ assert "hostaddr" not in cloud.connect.call_args.kwargs++ def test_a_stalled_lookup_stays_a_retryable_timeout(self) -> None:+ release = threading.Event()+ try:+ with self._production_cloud(lambda *a, **k: release.wait()) as cloud:+ with pytest.raises(psycopg.OperationalError, match="Timed out resolving") as exc_info:+ self._connect(team_id=999, connect_timeout=0)+ finally:+ release.set()++ assert "Database host not allowed" not in str(exc_info.value)+ cloud.connect.assert_not_called()+++class TestPostgresSourceDialsOnlyValidatedAddresses:+ @staticmethod+ @contextmanager+ def _tunnel() -> Iterator[tuple[str, int]]:+ yield ("db.example.com", 5432)++ @contextmanager+ def _production_cloud(self, *addresses: str) -> Iterator[None]:+ addrinfo = [+ (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (address, 5432)) for address in addresses+ ]+ with (+ override_settings(CLOUD_DEPLOYMENT="US"),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.settings"+ ) as mock_settings,+ patch("posthog.psycopg_helpers.socket.getaddrinfo", return_value=addrinfo),+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=True),+ patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.time.sleep"),+ ):+ mock_settings.TEST = False+ mock_settings.DEBUG = False+ mock_settings.E2E_TESTING = False+ yield++ def _call_postgres_source(self, team_id: int | None) -> SourceResponse:+ return postgres_source(+ tunnel=self._tunnel,+ user="u",+ password="p",+ database="db",+ sslmode="prefer",+ schema="public",+ table_names=["t"],+ should_use_incremental_field=False,+ logger=structlog.get_logger(),+ db_incremental_field_last_value=None,+ team_id=team_id,+ )++ def test_the_setup_connect_refuses_an_internal_address(self) -> None:+ with self._production_cloud("52.1.2.3", "10.0.0.5"):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect"+ ) as connect_mock:+ with pytest.raises(Exception, match="Database host not allowed"):+ self._call_postgres_source(team_id=999)++ connect_mock.assert_not_called()++ def test_the_setup_connect_dials_the_validated_set(self) -> None:+ cursor = mock.MagicMock()+ cursor.execute.side_effect = psycopg.errors.InternalError_("XX000: internal error")+ cursor_cm = mock.MagicMock()+ cursor_cm.__enter__.return_value = cursor+ cursor_cm.__exit__.return_value = False+ connection = mock.MagicMock()+ connection.closed = False+ connection.cursor.return_value = cursor_cm+ connection.__enter__.return_value = connection+ connection.__exit__.return_value = False++ with self._production_cloud("2600:1f18::1", "52.1.2.3"):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect",+ return_value=connection,+ ) as connect_mock:+ with pytest.raises(psycopg.errors.InternalError_):+ self._call_postgres_source(team_id=999)++ assert connect_mock.call_args.kwargs["host"] == "db.example.com,db.example.com"+ assert connect_mock.call_args.kwargs["hostaddr"] == "2600:1f18::1,52.1.2.3"++# Transaction-mode poolers (Supabase Supavisor on :6543, PgBouncer transaction mode, AWS RDS Proxy,# Neon's pooled endpoint) reject the libpq `options` startup parameter we send to pin# client_encoding=UTF8 and, on the CDC path, server-side timeouts. When they do, we drop `options`@@ -2640,7 +2876,7 @@ class TestConnectOptionsStartupParamFallback:"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect",connect_mock,):- result = _connect_with_options_fallback(host="db", options=FORCE_UTF8_CLIENT_ENCODING)+ result = _open_connection(host="db", options=FORCE_UTF8_CLIENT_ENCODING)assert result is good_connassert connect_mock.call_count == 2@@ -2658,7 +2894,7 @@ class TestConnectOptionsStartupParamFallback:connect_mock,):with pytest.raises(psycopg.OperationalError):- _connect_with_options_fallback(host="db")+ _open_connection(host="db")assert connect_mock.call_count == 1@@ -2670,7 +2906,7 @@ class TestConnectOptionsStartupParamFallback:connect_mock,):with pytest.raises(psycopg.OperationalError):- _connect_with_options_fallback(host="db", options=FORCE_UTF8_CLIENT_ENCODING)+ _open_connection(host="db", options=FORCE_UTF8_CLIENT_ENCODING)assert connect_mock.call_count == 1@@ -2692,7 +2928,7 @@ class TestConnectOptionsStartupParamFallback:connect_mock,):with pytest.raises(psycopg.OperationalError) as exc_info:- _connect_with_options_fallback(host="db", options=FORCE_UTF8_CLIENT_ENCODING)+ _open_connection(host="db", options=FORCE_UTF8_CLIENT_ENCODING)assert connect_mock.call_count == 2assert "The password that was provided for the role" in str(exc_info.value)@@ -4215,6 +4451,16 @@ class TestValidateCredentialsErrorMapping:'repeated authentication failures ("too many authentication failures"). This usually '"means the username or password is wrong. Check your credentials and try again.",),+ (+ f"{HOST_RESOLUTION_TIMEOUT_ERROR} after 15.0s",+ "PostHog couldn't resolve your database host right now. Check the host name, then try "+ "again in a moment.",+ ),+ (+ TEMPORARY_HOST_RESOLUTION_ERROR,+ "PostHog couldn't resolve your database host right now. Check the host name, then try "+ "again in a moment.",+ ),# Unmapped errors fall back to the generic message.("some brand new failure",@@ -4233,6 +4479,21 @@ class TestValidateCredentialsErrorMapping:assert valid is Falseassert error == expected+ def test_a_resolver_blip_during_validation_is_not_captured(self, source, config):+ with (+ mock.patch.object(source, "ssh_tunnel_is_valid", return_value=(True, None)),+ mock.patch.object(source, "is_database_host_valid", return_value=(True, None)),+ mock.patch.object(source, "get_schemas", side_effect=TemporaryHostResolutionError("db.example.com")),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.capture_exception"+ ) as mock_capture,+ ):+ valid, error = source.validate_credentials(config, team_id=1)++ assert valid is False+ assert error is not None and "Try again in a moment" in error+ mock_capture.assert_not_called()+@pytest.mark.parametrize("require_ssl,expects_ssl_guidance",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex 1a181041fe16..1e95560bd691 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -74,6 +74,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.hishistory_start_for_schema,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_context import bind_job_context+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import TemporaryHostResolutionErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (RESTClientNonRetryableError,RESTClientRetryableError,@@ -809,6 +810,15 @@ async def _handle_import_error(await logger.adebug("REST client exhausted its retries - re-raising for Temporal retry")raise error+ # The host policy's own lookup answered "try again" rather than a verdict on the host, so the+ # source is fine and a fresh attempt recovers. Classify it by type: every SQL source reaches+ # this through the shared tunnel layer, and the message carries the host, so no source could+ # list it in get_retryable_errors.+ if isinstance(error, TemporaryHostResolutionError):+ await logger.awarning(error_msg)+ await logger.adebug("Temporary host resolution failure - re-raising for Temporal retry")+ raise NonReportableError(error_msg) from error+# A transient S3/object-store hiccup talking to our own data-warehouse bucket (IMDS/STS# blip, SlowDown throttling) that surfaced during this run — e.g. resetting or opening the# Delta table. Not a PostHog defect and not a customer credential problem (seediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 27dcb2098263..baf4f529aa5f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrSchemaColumnTypeChangedException,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import TemporaryHostResolutionErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (RESTClientNonRetryableError,RESTClientRetryableError,@@ -290,6 +291,33 @@ async def test_source_classified_retryable_error_logged_as_warning_not_exceptionlogger.aexception.assert_not_awaited()+async def test_temporary_host_resolution_error_reraised_as_non_reportable():+ # The host policy's own lookup answered "try again" rather than a verdict on the host, so the+ # source is fine and a fresh attempt recovers. The message carries the host, so no source could+ # list it in get_retryable_errors, and the activity interceptor captures whatever escapes unless+ # it is a NonReportableError — without this branch a resolver outage mints one captured+ # exception per attempt, across every direct SQL source at once.+ error = TemporaryHostResolutionError("db.example.com")+ source = mock.MagicMock(spec=SimpleSource)+ source.get_non_retryable_errors.return_value = {}+ source.get_retryable_errors.return_value = set()++ logger = mock.MagicMock()+ logger.awarning = mock.AsyncMock()+ logger.aexception = mock.AsyncMock()+ logger.adebug = mock.AsyncMock()++ with mock.patch.object(module.SourceRegistry, "get_source", return_value=source):+ with pytest.raises(NonReportableError) as exc_info:+ await module._handle_import_error(mock.MagicMock(), logger, error)++ assert exc_info.value.__cause__ is error+ assert "db.example.com" in str(exc_info.value)+ logger.awarning.assert_awaited_once()+ logger.aexception.assert_not_awaited()++@pytest.mark.asyncioasync def test_rest_client_non_retryable_error_routes_through_handler_without_source_opt_in():# RESTClientNonRetryableError is the REST engine's "retrying can never help" signal (a non-JSONdiff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex b5128cd41754..4c5d376c5758 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -64,6 +64,7 @@ from products.warehouse_sources.backend.presentation.views.external_data_sourceDIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE,INVALID_CREDENTIALS_FALLBACK_MESSAGE,ExternalDataSourceViewSet,+ _classify_refresh_schemas_error,get_declared_field_names,get_direct_connection_metadata,get_nonsensitive_and_sensitive_field_names,@@ -79,6 +80,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basVersionDeprecation,WebhookCreationResult,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,+ HostNotAllowedError,+ TemporaryHostResolutionError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.custom.source import (MAX_CUSTOM_SOURCES_PER_TEAM,@@ -10439,6 +10445,9 @@ class TestCheckCDCPrerequisitesWizard(APIBaseTest):),("ssh_tunnel_error", BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")),("ssl_required_error", SSLRequiredError("SSL/TLS is required but not supported by the server")),+ # The host policy's own lookup answered "try again" while probing the source. Nothing is+ # wrong with the source and a fresh attempt recovers, so it must not be captured either.+ ("temporary_host_resolution_error", TemporaryHostResolutionError("db.example.com")),])@patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")@@ -14050,3 +14059,13 @@ class TestFanoutParentCreation(APIBaseTest):assert response.status_code == 201, response.json()assert ExternalDataSchema.objects.get(team_id=self.team.pk, name="issue_events").should_sync is True+++class TestRefreshSchemasErrorClassification(SimpleTestCase):+ def test_a_rejected_host_returns_the_guidance_without_a_source_registry(self) -> None:+ message, is_expected = _classify_refresh_schemas_error(+ None, HostNotAllowedError("Database host not allowed: resolves to a private address")+ )++ assert message == DATABASE_HOST_NOT_ALLOWED_GUIDANCE+ assert is_expected is True