: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): bypass egress proxy for tunneled ClickHouse connections (#73992)
Daniel RC5db0e49d6b0e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.pyindex 21b69b65dc57..680454dea8af 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py@@ -4,7 +4,7 @@ import reimport sslimport mathimport time-import functools+import threadingimport collectionsfrom collections.abc import Callable, Iteratorfrom contextlib import _GeneratorContextManager@@ -18,6 +18,8 @@ from clickhouse_connect.driver.client import Client as ClickHouseClientfrom clickhouse_connect.driver.exceptions import ClickHouseError, ProgrammingErrorfrom dlt.common.normalizers.naming.snake_case import NamingConventionfrom structlog.types import FilteringBoundLogger+from urllib3 import PoolManager+from urllib3.response import HTTPResponsefrom posthog.exceptions_capture import capture_exception@@ -29,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.parDEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _require_loopbackfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (Column,Table,@@ -44,6 +47,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sqlfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.types import IncrementalFieldType, PartitionSettings+# Why a connection is allowed to skip the egress proxy, or None to stay proxied. A reason+# rather than a bool so `_get_client` — where every call site converges — can check the+# claim against the address it was given instead of trusting the caller's pairing.+BypassEnvProxy = Literal["tunnel_loopback", "internal_team"] | None+# ClickHouse default portsCLICKHOUSE_HTTP_PORT = 8123CLICKHOUSE_HTTPS_PORT = 8443@@ -194,8 +202,39 @@ def _apply_session_settings(client: ClickHouseClient, settings: dict[str, Any]))-def _no_env_proxy_pool_manager(verify: bool) -> Any:+class _NoRedirectPoolManager(PoolManager):+ """A urllib3 manager that refuses to follow redirects.++ Only proxy-bypassing connections use this manager. urllib3 follows a cross-host redirect+ on the same manager, so without this the host we connect to could answer with a redirect+ to an arbitrary address and we would fetch it directly from the worker, which is the+ reachability the egress proxy exists to deny. A ClickHouse HTTP endpoint has no reason to+ redirect us, so refusing costs nothing: the 3xx response goes back to clickhouse-connect,+ which reports it as a connection error.++ Enforced by overriding `urlopen` rather than through the pool's `retries` option because+ clickhouse-connect passes its own `retries` on every request, which would take precedence+ over a pool-level default.+ """++ # The urllib3 1.26 stub types `urlopen` with the generic `RequestMethods` parameters and+ # omits `redirect`, even though it is the real third parameter of `PoolManager.urlopen`.+ # Declaring the stub's parameters instead would forward `encode_multipart` down to+ # `HTTPConnectionPool.urlopen`, which rejects it, so match the runtime signature.+ def urlopen(self, method: str, url: str, redirect: bool = True, **kw: Any) -> HTTPResponse: # type: ignore[override]+ return super().urlopen(method, url, redirect=False, **kw)+++# Bounds the manager cache below. `server_hostname` is user-controlled (the source's+# configured host), so an unbounded cache would let repeated credential validations with+# distinct hostnames retain a manager each for the life of the worker. Far above the number+# of distinct tunneled HTTPS hostnames a worker legitimately serves concurrently.+_POOL_MANAGER_CACHE_MAX = 32+_pool_managers: collections.OrderedDict[tuple[bool, str | None], Any] = collections.OrderedDict()+_pool_managers_lock = threading.Lock()+++def _no_env_proxy_pool_manager(verify: bool, server_hostname: str | None = None) -> Any:"""A shared urllib3 pool manager that never consults HTTP(S)_PROXY env vars.clickhouse-connect only checks the proxy env vars when it builds its own@@ -203,8 +242,43 @@ def _no_env_proxy_pool_manager(verify: bool) -> Any:from the egress proxy (see posthog/security/outbound_proxy.py for therequests/httpx equivalents). Cached because clients don't own an injectedmanager (`close()` leaves it alive), so per-call managers would leak.++ `server_hostname` keeps TLS verification honest through an SSH tunnel: we dial the+ tunnel's loopback bind, but SNI and hostname validation must run against the database's+ own hostname or the certificate can never match. Mirrors what clickhouse-connect does+ with `server_host_name` when it builds its own manager — a branch it skips entirely+ when handed a `pool_mgr`.++ LRU-bounded: eviction closes the manager's pools and removes it from the library's+ process-global registry, the two places that would otherwise retain it forever. An+ evicted manager still held by a live client keeps working — urllib3 rebuilds pools on+ demand — it just stops being shared or expiry-swept.++ Built from clickhouse-connect's own options factory so the TCP keepalive tuning and+ certificate handling match a direct connection, then recorded where the library tracks+ its own managers so connection expiry and interpreter-exit cleanup cover this one too."""- return httputil.get_pool_manager(verify=verify)+ key = (verify, server_hostname)+ with _pool_managers_lock:+ manager = _pool_managers.get(key)+ if manager is not None:+ _pool_managers.move_to_end(key)+ return manager++ options = httputil.get_pool_manager_options(verify=verify)+ if server_hostname:+ if verify:+ options["assert_hostname"] = server_hostname+ options["server_hostname"] = server_hostname+ manager = _NoRedirectPoolManager(**options)+ httputil.all_managers[manager] = int(time.time())+ _pool_managers[key] = manager++ while len(_pool_managers) > _POOL_MANAGER_CACHE_MAX:+ _, evicted = _pool_managers.popitem(last=False)+ httputil.all_managers.pop(evicted, None)+ evicted.clear()+ return managerdef _get_client(@@ -218,7 +292,8 @@ def _get_client(verify: bool,query_timeout: int = DATA_QUERY_TIMEOUT_SECONDS,settings: Optional[dict[str, Any]] = None,- bypass_env_proxy: bool = False,+ bypass_env_proxy: BypassEnvProxy = None,+ server_hostname: str | None = None,) -> ClickHouseClient:"""Create a ClickHouse HTTP client.@@ -227,11 +302,27 @@ def _get_client(reader that we use to read very large tables without buffering them inmemory.- `bypass_env_proxy` connects directly instead of honouring the- HTTP(S)_PROXY env vars. Only ever set for PostHog-internal teams- (`is_team_allowlisted_for_internal_hosts`) — for customer-supplied config- the egress proxy is the SSRF backstop and must stay in the path.+ `bypass_env_proxy` names why the connection may skip the HTTP(S)_PROXY env+ vars: "internal_team" for PostHog-internal teams+ (`is_team_allowlisted_for_internal_hosts`), "tunnel_loopback" for an+ address that came out of our own SSH tunnel — the proxy blocks the tunnel's+ loopback bind, and no request would reach the forwarded port. For a+ customer-supplied host the egress proxy is the SSRF backstop and must stay+ in the path, so the tunnel claim is checked against the address here: the+ flag and the host travel to this point independently, and a caller pairing+ "tunnel_loopback" with a non-loopback host has lost that pairing.++ `server_hostname` (tunnel only) is the database's own hostname, so TLS SNI+ and certificate hostname validation run against it rather than against the+ loopback address we dial — disabling verification is not the supported way+ to make HTTPS work through a tunnel."""+ if bypass_env_proxy == "tunnel_loopback":+ _require_loopback(host)+ pool_mgr = None+ if bypass_env_proxy:+ tunnel_tls_hostname = server_hostname if bypass_env_proxy == "tunnel_loopback" and secure else None+ pool_mgr = _no_env_proxy_pool_manager(verify, tunnel_tls_hostname)attempt = 0while True:try:@@ -248,7 +339,7 @@ def _get_client(send_receive_timeout=query_timeout,query_limit=0, # we manage limits ourselvescompress=True,- pool_mgr=_no_env_proxy_pool_manager(verify) if bypass_env_proxy else None,+ pool_mgr=pool_mgr,)except (ClickHouseError, OSError, ssl.SSLError) as e:# OSError covers socket.gaierror, ConnectionRefusedError, TimeoutError,@@ -353,7 +444,8 @@ def get_schemas(secure: bool,verify: bool,names: list[str] | None = None,- bypass_env_proxy: bool = False,+ bypass_env_proxy: BypassEnvProxy = None,+ server_hostname: str | None = None,) -> dict[str, list[tuple[str, str, bool]]]:"""Discover columns for all tables in the given database.@@ -372,6 +464,7 @@ def get_schemas(verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,bypass_env_proxy=bypass_env_proxy,+ server_hostname=server_hostname,)try:@@ -469,7 +562,8 @@ def get_clickhouse_row_count(secure: bool,verify: bool,names: list[str] | None = None,- bypass_env_proxy: bool = False,+ bypass_env_proxy: BypassEnvProxy = None,+ server_hostname: str | None = None,) -> dict[str, int]:"""Return total_rows per table from `system.tables`.@@ -492,6 +586,7 @@ def get_clickhouse_row_count(verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,bypass_env_proxy=bypass_env_proxy,+ server_hostname=server_hostname,)try:@@ -595,7 +690,8 @@ def get_connection_metadata(password: str | None,secure: bool,verify: bool,- bypass_env_proxy: bool = False,+ bypass_env_proxy: BypassEnvProxy = None,+ server_hostname: str | None = None,) -> dict[str, Any]:"""Probe the server for version metadata.@@ -613,6 +709,7 @@ def get_connection_metadata(verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,bypass_env_proxy=bypass_env_proxy,+ server_hostname=server_hostname,)try:@@ -847,7 +944,8 @@ def get_primary_keys_for_schemas(secure: bool,verify: bool,table_names: list[str],- bypass_env_proxy: bool = False,+ bypass_env_proxy: BypassEnvProxy = None,+ server_hostname: str | None = None,) -> dict[str, list[str] | None]:"""Detect primary keys (sorting key columns) for multiple tables.@@ -870,6 +968,7 @@ def get_primary_keys_for_schemas(verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,bypass_env_proxy=bypass_env_proxy,+ server_hostname=server_hostname,)try:for table_name in table_names:@@ -1272,7 +1371,8 @@ def clickhouse_source(incremental_field_type: Optional[IncrementalFieldType] = None,row_filters: Optional[list[ValidatedRowFilter]] = None,enabled_columns: Optional[list[str]] = None,- bypass_env_proxy: bool = False,+ bypass_env_proxy: BypassEnvProxy = None,+ server_hostname: str | None = None,) -> SourceResponse:"""Build a SourceResponse that pulls a single ClickHouse table.@@ -1296,6 +1396,7 @@ def clickhouse_source(verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,bypass_env_proxy=bypass_env_proxy,+ server_hostname=server_hostname,)try:@@ -1335,6 +1436,7 @@ def clickhouse_source(verify=verify,names=[table_name],bypass_env_proxy=bypass_env_proxy,+ server_hostname=server_hostname,)rows_to_sync: int | None = row_counts.get(table_name)@@ -1381,6 +1483,7 @@ def clickhouse_source(query_timeout=DATA_QUERY_TIMEOUT_SECONDS,settings=_query_settings(chunk_size),bypass_env_proxy=bypass_env_proxy,+ server_hostname=server_hostname,)try:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.pyindex 0dd63c681127..238cf3b8a374 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py@@ -22,6 +22,7 @@ from posthog.exceptions_capture import capture_exceptionfrom products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse.clickhouse import (NOT_A_CLICKHOUSE_HTTP_RESPONSE,+ BypassEnvProxy,ClickHouseConnectionError,_get_client,clickhouse_source,@@ -69,6 +70,13 @@ _TEMPORARILY_UNAVAILABLE = ("ClickHouse is temporarily busy or unavailable and didn't accept the connection. Wait a moment and try again.")+# Connections that skip the egress proxy don't follow redirects, so a redirecting endpoint+# comes back as a 3xx response code instead of a request to wherever it pointed.+_REDIRECTED = (+ "We reached your ClickHouse host but it redirected us, and redirects aren't followed. Point the source at the "+ "ClickHouse HTTP interface directly rather than at a proxy or load balancer in front of it."+)+# Error message → user-friendly translation. Matched as a substring of the# exception string. Patterns are lowercase-matched.ClickHouseErrors: dict[str, str] = {@@ -82,6 +90,12 @@ ClickHouseErrors: dict[str, str] = {"name or service not known": "Could not resolve the ClickHouse host","connection refused": "Could not connect to ClickHouse on the given host/port","connection timed out": "Connection to ClickHouse timed out. Does your database have our IP addresses allow-listed?",+ # Must stay above the generic "ssl" entry, which would otherwise match first and send the+ # user to the wrong toggle. Verification runs against the configured ClickHouse host even+ # over an SSH tunnel (server_hostname), so a mismatch is real: the certificate doesn't+ # cover the host the user configured. Deliberately does not suggest turning verification+ # off — that would train users into a MITM-able setup.+ "hostname mismatch": "The server's TLS certificate doesn't cover the ClickHouse host configured for this source. Use a host name the certificate covers.","ssl": "TLS/SSL handshake failed. If your server does not use TLS, disable the HTTPS toggle.",# The host answered but isn't serving the ClickHouse HTTP interface on this# host/port (wrong port, a proxy, or a native-protocol port). Same wording@@ -90,6 +104,10 @@ ClickHouseErrors: dict[str, str] = {# `_get_client` raises this when the host answers 2xx with a body that isn't a# ClickHouse response (a proxy/LB page, or a different service on the host/port)."did not return a valid clickhouse response": NOT_A_CLICKHOUSE_HTTP_RESPONSE,+ "returned response code 301": _REDIRECTED,+ "returned response code 302": _REDIRECTED,+ "returned response code 307": _REDIRECTED,+ "returned response code 308": _REDIRECTED,"returned response code 429": _TEMPORARILY_UNAVAILABLE,"returned response code 502": _TEMPORARILY_UNAVAILABLE,"returned response code 503": _TEMPORARILY_UNAVAILABLE,@@ -110,6 +128,26 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valdef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLICKHOUSE+ def _bypass_env_proxy(self, config: ClickHouseSourceConfig, team_id: int) -> BypassEnvProxy:+ """Why this connection may skip the egress proxy, or None to stay proxied.++ Two cases, both of which the proxy would refuse. Internal teams may point a source at a+ PostHog-internal host. And a tunneled connection is made to the tunnel's own loopback+ bind address, which the proxy blocks by design — clickhouse-connect honours HTTP_PROXY+ for every host including loopback, so the request would never reach the forwarded port+ and the tunnel would open no channel to the customer's ClickHouse. The tunnel claim is+ checked twice downstream: the tunnel helpers refuse to yield a non-loopback bind, and+ `_get_client` refuses a non-loopback host claiming "tunnel_loopback".++ ClickHouse is the only tunnel-capable source this bites: the other database drivers use+ raw TCP sockets and ignore the proxy env vars entirely.+ """+ if self.ssh_tunnel_enabled(config):+ return "tunnel_loopback"+ if is_team_allowlisted_for_internal_hosts(team_id):+ return "internal_team"+ return None+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(@@ -330,7 +368,8 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valverify=config.verify,query_timeout=query_timeout,settings=settings,- bypass_env_proxy=is_team_allowlisted_for_internal_hosts(team_id),+ bypass_env_proxy=self._bypass_env_proxy(config, team_id),+ server_hostname=config.host,)try:yield client@@ -348,9 +387,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val) -> list[SourceSchema]:schemas: list[SourceSchema] = []- # Internal teams may point at PostHog-internal ClickHouse hosts, which the- # egress proxy would refuse — connect those directly.- bypass_env_proxy = is_team_allowlisted_for_internal_hosts(team_id)+ bypass_env_proxy = self._bypass_env_proxy(config, team_id)with self.with_ssh_tunnel(config, team_id) as (host, port):db_schemas = get_clickhouse_schemas(@@ -363,6 +400,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valverify=config.verify,names=names,bypass_env_proxy=bypass_env_proxy,+ server_hostname=config.host,)row_counts: dict[str, int] = {}@@ -377,6 +415,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valverify=config.verify,names=names,bypass_env_proxy=bypass_env_proxy,+ server_hostname=config.host,)detected_pks = get_clickhouse_primary_keys_for_schemas(@@ -389,6 +428,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valverify=config.verify,table_names=list(db_schemas.keys()),bypass_env_proxy=bypass_env_proxy,+ server_hostname=config.host,)for table_name, columns in db_schemas.items():@@ -483,7 +523,8 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valpassword=config.password,secure=config.secure,verify=config.verify,- bypass_env_proxy=is_team_allowlisted_for_internal_hosts(team_id),+ bypass_env_proxy=self._bypass_env_proxy(config, team_id),+ server_hostname=config.host,)def source_for_pipeline(self, config: ClickHouseSourceConfig, inputs: SourceInputs) -> SourceResponse:@@ -509,7 +550,8 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valchunk_size_override=schema.chunk_size_override,row_filters=inputs.row_filters,enabled_columns=inputs.enabled_columns,- bypass_env_proxy=is_team_allowlisted_for_internal_hosts(inputs.team_id),+ bypass_env_proxy=self._bypass_env_proxy(config, inputs.team_id),+ server_hostname=config.host,)def reconcile_schema_metadata(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.pyindex add304fb3fca..cf64a8efec0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py@@ -1,4 +1,8 @@-from collections.abc import AsyncIterable+import os+import socket+import threading+from collections.abc import AsyncIterable, Iterator+from contextlib import contextmanagerimport pytestfrom posthog.test.base import BaseTest@@ -6,6 +10,7 @@ from unittest.mock import MagicMock, call, patchimport pyarrow as pafrom clickhouse_connect.driver.exceptions import ClickHouseError, OperationalError, ProgrammingError+from parameterized import parameterizedfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -31,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouseget_primary_keys_for_schemas,)from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse.source import (+ _REDIRECTED,_TEMPORARILY_UNAVAILABLE,GENERIC_CONNECTION_ERROR,ClickHouseSource,@@ -953,6 +959,26 @@ class TestTranslateError:msg = f"HTTPDriver for https://host:8443 returned response code {code}"assert ClickHouseSource._translate_error(msg) == _TEMPORARILY_UNAVAILABLE+ @pytest.mark.parametrize("code", ["301", "302", "307", "308"])+ def test_redirect_responses_name_the_redirect(self, code):+ # Proxy-bypassing connections don't follow redirects, so the 3xx reaches the user.+ msg = f"HTTPDriver for https://host:8443 returned response code {code}"+ assert ClickHouseSource._translate_error(msg) == _REDIRECTED++ def test_certificate_hostname_mismatch_names_the_certificate_not_the_toggles(self):+ # Verification runs against the configured host even over a tunnel, so a mismatch is+ # a real certificate problem. Matching the generic "ssl" entry first would tell the+ # user to disable HTTPS, and the message must not suggest turning verification off.+ msg = (+ "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, "+ "certificate is not valid for '127.0.0.1'"+ )+ translated = ClickHouseSource._translate_error(msg)+ assert translated is not None+ assert "certificate" in translated+ assert "HTTPS" not in translated+ assert "Verify SSL" not in translated+class TestGetSchemas:"""Tests `get_schemas` with a fully mocked ClickHouse client."""@@ -1424,8 +1450,8 @@ class TestBypassEnvProxy:@pytest.mark.parametrize("bypass,expected_pool_mgr_factory",[- (True, lambda: ch_module._no_env_proxy_pool_manager(True)),- (False, lambda: None),+ ("internal_team", lambda: ch_module._no_env_proxy_pool_manager(True, None)),+ (None, lambda: None),],)def test_get_client_forwards_pool_manager_only_when_bypassing(self, bypass, expected_pool_mgr_factory):@@ -1443,6 +1469,21 @@ class TestBypassEnvProxy:assert mock_get_client.call_count == 1assert mock_get_client.call_args.kwargs["pool_mgr"] is expected_pool_mgr_factory()+ def test_eviction_releases_the_manager_everywhere_it_is_retained(self):+ # The cache key contains the user-controlled hostname, so it must be bounded — and a+ # bounded cache only helps if eviction also drops the manager from clickhouse-connect's+ # process-global registry, the other place that would retain it for the worker's life.+ from clickhouse_connect.driver.httputil import all_managers++ with patch.object(ch_module, "_POOL_MANAGER_CACHE_MAX", 2):+ first = ch_module._no_env_proxy_pool_manager(True, "evict-me.example")+ assert first in all_managers+ for n in range(2):+ ch_module._no_env_proxy_pool_manager(True, f"filler-{n}.example")++ assert first not in all_managers+ assert ch_module._no_env_proxy_pool_manager(True, "evict-me.example") is not first+class TestInternalHostTeamAllowlist:@pytest.mark.parametrize(@@ -1465,31 +1506,166 @@ class TestInternalHostTeamAllowlist:assert mixins.is_team_allowlisted_for_internal_hosts(team_id) is expected+_FORBIDDEN_RESPONSE = b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"+++@contextmanager+def _recording_server(response: bytes = _FORBIDDEN_RESPONSE) -> Iterator[tuple[int, list[str]]]:+ server = socket.create_server(("127.0.0.1", 0))+ server.settimeout(0.1)+ requests: list[str] = []+ stop = threading.Event()++ def serve() -> None:+ while not stop.is_set():+ try:+ conn, _ = server.accept()+ except (TimeoutError, OSError):+ continue+ with conn:+ requests.append(conn.recv(8192).decode("latin-1").split("\r\n")[0])+ conn.sendall(response)++ thread = threading.Thread(target=serve, daemon=True)+ thread.start()+ try:+ yield server.getsockname()[1], requests+ finally:+ stop.set()+ thread.join(timeout=5)+ server.close()+++def _connect_to(*, port: int, bypass_env_proxy: "ch_module.BypassEnvProxy") -> None:+ _get_client(+ host="127.0.0.1",+ port=port,+ database="default",+ user="default",+ password=None,+ secure=False,+ verify=True,+ bypass_env_proxy=bypass_env_proxy,+ )+++class TestGetClientEgressProxyRouting:+ """Where the connection actually goes, which is what decides whether a tunnel works.++ PostHog's runtime points HTTP_PROXY at the Smokescreen egress proxy, and Smokescreen blocks+ loopback. Routing a tunneled connection through it means the request never reaches the SSH+ tunnel's local forwarded port, so the tunnel opens no channel to the customer's ClickHouse+ and the source fails with a generic connection error. The stub servers answer with a+ deterministic 403 rather than dropping the connection so that `_get_client` raises on the+ first attempt instead of entering its transient-retry backoff.+ """++ @parameterized.expand([("tunneled", "tunnel_loopback"), ("internal", "internal_team"), ("proxied", None)])+ def test_only_a_proxied_connection_goes_through_the_egress_proxy(self, _name: str, reason) -> None:+ with _recording_server() as (proxy_port, proxy_requests):+ with _recording_server() as (bound_port, bound_requests):+ proxy_url = f"http://127.0.0.1:{proxy_port}"+ env = {"HTTP_PROXY": proxy_url, "http_proxy": proxy_url}+ with patch.dict(os.environ, env):+ os.environ.pop("NO_PROXY", None)+ os.environ.pop("no_proxy", None)++ with pytest.raises(ClickHouseConnectionError):+ _connect_to(port=bound_port, bypass_env_proxy=reason)++ bypassed = reason is not None+ assert bool(bound_requests) == bypassed+ assert bool(proxy_requests) == (not bypassed)++ def test_redirect_away_from_the_target_is_not_followed(self) -> None:+ # A bypassing connection skips the egress proxy, so following a redirect would let the+ # host we reached send us to an address the proxy would have denied.+ with _recording_server() as (elsewhere_port, elsewhere_requests):+ redirect = (+ f"HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{elsewhere_port}/\r\n"+ "Content-Length: 0\r\nConnection: close\r\n\r\n"+ ).encode()+ with _recording_server(response=redirect) as (bound_port, bound_requests):+ with pytest.raises(ClickHouseConnectionError):+ _connect_to(port=bound_port, bypass_env_proxy="tunnel_loopback")++ assert bound_requests+ assert elsewhere_requests == []++ def test_tunneled_https_verifies_against_the_database_hostname(self) -> None:+ # We dial the tunnel's loopback bind, so SNI and hostname validation must run against+ # the database's own hostname or a valid certificate can never match — and the+ # workaround users would reach for is disabling verification, which invites MITM+ # between the SSH server and ClickHouse.+ with patch.object(ch_module, "get_client") as mock_get_client:+ _get_client(+ host="127.0.0.1",+ port=8443,+ database="default",+ user="default",+ password=None,+ secure=True,+ verify=True,+ bypass_env_proxy="tunnel_loopback",+ server_hostname="clickhouse.internal",+ )+ manager = mock_get_client.call_args.kwargs["pool_mgr"]+ pool = manager.connection_from_host("127.0.0.1", 8443, scheme="https")+ assert pool.assert_hostname == "clickhouse.internal"+ assert pool.conn_kw["server_hostname"] == "clickhouse.internal"+ # Plain-HTTP tunnels must not share the hostname-pinned manager.+ assert manager is not ch_module._no_env_proxy_pool_manager(True, None)++ def test_tunnel_claim_with_non_loopback_host_is_refused(self) -> None:+ # The flag and the host reach `_get_client` independently; a caller pairing the+ # tunnel claim with a host that didn't come from a tunnel must fail loudly, before+ # any connection is attempted with the proxy-bypassing manager.+ with patch.object(ch_module, "get_client") as mock_get_client:+ with pytest.raises(Exception, match="non-loopback"):+ _get_client(+ host="ch.example.com",+ port=8443,+ database="default",+ user="default",+ password=None,+ secure=True,+ verify=True,+ bypass_env_proxy="tunnel_loopback",+ )+ mock_get_client.assert_not_called()++class TestDirectQueryClientBypassEnvProxy:"""`direct_query_client` backs the HogQL direct-SQL adapter, and unlike every other`_get_client` call site on `ClickHouseSource` it once omitted `bypass_env_proxy` entirely —an allowlisted internal team's direct query silently routed through the egress proxy andfailed to reach the PostHog-internal host it was pointed at.++ A tunneled connection must bypass for a different reason: the address is our own loopback+ bind, which the proxy blocks, so a customer team with a tunnel never reached its ClickHouse."""@pytest.mark.parametrize(- "region,team_id,expected_bypass",+ "region,team_id,tunneled,expected_bypass",[- ("US", 2, True),- ("US", 12345, False),+ ("US", 2, False, "internal_team"),+ ("US", 12345, False, None),+ ("US", 12345, True, "tunnel_loopback"),],)- def test_forwards_bypass_env_proxy_from_team_allowlist(self, region, team_id, expected_bypass):+ def test_forwards_bypass_env_proxy_from_team_allowlist(self, region, team_id, tunneled, expected_bypass):from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse import source as source_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.common import mixinssource = ClickHouseSource()config = MagicMock()+ config.host = "db.example.com"config.database = "default"config.user = "default"config.password = Noneconfig.secure = Trueconfig.verify = True+ config.ssh_tunnel = MagicMock(enabled=True) if tunneled else Nonewith patch.object(mixins, "get_instance_region", return_value=region):with patch.object(source, "with_ssh_tunnel") as mock_with_ssh_tunnel:@@ -1498,4 +1674,7 @@ class TestDirectQueryClientBypassEnvProxy:with source.direct_query_client(config, team_id, query_timeout=60):pass- assert mock_get_client.call_args.kwargs["bypass_env_proxy"] is expected_bypass+ assert mock_get_client.call_args.kwargs["bypass_env_proxy"] == expected_bypass+ # The configured host always rides along; `_get_client` only applies it to TLS when+ # the bypass reason is the tunnel.+ assert mock_get_client.call_args.kwargs["server_hostname"] == "db.example.com"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 d7e04768a3ff..a544852e6a5f 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,5 +1,6 @@import timeimport socket+import ipaddressfrom collections.abc import Callable, Generatorfrom contextlib import _GeneratorContextManager, contextmanagerfrom typing import Any@@ -183,6 +184,25 @@ def _logged_connection(config, team_id: int | None) -> Generator[None]:raise+def _require_loopback(host: str) -> str:+ """Refuse to treat a non-loopback address as a tunnel bind.++ ClickHouse skips the egress proxy for tunneled connections on the strength of the tunnel+ branch only ever yielding its own loopback bind address (`SSHTunnel.get_tunnel` pins+ `local_bind_address` to 127.0.0.1). That invariant lives in a different file from the+ bypass, so enforce it where the address is produced: if a future change makes this branch+ yield anything else — a fallback to the configured host, a non-loopback bind — the proxy+ bypass would silently extend to it, and this raises instead.+ """+ try:+ is_loopback = ipaddress.ip_address(host).is_loopback+ except ValueError:+ is_loopback = False+ if not is_loopback:+ raise Exception(f"SSH tunnel bound to non-loopback address {host!r}; refusing to use it")+ return host++@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."""@@ -195,7 +215,7 @@ def open_ssh_tunnel(config, team_id: int | None = None) -> Generator[tuple[str,if tunnel is None:raise Exception("Can't open tunnel to SSH server")- yield tunnel.local_bind_host, tunnel.local_bind_port+ yield _require_loopback(tunnel.local_bind_host), tunnel.local_bind_portelse:yield config.host, config.port@@ -218,7 +238,7 @@ def make_ssh_tunnel_factory(with ssh_tunnel.get_tunnel(config.host, config.port) as tunnel:if tunnel is None:raise Exception("Can't open tunnel to SSH server")- yield tunnel.local_bind_host, tunnel.local_bind_port+ yield _require_loopback(tunnel.local_bind_host), tunnel.local_bind_portreturn with_ssh_func@@ -241,6 +261,16 @@ class SSHTunnelMixin:) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:return make_ssh_tunnel_factory(config, team_id)+ def ssh_tunnel_enabled(self, config) -> bool:+ """Whether the tunnel helpers above will tunnel rather than connect directly.++ For callers that need to know which branch was taken, because the `(host, port)` they+ receive means something different in each case: a tunnel yields our own local bind+ address, while a direct connection yields the user's configured host. Shares+ `_enabled_ssh_tunnel` with the branch itself so the two cannot drift apart.+ """+ return _enabled_ssh_tunnel(config) is not None+def ssh_tunnel_is_valid(self, config, team_id: int) -> tuple[bool, str | None]:if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:if config.ssh_tunnel.host:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.pyindex 33912fbd1f43..0d0fef8ba334 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@@ -317,6 +317,22 @@ class TestConnectionOpenLogging(SimpleTestCase):assert all(call.kwargs["team_id"] == 42 for call in mock_logger.info.call_args_list)+class TestTunnelYieldsLoopbackOnly(SimpleTestCase):+ # ClickHouse bypasses the egress proxy for tunneled connections on the strength of the+ # tunnel branch only ever yielding its own loopback bind. A tunnel bound anywhere else+ # must be refused, not silently handed to a proxy-bypassing client.+ @parameterized.expand([("open_ssh_tunnel", None), ("factory", None)])+ def test_non_loopback_bind_is_refused(self, entrypoint: str, _unused: None):+ config = FakeConfig(ssh_tunnel=FakeSSHTunnelConfig(enabled=True, host="0.tcp.ngrok.example"))+ with patch(f"{_MIXINS_MODULE}.SSHTunnel") as mock_ssh, patch(f"{_MIXINS_MODULE}.logger"):+ tunnel = mock_ssh.from_config.return_value.get_tunnel.return_value.__enter__.return_value+ tunnel.local_bind_host, tunnel.local_bind_port = "10.0.0.5", 55555+ cm = open_ssh_tunnel(config) if entrypoint == "open_ssh_tunnel" else make_ssh_tunnel_factory(config)()+ with pytest.raises(Exception, match="non-loopback"):+ with cm:+ pass++class TestOAuthMixinIntegrationFetchResilience(SimpleTestCase):@parameterized.expand([