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(warehouse-sources): let MySQL verify the server certificate (#98656)

Daniel RC88b220fc9602
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mysql.py
index 46de9a263601..76406ed725e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mysql.py
@@ -14,4 +14,5 @@ class MySQLSourceConfig(config.Config):
port: int = config.value(converter=int)
schema: str | None = None
using_ssl: bool = config.value(default=config.str_to_bool("true"), converter=config.str_to_bool)
+ verify_server_certificate: bool = config.value(default=config.str_to_bool("false"), converter=config.str_to_bool)
ssh_tunnel: SSHTunnelConfig | None = None
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 e24d9ce835c1..cfa745f37ec8 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
@@ -31,7 +31,7 @@ import pyarrow as pa
import pymysql
import structlog
import pymysql.converters
-from pymysql.constants import CR, FIELD_TYPE
+from pymysql.constants import CLIENT, CR, FIELD_TYPE
from pymysql.cursors import Cursor, SSCursor
from structlog.types import FilteringBoundLogger
@@ -688,15 +688,43 @@ def _reconnect_pinned(connection: pymysql.Connection, team_id: int | None) -> No
connection.connect(sock=_pinned_socket(connection.host, connection.port, connection.connect_timeout, team_id))
+class _TLSRequiredConnection(pymysql.Connection):
+ """A connection that refuses to authenticate when the server offers no TLS.
+
+ pymysql wraps the socket only when the server advertises the TLS capability, and that check
+ has no else branch, so a missing or stripped flag is served in plaintext and raises nothing.
+ Refusing here stops the credentials before they cross that connection, and covers every
+ reconnect as well: `Connection.connect()` runs this method each time it reopens the socket.
+ """
+
+ def _request_authentication(self) -> None:
+ # The stubs declare neither the handshake hook nor the capability flags it reads.
+ offers_tls = bool(self.server_capabilities & CLIENT.SSL) # type: ignore[attr-defined]
+ if self.ssl and not offers_tls:
+ raise pymysql.err.OperationalError(
+ CR.CR_SSL_CONNECTION_ERROR,
+ "The MySQL server did not offer a TLS connection. Turn off certificate "
+ "verification for this source, or enable TLS on the server.",
+ )
+ super()._request_authentication() # type: ignore[misc]
+
+
+def _new_connection(kwargs: dict[str, Any], **extra: Any) -> pymysql.Connection:
+ """Build the connection, refusing plaintext when this source verifies the certificate."""
+ if kwargs.get("ssl_verify_cert"):
+ return _TLSRequiredConnection(**kwargs, **extra)
+ return pymysql.connect(**kwargs, **extra)
+
+
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)
+ return _new_connection(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 = _new_connection(kwargs, defer_connect=True)
connection.connect(sock=sock)
return connection
@@ -1052,10 +1080,18 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
so multi-GB filesorts don't drop on middlebox timeouts before the
first rows are ready.
"""
+ verify_certificate = config.verify_server_certificate
ssl_ca: str | None = None
- if config.using_ssl:
+ # Verification implies TLS, so a user who asks us to check the certificate gets the
+ # encrypted connection that check needs, whatever `using_ssl` says.
+ if config.using_ssl or verify_certificate:
ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"
+ # The tunnel presents the database on a loopback address, so the certificate's hostname
+ # cannot match the address pymysql dials. The chain check still applies there.
+ tunnel = config.ssh_tunnel
+ verify_hostname = verify_certificate and not (tunnel is not None and tunnel.enabled)
+
with self._ssh_tunnel_endpoint(config, team_id) as (host, port):
kwargs: dict[str, Any] = {
"host": host,
@@ -1067,6 +1103,10 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
"password": config.password,
"connect_timeout": 10,
"ssl_ca": ssl_ca,
+ # pymysql resolves `ssl_ca` on its own to `verify_mode=CERT_NONE`, so only an
+ # explicit True verifies. None leaves that prior behavior untouched.
+ "ssl_verify_cert": True if verify_certificate else None,
+ "ssl_verify_identity": True if verify_hostname else None,
"conv": _MYSQL_SAFE_CONVERSIONS,
"init_command": "SET workload = 'OLAP';" if host.endswith("psdb.cloud") else None,
}
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 b2e2377fe46f..5837879427d9 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
@@ -179,6 +179,23 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase
SourceFieldSelectConfigOption(label="No", value="false"),
],
),
+ SourceFieldSelectConfig(
+ name="verify_server_certificate",
+ label="Verify the server certificate?",
+ required=True,
+ defaultValue="false",
+ converter=SourceFieldSelectConfigConverter.STR_TO_BOOL,
+ caption=(
+ "Check that your database's TLS certificate comes from a trusted authority. "
+ "A self-signed certificate or a private authority does not pass, so leave this off "
+ "if you use one. Through an SSH tunnel we check the certificate chain but not the "
+ "hostname, because the tunnel presents your database on a local address."
+ ),
+ options=[
+ SourceFieldSelectConfigOption(label="Yes", value="true"),
+ SourceFieldSelectConfigOption(label="No", value="false"),
+ ],
+ ),
SourceFieldSSHTunnelConfig(name="ssh_tunnel", label="Use SSH tunnel?"),
],
),
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 3239c39ea510..350717690d57 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
@@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
import pymysql
+from pymysql.constants import CLIENT
from sshtunnel import BaseSSHTunnelForwarderError
from posthog.dataclasses import frozen
@@ -53,6 +54,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq
_safe_convert_date,
_safe_convert_datetime,
_sanitize_identifier,
+ _TLSRequiredConnection,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.source import (
_INVALID_CREDENTIALS_ERROR,
@@ -2798,3 +2800,69 @@ class TestMySQLConnectDialsOnlyValidatedAddresses:
cloud.create_connection.assert_not_called()
connection.connect.assert_not_called()
+
+
+@contextmanager
+def _loopback_tunnel() -> Iterator[tuple[str, int]]:
+ yield "127.0.0.1", 13306
+
+
+class TestConnectCertificateVerification:
+ @staticmethod
+ def _connect(mocker, *, using_ssl: str, verify: str, tunneled: bool) -> tuple[dict, bool]:
+ connection = MagicMock()
+ plain = mocker.patch(f"{_MYSQL_MODULE}.pymysql.connect", return_value=connection)
+ refusing = mocker.patch(f"{_MYSQL_MODULE}._TLSRequiredConnection", return_value=connection)
+ overrides: dict = {"using_ssl": using_ssl, "verify_server_certificate": verify}
+ if tunneled:
+ overrides["ssh_tunnel"] = {"enabled": "true", "host": "bastion.example.com", "port": "22"}
+ mocker.patch(f"{_MYSQL_MODULE}.open_ssh_tunnel", return_value=_loopback_tunnel())
+
+ with MySQLImplementation().connect(_make_config(**overrides)):
+ pass
+
+ used = refusing if refusing.called else plain
+ return used.call_args.kwargs, refusing.called
+
+ @pytest.mark.parametrize(
+ "using_ssl,verify,tunneled,expected_ca,expected_cert,expected_identity",
+ [
+ ("true", "false", False, True, None, None),
+ ("false", "false", False, False, None, None),
+ ("true", "true", False, True, True, True),
+ ("true", "true", True, True, True, None),
+ ("false", "true", False, True, True, True),
+ ],
+ )
+ def test_verification_kwargs(
+ self, mocker, using_ssl, verify, tunneled, expected_ca, expected_cert, expected_identity
+ ):
+ # pymysql resolves `ssl_ca` on its own to `verify_mode=CERT_NONE`, so a default that stopped
+ # being None would start verifying every existing source. `ssl_verify_identity` through the
+ # tunnel would check the certificate against the loopback address the forwarder binds.
+ kwargs, refuses_plaintext = self._connect(mocker, using_ssl=using_ssl, verify=verify, tunneled=tunneled)
+
+ assert (kwargs["ssl_ca"] is not None) is expected_ca
+ assert kwargs["ssl_verify_cert"] is expected_cert
+ assert kwargs["ssl_verify_identity"] is expected_identity
+ assert refuses_plaintext is (expected_cert is True)
+
+ @pytest.mark.parametrize("capabilities,refused", [(0, True), (CLIENT.SSL, False)])
+ def test_authentication_against_a_server_that_advertises_tls_or_not(self, mocker, capabilities, refused):
+ # The credentials go out during `_request_authentication`, and every reconnect runs it
+ # again, so refusing here is what keeps both off a plaintext connection.
+ # `ssl_verify_cert` is what the connect path passes, and it sets `ssl` without reading a CA
+ # file off disk, which no fixed path can promise across a developer machine and CI.
+ connection = _TLSRequiredConnection(
+ host="db.example.com", user="u", password="p", ssl_verify_cert=True, defer_connect=True
+ )
+ connection.server_capabilities = capabilities # type: ignore[attr-defined]
+ delegate = mocker.patch.object(pymysql.connections.Connection, "_request_authentication")
+
+ if refused:
+ with pytest.raises(pymysql.err.OperationalError, match="did not offer a TLS connection"):
+ connection._request_authentication()
+ delegate.assert_not_called()
+ else:
+ connection._request_authentication()
+ delegate.assert_called_once()