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.

fix(warehouse-sources): pin redshift and mysql connects (#97454)

Daniel RCcc6d5683b2c1
diff --git a/posthog/hogql/direct_sql/mysql_adapter.py b/posthog/hogql/direct_sql/mysql_adapter.py
index 5bfdb1abf140..98733d2c0897 100644
--- a/posthog/hogql/direct_sql/mysql_adapter.py
+++ b/posthog/hogql/direct_sql/mysql_adapter.py
@@ -168,7 +168,9 @@ class MySQLAdapter:
try:
with request.timings.measure("mysql_execute"):
- with mysql_implementation.connect(source_config, read_timeout=statement_timeout_seconds) as connection:
+ with mysql_implementation.connect(
+ source_config, read_timeout=statement_timeout_seconds, team_id=request.team.pk
+ ) as connection:
with connection.cursor() as cursor:
try:
# MySQL 8 only and SELECT-only; MariaDB uses a different variable.
diff --git a/posthog/hogql/direct_sql/redshift_adapter.py b/posthog/hogql/direct_sql/redshift_adapter.py
index 618f13ac00a4..c9035f4acb6e 100644
--- a/posthog/hogql/direct_sql/redshift_adapter.py
+++ b/posthog/hogql/direct_sql/redshift_adapter.py
@@ -152,7 +152,7 @@ class RedshiftAdapter:
with request.timings.measure("redshift_execute"), observe_direct_query("redshift"):
# `connect` opens the SSH tunnel (if any) and applies the shared Redshift SSL
# conventions in one place.
- with redshift_implementation.connect(source_config) as connection:
+ with redshift_implementation.connect(source_config, team_id=request.team.pk) as connection:
# One round trip for the session setup: statement_timeout is a validated int
# (milliseconds) so inlining it is injection-safe, and the search_path
# identifier is escaped. Multi-statement execute is fine with no parameters.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/README.md b/products/warehouse_sources/backend/temporal/data_imports/sources/README.md
index b48dfe565cac..362b5937b037 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. 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.
+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, Redshift and MySQL clients do.
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.
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 1a51d1f8cb39..23161c361f98 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
@@ -1218,7 +1218,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
# ------------------------------------------------------------------
@contextmanager
- def connect(self, config: BigQuerySourceConfig) -> Iterator[bigquery.Client]:
+ def connect(self, config: BigQuerySourceConfig, *, team_id: int | None = None) -> Iterator[bigquery.Client]:
# Without a custom region the client is built with `location=None`, so discovery
# query jobs default to the US multi-region and miss datasets in other regions.
# Auto-detect the dataset's location so discovery runs where the data lives.
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 ea135f68542d..42f22bd0ac7d 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
@@ -34,7 +34,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ HostNotAllowedError,
SSHTunnelMixin,
+ TemporaryHostResolutionError,
ValidateDatabaseHostMixin,
is_team_allowlisted_for_internal_hosts,
)
@@ -518,6 +520,10 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val
try:
self.get_schemas(config, team_id, names=[schema_name] if schema_name else None, api_version=api_version)
+ except (HostNotAllowedError, TemporaryHostResolutionError) as e:
+ # The host policy refused the host, or its lookup never answered. Both carry their own
+ # user-facing wording and neither is a PostHog defect, so they are not captured.
+ return False, str(e)
except BaseSSHTunnelForwarderError as e:
return (
False,
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 3dec987c2ec9..9cd620d8f921 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
@@ -48,6 +48,12 @@ _NON_ASCII_HOST_ERROR = (
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"
+# Stored as the job's error once every retry of a connect was spent on the pin's own lookup failing.
+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."
+)
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 "
@@ -232,7 +238,7 @@ def pinned_host_kwargs(host: str, *, port: int, connect_timeout: float, team_id:
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:
+ if host_lookup_is_skipped():
return {"host": host}
if is_cloud() and (guard_error := _single_host_error(host)) is not None:
@@ -256,6 +262,11 @@ def pinned_host_kwargs(host: str, *, port: int, connect_timeout: float, team_id:
}
+def host_lookup_is_skipped() -> bool:
+ """Dev and test connect to local or fake hosts, so the pins skip the lookup there, as `_get_sslmode` does."""
+ return bool(settings.TEST or settings.DEBUG or settings.E2E_TESTING)
+
+
def _normalize_host(host: str) -> str:
return host.lower().strip().rstrip(".")
@@ -479,14 +490,17 @@ def _check_direct_host(config, team_id: int | None) -> None:
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.
+ The Postgres and Redshift clients close that race themselves: `pinned_host_kwargs` in
+ this module resolves the host once, validates that answer with `check_resolved_addresses`,
+ and dials exactly those addresses through libpq's `host`/`hostaddr` pair. The MySQL client
+ resolves the host itself, validates the answer with `check_resolved_addresses`, and dials
+ it on a socket it opens, so the hostname still reaches TLS. The MSSQL client hands the
+ hostname to its driver, whose single `server` argument is both the dial target and the
+ login server name, so for MSSQL this check is the only one.
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).
+ team yet.
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.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
index 9f53fca20b3f..0af722c1c451 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
@@ -116,7 +116,7 @@ class SQLSource(SimpleSource[ConfigType], Generic[ConfigType]):
api_version: str | None = None,
) -> list[SourceSchema]:
impl = self.get_implementation
- with impl.connect(config) as conn:
+ with impl.connect(config, team_id=team_id) as conn:
columns_by_table = impl.get_columns(conn, config, names)
if not columns_by_table:
return []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/implementation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/implementation.py
index be92f2b67bf8..d32b41f6e78b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/implementation.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/implementation.py
@@ -114,11 +114,16 @@ class SQLSourceImplementation(Generic[ConfigT, ConnT, CursorT], ABC):
# ------------------------------------------------------------------
@abstractmethod
- def connect(self, config: ConfigT) -> AbstractContextManager[ConnT]:
+ def connect(self, config: ConfigT, *, team_id: int | None = None) -> AbstractContextManager[ConnT]:
"""Open a driver connection for the duration of schema discovery.
Implementations own the full lifecycle — SSH tunnel (if any),
TLS, auth, cursor setup — and clean it up on exit.
+
+ `team_id` feeds the host policy that decides where the connection may go. The
+ internal-analytics teams are exempt from it, so a connect that drops the team fails
+ closed for them; every caller that has a team must pass it. Drivers that reach the
+ vendor over HTTPS through the egress proxy accept it and ignore it.
"""
@abstractmethod
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_base.py
index da935706dcfc..8263b1c48520 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_base.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import dataclasses
+from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
@@ -64,9 +65,11 @@ class _FakeImplementation(SQLSourceImplementation[_FakeConfig, object, Any]):
self.get_primary_keys_called = False
self.get_row_counts_called = False
self.get_foreign_keys_called = False
+ self.connect_team_ids: list[int | None] = []
@contextmanager
- def connect(self, config: _FakeConfig):
+ def connect(self, config: _FakeConfig, *, team_id: int | None = None) -> Iterator[object]:
+ self.connect_team_ids.append(team_id)
yield object()
def get_columns(
@@ -127,6 +130,11 @@ def _make_source(**data: Any) -> tuple[_FakeSQLSource, _FakeImplementation]:
class TestGetSchemas:
+ def test_connect_receives_the_team(self) -> None:
+ source, impl = _make_source(columns_by_table={"messages": [("id", "int", False)]})
+ source.get_schemas(_FakeConfig(), team_id=7)
+ assert impl.connect_team_ids == [7]
+
def test_returns_one_source_schema_per_table(self) -> None:
source, _ = _make_source(
columns_by_table={
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_implementation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_implementation.py
index 49e8a211c677..f03801f128af 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_implementation.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_implementation.py
@@ -9,6 +9,7 @@ each implementation (e.g. `mysql/tests/test_mysql.py`).
from __future__ import annotations
import dataclasses
+from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
@@ -50,7 +51,9 @@ class _FakeImplementation(SQLSourceImplementation[_FakeConfig, Any, Any]):
self.fetch_average_row_size_calls: list[tuple[Any, ...]] = []
@contextmanager
- def connect(self, config): # pragma: no cover — not exercised by these tests
+ def connect(
+ self, config: Any, *, team_id: int | None = None
+ ) -> Iterator[object]: # pragma: no cover — not exercised by these tests
yield object()
def get_columns(self, conn, config, names): # pragma: no cover
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/resolver.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/resolver.py
new file mode 100644
index 000000000000..3ee986633b09
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/resolver.py
@@ -0,0 +1,6 @@
+import socket
+
+
+# nosemgrep: semgrep.rules.devex.tuple-return-prefer-dataclass -- mirrors socket.getaddrinfo's positional result
+def addrinfo(port: int, *addresses: str) -> list[tuple[int, int, int, str, tuple[str, int]]]:
+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (address, port)) for address in addresses]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py
index c9b71dc9cbdd..d72a33c6c28b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py
@@ -163,7 +163,7 @@ class DatabricksImplementation(SQLSourceImplementation[DatabricksSourceConfig, A
# ------------------------------------------------------------------
@contextmanager
- def connect(self, config: DatabricksSourceConfig) -> Iterator[Any]:
+ def connect(self, config: DatabricksSourceConfig, *, team_id: int | None = None) -> Iterator[Any]:
"""Open a Databricks SQL warehouse connection for the duration of the context.
Branches on `config.auth_type.selection`: a personal access token is
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
index 5f302bc57963..4a7b51107c08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
@@ -259,7 +259,9 @@ class MotherDuckImplementation(SQLSourceImplementation[MotherduckSourceConfig, A
# ------------------------------------------------------------------
@contextmanager
- def connect(self, config: MotherduckSourceConfig, catalog: Optional[str] = None) -> Iterator[Any]:
+ def connect(
+ self, config: MotherduckSourceConfig, catalog: Optional[str] = None, *, team_id: int | None = None
+ ) -> Iterator[Any]:
"""Open a MotherDuck-backed DuckDB connection for the duration of the context.
`catalog` pins the connection's current database, so a caller reading one table
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
index 27bec1fa00ca..e326021a36a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
@@ -363,13 +363,18 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
# ------------------------------------------------------------------
@contextmanager
- def connect(self, config: MSSQLSourceConfig) -> Iterator[pymssql.Connection]:
+ def connect(self, config: MSSQLSourceConfig, *, team_id: int | None = None) -> Iterator[pymssql.Connection]:
"""Open a pymssql connection for the duration of the context.
Opens the SSH tunnel (if configured) once, then connects with the
MSSQL-wide conventions: 5s login timeout.
+
+ The hostname goes to pymssql as is. `pymssql.connect` takes one `server`, which FreeTDS
+ uses both to dial and as the login server name, so there is no way to dial a pinned
+ address and log in as the configured host. The tunnel layer's host check is the control
+ on this path.
"""
- with self._ssh_tunnel_endpoint(config) as (host, port):
+ with self._ssh_tunnel_endpoint(config, team_id) as (host, port):
with pymssql.connect(
server=host,
# pymssql requires port to be str
@@ -382,7 +387,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
yield conn
@contextmanager
- def _ssh_tunnel_endpoint(self, config: MSSQLSourceConfig) -> Iterator[tuple[str, int]]:
+ def _ssh_tunnel_endpoint(self, config: MSSQLSourceConfig, team_id: int | None) -> Iterator[tuple[str, int]]:
"""Yield the `(host, port)` to connect to, going through the SSH tunnel if configured.
Translates a bare paramiko handshake `EOFError` into `_SSH_HANDSHAKE_EOF_ERROR`. The
@@ -391,7 +396,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
"""
with ExitStack() as stack:
try:
- host, port = stack.enter_context(open_ssh_tunnel(config))
+ host, port = stack.enter_context(open_ssh_tunnel(config, team_id))
except EOFError as e:
raise Exception(_SSH_HANDSHAKE_EOF_ERROR) from e
yield host, port
@@ -900,7 +905,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
enabled_columns = inputs.enabled_columns
row_filters = inputs.row_filters
- with self.connect(config) as connection:
+ with self.connect(config, team_id=inputs.team_id) as connection:
with connection.cursor() as cursor:
primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
full_table = self.get_table_metadata(cursor, schema, table_name)
@@ -936,7 +941,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
def get_rows() -> Iterator[Any]:
binary_reporter = BinaryColumnReporter(logger)
- with self.connect(config) as streaming_connection:
+ with self.connect(config, team_id=inputs.team_id) as streaming_connection:
with streaming_connection.cursor() as cursor:
query, args = _build_query(
schema,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py
index 78381471e851..27c58af44263 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py
@@ -15,7 +15,9 @@ from posthog.exceptions_capture import capture_exception
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
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
@@ -276,6 +278,10 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase
try:
self.get_schemas(config, team_id, api_version=api_version)
+ except (HostNotAllowedError, TemporaryHostResolutionError) as e:
+ # The host policy refused the host, or its lookup never answered. Both carry their own
+ # user-facing wording and neither is a PostHog defect, so they are not captured.
+ return False, str(e)
except OperationalError as e:
error_msg = " ".join(str(n) for n in e.args)
for key, value in MSSQLErrors.items():
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
index bd806c552ebc..4ee46df59e6a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
@@ -17,6 +17,7 @@ module-scope primitives.
from __future__ import annotations
import time
+import socket
import datetime
import collections
from collections.abc import Callable, Iterator
@@ -25,11 +26,12 @@ from typing import Any, TypeVar
from django.conf import settings
+import psycopg
import pyarrow as pa
import pymysql
import structlog
import pymysql.converters
-from pymysql.constants import FIELD_TYPE
+from pymysql.constants import CR, FIELD_TYPE
from pymysql.cursors import Cursor, SSCursor
from structlog.types import FilteringBoundLogger
@@ -37,6 +39,11 @@ from structlog.types import FilteringBoundLogger
# explain_query, fetch_average_row_size) deliberately do NOT report handled failures here;
# their guard tests patch `mysql.capture_exception` to enforce that.
from posthog.exceptions_capture import capture_exception # noqa: F401
+from posthog.psycopg_helpers import (
+ is_resolvable_hostname,
+ prefer_routable_addresses,
+ resolve_psycopg_hostaddr_with_timeout,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
DEFAULT_NUMERIC_PRECISION,
@@ -46,7 +53,14 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
restrict_schema_to_columns,
table_from_iterator,
)
-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 (
+ DATABASE_HOST_NOT_ALLOWED_ERROR,
+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,
+ HostNotAllowedError,
+ check_resolved_addresses,
+ host_lookup_is_skipped,
+ open_ssh_tunnel,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
BacktickIdentifierQuoter,
Column,
@@ -586,18 +600,120 @@ def _is_transient_cant_create_thread(e: BaseException) -> bool:
return code == _CANT_CREATE_THREAD_CODE
-def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:
+def _pinned_addresses(host: str, port: int, connect_timeout: int, team_id: int | None) -> tuple[str, ...]:
+ """Resolve `host` once, validate the answer, and return the addresses the connection may dial.
+
+ pymysql resolves the hostname itself inside `Connection.connect`, and the tunnel layer only
+ checked the host without pinning, so that second lookup is the one that picks the socket
+ target. A record can answer public on the check and private on the connect. Resolving here and
+ dialing exactly this answer leaves it nothing to slip past.
+
+ Empty means there is nothing to pin and pymysql connects by name: an IP literal (the SSH
+ tunnel yields its loopback bind address this way), or an exempt host whose lookup failed. An
+ exempt host that resolved dials what it resolved. A refused host raises the typed rejection
+ the non-retryable classifiers match. The lookup is bounded by `connect_timeout`; a deadline
+ or a resolver "try again" answer raises the error pymysql raises for its own failed lookup,
+ so the transient-connect retry runs a fresh lookup on the next attempt.
+ """
+ if host_lookup_is_skipped():
+ return ()
+
+ if not is_resolvable_hostname(host):
+ return ()
+
+ try:
+ addresses = (
+ resolve_psycopg_hostaddr_with_timeout(host, port, connect_timeout, raise_on_temporary_failure=True) or []
+ )
+ except psycopg.OperationalError as e:
+ # The bounded resolver reports a blip and a deadline as a psycopg error. pymysql's own
+ # wording for the same failures is what the transient-connect classifiers match.
+ reason = (
+ _DNS_TEMPORARY_FAILURE_TOKEN if isinstance(e.__cause__, socket.gaierror) else "timed out resolving host"
+ )
+ raise pymysql.err.OperationalError(
+ CR.CR_CONN_HOST_ERROR, f"Can't connect to MySQL server on {host!r} ({reason})"
+ ) from e
+ except UnicodeError:
+ addresses = []
+
+ 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 DATABASE_HOST_NOT_ALLOWED_GUIDANCE}"
+ )
+ return tuple(prefer_routable_addresses(list(resolution.addresses)))
+
+
+def _dial_pinned_address(host: str, addresses: tuple[str, ...], port: int, connect_timeout: int) -> socket.socket:
+ """Open the TCP socket for pymysql to one of `addresses`, trying them in order.
+
+ pymysql skips its own socket setup when it is handed a socket, so this mirrors it: the same
+ keepalive and no-delay options, and the timeout cleared after the connect because pymysql
+ applies its read and write timeouts per operation. A failure is raised as the same
+ `OperationalError(2003)` pymysql raises for its own connect, so the transient-connect
+ classifiers keep matching on the message.
+ """
+ last_error: OSError | None = None
+ for address in addresses:
+ try:
+ sock = socket.create_connection((address, port), connect_timeout)
+ except OSError as e:
+ last_error = e
+ continue
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
+ sock.settimeout(None)
+ return sock
+ raise pymysql.err.OperationalError(
+ CR.CR_CONN_HOST_ERROR, f"Can't connect to MySQL server on {host!r} ({last_error})"
+ ) from last_error
+
+
+def _pinned_socket(host: str, port: int, connect_timeout: int, team_id: int | None) -> socket.socket | None:
+ """The socket pymysql connects over, or None when it may dial `host` by name."""
+ addresses = _pinned_addresses(host, port, connect_timeout, team_id)
+ if not addresses:
+ return None
+ return _dial_pinned_address(host, addresses, port, connect_timeout)
+
+
+def _reconnect_pinned(connection: pymysql.Connection, team_id: int | None) -> None:
+ """Reopen a dropped pymysql connection to a freshly validated address.
+
+ `Connection.connect()` with no socket resolves `connection.host` again and dials whatever
+ that lookup returns, which would reopen the gap the pinned first connect closed.
+ """
+ connection.connect(sock=_pinned_socket(connection.host, connection.port, connection.connect_timeout, team_id))
+
+
+def _open_pymysql_connection(kwargs: dict[str, Any], team_id: int | None) -> pymysql.Connection:
+ sock = _pinned_socket(kwargs["host"], kwargs["port"], kwargs["connect_timeout"], team_id)
+ if sock is None:
+ return pymysql.connect(**kwargs)
+
+ # `host` stays the hostname so pymysql sends it as the TLS server name, and PlanetScale, which
+ # turns on `ssl_verify_identity`, verifies the certificate against it. Python sends no SNI for
+ # an IP literal. Only the TCP connect goes to the pinned address.
+ connection = pymysql.connect(**kwargs, defer_connect=True)
+ connection.connect(sock=sock)
+ return connection
+
+
+def _connect_with_transient_retry(kwargs: dict[str, Any], team_id: int | None) -> pymysql.Connection:
"""Open a pymysql connection, retrying a transient drop or timeout on connect.
Mirrors the in-process connect retry the Postgres source uses: a momentary
drop or timeout while establishing the connection recovers on a fresh attempt,
so retry it here with a bounded backoff instead of failing schema discovery /
sync setup on the first blip and surfacing it as captured error-tracking noise.
+ The pinned lookup runs inside the loop, so a resolver blip retries with a
+ fresh answer rather than a stale address list.
"""
attempt = 0
while True:
try:
- return pymysql.connect(**kwargs)
+ return _open_pymysql_connection(kwargs, team_id)
except pymysql.err.DatabaseError as e:
attempt += 1
if attempt >= _MAX_CONNECT_ATTEMPTS or not (
@@ -879,6 +995,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
config: MySQLSourceConfig,
*,
read_timeout: int | None = None,
+ team_id: int | None = None,
) -> Iterator[pymysql.Connection]:
"""Open a pymysql connection for the duration of the context.
@@ -894,7 +1011,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
if config.using_ssl:
ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"
- with self._ssh_tunnel_endpoint(config) as (host, port):
+ with self._ssh_tunnel_endpoint(config, team_id) as (host, port):
kwargs: dict[str, Any] = {
"host": host,
# pymysql rejects a non-int port; config.port can arrive as a string when the
@@ -910,11 +1027,11 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
}
if read_timeout is not None:
kwargs["read_timeout"] = read_timeout
- with _connect_with_transient_retry(kwargs) as conn:
+ with _connect_with_transient_retry(kwargs, team_id) as conn:
yield conn
@contextmanager
- def _ssh_tunnel_endpoint(self, config: MySQLSourceConfig) -> Iterator[tuple[str, int]]:
+ def _ssh_tunnel_endpoint(self, config: MySQLSourceConfig, team_id: int | None) -> Iterator[tuple[str, int]]:
"""Yield the `(host, port)` to connect to, going through the SSH tunnel if configured.
Translates a bare paramiko handshake `EOFError` into `_SSH_HANDSHAKE_EOF_ERROR`. The
@@ -923,7 +1040,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
"""
with ExitStack() as stack:
try:
- host, port = stack.enter_context(open_ssh_tunnel(config))
+ host, port = stack.enter_context(open_ssh_tunnel(config, team_id))
except EOFError as e:
raise Exception(_SSH_HANDSHAKE_EOF_ERROR) from e
yield host, port
@@ -1427,7 +1544,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
row_filters = inputs.row_filters
def _discover_metadata() -> tuple[list[str] | None, pa.Schema, int, PartitionSettings | None, int]:
- with self.connect(config) as connection:
+ with self.connect(config, team_id=inputs.team_id) as connection:
with connection.cursor() as cursor:
primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
full_table = self.get_table_metadata(cursor, schema, table_name)
@@ -1480,7 +1597,9 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
replays a few already-processed rows; the delta merge
dedupes by primary key.
"""
- with self.connect(config, read_timeout=STATEMENT_TIMEOUT_SECONDS) as streaming_connection:
+ with self.connect(
+ config, read_timeout=STATEMENT_TIMEOUT_SECONDS, team_id=inputs.team_id
+ ) as streaming_connection:
# Bump server-side timeouts for large table scans. The
# defaults (60s each) are too low for multi-GB unbuffered
# queries — the server drops the connection before the
@@ -1530,7 +1649,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
# Detach the cursor bound to the dead socket first so its later teardown
# can't drain the freshly reopened connection (see _release_streaming_cursor).
_release_streaming_cursor(ss_cursor)
- streaming_connection.connect()
+ _reconnect_pinned(streaming_connection, inputs.team_id)
ss_cursor = streaming_connection.cursor(SSCursor)
ss_cursor.execute(query, args)
@@ -1595,7 +1714,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
)
raise
- with self.connect(config) as probe_connection:
+ with self.connect(config, team_id=inputs.team_id) as probe_connection:
with probe_connection.cursor() as probe_cursor:
force_index_name = self.find_index_for_cursor(
probe_cursor, schema, table_name, incremental_field, logger
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py
index b2ed7c37721b..bd74f23e5580 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py
@@ -22,7 +22,9 @@ from posthog.exceptions_capture import capture_exception
from products.data_warehouse.backend.facade.api import reconcile_mysql_schemas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
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
@@ -431,7 +433,7 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase
) -> dict[str, object]:
# `require_ssl` keeps signature parity with Postgres; MySQL SSL is governed by
# `config.using_ssl` inside `connect`.
- with self.get_implementation.connect(config) as conn:
+ with self.get_implementation.connect(config, team_id=team_id) as conn:
return get_mysql_connection_metadata(conn, database=config.database)
def validate_credentials(
@@ -464,6 +466,10 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase
try:
self.get_schemas(config, team_id, api_version=api_version)
+ except (HostNotAllowedError, TemporaryHostResolutionError) as e:
+ # The host policy refused the host, or its lookup never answered. Both carry their own
+ # user-facing wording and neither is a PostHog defect, so they are not captured.
+ return False, str(e)
except BaseSSHTunnelForwarderError as e:
# sshtunnel surfaces raw library strings (e.g. "Could not establish session to SSH
# gateway"); map them to the friendly guidance in `get_non_retryable_errors` — which the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
index 3c6784ddddd1..286657c5d173 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
@@ -1,18 +1,26 @@
+import socket
import datetime
-from collections.abc import Generator
+from collections.abc import Generator, Iterator
+from contextlib import contextmanager
from typing import cast
import pytest
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
import pymysql
from sshtunnel import BaseSSHTunnelForwarderError
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedError
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import Table, TableStats
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ColumnTypeCategory,
ValidatedRowFilter,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import addrinfo
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mysql import MySQLSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import (
@@ -39,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq
_is_transient_too_many_connections,
_is_transient_vitess_dial_timeout,
_is_transient_vitess_reparent,
+ _reconnect_pinned,
_release_streaming_cursor,
_retry_on_transient_tablet_unavailable,
_safe_convert_date,
@@ -2586,3 +2595,125 @@ class TestConnectPortCoercion:
passed_port = mock_connect.call_args.kwargs["port"]
assert passed_port == 3306
assert isinstance(passed_port, int)
+
+
+_MYSQL_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql"
+_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"
+
+
+@frozen
+class _CloudConnect:
+ getaddrinfo: MagicMock
+ create_connection: MagicMock
+ pymysql_connect: MagicMock
+
+
+class TestMySQLConnectDialsOnlyValidatedAddresses:
+ @contextmanager
+ def _connect_on_cloud(self, *addresses: str, tunnel_host: str = "db.example.com") -> Iterator[_CloudConnect]:
+ with (
+ override_settings(CLOUD_DEPLOYMENT="US"),
+ patch(f"{_MYSQL_MODULE}.open_ssh_tunnel") as tunnel_mock,
+ patch(f"{_MIXINS_MODULE}.settings") as mock_settings,
+ patch(
+ "posthog.psycopg_helpers.socket.getaddrinfo", return_value=addrinfo(3306, *addresses)
+ ) as getaddrinfo_mock,
+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=True),
+ patch(f"{_MYSQL_MODULE}.socket.create_connection") as create_connection_mock,
+ patch(f"{_MYSQL_MODULE}.pymysql.connect") as pymysql_connect_mock,
+ patch(f"{_MYSQL_MODULE}.time.sleep"),
+ ):
+ tunnel_mock.return_value.__enter__.return_value = (tunnel_host, 3306)
+ mock_settings.TEST = False
+ mock_settings.DEBUG = False
+ mock_settings.E2E_TESTING = False
+ yield _CloudConnect(
+ getaddrinfo=getaddrinfo_mock,
+ create_connection=create_connection_mock,
+ pymysql_connect=pymysql_connect_mock,
+ )
+
+ def test_dials_the_validated_address_and_keeps_the_hostname_for_tls(self) -> None:
+ with self._connect_on_cloud("52.1.2.3") as cloud:
+ with MySQLImplementation().connect(_make_config(host="db.example.com"), team_id=999):
+ pass
+
+ cloud.create_connection.assert_called_once_with(("52.1.2.3", 3306), 10)
+ connect_kwargs = cloud.pymysql_connect.call_args.kwargs
+ assert connect_kwargs["host"] == "db.example.com"
+ assert connect_kwargs["defer_connect"] is True
+ cloud.pymysql_connect.return_value.connect.assert_called_once_with(sock=cloud.create_connection.return_value)
+
+ def test_an_internal_address_in_the_resolved_set_refuses_the_connect(self) -> None:
+ with self._connect_on_cloud("52.1.2.3", "10.0.0.5") as cloud:
+ with pytest.raises(Exception, match="Database host not allowed"):
+ with MySQLImplementation().connect(_make_config(host="db.example.com"), team_id=999):
+ pass
+
+ cloud.create_connection.assert_not_called()
+ cloud.pymysql_connect.assert_not_called()
+
+ def test_falls_over_to_the_next_validated_address(self) -> None:
+ with self._connect_on_cloud("52.1.2.3", "52.1.2.4") as cloud:
+ second_socket = MagicMock()
+ cloud.create_connection.side_effect = [OSError(111, "Connection refused"), second_socket]
+ with MySQLImplementation().connect(_make_config(host="db.example.com"), team_id=999):
+ pass
+
+ assert cloud.create_connection.call_args.args[0] == ("52.1.2.4", 3306)
+ cloud.pymysql_connect.return_value.connect.assert_called_once_with(sock=second_socket)
+
+ def test_every_address_failing_raises_the_error_pymysql_would_raise(self) -> None:
+ with self._connect_on_cloud("52.1.2.3") as cloud:
+ cloud.create_connection.side_effect = OSError(111, "Connection refused")
+ with pytest.raises(pymysql.err.OperationalError) as exc_info:
+ with MySQLImplementation().connect(_make_config(host="db.example.com"), team_id=999):
+ pass
+
+ assert exc_info.value.args[0] == 2003
+ assert "Can't connect to MySQL server on 'db.example.com'" in exc_info.value.args[1]
+
+ def test_a_tunnel_loopback_literal_connects_by_name_without_a_lookup(self) -> None:
+ with self._connect_on_cloud(tunnel_host="127.0.0.1") as cloud:
+ with MySQLImplementation().connect(_make_config(host="db.example.com"), team_id=999):
+ pass
+
+ cloud.getaddrinfo.assert_not_called()
+ cloud.create_connection.assert_not_called()
+ cloud.pymysql_connect.return_value.connect.assert_not_called()
+ assert cloud.pymysql_connect.call_args.kwargs["host"] == "127.0.0.1"
+
+ def test_the_team_reaches_the_host_policy(self) -> None:
+ with self._connect_on_cloud("10.0.0.5") as cloud:
+ with MySQLImplementation().connect(_make_config(host="db.example.com"), team_id=2):
+ pass
+
+ cloud.create_connection.assert_called_once_with(("10.0.0.5", 3306), 10)
+
+ def test_a_resolver_blip_is_retried_with_a_fresh_lookup(self) -> None:
+ with self._connect_on_cloud() as cloud:
+ cloud.getaddrinfo.side_effect = socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")
+ with pytest.raises(pymysql.err.OperationalError) as exc_info:
+ with MySQLImplementation().connect(_make_config(host="db.example.com"), team_id=999):
+ pass
+
+ assert exc_info.value.args[0] == 2003
+ assert cloud.getaddrinfo.call_count == _MAX_CONNECT_ATTEMPTS
+ cloud.create_connection.assert_not_called()
+
+ def test_a_reconnect_dials_a_freshly_validated_address(self) -> None:
+ with self._connect_on_cloud("52.1.2.3") as cloud:
+ connection = MagicMock(host="db.example.com", port=3306, connect_timeout=10)
+ _reconnect_pinned(connection, team_id=999)
+
+ cloud.create_connection.assert_called_once_with(("52.1.2.3", 3306), 10)
+ connection.connect.assert_called_once_with(sock=cloud.create_connection.return_value)
+
+ def test_a_reconnect_refuses_a_record_that_now_answers_private(self) -> None:
+ with self._connect_on_cloud("10.0.0.5") as cloud:
+ connection = MagicMock(host="db.example.com", port=3306, connect_timeout=10)
+ with pytest.raises(HostNotAllowedError):
+ _reconnect_pinned(connection, team_id=999)
+
+ cloud.create_connection.assert_not_called()
+ connection.connect.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py
index d1826fed27b6..5fddc3b212eb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py
@@ -32,12 +32,13 @@ class PlanetScaleMySQLImplementation(MySQLImplementation):
config: MySQLSourceConfig,
*,
read_timeout: int | None = None,
+ team_id: int | None = None,
) -> Iterator[pymysql.Connection]:
ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"
# PlanetScale has no SSH tunnel option, so this resolves to the configured host and
# port. It is reused for the shared connection logging that wraps every SQL source.
- with self._ssh_tunnel_endpoint(config) as (host, port):
+ with self._ssh_tunnel_endpoint(config, team_id) as (host, port):
kwargs: dict[str, Any] = {
"host": host,
# pymysql rejects a non-int port; config.port arrives as a string when the config
@@ -59,5 +60,7 @@ class PlanetScaleMySQLImplementation(MySQLImplementation):
}
if read_timeout is not None:
kwargs["read_timeout"] = read_timeout
- with _connect_with_transient_retry(kwargs) as conn:
+ # `ssl_verify_identity` checks the certificate against `host`, which the pinned socket
+ # leaves as the hostname.
+ with _connect_with_transient_retry(kwargs, team_id) as conn:
yield conn
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 6df1a933f965..a7a60c556b5e 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
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
FieldType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ HOST_RESOLUTION_EXHAUSTED_MESSAGE,
HostNotAllowedError,
SSHTunnelMixin,
TemporaryHostResolutionError,
@@ -294,11 +295,6 @@ _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. "
@@ -1076,8 +1072,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,
+ HOST_RESOLUTION_TIMEOUT_ERROR: HOST_RESOLUTION_EXHAUSTED_MESSAGE,
+ TEMPORARY_HOST_RESOLUTION_ERROR: HOST_RESOLUTION_EXHAUSTED_MESSAGE,
}
def reconcile_schema_metadata(
diff --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.py
index 10188b05a012..3ad05de93ba6 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
@@ -51,6 +51,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
ColumnTypeCategory,
ValidatedRowFilter,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import addrinfo
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (
ForeignServerUnreachableError,
@@ -2619,11 +2620,6 @@ class _ProductionCloud:
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 = (
@@ -2664,7 +2660,7 @@ class TestConnectToPostgresDialsOnlyValidatedAddresses:
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 self._production_cloud(addrinfo(5432, *addresses)) as cloud:
with pytest.raises(Exception, match="Database host not allowed"):
self._connect(team_id=999)
@@ -2685,21 +2681,21 @@ class TestConnectToPostgresDialsOnlyValidatedAddresses:
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:
+ with self._production_cloud(addrinfo(5432, "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:
+ with self._production_cloud(addrinfo(5432, "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 self._production_cloud(addrinfo(5432, "10.0.0.5")) as cloud:
with pytest.raises(Exception, match="Database host not allowed"):
self._connect()
@@ -2721,7 +2717,7 @@ class TestConnectToPostgresDialsOnlyValidatedAddresses:
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 self._production_cloud(addrinfo(5432, "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)
@@ -2729,7 +2725,7 @@ class TestConnectToPostgresDialsOnlyValidatedAddresses:
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:
+ with self._production_cloud(addrinfo(5432, "127.0.0.1")) as cloud:
self._connect(host="127.0.0.1", team_id=999)
cloud.getaddrinfo.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index bec8806dd81e..add0b88eab98 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -41,7 +41,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers
incremental_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,
@@ -822,23 +825,30 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
# ------------------------------------------------------------------
@contextmanager
- def connect(self, config: RedshiftSourceConfig) -> Iterator[psycopg.Connection]:
+ def connect(self, config: RedshiftSourceConfig, *, team_id: int | None = None) -> Iterator[psycopg.Connection]:
"""Open a psycopg connection for the duration of the context.
Opens the SSH tunnel (if configured) and connects with the
Redshift-wide SSL conventions in one place — every listing
method takes the resulting connection, so discovery against an
SSH-tunneled cluster only opens the tunnel once.
+
+ Redshift speaks the Postgres wire protocol through the same libpq, so it dials the
+ addresses it validated the same way: `pinned_host_kwargs` resolves the host once, checks
+ that answer against the host policy, and pins it through the `host`/`hostaddr` pair.
"""
- with open_ssh_tunnel(config) as (host, port):
- with psycopg.connect(
- host=host,
- port=port,
- dbname=config.database,
- user=config.user,
- password=config.password,
+ with open_ssh_tunnel(config, team_id) as (host, port):
+ connect_kwargs: dict[str, Any] = {
+ "port": port,
+ "dbname": config.database,
+ "user": config.user,
+ "password": config.password,
**_REDSHIFT_CONNECT_OPTS,
- ) as conn:
+ **pinned_host_kwargs(
+ host, port=port, connect_timeout=_REDSHIFT_CONNECT_OPTS["connect_timeout"], team_id=team_id
+ ),
+ }
+ with psycopg.connect(**connect_kwargs) as conn:
conn.adapters.register_loader("date", SafeDateLoader)
yield conn
@@ -1536,7 +1546,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
row_filters = inputs.row_filters
def _discover_and_probe() -> RedshiftTableSetup:
- with self.connect(config) as connection:
+ with self.connect(config, team_id=inputs.team_id) as connection:
# Autocommit so each best-effort discovery probe runs in its own transaction. A probe
# that fails — a permission error, an EXPLAIN the cluster rejects, a cancelled COUNT(*) —
# otherwise leaves the shared transaction aborted (INERROR), and every probe after it
@@ -1654,7 +1664,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
def get_rows() -> Iterator[Any]:
arrow_schema = table.to_arrow_schema()
- with self.connect(config) as streaming_connection:
+ with self.connect(config, team_id=inputs.team_id) as streaming_connection:
streaming_connection.adapters.register_loader("json", JsonAsStringLoader)
query = _build_query(
schema,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py
index 7018f7b89207..327be1f6d441 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py
@@ -14,12 +14,16 @@ from posthog.schema import (
)
from posthog.exceptions_capture import capture_exception
+from posthog.psycopg_helpers import HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERROR
from products.data_warehouse.backend.facade.api import reconcile_redshift_schemas
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ HOST_RESOLUTION_EXHAUSTED_MESSAGE,
+ HostNotAllowedError,
SSHTunnelMixin,
+ TemporaryHostResolutionError,
ValidateDatabaseHostMixin,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
@@ -157,6 +161,14 @@ class RedshiftSource(SQLSource[RedshiftSourceConfig], SSHTunnelMixin, ValidateDa
),
)
+ def get_retryable_errors(self) -> set[str]:
+ # 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.
+ return {HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERROR}
+
+ def get_retry_exhausted_errors(self) -> dict[str, str]:
+ return dict.fromkeys(self.get_retryable_errors(), HOST_RESOLUTION_EXHAUSTED_MESSAGE)
+
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
**self.default_non_retryable_errors(),
@@ -225,6 +237,10 @@ class RedshiftSource(SQLSource[RedshiftSourceConfig], SSHTunnelMixin, ValidateDa
try:
self.get_schemas(config, team_id, api_version=api_version)
+ except (HostNotAllowedError, TemporaryHostResolutionError) as e:
+ # The host policy refused the host, or its lookup never answered. Both carry their own
+ # user-facing wording and neither is a PostHog defect, so they are not captured.
+ return False, str(e)
except OperationalError as e:
error_msg = " ".join(str(n) for n in e.args)
for key, value in RedshiftErrors.items():
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
index 12774276bd55..baf5199d8286 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -1,22 +1,33 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import date
import pytest
from unittest.mock import MagicMock, call, patch
+from django.test import override_settings
+
import psycopg
import pyarrow as pa
from psycopg import sql
from psycopg.pq import TransactionStatus
from sshtunnel import BaseSSHTunnelForwarderError
+from posthog.psycopg_helpers import HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERROR
+
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
TemporaryFileSizeExceedsLimitException,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ HostNotAllowedError,
+ TemporaryHostResolutionError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import Table, TableStats
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ColumnTypeCategory,
ValidatedRowFilter,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import addrinfo
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.redshift import (
RedshiftSourceConfig,
@@ -1242,6 +1253,16 @@ class TestRedshiftSourceNonRetryableErrors:
is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
assert is_non_retryable
+ @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, error_msg):
+ source = RedshiftSource()
+ assert any(pattern in error_msg for pattern in source.get_retryable_errors())
+ assert not any(pattern in error_msg for pattern in source.get_non_retryable_errors())
+ assert source.get_retryable_errors() == set(source.get_retry_exhausted_errors().keys())
+
def test_query_timeout_raw_message_is_non_retryable(self):
# Mirrors the `InsufficientPrivilege` case above: the activity-level check matches raw
# `str(exception)`, which for `QueryTimeoutException` is just the message with no class
@@ -1280,6 +1301,29 @@ class TestRedshiftValidateCredentials:
assert error is not None and "does not support SSL" in error
capture.assert_not_called()
+ @pytest.mark.parametrize(
+ "refusal,expected_fragment",
+ [
+ (HostNotAllowedError("Database host not allowed: resolves to a private address"), "not allowed"),
+ (TemporaryHostResolutionError("db.example.com"), "Try again in a moment"),
+ ],
+ )
+ def test_a_host_the_policy_refuses_is_returned_without_capturing(self, mocker, refusal, expected_fragment):
+ config = _make_config()
+ source = RedshiftSource()
+ mocker.patch.object(source, "ssh_tunnel_is_valid", return_value=(True, None))
+ mocker.patch.object(source, "is_database_host_valid", return_value=(True, None))
+ mocker.patch.object(source, "get_schemas", side_effect=refusal)
+ capture = mocker.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.source.capture_exception"
+ )
+
+ ok, error = source.validate_credentials(config, team_id=1)
+
+ assert ok is False
+ assert error is not None and expected_fragment in error
+ capture.assert_not_called()
+
def test_ssh_gateway_session_error_maps_to_actionable_message(self, mocker):
# sshtunnel's raw "Could not establish session to SSH gateway" is meaningless to the user;
# it must be replaced with concrete guidance rather than surfaced verbatim.
@@ -1622,3 +1666,44 @@ class TestGetConnectionMetadata:
metadata = RedshiftSource().get_connection_metadata(_make_config(schema=schema), team_id=1)
assert metadata == {"engine": "redshift", "database": "dev", "schema": expected_schema}
+
+
+_REDSHIFT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift"
+
+
+class TestRedshiftConnectDialsOnlyValidatedAddresses:
+ @contextmanager
+ def _production_cloud(self, *addresses: str) -> Iterator[MagicMock]:
+ with (
+ override_settings(CLOUD_DEPLOYMENT="US"),
+ patch(f"{_REDSHIFT_MODULE}.open_ssh_tunnel") as tunnel_mock,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.settings"
+ ) as mock_settings,
+ patch("posthog.psycopg_helpers.socket.getaddrinfo", return_value=addrinfo(5439, *addresses)),
+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=True),
+ patch(f"{_REDSHIFT_MODULE}.psycopg.connect") as connect_mock,
+ ):
+ tunnel_mock.return_value.__enter__.return_value = ("db.example.com", 5439)
+ mock_settings.TEST = False
+ mock_settings.DEBUG = False
+ mock_settings.E2E_TESTING = False
+ connect_mock.return_value.__enter__.return_value = MagicMock()
+ yield connect_mock
+
+ def test_a_public_set_is_dialed_pinned_with_the_hostname_kept(self) -> None:
+ with self._production_cloud("52.1.2.3", "52.1.2.4") as connect_mock:
+ with RedshiftImplementation().connect(_make_config(), team_id=999):
+ pass
+
+ kwargs = connect_mock.call_args.kwargs
+ assert kwargs["host"] == "db.example.com,db.example.com"
+ assert kwargs["hostaddr"] == "52.1.2.3,52.1.2.4"
+ assert kwargs["port"] == 5439
+
+ def test_the_team_reaches_the_host_policy(self) -> None:
+ with self._production_cloud("10.0.0.5") as connect_mock:
+ with RedshiftImplementation().connect(_make_config(), team_id=2):
+ pass
+
+ assert connect_mock.call_args.kwargs["hostaddr"] == "10.0.0.5"
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 c84edf50b1b1..8262b30c6882 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
@@ -237,6 +237,8 @@ class SnowflakeImplementation(
def connect(
self,
config: SnowflakeSourceConfig,
+ *,
+ team_id: int | None = None,
) -> Iterator[snowflake.connector.SnowflakeConnection]:
"""Open a Snowflake connection for the duration of the context.