: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
feat(data-warehouse): bypass env proxy for internal-team ClickHouse direct connections (#74205)
Tom Owersfcefa587bef4
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 074aba21a13a..a2695ff06215 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,6 +4,7 @@ import reimport sslimport mathimport time+import functoolsimport collectionsfrom collections.abc import Callable, Iteratorfrom contextlib import _GeneratorContextManager@@ -12,6 +13,7 @@ from typing import Any, Literal, Optionalimport pyarrow as paimport structlogfrom clickhouse_connect import get_client+from clickhouse_connect.driver import httputilfrom clickhouse_connect.driver.client import Client as ClickHouseClientfrom clickhouse_connect.driver.exceptions import ClickHouseError, ProgrammingErrorfrom dlt.common.normalizers.naming.snake_case import NamingConvention@@ -174,6 +176,19 @@ def _apply_session_settings(client: ClickHouseClient, settings: dict[str, Any]))+def _no_env_proxy_pool_manager(verify: bool) -> 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+ pool manager, so handing it one is the sanctioned per-code-path opt-out+ from the egress proxy (see posthog/security/outbound_proxy.py for the+ requests/httpx equivalents). Cached because clients don't own an injected+ manager (`close()` leaves it alive), so per-call managers would leak.+ """+ return httputil.get_pool_manager(verify=verify)++def _get_client(*,host: str,@@ -185,6 +200,7 @@ def _get_client(verify: bool,query_timeout: int = DATA_QUERY_TIMEOUT_SECONDS,settings: Optional[dict[str, Any]] = None,+ bypass_env_proxy: bool = False,) -> ClickHouseClient:"""Create a ClickHouse HTTP client.@@ -192,6 +208,11 @@ def _get_client(firewall-friendly, easy to tunnel via SSH, and exposes a streaming Arrowreader 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."""attempt = 0while True:@@ -209,6 +230,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,)except (ClickHouseError, OSError, ssl.SSLError) as e:# OSError covers socket.gaierror, ConnectionRefusedError, TimeoutError,@@ -308,6 +330,7 @@ def get_schemas(secure: bool,verify: bool,names: list[str] | None = None,+ bypass_env_proxy: bool = False,) -> dict[str, list[tuple[str, str, bool]]]:"""Discover columns for all tables in the given database.@@ -325,6 +348,7 @@ def get_schemas(secure=secure,verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,+ bypass_env_proxy=bypass_env_proxy,)try:@@ -415,6 +439,7 @@ def get_clickhouse_row_count(secure: bool,verify: bool,names: list[str] | None = None,+ bypass_env_proxy: bool = False,) -> dict[str, int]:"""Return total_rows per table from `system.tables`.@@ -436,6 +461,7 @@ def get_clickhouse_row_count(secure=secure,verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,+ bypass_env_proxy=bypass_env_proxy,)try:@@ -539,6 +565,7 @@ def get_connection_metadata(password: str | None,secure: bool,verify: bool,+ bypass_env_proxy: bool = False,) -> dict[str, Any]:"""Probe the server for version metadata.@@ -555,6 +582,7 @@ def get_connection_metadata(secure=secure,verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,+ bypass_env_proxy=bypass_env_proxy,)try:@@ -789,6 +817,7 @@ def get_primary_keys_for_schemas(secure: bool,verify: bool,table_names: list[str],+ bypass_env_proxy: bool = False,) -> dict[str, list[str] | None]:"""Detect primary keys (sorting key columns) for multiple tables.@@ -810,6 +839,7 @@ def get_primary_keys_for_schemas(secure=secure,verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,+ bypass_env_proxy=bypass_env_proxy,)try:for table_name in table_names:@@ -1194,6 +1224,7 @@ 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,) -> SourceResponse:"""Build a SourceResponse that pulls a single ClickHouse table.@@ -1216,6 +1247,7 @@ def clickhouse_source(secure=secure,verify=verify,query_timeout=METADATA_QUERY_TIMEOUT_SECONDS,+ bypass_env_proxy=bypass_env_proxy,)try:@@ -1254,6 +1286,7 @@ def clickhouse_source(secure=secure,verify=verify,names=[table_name],+ bypass_env_proxy=bypass_env_proxy,)rows_to_sync: int | None = row_counts.get(table_name)@@ -1298,6 +1331,7 @@ def clickhouse_source(verify=verify,query_timeout=DATA_QUERY_TIMEOUT_SECONDS,settings=_query_settings(chunk_size),+ bypass_env_proxy=bypass_env_proxy,)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 3d5050e61911..a675df3817e5 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@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (SSHTunnelMixin,ValidateDatabaseHostMixin,+ is_team_allowlisted_for_internal_hosts,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema@@ -330,6 +331,10 @@ 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)+with self.with_ssh_tunnel(config, team_id) as (host, port):db_schemas = get_clickhouse_schemas(host=host,@@ -340,6 +345,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valsecure=config.secure,verify=config.verify,names=names,+ bypass_env_proxy=bypass_env_proxy,)row_counts: dict[str, int] = {}@@ -353,6 +359,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valsecure=config.secure,verify=config.verify,names=names,+ bypass_env_proxy=bypass_env_proxy,)detected_pks = get_clickhouse_primary_keys_for_schemas(@@ -364,6 +371,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Valsecure=config.secure,verify=config.verify,table_names=list(db_schemas.keys()),+ bypass_env_proxy=bypass_env_proxy,)for table_name, columns in db_schemas.items():@@ -458,6 +466,7 @@ 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),)def source_for_pipeline(self, config: ClickHouseSourceConfig, inputs: SourceInputs) -> SourceResponse:@@ -483,6 +492,7 @@ 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),)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 125e15408b6e..e43e5ca0a96c 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@@ -1319,3 +1319,70 @@ class TestClickHouseReconcileSchemaMetadata(BaseTest):metadata = schema.schema_metadataassert metadata is not Noneassert [column["name"] for column in metadata["columns"]] == ["uuid", "timestamp"]+++class TestBypassEnvProxy:+ """The proxy bypass for PostHog-internal direct connections.++ `bypass_env_proxy=True` must hand clickhouse-connect a pool manager, which+ stops it consulting HTTP(S)_PROXY env vars; `False` must leave the default+ (proxy-honouring) behaviour intact.+ """++ @pytest.mark.parametrize("verify", [True, False])+ def test_no_env_proxy_pool_manager_ignores_proxy_env(self, verify):+ from urllib3 import PoolManager, ProxyManager++ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse.clickhouse import (+ _no_env_proxy_pool_manager,+ )++ with patch.dict("os.environ", {"HTTPS_PROXY": "http://egress-proxy:4750"}):+ manager = _no_env_proxy_pool_manager(verify)+ assert isinstance(manager, PoolManager)+ assert not isinstance(manager, ProxyManager)+ # Cached: streaming clients must share the manager (they don't own it).+ assert _no_env_proxy_pool_manager(verify) is manager++ @pytest.mark.parametrize(+ "bypass,expected_pool_mgr_factory",+ [+ (True, lambda: ch_module._no_env_proxy_pool_manager(True)),+ (False, lambda: None),+ ],+ )+ def test_get_client_forwards_pool_manager_only_when_bypassing(self, bypass, expected_pool_mgr_factory):+ with patch.object(ch_module, "get_client") as mock_get_client:+ _get_client(+ host="ch.example.com",+ port=8443,+ database="default",+ user="reader",+ password="secret",+ secure=True,+ verify=True,+ bypass_env_proxy=bypass,+ )+ assert mock_get_client.call_count == 1+ assert mock_get_client.call_args.kwargs["pool_mgr"] is expected_pool_mgr_factory()+++class TestInternalHostTeamAllowlist:+ @pytest.mark.parametrize(+ "region,team_id,expected",+ [+ ("US", 2, True),+ ("US", 1, False),+ ("US", 12345, False),+ ("EU", 1, True),+ ("EU", 2, False),+ ("EU", 12345, False),+ (None, 2, False),+ ("DEV", 2, False),+ ],+ )+ def test_allowlist(self, region, team_id, expected):+ from products.warehouse_sources.backend.temporal.data_imports.sources.common import mixins++ with patch.object(mixins, "get_instance_region", return_value=region):+ assert mixins.is_team_allowlisted_for_internal_hosts(team_id) is expecteddiff --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 fdfe604e60d4..d7e04768a3ff 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@@ -27,6 +27,17 @@ _INTERNAL_IP_ERROR = (_DNS_FAILURE_ERROR = "Host could not be resolved"+def is_team_allowlisted_for_internal_hosts(team_id: int) -> bool:+ """Whether this team may point warehouse sources at PostHog-internal hosts.++ Only our own internal analytics projects: team 2 in US, team 1 in EU.+ Gates both the SSRF host check and the egress-proxy bypass for direct+ connections to internal databases.+ """+ region = get_instance_region()+ return (region == "US" and team_id == 2) or (region == "EU" and team_id == 1)++def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:"""Validate that a host is not an internal/private IP address.@@ -68,7 +79,7 @@ def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:_log("allow", "e2e", None)return True, None- if (region == "US" and team_id == 2) or (region == "EU" and team_id == 1):+ if is_team_allowlisted_for_internal_hosts(team_id):_log("allow", "team_allowlist", None)return True, None