: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): re-check the database host at connect time (#93742)
Tom Piccirello1dccc3f56e8a
diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex 1ff2faf589ea..40aa7f6fce6d 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -691,9 +691,14 @@ def _is_safe_public_ip(host: str) -> bool:if ip.sixtofour:return _is_safe_public_ip(str(ip.sixtofour))- return not (- ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified- )+ # Require global routability rather than enumerating the families to reject. The enumeration+ # missed shared address space (100.64.0.0/10), which is neither private nor global to+ # `ipaddress` but is routinely internal, and which `posthog/security/url_validation.py` and+ # `rust/common/dns` both already reject. Two families count as global by this measure and+ # keep their own clause: multicast, and the reserved IPv6 blocks. Reserved matters because+ # `::/8` holds the NAT64 well-known prefix (64:ff9b::/96) and the deprecated IPv4-compatible+ # form, both of which carry an embedded IPv4 address that the unwrapping above does not see.+ return ip.is_global and not ip.is_multicast and not ip.is_reserved# The AWS half matches the global, regional, dashed-regional, dualstack and accelerate endpoints,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 bd91881e32fe..827527ac4dfc 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@@ -118,6 +118,15 @@ MAX_INCREMENTAL_SOURCE_RETRIES = 3 if settings.DEBUG else 9Any_Source_Errors: dict[str, str | None] = {"Could not establish session to SSH gateway": None,+ # Raised by `_check_direct_host` when a direct (untunneled) database connection's host doesn't+ # 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."+ ),# 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# SSH-capable source (Postgres, Redshift, MySQL, MSSQL, ClickHouse). The auth config is fixed,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.pyindex 0fe973b986fd..1ab80368d93b 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@@ -69,9 +69,9 @@ def resolve_safe_host(host: str, team_id: int | None) -> HostResolution:Only enforced on cloud deployments — self-hosted instances are allowedto connect to any host.- Resolves hostnames via DNS and checks all resolved IPs against- _is_safe_public_ip to block private, loopback, link-local, multicast,- reserved, and IPv6-mapped internal addresses.+ Resolves hostnames via DNS and requires every resolved IP to be globally routable per+ _is_safe_public_ip, which blocks private, loopback, link-local, multicast, reserved,+ shared address space (CGNAT), and their IPv6-mapped forms.team whitelist: team_id 2 in US, team_id 1 in EU are allowedto use internal IPs.@@ -263,6 +263,39 @@ def _pinned_ssh_host(ssh_config, team_id: int | None) -> str:return resolution.connect_host+def _check_direct_host(config, team_id: int | None) -> None:+ """Refuse a direct database connection to a host that resolves somewhere internal.++ The connect-time counterpart to `is_database_host_valid`, which runs at the API layer on+ create, update, and direct query. The sync path goes from the stored config straight to the+ connection, so without this a host that resolved to a public address at setup is never+ re-checked on any later scheduled run. A direct database connection is a raw socket, so the+ HTTP 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.++ A `team_id` of None fails closed. It changes nothing for a customer team, whose result is the+ same either way; it only costs the internal-host exemption on entry points that don't carry a+ team 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.+ """+ resolution = resolve_safe_host(config.host, team_id)+ if resolution.connect_host is None:+ raise Exception(f"Database host not allowed: {resolution.error}")++@contextmanagerdef open_ssh_tunnel(config, team_id: int | None = None) -> Generator[tuple[str, int]]:"""Yield `(host, port)` for a database connection, going through an SSH tunnel if configured."""@@ -279,6 +312,7 @@ def open_ssh_tunnel(config, team_id: int | None = None) -> Generator[tuple[str,yield _require_loopback(tunnel.local_bind_host), tunnel.local_bind_portelse:+ _check_direct_host(config, team_id)yield config.host, config.port@@ -311,6 +345,9 @@ def make_ssh_tunnel_factory(@contextmanagerdef without_ssh_func():with _logged_connection(config, team_id):+ # Checked per reopen, not once when the factory is built, so a long-running+ # sync that reconnects re-checks the host each time.+ _check_direct_host(config, team_id)yield config.host, config.portreturn without_ssh_funcdiff --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 5669d3dd3cf0..a36b0ba796c8 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@@ -12,6 +12,8 @@ from parameterized import parameterizedfrom posthog.models.integration import Integration+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (OAuthMixin,SSHTunnelMixin,@@ -36,9 +38,15 @@ class TestIsHostSafe(SimpleTestCase):("localhost", "localhost"),("link_local_imds", "169.254.169.254"),("link_local", "169.254.1.1"),+ ("cgnat_shared_address_space", "100.64.1.1"),+ ("cgnat_upper", "100.127.255.254"),+ ("ipv6_mapped_cgnat", "::ffff:100.64.1.1"),("ipv6_mapped_loopback", "::ffff:127.0.0.1"),("ipv6_mapped_imds", "::ffff:169.254.169.254"),("ipv6_mapped_private", "::ffff:10.0.0.1"),+ ("nat64_imds", "64:ff9b::169.254.169.254"),+ ("ipv4_compatible_imds", "::169.254.169.254"),+ ("ipv6_reserved", "4000::1"),("ipv6_loopback", "::1"),("multicast", "224.0.0.1"),("reserved", "0.0.0.0"),@@ -485,3 +493,60 @@ class TestOAuthMixinIntegrationFetchResilience(SimpleTestCase):OAuthMixin().get_oauth_integration(integration_id=1, team_id=2)assert get.call_count == 2+++class TestDirectHostIsCheckedAtConnect(SimpleTestCase):+ # A direct database connection is a raw socket that the HTTP egress proxy never sees, and the+ # sync path reaches these entry points from stored config without re-running+ # `is_database_host_valid`, so what they do here is the only control on where it connects.+ @staticmethod+ def _resolves_to(ip: str) -> list:+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (ip, 0))]++ @staticmethod+ def _connection_cm(entrypoint: str, config, team_id: int):+ if entrypoint == "open_ssh_tunnel":+ return open_ssh_tunnel(config, team_id)+ return make_ssh_tunnel_factory(config, team_id)()++ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_yields_the_hostname_so_sni_and_multi_address_failover_survive(self, entrypoint: str):+ config = FakeConfig(host="db.example.com", ssh_tunnel=None)+ with (+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=self._resolves_to("93.184.216.34")),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ with self._connection_cm(entrypoint, config, 999) as (host, port):+ assert (host, port) == ("db.example.com", 5432)++ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_host_resolving_to_an_internal_ip_is_refused(self, entrypoint: str):+ config = FakeConfig(host="db.example.com", ssh_tunnel=None)+ with (+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=self._resolves_to("169.254.169.254")),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ with pytest.raises(Exception, match="Database host not allowed"):+ with self._connection_cm(entrypoint, config, 999):+ pass+++class TestDirectHostRejectionIsNonRetryable(SimpleTestCase):+ # The rejection is a config problem only the customer can fix, so it has to stop the schedule+ # the way its SSH counterpart does. Raising it through the real path couples the wording to the+ # registered pattern: reword one without the other and this fails.+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_rejection_message_matches_a_registered_non_retryable_error(self):+ config = FakeConfig(host="db.example.com", ssh_tunnel=None)+ addrinfo = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("169.254.169.254", 0))]+ with (+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=addrinfo),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ with pytest.raises(Exception) as exc:+ with open_ssh_tunnel(config, 999):+ pass++ assert error_message_matches(str(exc.value), Any_Source_Errors.keys())