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): reject unusable postgres destination hosts on create (#112160)

Tom Owers5ff215c18f16
diff --git a/posthog/models/integration/postgres.py b/posthog/models/integration/postgres.py
index 81627719638e..b8a45edfcb43 100644
--- a/posthog/models/integration/postgres.py
+++ b/posthog/models/integration/postgres.py
@@ -3,10 +3,13 @@
from typing import ClassVar, Literal, NamedTuple
from posthog.models.user import User
+from posthog.psycopg_helpers import has_ipv6_route
+from posthog.security.postgres_hosts import ipv6_only_host_message
from posthog.security.url_validation import (
INVALID_HOST_MESSAGE,
UNREACHABLE_HOST_MESSAGE,
ShapeError,
+ resolve_host_ips,
validate_external_host,
)
@@ -89,6 +92,10 @@ class PostgreSQLServerIntegration:
except ValueError:
raise common.IntegrationError(UNREACHABLE_HOST_MESSAGE)
+ resolved_ips = resolve_host_ips(host)
+ if resolved_ips and all(ip.version == 6 for ip in resolved_ips) and not has_ipv6_route():
+ raise common.IntegrationError(ipv6_only_host_message(host))
+
port = config.get("port", None)
try:
port = int(port) # type: ignore
diff --git a/posthog/models/test/integration/test_postgres.py b/posthog/models/test/integration/test_postgres.py
index 0294b4b8d144..9f7dab023df7 100644
--- a/posthog/models/test/integration/test_postgres.py
+++ b/posthog/models/test/integration/test_postgres.py
@@ -1,6 +1,9 @@
"""Tests for direct-connection PostgreSQL-protocol integrations."""
+import ipaddress
+
from posthog.test.base import BaseTest
+from unittest.mock import patch
from parameterized import parameterized, parameterized_class
@@ -10,9 +13,14 @@ from posthog.models.integration import (
Authority,
Credentials,
Integration,
+ IntegrationError,
PostgreSQLIntegration,
RedshiftIntegration,
)
+from posthog.security.postgres_hosts import IPV6_ONLY_HOST_MESSAGE, SUPABASE_DIRECT_HOST_DESTINATION_HINT
+
+IPV4 = ipaddress.ip_address("203.0.113.10")
+IPV6 = ipaddress.ip_address("2001:db8::10")
@parameterized_class(
@@ -123,3 +131,43 @@ class TestPostgreSQLIntegrationModel(BaseTest):
assert integration.sensitive_config["password"] == "super-secret"
assert pq.integration_kind == self.integration_kind
+
+ @parameterized.expand(
+ [
+ ("ipv6_only_no_route", "db.example.com", {IPV6}, False, IPV6_ONLY_HOST_MESSAGE),
+ (
+ "several_ipv6_no_route",
+ "db.example.com",
+ {IPV6, ipaddress.ip_address("2001:db8::11")},
+ False,
+ IPV6_ONLY_HOST_MESSAGE,
+ ),
+ ("ipv6_only_with_route", "db.example.com", {IPV6}, True, None),
+ ("dual_stack_no_route", "db.example.com", {IPV4, IPV6}, False, None),
+ ("ipv4_only_no_route", "db.example.com", {IPV4}, False, None),
+ ("unresolved_is_left_to_host_validation", "db.example.com", set(), False, None),
+ (
+ "supabase_direct_host_gets_pooler_hint",
+ "db.abcdefghijklmnop.supabase.co",
+ {IPV6},
+ False,
+ SUPABASE_DIRECT_HOST_DESTINATION_HINT,
+ ),
+ ("supabase_direct_host_with_ipv4_add_on", "db.abcdefghijklmnop.supabase.co", {IPV4}, False, None),
+ ]
+ )
+ def test_integration_from_config_rejects_ipv6_only_hosts(self, _name, host, resolved, has_route, expected_error):
+ kwargs = {"team_id": self.team.pk, "host": host, "port": 5432, "user": "exporter", "password": "pw"}
+
+ with (
+ patch("posthog.models.integration.postgres.validate_external_host"),
+ patch("posthog.models.integration.postgres.resolve_host_ips", return_value=resolved),
+ patch("posthog.models.integration.postgres.has_ipv6_route", return_value=has_route),
+ ):
+ if expected_error is None:
+ integration = self.integration_cls.integration_from_config(**kwargs)
+ assert integration.config["host"] == host
+ else:
+ with self.assertRaises(IntegrationError) as raised:
+ self.integration_cls.integration_from_config(**kwargs)
+ assert str(raised.exception) == expected_error
diff --git a/posthog/security/postgres_hosts.py b/posthog/security/postgres_hosts.py
new file mode 100644
index 000000000000..8a7c1ec32929
--- /dev/null
+++ b/posthog/security/postgres_hosts.py
@@ -0,0 +1,31 @@
+import re
+
+# Supabase's direct connection host (`db.<ref>.supabase.co`) is IPv6-only and so is
+# unreachable from PostHog's IPv4 egress, unless the project has Supabase's IPv4 add-on.
+SUPABASE_DIRECT_HOST_RE = re.compile(r"^db\.[a-z0-9]+\.supabase\.co$", re.IGNORECASE)
+
+SUPABASE_DIRECT_HOST_IPV4_HINT = (
+ "Couldn't reach the Supabase direct host (db.<ref>.supabase.co). It's IPv6-only unless you "
+ "enable Supabase's IPv4 add-on (Project settings → Add-ons), which is required for change "
+ "data capture. For standard (non-CDC) syncs, use the Session pooler host instead "
+ "(aws-0-<region>.pooler.supabase.com) with username postgres.<project-ref>."
+)
+
+# Port 5432 is the Session pooler. Port 6543 is the Transaction pooler, which does not
+# support the transactions and DDL that a destination writer runs.
+SUPABASE_DIRECT_HOST_DESTINATION_HINT = (
+ "The Supabase direct host (db.<ref>.supabase.co) only accepts IPv6 connections, and PostHog "
+ "connects over IPv4. Use the Session pooler host instead (aws-0-<region>.pooler.supabase.com) "
+ "with port 5432 and username postgres.<project-ref>. Do not use the Transaction pooler on "
+ "port 6543."
+)
+
+IPV6_ONLY_HOST_MESSAGE = (
+ "This host only accepts IPv6 connections, and PostHog connects over IPv4. Use a host that has an IPv4 address."
+)
+
+
+def ipv6_only_host_message(host: str) -> str:
+ if SUPABASE_DIRECT_HOST_RE.match(host.strip()):
+ return SUPABASE_DIRECT_HOST_DESTINATION_HINT
+ return IPV6_ONLY_HOST_MESSAGE
diff --git a/products/warehouse_sources/backend/presentation/destination_connection_check.py b/products/warehouse_sources/backend/presentation/destination_connection_check.py
new file mode 100644
index 000000000000..d8951ca1b906
--- /dev/null
+++ b/products/warehouse_sources/backend/presentation/destination_connection_check.py
@@ -0,0 +1,143 @@
+import socket
+import tempfile
+import threading
+from collections.abc import Iterator
+from contextlib import contextmanager
+from enum import StrEnum
+
+import psycopg
+from psycopg import errors as pg_errors
+
+from posthog.models.integration import Integration, PostgreSQLIntegration
+from posthog.models.integration.postgres import MISSING_CERT_PATH
+
+from products.warehouse_sources.backend.facade.source_management import HostNotAllowedError, pinned_host_kwargs
+
+CONNECT_TIMEOUT_SECONDS = 5
+STATEMENT_TIMEOUT_MILLISECONDS = 5_000
+DEFAULT_DATABASE = "postgres"
+DEFAULT_SCHEMA = "public"
+
+
+class CheckFailure(StrEnum):
+ UNREACHABLE = "unreachable"
+ AUTHENTICATION = "authentication"
+ UNKNOWN_DATABASE = "unknown_database"
+ MISSING_PRIVILEGE = "missing_privilege"
+
+
+# The messages never include the driver's error text, because that text can echo the user name,
+# the host and parts of the connection string.
+FAILURE_MESSAGES: dict[CheckFailure, str] = {
+ CheckFailure.UNREACHABLE: (
+ "PostHog could not connect to this server. Check the host and port. Then check that the "
+ "server accepts connections from PostHog's IP addresses and has an IPv4 address."
+ ),
+ CheckFailure.AUTHENTICATION: "The server rejected the user name or password. Check them and try again.",
+ CheckFailure.UNKNOWN_DATABASE: "The database does not exist on this server. Check the database name and try again.",
+ CheckFailure.MISSING_PRIVILEGE: (
+ "The user cannot create tables in the schema. Grant the CREATE privilege on the schema, or "
+ "on the database if the schema does not exist yet, and try again."
+ ),
+}
+
+
+class DestinationConnectionCheckError(Exception):
+ def __init__(self, failure: CheckFailure) -> None:
+ super().__init__(FAILURE_MESSAGES[failure])
+ self.failure = failure
+
+
+@contextmanager
+def _ssl_root_cert_path(ssl_root_cert: str) -> Iterator[str]:
+ if ssl_root_cert in ("system", MISSING_CERT_PATH):
+ yield ssl_root_cert
+ return
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".crt") as cert_file:
+ cert_file.write(ssl_root_cert)
+ cert_file.flush()
+ yield cert_file.name
+
+
+@contextmanager
+def _query_deadline(connection: psycopg.Connection, timeout_seconds: float) -> Iterator[None]:
+ """Interrupt libpq's socket if an untrusted server ignores the statement timeout."""
+
+ def _interrupt() -> None:
+ try:
+ interrupt_socket = socket.socket(fileno=connection.pgconn.socket)
+ try:
+ interrupt_socket.shutdown(socket.SHUT_RDWR)
+ finally:
+ # The request thread owns libpq's descriptor and closes it after the query unwinds.
+ interrupt_socket.detach()
+ except Exception:
+ pass
+
+ timer = threading.Timer(timeout_seconds, _interrupt)
+ timer.daemon = True
+ timer.start()
+ try:
+ yield
+ finally:
+ timer.cancel()
+ # Wait for a callback that already started before the connection owner can close and reuse its descriptor.
+ timer.join()
+
+
+def check_postgres_destination(integration: Integration, config: dict[str, str] | None) -> None:
+ """Connect to the destination with a short timeout and check that a writer can create tables.
+
+ Raises `DestinationConnectionCheckError`. The writer runs `CREATE SCHEMA IF NOT EXISTS`, so a
+ schema that does not exist yet needs the CREATE privilege on the database instead.
+ """
+ config = config or {}
+ database = config.get("database") or DEFAULT_DATABASE
+ schema = config.get("schema") or DEFAULT_SCHEMA
+
+ postgres = PostgreSQLIntegration(integration)
+ credentials = postgres.credentials()
+ authority = postgres.authority()
+ tls = postgres.tls()
+
+ try:
+ host_kwargs = pinned_host_kwargs(
+ authority.host,
+ port=authority.port,
+ connect_timeout=CONNECT_TIMEOUT_SECONDS,
+ team_id=integration.team_id,
+ )
+ with _ssl_root_cert_path(tls.ssl_root_cert) as ssl_root_cert:
+ with psycopg.connect(
+ user=credentials.user,
+ password=credentials.password,
+ dbname=database,
+ port=authority.port,
+ sslmode=tls.ssl_mode,
+ sslrootcert=ssl_root_cert,
+ connect_timeout=CONNECT_TIMEOUT_SECONDS,
+ options=f"-c statement_timeout={STATEMENT_TIMEOUT_MILLISECONDS}",
+ autocommit=True,
+ **host_kwargs,
+ ) as connection:
+ with _query_deadline(connection, CONNECT_TIMEOUT_SECONDS), connection.cursor() as cursor:
+ cursor.execute("SELECT 1")
+ cursor.execute("SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = %s)", (schema,))
+ schema_row = cursor.fetchone()
+ if schema_row is not None and schema_row[0]:
+ cursor.execute("SELECT has_schema_privilege(current_user, %s, 'CREATE')", (schema,))
+ else:
+ cursor.execute("SELECT has_database_privilege(current_user, current_database(), 'CREATE')")
+ privilege_row = cursor.fetchone()
+ if privilege_row is None or not privilege_row[0]:
+ raise DestinationConnectionCheckError(CheckFailure.MISSING_PRIVILEGE)
+ except DestinationConnectionCheckError:
+ raise
+ except (pg_errors.InvalidPassword, pg_errors.InvalidAuthorizationSpecification) as error:
+ raise DestinationConnectionCheckError(CheckFailure.AUTHENTICATION) from error
+ except pg_errors.InvalidCatalogName as error:
+ raise DestinationConnectionCheckError(CheckFailure.UNKNOWN_DATABASE) from error
+ except pg_errors.InsufficientPrivilege as error:
+ raise DestinationConnectionCheckError(CheckFailure.MISSING_PRIVILEGE) from error
+ except (psycopg.Error, HostNotAllowedError) as error:
+ raise DestinationConnectionCheckError(CheckFailure.UNREACHABLE) from error
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_destination.py b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
index 8b9254837e26..e8980c6670ae 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_destination.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
@@ -20,6 +20,11 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSchema,
ExternalDataSource,
)
+from products.warehouse_sources.backend.presentation.destination_connection_check import (
+ CheckFailure,
+ DestinationConnectionCheckError,
+ check_postgres_destination,
+)
# Which Integration kind holds the credentials for each destination type. A type absent from
# this map needs no integration; the PostHog warehouse is the only such type today.
@@ -178,9 +183,24 @@ class ExternalDataDestinationSerializer(serializers.ModelSerializer):
if self.instance is not None:
self._reject_retargeting(attrs)
+ elif destination_type == ExternalDataDestination.Type.POSTGRES:
+ self._check_postgres_connection(integration, attrs.get("config"))
return attrs
+ # Only creation tests the connection. A destination keeps its server, database and schema
+ # after that (see `_reject_retargeting`), so there is nothing new to test on update.
+ def _check_postgres_connection(self, integration: Integration, config: dict[str, Any] | None) -> None:
+ try:
+ check_postgres_destination(integration, config)
+ except DestinationConnectionCheckError as error:
+ field = (
+ "config"
+ if error.failure in (CheckFailure.UNKNOWN_DATABASE, CheckFailure.MISSING_PRIVILEGE)
+ else "integration"
+ )
+ raise ValidationError({field: str(error)})
+
# Where a destination points is fixed once it exists. Everything already synced sits at the
# current server and schema, so repointing one strands that data and needs a full resync of
# every table that syncs there. A second destination is the supported way to write elsewhere.
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 ae7ded4cddb5..b89bafbc8519 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
@@ -1,6 +1,11 @@
import re
from typing import Optional
+from posthog.security.postgres_hosts import (
+ SUPABASE_DIRECT_HOST_IPV4_HINT as _SUPABASE_DIRECT_HOST_IPV4_HINT,
+ SUPABASE_DIRECT_HOST_RE as _SUPABASE_DIRECT_HOST_RE,
+)
+
from products.warehouse_sources.backend.facade.source_config import (
DataWarehouseSourceCategory,
ReleaseStatus,
@@ -22,11 +27,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.s
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
-# Supabase's direct connection host (`db.<ref>.supabase.co`) is IPv6-only and so is
-# unreachable from PostHog's IPv4 egress — by far the biggest cause of Supabase
-# connection failures. Users need the connection pooler host instead.
-_SUPABASE_DIRECT_HOST_RE = re.compile(r"^db\.[a-z0-9]+\.supabase\.co$", re.IGNORECASE)
-
# The Supabase dashboard shows `https://<ref>.supabase.co` as the "Project URL" — that's the
# REST/API endpoint, not a Postgres host. Pasting it (often with the scheme) into the host field
# just yields an opaque DNS failure, so detect it and point users at the actual database host.
@@ -62,13 +62,6 @@ _SUPABASE_POOLER_HOST_CAPTION = (
"the pooler."
)
-_SUPABASE_DIRECT_HOST_IPV4_HINT = (
- "Couldn't reach the Supabase direct host (db.<ref>.supabase.co). It's IPv6-only unless you "
- "enable Supabase's IPv4 add-on (Project settings → Add-ons), which is required for change "
- "data capture. For standard (non-CDC) syncs, use the Session pooler host instead "
- "(aws-0-<region>.pooler.supabase.com) with username postgres.<project-ref>."
-)
-
# Supabase Realtime stores messages in daily partitions of its internal `realtime.messages` table
# named `realtime.messages_YYYY_MM_DD`, and its retention job drops the old partitions. A sync that
# targets one of these dated partitions fails with `relation "realtime.messages_..." does not exist`
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
index 6608c7464fa5..a6a4a5b18e1a 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
@@ -22,6 +22,11 @@ from products.warehouse_sources.backend.models.external_data_destination import
)
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.presentation.destination_connection_check import (
+ FAILURE_MESSAGES,
+ CheckFailure,
+ DestinationConnectionCheckError,
+)
from products.warehouse_sources.backend.presentation.views.external_data_destination import (
ExternalDataDestinationViewSet,
)
@@ -31,6 +36,11 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
class DestinationAPITestBase(APIBaseTest):
def setUp(self) -> None:
super().setUp()
+ check_patcher = patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_destination.check_postgres_destination"
+ )
+ self.check_connection = check_patcher.start()
+ self.addCleanup(check_patcher.stop)
self.base = f"/api/projects/{self.team.pk}/external_data_destinations"
self.source = ExternalDataSource.objects.create(
team=self.team,
@@ -90,6 +100,58 @@ class TestExternalDataDestinationAPI(DestinationAPITestBase):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "integration" in response.json()["attr"]
+ @parameterized.expand(
+ [
+ (CheckFailure.UNREACHABLE, "integration"),
+ (CheckFailure.AUTHENTICATION, "integration"),
+ (CheckFailure.UNKNOWN_DATABASE, "config"),
+ (CheckFailure.MISSING_PRIVILEGE, "config"),
+ ]
+ )
+ def test_a_postgres_destination_that_fails_the_connection_test_is_not_created(
+ self, failure: CheckFailure, expected_field: str
+ ) -> None:
+ self.check_connection.side_effect = DestinationConnectionCheckError(failure)
+
+ response = self.client.post(
+ self.base,
+ {
+ "type": ExternalDataDestination.Type.POSTGRES,
+ "name": "unusable",
+ "integration": self._integration().pk,
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == expected_field
+ assert response.json()["detail"] == FAILURE_MESSAGES[failure]
+ assert not ExternalDataDestination.objects.for_team(self.team.pk).filter(name="unusable").exists()
+
+ def test_the_connection_test_gets_the_requested_config(self) -> None:
+ integration = self._integration()
+
+ response = self.client.post(
+ self.base,
+ {
+ "type": ExternalDataDestination.Type.POSTGRES,
+ "name": "with config",
+ "integration": integration.pk,
+ "config": {"database": "analytics", "schema": "posthog"},
+ },
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ self.check_connection.assert_called_once_with(integration, {"database": "analytics", "schema": "posthog"})
+
+ def test_updating_a_destination_does_not_run_the_connection_test(self) -> None:
+ destination = self._create_destination()
+ self.check_connection.reset_mock()
+
+ response = self.client.patch(f"{self.base}/{destination.id}", {"name": "renamed"})
+
+ assert response.status_code == status.HTTP_200_OK
+ self.check_connection.assert_not_called()
+
def test_the_posthog_warehouse_is_not_user_managed(self) -> None:
response = self.client.post(self.base, {"type": ExternalDataDestination.Type.POSTHOG_WAREHOUSE, "name": "mine"})
diff --git a/products/warehouse_sources/backend/tests/test_destination_connection_check.py b/products/warehouse_sources/backend/tests/test_destination_connection_check.py
new file mode 100644
index 000000000000..44343a170c9f
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_destination_connection_check.py
@@ -0,0 +1,199 @@
+import socket
+from contextlib import contextmanager
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import psycopg
+from parameterized import parameterized
+from psycopg import errors as pg_errors
+
+from posthog.models.integration import Integration
+
+from products.warehouse_sources.backend.presentation.destination_connection_check import (
+ FAILURE_MESSAGES,
+ CheckFailure,
+ DestinationConnectionCheckError,
+ _query_deadline,
+ check_postgres_destination,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedError
+
+MODULE = "products.warehouse_sources.backend.presentation.destination_connection_check"
+
+
+def _integration(**config_overrides: Any) -> Integration:
+ return Integration(
+ kind=Integration.IntegrationKind.POSTGRESQL,
+ config={"host": "db.example.com", "port": 5432, "user": "writer", "ssl_mode": "require", **config_overrides},
+ sensitive_config={"password": "hunter2"},
+ )
+
+
+def _connection(*, fetches: list[tuple[Any, ...] | None], execute_error: Exception | None = None) -> MagicMock:
+ cursor = MagicMock()
+ cursor.fetchone.side_effect = fetches
+ if execute_error is not None:
+ cursor.execute.side_effect = execute_error
+ connection = MagicMock()
+ connection.__enter__.return_value = connection
+ connection.cursor.return_value.__enter__.return_value = cursor
+ connection.cursor_mock = cursor
+ return connection
+
+
+def test_query_deadline_interrupts_the_connection_socket() -> None:
+ connection = MagicMock()
+ connection.pgconn.socket = 42
+ timer = MagicMock()
+
+ with (
+ patch(f"{MODULE}.threading.Timer", return_value=timer) as timer_constructor,
+ patch(f"{MODULE}.socket.socket") as socket_constructor,
+ _query_deadline(connection, 5),
+ ):
+ timer_constructor.call_args.args[1]()
+
+ timer_constructor.assert_called_once_with(5, timer_constructor.call_args.args[1])
+ timer.start.assert_called_once_with()
+ timer.cancel.assert_called_once_with()
+ timer.join.assert_called_once_with()
+ socket_constructor.assert_called_once_with(fileno=42)
+ socket_constructor.return_value.shutdown.assert_called_once_with(socket.SHUT_RDWR)
+ socket_constructor.return_value.detach.assert_called_once_with()
+
+
+class TestCheckPostgresDestination:
+ def test_a_usable_destination_passes(self) -> None:
+ connection = _connection(fetches=[(True,), (True,)])
+
+ with (
+ patch(
+ f"{MODULE}.pinned_host_kwargs",
+ return_value={"host": "db.example.com", "hostaddr": "203.0.113.10"},
+ ) as pinned_host,
+ patch(f"{MODULE}.psycopg.connect", return_value=connection) as connect,
+ ):
+ check_postgres_destination(_integration(), {"database": "analytics", "schema": "posthog"})
+
+ pinned_host.assert_called_once_with("db.example.com", port=5432, connect_timeout=5, team_id=None)
+ assert connect.call_args.kwargs["dbname"] == "analytics"
+ assert connect.call_args.kwargs["hostaddr"] == "203.0.113.10"
+ assert connect.call_args.kwargs["connect_timeout"] == 5
+ assert connect.call_args.kwargs["options"] == "-c statement_timeout=5000"
+ assert connect.call_args.kwargs["autocommit"] is True
+ statements = [call.args[0] for call in connection.cursor_mock.execute.call_args_list]
+ assert "has_schema_privilege" in statements[-1]
+
+ @parameterized.expand(
+ [
+ ("existing_schema_with_privilege", [(True,), (True,)], "has_schema_privilege", None),
+ (
+ "existing_schema_without_privilege",
+ [(True,), (False,)],
+ "has_schema_privilege",
+ CheckFailure.MISSING_PRIVILEGE,
+ ),
+ ("new_schema_with_database_privilege", [(False,), (True,)], "has_database_privilege", None),
+ (
+ "new_schema_without_database_privilege",
+ [(False,), (False,)],
+ "has_database_privilege",
+ CheckFailure.MISSING_PRIVILEGE,
+ ),
+ ]
+ )
+ def test_the_create_privilege_check(
+ self,
+ _name: str,
+ fetches: list[tuple[Any, ...] | None],
+ expected_function: str,
+ expected_failure: CheckFailure | None,
+ ) -> None:
+ connection = _connection(fetches=fetches)
+
+ with patch(f"{MODULE}.psycopg.connect", return_value=connection):
+ if expected_failure is None:
+ check_postgres_destination(_integration(), {})
+ else:
+ with pytest.raises(DestinationConnectionCheckError) as raised:
+ check_postgres_destination(_integration(), {})
+ assert raised.value.failure == expected_failure
+
+ assert expected_function in connection.cursor_mock.execute.call_args_list[-1].args[0]
+
+ @parameterized.expand(
+ [
+ ("connection_refused", psycopg.OperationalError("connection refused"), CheckFailure.UNREACHABLE),
+ ("network_unreachable", psycopg.OperationalError("Network is unreachable"), CheckFailure.UNREACHABLE),
+ ("timeout", pg_errors.ConnectionTimeout("timeout expired"), CheckFailure.UNREACHABLE),
+ ("bad_password", pg_errors.InvalidPassword("password authentication failed"), CheckFailure.AUTHENTICATION),
+ (
+ "rejected_user",
+ pg_errors.InvalidAuthorizationSpecification("no pg_hba.conf entry"),
+ CheckFailure.AUTHENTICATION,
+ ),
+ (
+ "unknown_database",
+ pg_errors.InvalidCatalogName('database "nope" does not exist'),
+ CheckFailure.UNKNOWN_DATABASE,
+ ),
+ ("denied_by_server", pg_errors.InsufficientPrivilege("permission denied"), CheckFailure.MISSING_PRIVILEGE),
+ ]
+ )
+ def test_connection_failures_map_to_one_message_without_driver_text(
+ self, _name: str, error: Exception, expected_failure: CheckFailure
+ ) -> None:
+ with patch(f"{MODULE}.psycopg.connect", side_effect=error):
+ with pytest.raises(DestinationConnectionCheckError) as raised:
+ check_postgres_destination(_integration(), None)
+
+ assert raised.value.failure == expected_failure
+ assert str(raised.value) == FAILURE_MESSAGES[expected_failure]
+ for secret in ("hunter2", "writer", "db.example.com"):
+ assert secret not in str(raised.value)
+
+ def test_an_unsafe_resolved_host_is_classified_as_unreachable(self) -> None:
+ with patch(f"{MODULE}.pinned_host_kwargs", side_effect=HostNotAllowedError("blocked")):
+ with pytest.raises(DestinationConnectionCheckError) as raised:
+ check_postgres_destination(_integration(), None)
+
+ assert raised.value.failure == CheckFailure.UNREACHABLE
+
+ def test_a_failure_while_running_queries_is_classified(self) -> None:
+ connection = _connection(fetches=[], execute_error=pg_errors.InsufficientPrivilege("permission denied"))
+
+ with patch(f"{MODULE}.psycopg.connect", return_value=connection):
+ with pytest.raises(DestinationConnectionCheckError) as raised:
+ check_postgres_destination(_integration(), None)
+
+ assert raised.value.failure == CheckFailure.MISSING_PRIVILEGE
+
+ @parameterized.expand(
+ [
+ ("no_cert", {"ssl_mode": "require"}, "/tmp/posthog/batch-exports/MISSING.crt", False),
+ ("system_cert", {"ssl_mode": "require", "ssl_root_cert": "system"}, "system", False),
+ ("pasted_cert", {"ssl_mode": "verify-ca", "ssl_root_cert": "CERT-DATA"}, None, True),
+ ]
+ )
+ def test_the_root_certificate_is_passed_as_a_file(
+ self, _name: str, overrides: dict[str, str], expected_path: str | None, is_temp_file: bool
+ ) -> None:
+ seen: dict[str, Any] = {}
+
+ @contextmanager
+ def _fake_connect(**kwargs: Any):
+ seen["path"] = kwargs["sslrootcert"]
+ if is_temp_file:
+ with open(kwargs["sslrootcert"]) as cert_file:
+ seen["contents"] = cert_file.read()
+ yield _connection(fetches=[(True,), (True,)])
+
+ with patch(f"{MODULE}.psycopg.connect", side_effect=lambda **kwargs: _fake_connect(**kwargs)):
+ check_postgres_destination(_integration(**overrides), None)
+
+ if is_temp_file:
+ assert seen["contents"] == "CERT-DATA"
+ else:
+ assert seen["path"] == expected_path