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(data-warehouse): check SSL support when setting up a Postgres source (#95721)

Tom Owers0f536ee070e2
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index d9d3a108277d..7d2617c074d5 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -76,6 +76,7 @@ _LAZY = {
"SSL_REQUIRED_AFTER_DATE": "sources.postgres.postgres",
"_get_sslmode": "sources.postgres.postgres",
"get_primary_key_columns": "sources.postgres.postgres",
+ "new_source_requires_ssl": "sources.postgres.postgres",
"source_requires_ssl": "sources.postgres.postgres",
"PostgresSource": "sources.postgres.source",
"RedshiftSource": "sources.redshift.source",
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index c81902e875d6..d309908c4079 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -154,6 +154,7 @@ from products.warehouse_sources.backend.facade.source_management import (
filter_integration_accounts,
get_cdc_adapter,
get_primary_key_columns,
+ new_source_requires_ssl,
purge_buffer_prefix,
repair_cdc_source,
source_requires_ssl,
@@ -3432,7 +3433,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
try:
if isinstance(source, (PostgresSource, MySQLSource)):
credentials_valid, credentials_error = source.validate_credentials_for_access_method(
- cast(Any, source_config), self.team_id, access_method
+ cast(Any, source_config),
+ self.team_id,
+ access_method,
+ require_ssl=new_source_requires_ssl(source_config),
)
elif isinstance(source, CustomSource):
# Schema discovery for an as-yet-uncreated source: an integration-backed manifest may only use
@@ -3909,7 +3913,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
try:
if isinstance(source, (PostgresSource, MySQLSource)):
credentials_valid, credentials_error = source.validate_credentials_for_access_method(
- cast(Any, source_config), self.team_id, access_method
+ cast(Any, source_config),
+ self.team_id,
+ access_method,
+ require_ssl=new_source_requires_ssl(source_config),
)
elif isinstance(source, CustomSource):
# Create-time validation for an integration-backed manifest may only use an unbound integration
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 7774ccc4f801..b2ed7c37721b 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
@@ -435,8 +435,15 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase
return get_mysql_connection_metadata(conn, database=config.database)
def validate_credentials(
- self, config: MySQLSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
+ self,
+ config: MySQLSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ require_ssl: bool = False,
) -> tuple[bool, str | None]:
+ # `require_ssl` keeps signature parity with Postgres; MySQL SSL is governed by
+ # `config.using_ssl` inside `connect`.
is_ssh_valid, ssh_valid_errors = self.ssh_tunnel_is_valid(config, team_id)
if not is_ssh_valid:
return is_ssh_valid, ssh_valid_errors
@@ -504,5 +511,8 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase
access_method: str,
schema_name: Optional[str] = None,
api_version: str | None = None,
+ require_ssl: bool = False,
) -> tuple[bool, str | None]:
- return self.validate_credentials(config, team_id, schema_name=schema_name, api_version=api_version)
+ return self.validate_credentials(
+ config, team_id, schema_name=schema_name, api_version=api_version, require_ssl=require_ssl
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/source.py
index 08dd61078ac5..efa9a8e787bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/source.py
@@ -197,6 +197,7 @@ class PlanetScaleMySQLSource(MySQLSource):
team_id: int,
schema_name: Optional[str] = None,
api_version: str | None = None,
+ require_ssl: bool = False,
) -> tuple[bool, str | None]:
host = config.host or ""
if "://" in host:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py
index 7f9fa49ac258..ea4770fd1eff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_postgres/source.py
@@ -146,11 +146,14 @@ class PlanetScalePostgresSource(PostgresSource):
team_id: int,
schema_name: str | None = None,
api_version: str | None = None,
+ require_ssl: bool = False,
) -> tuple[bool, str | None]:
if _PLANETSCALE_WEB_HOST_RE.search(_bare_host(config.host or "")):
return False, _HOST_IS_DASHBOARD_ERROR
- return super().validate_credentials(config, team_id, schema_name=schema_name, api_version=api_version)
+ return super().validate_credentials(
+ config, team_id, schema_name=schema_name, api_version=api_version, require_ssl=require_ssl
+ )
def check_cdc_prerequisites(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 15b8591f0538..d109443281de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -163,16 +163,13 @@ _MAX_INITIAL_READ_DROP_RETRIES = 5
_MAX_INITIAL_READ_LOCK_TIMEOUT_RETRIES = 5
-def source_requires_ssl(source: ExternalDataSource, source_config: Any = None) -> bool:
- """Return whether this source must connect over SSL/TLS.
+def new_source_requires_ssl(source_config: Any = None) -> bool:
+ """Return whether a source created now must connect over SSL/TLS.
- SSL is required for sources created after the cutoff date, unless the
- user has explicitly opted out via the ``require_tls`` toggle on an active
- SSH tunnel.
+ A source created now is always past the cutoff date, so only the SSH tunnel opt-out can
+ relax the requirement. Shares that branch with `source_requires_ssl` so the credential
+ check the wizard runs cannot drift from the connection the sync later opens.
"""
- if source.created_at < SSL_REQUIRED_AFTER_DATE:
- return False
-
if source_config is not None:
# Not every source config carries an SSH tunnel (e.g. Snowflake), and the param is typed
# `Any` — only the tunnel opt-out can relax the SSL requirement, so its absence means "required".
@@ -183,6 +180,19 @@ def source_requires_ssl(source: ExternalDataSource, source_config: Any = None) -
return True
+def source_requires_ssl(source: ExternalDataSource, source_config: Any = None) -> bool:
+ """Return whether this source must connect over SSL/TLS.
+
+ SSL is required for sources created after the cutoff date, unless the
+ user has explicitly opted out via the ``require_tls`` toggle on an active
+ SSH tunnel.
+ """
+ if source.created_at < SSL_REQUIRED_AFTER_DATE:
+ return False
+
+ return new_source_requires_ssl(source_config)
+
+
class SSLRequiredError(Exception):
"""Raised when SSL/TLS is required but the database does not support it."""
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 7a7d0be2cacd..ce35b101457c 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
@@ -250,6 +250,14 @@ _SSH_GATEWAY_UNREACHABLE_MESSAGE = (
"the bastion is running, and that PostHog's IP addresses are allowed through its firewall."
)
+# A source past the SSL cutoff connects with sslmode=require, so a server built without SSL support
+# fails the moment the sync — or a direct query — opens its connection. An SSH tunnel with
+# `require_tls` off is the supported way to reach such a server.
+_SSL_UNSUPPORTED_ERROR = (
+ "Your database doesn't support the encrypted connection PostHog requires. Enable SSL/TLS on "
+ "your database server, or connect through an SSH tunnel instead."
+)
+
@SourceRegistry.register
class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
@@ -1271,6 +1279,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
team_id: int,
schema_name: Optional[str] = None,
api_version: str | None = None,
+ require_ssl: bool = False,
) -> tuple[bool, str | None]:
is_ssh_valid, ssh_valid_errors = self.ssh_tunnel_is_valid(config, team_id)
if not is_ssh_valid:
@@ -1296,8 +1305,21 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
return valid_host, host_errors
try:
- self.get_schemas(config, team_id, names=[schema_name] if schema_name else None, api_version=api_version)
+ self.get_schemas(
+ config,
+ team_id,
+ names=[schema_name] if schema_name else None,
+ api_version=api_version,
+ require_ssl=require_ssl,
+ )
except SSLRequiredError as e:
+ # Real callers only raise this when `require_ssl` is set (see `_connect_to_postgres`),
+ # so the setup-time actionable copy belongs here. A caller that explicitly probed with
+ # `require_ssl=False` and still got this exception (only reachable in tests that mock
+ # the connection directly) keeps the exception's own wording rather than claiming an SSH
+ # tunnel opt-out that was never relevant to the probe just made.
+ if require_ssl:
+ return False, _SSL_UNSUPPORTED_ERROR
return False, str(e)
except OperationalError as e:
error_msg = " ".join(str(n) for n in e.args)
@@ -1329,8 +1351,11 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
access_method: str,
schema_name: Optional[str] = None,
api_version: str | None = None,
+ require_ssl: bool = False,
) -> tuple[bool, str | None]:
- return self.validate_credentials(config, team_id, schema_name=schema_name, api_version=api_version)
+ return self.validate_credentials(
+ config, team_id, schema_name=schema_name, api_version=api_version, require_ssl=require_ssl
+ )
def get_connection_metadata(
self, config: PostgresSourceConfig, team_id: int, require_ssl: bool = False
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 763d2d758f4f..97c7da79bbb2 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
@@ -134,6 +134,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
get_leading_index_columns,
get_postgres_row_count,
get_schemas,
+ new_source_requires_ssl,
postgres_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
@@ -3980,7 +3981,7 @@ class TestPostgresSourceForPipelineSchemaResolution:
assert valid is True
assert error is None
- validate_credentials.assert_called_once_with(config, 1, schema_name=None, api_version=None)
+ validate_credentials.assert_called_once_with(config, 1, schema_name=None, api_version=None, require_ssl=False)
def test_validate_credentials_for_access_method_allows_blank_schema_for_direct_queries(self, source):
config = source.parse_config(
@@ -3999,7 +4000,38 @@ class TestPostgresSourceForPipelineSchemaResolution:
assert valid is True
assert error is None
- validate_credentials.assert_called_once_with(config, 1, schema_name=None, api_version=None)
+ validate_credentials.assert_called_once_with(config, 1, schema_name=None, api_version=None, require_ssl=False)
+
+
+class TestNewSourceRequiresSSL:
+ def _config(self, ssh_tunnel: dict | None = None):
+ return PostgresSource().parse_config(
+ {
+ "host": "localhost",
+ "port": 5432,
+ "database": "postgres",
+ "user": "postgres",
+ "password": "postgres",
+ "schema": "public",
+ **({"ssh_tunnel": ssh_tunnel} if ssh_tunnel else {}),
+ }
+ )
+
+ def test_plain_connection_requires_ssl(self):
+ assert new_source_requires_ssl(self._config()) is True
+
+ @pytest.mark.parametrize("require_tls,expected", [(True, True), (False, False)])
+ def test_ssh_tunnel_can_opt_out_of_ssl(self, require_tls, expected):
+ config = self._config(
+ {
+ "enabled": True,
+ "host": "bastion.example.com",
+ "port": "22",
+ "auth": {"selection": "password", "username": "tunnel", "password": "tunnel"},
+ "require_tls": {"enabled": require_tls},
+ }
+ )
+ assert new_source_requires_ssl(config) is expected
class TestValidateCredentialsErrorMapping:
@@ -4163,6 +4195,40 @@ class TestValidateCredentialsErrorMapping:
assert valid is False
assert error == expected
+ @pytest.mark.parametrize(
+ "require_ssl,expects_ssl_guidance",
+ [
+ # The wizard now probes with the same SSL requirement the sync will use, so a server
+ # built without SSL support is rejected during setup instead of at the first sync or
+ # direct query.
+ (True, True),
+ # Sources predating the SSL cutoff still connect permissively, so the same server keeps
+ # validating and the generic mapping applies.
+ (False, False),
+ ],
+ )
+ def test_unsupported_ssl_is_reported_while_setting_the_source_up(
+ self, source, config, require_ssl, expects_ssl_guidance
+ ):
+ connect_mock = mock.MagicMock(
+ side_effect=psycopg.OperationalError("server does not support SSL, but SSL was required")
+ )
+ with (
+ mock.patch.object(source, "ssh_tunnel_is_valid", return_value=(True, None)),
+ mock.patch.object(source, "is_database_host_valid", return_value=(True, None)),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ connect_mock,
+ ),
+ ):
+ valid, error = source.validate_credentials(config, team_id=1, require_ssl=require_ssl)
+
+ assert valid is False
+ assert error is not None
+ assert ("SSH tunnel" in error) is expects_ssl_guidance
+ # The raw libpq wording is debugging detail, not something the wizard should show.
+ assert "server does not support SSL" not in error
+
def test_ssh_gateway_session_error_maps_to_actionable_message(self, source, config):
# 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.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py
index 238ae9a0aa54..2028a834da4c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py
@@ -179,6 +179,7 @@ class SupabaseSource(PostgresSource):
team_id: int,
schema_name: Optional[str] = None,
api_version: str | None = None,
+ require_ssl: bool = False,
) -> tuple[bool, str | None]:
bare_host = _strip_host_scheme(config.host or "")
project_host = _SUPABASE_PROJECT_HOST_RE.match(bare_host)
@@ -200,7 +201,7 @@ class SupabaseSource(PostgresSource):
# failures (bad password, missing database, SSL) already have clear messages, and
# blaming them on IPv4 would misdirect the user.
is_direct_host = bool(_SUPABASE_DIRECT_HOST_RE.match((config.host or "").strip()))
- success, error = super().validate_credentials(config, team_id, schema_name=schema_name)
+ success, error = super().validate_credentials(config, team_id, schema_name=schema_name, require_ssl=require_ssl)
if not success and is_direct_host and error == _HOST_UNREACHABLE_ERROR:
return False, _SUPABASE_DIRECT_HOST_IPV4_HINT
return success, error
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 3e1da2462d13..75b4bc19503b 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -5054,6 +5054,30 @@ class TestExternalDataSource(APIBaseTest):
validate.assert_called_once()
self.assertEqual(validate.call_args.args[2], "direct")
+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")
+ def test_database_schema_postgres_requires_ssl_while_setting_the_source_up(self, mock_get_source):
+ source = PostgresSource()
+ mock_get_source.return_value = source
+
+ with patch.object(source, "validate_credentials_for_access_method", return_value=(True, None)) as validate:
+ self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/database_schema/",
+ data={
+ "source_type": "Postgres",
+ "host": "localhost",
+ "port": 5432,
+ "database": "app",
+ "user": "user",
+ "password": "pass",
+ "schema": "public",
+ },
+ )
+
+ # A source created now syncs over SSL, so the setup probe has to hold the connection to the
+ # same requirement — otherwise a server without SSL support only fails after setup reports
+ # success.
+ self.assertIs(validate.call_args.kwargs["require_ssl"], True)
+
@parameterized.expand(
[
# (test name, source_type, supports_xmin, expected_xmin_available)