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): require db password reentry on ssh tunnel change (#60337)

Daniel RCe69aff3f9b38
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 6f71d18be296..5dc761557281 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -243,6 +243,28 @@ def strip_sensitive_from_dict(data: dict, nonsensitive: set[str], sensitive: set
return result
+# Fields whose change could redirect the database connection to a different server
+# (and therefore exfiltrate credentials via a poisoned SSH tunnel — VERIA-311).
+_SSH_TUNNEL_CONNECTION_FIELDS = ("enabled", "host", "port")
+
+
+def ssh_tunnel_connection_changed(existing: Any, incoming: Any) -> bool:
+ """True if the SSH tunnel's connection target (enabled/host/port) changed.
+
+ Scalars are coerced to strings to ignore type drift between stored values
+ (often strings) and JSON-parsed input (bools/ints). Only `None` collapses to ""
+ — `or ""` would also swallow falsy-but-meaningful values like `False` and 0,
+ making stored "False" falsely diverge from JSON `false`.
+ """
+ existing = existing if isinstance(existing, dict) else {}
+ incoming = incoming if isinstance(incoming, dict) else {}
+
+ def _coerce(value: Any) -> str:
+ return "" if value is None else str(value)
+
+ return any(_coerce(existing.get(key)) != _coerce(incoming.get(key)) for key in _SSH_TUNNEL_CONNECTION_FIELDS)
+
+
def get_direct_postgres_connection_metadata(
*,
source_impl: Any,
@@ -664,11 +686,22 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
connection_host_changed = "host" in incoming_job_inputs and incoming_job_inputs[
"host"
] != existing_job_inputs.get("host")
- if connection_host_changed:
+
+ # If the SSH tunnel's connection target changed, also require credentials. Without this an
+ # editor could swap in a tunnel that routes the backend's auth to an attacker-controlled
+ # server, exfiltrating the stored database credentials (VERIA-311).
+ ssh_tunnel_changed = "ssh_tunnel" in incoming_job_inputs and ssh_tunnel_connection_changed(
+ existing_job_inputs.get("ssh_tunnel"),
+ incoming_job_inputs.get("ssh_tunnel"),
+ )
+
+ if connection_host_changed or ssh_tunnel_changed:
missing_credentials = [
key for key in sensitive_fields if existing_job_inputs.get(key) and not incoming_job_inputs.get(key)
]
if missing_credentials:
+ if ssh_tunnel_changed:
+ raise ValidationError("Changing the SSH tunnel requires re-entering your database credentials.")
raise ValidationError("Changing the connection host requires re-entering your credentials.")
# Preserve sensitive credentials not explicitly provided (API response omits them for security)
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index 3a3aeb51ed17..9fbd1315ffda 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -3256,6 +3256,8 @@ class TestExternalDataSource(APIBaseTest):
f"/api/environments/{self.team.pk}/external_data_sources/{str(source.pk)}/",
data={
"job_inputs": {
+ # Adding an SSH tunnel requires re-supplying the database password.
+ "password": "password",
"ssh_tunnel": {
"enabled": True,
"host": "ssh.example.com",
@@ -3267,7 +3269,7 @@ class TestExternalDataSource(APIBaseTest):
"passphrase": "testphrase",
"private_key": "testkey",
},
- }
+ },
},
},
)
@@ -4095,6 +4097,8 @@ class TestExternalDataSource(APIBaseTest):
f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
data={
"job_inputs": {
+ # Disabling the SSH tunnel is an SSH tunnel change — DB password must be re-supplied.
+ "password": "db_password",
"ssh_tunnel": {
"enabled": False,
},
@@ -4148,6 +4152,8 @@ class TestExternalDataSource(APIBaseTest):
f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
data={
"job_inputs": {
+ # Re-supply DB password so the failure comes from the mocked credential check below.
+ "password": "db_password",
"ssh_tunnel": {
"enabled": False,
},
@@ -4203,6 +4209,8 @@ class TestExternalDataSource(APIBaseTest):
f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
data={
"job_inputs": {
+ # DB password is re-supplied; SSH auth is missing so SSH credential check fails.
+ "password": "db_password",
"ssh_tunnel": {
"enabled": True,
"host": "new-ssh.example.com",
@@ -4255,6 +4263,8 @@ class TestExternalDataSource(APIBaseTest):
f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
data={
"job_inputs": {
+ # Changing the SSH tunnel forces re-entry of the database password.
+ "password": "db_password",
"ssh_tunnel": {
"enabled": True,
"host": "new-ssh.example.com",
@@ -4313,6 +4323,8 @@ class TestExternalDataSource(APIBaseTest):
f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
data={
"job_inputs": {
+ # Changing any SSH tunnel field forces re-entry of the database password.
+ "password": "db_password",
"ssh_tunnel": {
"enabled": True,
"host": "ssh.example.com",
@@ -4398,6 +4410,175 @@ class TestExternalDataSource(APIBaseTest):
# After update, it should be normalized to 'auth' format
assert source.job_inputs["ssh_tunnel"]["auth"]["password"] == "ssh_secret_password" # SSH password preserved
+ def test_update_source_ssh_tunnel_change_requires_db_password_reentry(self):
+ """VERIA-311: any change to ssh_tunnel must force the database password to be re-supplied,
+ otherwise an editor could inject a tunnel that exfiltrates the stored credentials."""
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Postgres",
+ created_by=self.user,
+ prefix="test_veria_311",
+ job_inputs={
+ "source_type": "Postgres",
+ "host": "db.example.com",
+ "port": "5432",
+ "database": "mydb",
+ "user": "dbuser",
+ "password": "db_password",
+ "schema": "public",
+ "ssh_tunnel": {
+ "enabled": "True",
+ "host": "ssh.example.com",
+ "port": "22",
+ "auth": {
+ "type": "password",
+ "username": "sshuser",
+ "password": "ssh_secret_password",
+ },
+ },
+ },
+ )
+
+ # Editor swaps the SSH tunnel for an attacker-controlled one without re-entering the DB password.
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "ssh_tunnel": {
+ "enabled": True,
+ "host": "attacker.example.com",
+ "port": 22,
+ "auth": {
+ "selection": "password",
+ "username": "sshuser",
+ "password": "attacker_password",
+ },
+ },
+ },
+ },
+ )
+
+ assert response.status_code == 400
+ assert "database credentials" in str(response.json())
+
+ source.refresh_from_db()
+ assert source.job_inputs["ssh_tunnel"]["host"] == "ssh.example.com"
+ assert source.job_inputs["password"] == "db_password"
+
+ @patch(
+ "posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_update_source_ssh_tunnel_disabled_string_vs_bool_no_false_positive(self, mock_validate_credentials):
+ """Regression: stored `enabled: "False"` must compare equal to incoming JSON `false`.
+
+ A naive `str(value or "")` collapses falsy values to "", so stored "False" would diverge
+ from incoming False and spuriously demand a password re-entry on every save.
+ """
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Postgres",
+ created_by=self.user,
+ prefix="test_disabled_false_string",
+ job_inputs={
+ "source_type": "Postgres",
+ "host": "db.example.com",
+ "port": "5432",
+ "database": "mydb",
+ "user": "dbuser",
+ "password": "db_password",
+ "schema": "public",
+ "ssh_tunnel": {
+ "enabled": "False",
+ "host": "ssh.example.com",
+ "port": "22",
+ "auth": {
+ "type": "password",
+ "username": "sshuser",
+ "password": "ssh_secret_password",
+ },
+ },
+ },
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "database": "renamed_db",
+ "ssh_tunnel": {
+ "enabled": False,
+ "host": "ssh.example.com",
+ "port": 22,
+ },
+ },
+ },
+ )
+
+ assert response.status_code == 200, response.json()
+ source.refresh_from_db()
+ assert source.job_inputs["database"] == "renamed_db"
+ assert source.job_inputs["password"] == "db_password"
+ mock_validate_credentials.assert_called_once()
+
+ @patch(
+ "posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_update_source_ssh_tunnel_no_change_does_not_require_db_password(self, mock_validate_credentials):
+ """Re-submitting the same ssh_tunnel (e.g. when saving an unrelated field after a GET) must
+ NOT force the user to re-enter the database password — that would break the no-op save path."""
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Postgres",
+ created_by=self.user,
+ prefix="test_no_change",
+ job_inputs={
+ "source_type": "Postgres",
+ "host": "db.example.com",
+ "port": "5432",
+ "database": "mydb",
+ "user": "dbuser",
+ "password": "db_password",
+ "schema": "public",
+ "ssh_tunnel": {
+ "enabled": "True",
+ "host": "ssh.example.com",
+ "port": "22",
+ "auth": {
+ "type": "password",
+ "username": "sshuser",
+ "password": "ssh_secret_password",
+ },
+ },
+ },
+ )
+
+ get_response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}")
+ assert get_response.status_code == 200
+ ssh_tunnel_from_get = get_response.json()["job_inputs"]["ssh_tunnel"]
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={"job_inputs": {"ssh_tunnel": ssh_tunnel_from_get, "database": "renamed_db"}},
+ )
+
+ assert response.status_code == 200, response.json()
+ source.refresh_from_db()
+ assert source.job_inputs["database"] == "renamed_db"
+ assert source.job_inputs["password"] == "db_password"
+ assert source.job_inputs["ssh_tunnel"]["auth"]["password"] == "ssh_secret_password"
+ mock_validate_credentials.assert_called_once()
+
def test_snowflake_auth_type_create_and_update(self):
"""Test that we can create and update the auth type for a Snowflake source"""
with (