Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): log outbound connections to customer databases (#68307)

Felipe Rosa de Almeida92494447ab1b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
index e24472b280cf..2bbe2ab0975f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
@@ -21,6 +21,7 @@ from contextlib import contextmanager
from datetime import date, datetime
from decimal import Decimal
from typing import Any
+from urllib.parse import urlparse
import pyarrow as pa
import structlog
@@ -55,6 +56,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
DEFAULT_RETRY,
TrackedHTTPAdapter,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
ColumnTypeCategory,
ValidatedRowFilter,
@@ -277,6 +279,16 @@ def bigquery_client(
credentials=credentials,
_http=authed_session,
)
+ # `_connection.API_BASE_URL` is the endpoint the client will actually call (it honors
+ # api_endpoint overrides and universe-domain hosts), so the logged host can't drift.
+ # It's a private attribute, so read it fail-soft: a library rename must degrade the log
+ # field, not crash the sync.
+ api_base_url: str = getattr(getattr(client, "_connection", None), "API_BASE_URL", None) or "bigquery.googleapis.com"
+ log_connection_open(
+ db_host=urlparse(api_base_url).hostname or api_base_url,
+ via="vendor_https",
+ project_id=project_id,
+ )
try:
yield client
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.py
index 66d7733cf6c6..faf861f03026 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
@@ -232,7 +232,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val
) -> list[SourceSchema]:
schemas: list[SourceSchema] = []
- with self.with_ssh_tunnel(config) as (host, port):
+ with self.with_ssh_tunnel(config, team_id) as (host, port):
db_schemas = get_clickhouse_schemas(
host=host,
port=port,
@@ -347,7 +347,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val
return None
def get_connection_metadata(self, config: ClickHouseSourceConfig, team_id: int) -> dict[str, object]:
- with self.with_ssh_tunnel(config) as (host, port):
+ with self.with_ssh_tunnel(config, team_id) as (host, port):
return get_clickhouse_connection_metadata(
host=host,
port=port,
@@ -361,7 +361,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val
def source_for_pipeline(self, config: ClickHouseSourceConfig, inputs: SourceInputs) -> SourceResponse:
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
- ssh_tunnel = self.make_ssh_tunnel_func(config)
+ ssh_tunnel = self.make_ssh_tunnel_func(config, inputs.team_id)
schema = ExternalDataSchema.objects.select_related("source").get(id=inputs.schema_id)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
index 08cacb2db873..218f1b822677 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
@@ -2,6 +2,7 @@ import time
import socket
from collections.abc import Callable, Generator
from contextlib import _GeneratorContextManager, contextmanager
+from typing import Any
from django.db import OperationalError, close_old_connections
@@ -101,42 +102,110 @@ def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:
return True, None
+def log_connection_open(
+ *,
+ db_host: str,
+ db_port: int | str | None = None,
+ via: str = "direct",
+ ssh_host: str | None = None,
+ ssh_port: int | str | None = None,
+ team_id: int | None = None,
+ **fields: Any,
+) -> None:
+ """Emit `data_imports.connection_open` — one line per outbound connection to a customer host."""
+ event_fields: dict[str, Any] = {"db_host": db_host, "via": via, **fields}
+ for key, value in (("db_port", db_port), ("ssh_host", ssh_host), ("ssh_port", ssh_port), ("team_id", team_id)):
+ if value is not None:
+ event_fields[key] = value
+ logger.info("data_imports.connection_open", **event_fields)
+
+
+def _enabled_ssh_tunnel(config) -> Any | None:
+ """Return the config's SSH tunnel settings when enabled, else None.
+
+ The single predicate for both the connection log and the tunnel/direct branch,
+ so the logged `via` can never disagree with the path actually taken.
+ """
+ ssh = getattr(config, "ssh_tunnel", None)
+ return ssh if ssh and ssh.enabled else None
+
+
+@contextmanager
+def _logged_connection(config, team_id: int | None) -> Generator[None]:
+ ssh = _enabled_ssh_tunnel(config)
+ if ssh is not None:
+ via, ssh_host, ssh_port = "ssh_tunnel", ssh.host, ssh.port
+ else:
+ via, ssh_host, ssh_port = "direct", None, None
+ log_connection_open(
+ db_host=config.host,
+ db_port=config.port,
+ via=via,
+ ssh_host=ssh_host,
+ ssh_port=ssh_port,
+ team_id=team_id,
+ )
+ try:
+ yield
+ except Exception as e:
+ # Coarse by design: the block spans the whole connection lifetime, so this also
+ # catches mid-sync errors — error_type disambiguates, and a down tunnel retrying
+ # is exactly the pattern this exists to make visible.
+ logger.warning(
+ "data_imports.connection_error",
+ db_host=config.host,
+ via=via,
+ error_type=type(e).__name__,
+ error=str(e)[:200],
+ **({"db_port": config.port} if config.port is not None else {}),
+ **({"team_id": team_id} if team_id is not None else {}),
+ )
+ raise
+
+
@contextmanager
-def open_ssh_tunnel(config) -> Generator[tuple[str, int]]:
+def 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."""
- if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:
- ssh_tunnel = SSHTunnel.from_config(config.ssh_tunnel)
+ with _logged_connection(config, team_id):
+ ssh_config = _enabled_ssh_tunnel(config)
+ if ssh_config is not None:
+ ssh_tunnel = SSHTunnel.from_config(ssh_config)
- with ssh_tunnel.get_tunnel(config.host, config.port) as tunnel:
- if tunnel is None:
- raise Exception("Can't open tunnel to SSH server")
+ 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
- else:
- yield config.host, config.port
+ yield tunnel.local_bind_host, tunnel.local_bind_port
+ else:
+ yield config.host, config.port
-def make_ssh_tunnel_factory(config) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:
+def make_ssh_tunnel_factory(
+ config, team_id: int | None = None
+) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:
"""Return a zero-arg factory that opens a fresh `open_ssh_tunnel(config)` context each call.
The dlt pipeline factories accept a tunnel-factory callable so the tunnel can be
(re)opened inside the pipeline process.
"""
- if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:
- ssh_tunnel = SSHTunnel.from_config(config.ssh_tunnel)
+ ssh_config = _enabled_ssh_tunnel(config)
+ if ssh_config is not None:
+ ssh_tunnel = SSHTunnel.from_config(ssh_config)
@contextmanager
def with_ssh_func():
- 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
+ with _logged_connection(config, team_id):
+ 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
return with_ssh_func
@contextmanager
def without_ssh_func():
- yield config.host, config.port
+ with _logged_connection(config, team_id):
+ yield config.host, config.port
return without_ssh_func
@@ -144,11 +213,13 @@ def make_ssh_tunnel_factory(config) -> Callable[[], _GeneratorContextManager[tup
class SSHTunnelMixin:
"""Mixin for sources that support SSH tunnels"""
- def with_ssh_tunnel(self, config) -> _GeneratorContextManager[tuple[str, int]]:
- return open_ssh_tunnel(config)
+ def with_ssh_tunnel(self, config, team_id: int | None = None) -> _GeneratorContextManager[tuple[str, int]]:
+ return open_ssh_tunnel(config, team_id)
- def make_ssh_tunnel_func(self, config) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:
- return make_ssh_tunnel_factory(config)
+ def make_ssh_tunnel_func(
+ self, config, team_id: int | None = None
+ ) -> Callable[[], _GeneratorContextManager[tuple[str, int]]]:
+ return make_ssh_tunnel_factory(config, team_id)
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:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
index a46ca7cdc88b..9e10e6e20143 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
@@ -16,6 +16,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
SSHTunnelMixin,
ValidateDatabaseHostMixin,
_is_host_safe,
+ make_ssh_tunnel_factory,
+ open_ssh_tunnel,
)
_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"
@@ -236,6 +238,73 @@ class TestSSHTunnelHostValidation(SimpleTestCase):
assert not valid
+class TestConnectionOpenLogging(SimpleTestCase):
+ def test_direct_connection_logs_open_event(self):
+ config = FakeConfig(ssh_tunnel=FakeSSHTunnelConfig(enabled=False, host=""))
+ with patch(f"{_MIXINS_MODULE}.logger") as mock_logger:
+ with open_ssh_tunnel(config, team_id=42) as (host, port):
+ assert (host, port) == ("dbhost.example.com", 5432)
+ mock_logger.info.assert_called_once()
+ args, kwargs = mock_logger.info.call_args
+ assert args[0] == "data_imports.connection_open"
+ assert kwargs["db_host"] == "dbhost.example.com"
+ assert kwargs["db_port"] == 5432
+ assert kwargs["via"] == "direct"
+ assert kwargs["team_id"] == 42
+ assert "ssh_host" not in kwargs
+ mock_logger.warning.assert_not_called()
+
+ def test_none_team_id_is_omitted_so_contextvars_can_fill_it(self):
+ config = FakeConfig(ssh_tunnel=None)
+ with patch(f"{_MIXINS_MODULE}.logger") as mock_logger:
+ with open_ssh_tunnel(config):
+ pass
+ _args, kwargs = mock_logger.info.call_args
+ assert "team_id" not in kwargs
+
+ def test_tunneled_connection_logs_both_hosts(self):
+ config = FakeConfig(ssh_tunnel=FakeSSHTunnelConfig(enabled=True, host="0.tcp.ngrok.example", port=12345))
+ with (
+ patch(f"{_MIXINS_MODULE}.SSHTunnel") as mock_ssh,
+ patch(f"{_MIXINS_MODULE}.logger") as mock_logger,
+ ):
+ tunnel = mock_ssh.from_config.return_value.get_tunnel.return_value.__enter__.return_value
+ tunnel.local_bind_host, tunnel.local_bind_port = "127.0.0.1", 55555
+ with open_ssh_tunnel(config, team_id=42) as (host, port):
+ assert (host, port) == ("127.0.0.1", 55555)
+ _args, kwargs = mock_logger.info.call_args
+ assert kwargs["via"] == "ssh_tunnel"
+ assert kwargs["ssh_host"] == "0.tcp.ngrok.example"
+ assert kwargs["ssh_port"] == 12345
+ assert kwargs["db_host"] == "dbhost.example.com"
+
+ def test_error_inside_connection_block_logs_connection_error(self):
+ config = FakeConfig(ssh_tunnel=None)
+ with patch(f"{_MIXINS_MODULE}.logger") as mock_logger:
+ with pytest.raises(ConnectionRefusedError):
+ with open_ssh_tunnel(config, team_id=42):
+ raise ConnectionRefusedError("connection refused")
+ mock_logger.warning.assert_called_once()
+ args, kwargs = mock_logger.warning.call_args
+ assert args[0] == "data_imports.connection_error"
+ assert kwargs["error_type"] == "ConnectionRefusedError"
+ assert kwargs["db_port"] == 5432
+ assert kwargs["team_id"] == 42
+
+ def test_factory_logs_once_per_reopen(self):
+ config = FakeConfig(ssh_tunnel=None)
+ factory = make_ssh_tunnel_factory(config, team_id=42)
+ with patch(f"{_MIXINS_MODULE}.logger") as mock_logger:
+ with factory() as (host, port):
+ assert (host, port) == ("dbhost.example.com", 5432)
+ with factory():
+ pass
+ assert mock_logger.info.call_count == 2
+ assert all(call.args[0] == "data_imports.connection_open" for call in mock_logger.info.call_args_list)
+ # The closure must carry team_id into every reopen — this is the sync-path attribution.
+ assert all(call.kwargs["team_id"] == 42 for call in mock_logger.info.call_args_list)
+
+
class TestOAuthMixinIntegrationFetchResilience(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
index c364205da735..7b7246ab662f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
@@ -8,6 +8,7 @@ import collections
from collections.abc import Callable, Iterator
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Optional
+from urllib.parse import urlparse
import certifi
import structlog
@@ -29,7 +30,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (
DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ _is_host_safe,
+ log_connection_open,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MongoDBSourceConfig
from products.warehouse_sources.backend.types import IncrementalFieldType, PartitionSettings
@@ -260,6 +264,8 @@ def _make_safe_server_selector(team_id: int) -> Callable[[list[ServerDescription
@contextlib.contextmanager
def mongo_client(connection_string: str, team_id: int) -> Iterator[MongoClient]:
+ # rpartition strips credentials; multiple hosts stay comma-joined as-is.
+ log_connection_open(db_host=urlparse(connection_string).netloc.rpartition("@")[2], team_id=team_id)
kwargs: dict[str, Any] = {
"serverSelectionTimeoutMS": 10000,
"tls": True,
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.py
index e5194c05a182..1c6aaa883c5e 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
@@ -36,7 +36,7 @@ def cdc_pg_connection(source: ExternalDataSource, connect_timeout: int = 15) ->
# that doesn't speak SSL fails with "server does not support SSL, but SSL was required".
require_ssl = source_requires_ssl(source, config)
- with source_impl.with_ssh_tunnel(config) as (host, port):
+ with source_impl.with_ssh_tunnel(config, source.team_id) as (host, port):
conn = _connect_to_postgres(
host=host,
port=port,
diff --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.py
index f725246ae492..826bb60dbca6 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
@@ -74,7 +74,7 @@ class PgCDCStreamReader:
source_impl = PostgresSource()
config = source_impl.parse_config(self._source.job_inputs or {})
- tunnel_cm = source_impl.with_ssh_tunnel(config)
+ tunnel_cm = source_impl.with_ssh_tunnel(config, self._source.team_id)
self._effective_host, self._effective_port = tunnel_cm.__enter__()
self._tunnel_cm = tunnel_cm
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py
index e6b604c533cf..133fb6fe9db0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_slot_manager.py
@@ -202,10 +202,10 @@ class TestCdcPgConnectionSsl:
if is_new_source
else SSL_REQUIRED_AFTER_DATE - dt.timedelta(days=1)
)
- source = SimpleNamespace(job_inputs={}, created_at=created_at)
+ source = SimpleNamespace(job_inputs={}, created_at=created_at, team_id=1)
@contextmanager
- def fake_tunnel(self, config):
+ def fake_tunnel(self, config, team_id=None):
yield ("127.0.0.1", 44549)
with (
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index f2838baa7d71..00267a2fca74 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
@@ -612,7 +612,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
) -> list[SourceSchema]:
schemas = []
- with self.with_ssh_tunnel(config) as (host, port):
+ with self.with_ssh_tunnel(config, team_id) as (host, port):
db_schemas = get_postgres_schemas(
host=host,
port=port,
@@ -870,7 +870,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
def get_connection_metadata(
self, config: PostgresSourceConfig, team_id: int, require_ssl: bool = False
) -> dict[str, object]:
- with self.with_ssh_tunnel(config) as (host, port):
+ with self.with_ssh_tunnel(config, team_id) as (host, port):
return get_postgres_connection_metadata(
host=host,
port=port,
@@ -930,7 +930,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
PostHogDatabaseConnectionError,
)
- ssh_tunnel = self.make_ssh_tunnel_func(config)
+ ssh_tunnel = self.make_ssh_tunnel_func(config, inputs.team_id)
# This reads sync metadata from PostHog's own database, not the customer's Postgres. A
# transient failure reaching our database here (e.g. a DNS blip resolving our host) raises
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
index 001f42057ee7..2bf6547c7c0c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
SourceInputs,
SourceResponse,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
AnsiIdentifierQuoter,
ValidatedRowFilter,
@@ -265,6 +266,10 @@ class SnowflakeImplementation(
"user": config.auth_type.user,
}
+ # Mirrors the connector's own host derivation for the common account-id formats.
+ # Deliberately not importing the connector's private `construct_hostname` — a rename
+ # there would crash every Snowflake sync at import time just to feed a log field.
+ log_connection_open(db_host=f"{config.account_id}.snowflakecomputing.com", via="vendor_https")
with snowflake.connector.connect(
account=config.account_id,
warehouse=config.warehouse,