: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ws): require credential re-entry when connection host changes (#57772)
estefania19c1b4a26a2a
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 0e1e75965509..ba2701d633eb 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -583,6 +583,17 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializernew_job_inputs = {**existing_job_inputs, **incoming_job_inputs}+ # If the connection host changed, require credentials to be re-entered.+ connection_host_changed = "host" in incoming_job_inputs and incoming_job_inputs[+ "host"+ ] != existing_job_inputs.get("host")+ if connection_host_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:+ raise ValidationError("Changing the connection host requires re-entering your credentials.")+# Preserve sensitive credentials not explicitly provided (API response omits them for security)for key in sensitive_fields:if existing_job_inputs.get(key) and not incoming_job_inputs.get(key):@@ -614,6 +625,10 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerincoming_ssh_tunnel = incoming_job_inputs.get("ssh_tunnel")if existing_ssh_tunnel and incoming_ssh_tunnel is not None:+ ssh_tunnel_host_changed = "host" in incoming_ssh_tunnel and incoming_ssh_tunnel[+ "host"+ ] != existing_ssh_tunnel.get("host")+# Deep-merge: start with existing, overlay incoming top-level keysmerged_ssh_tunnel = {**existing_ssh_tunnel, **incoming_ssh_tunnel}@@ -625,15 +640,19 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer(incoming_ssh_tunnel or {}).get("auth") or (incoming_ssh_tunnel or {}).get("auth_type") or {})+ if ssh_tunnel_host_changed and not incoming_auth:+ raise ValidationError("Changing the SSH tunnel host requires re-entering your SSH credentials.")+if not incoming_auth:# No auth in incoming request - preserve entire existing authmerged_ssh_tunnel["auth"] = {**existing_auth}else:# Merge auth, preserving sensitive fields not explicitly providedmerged_auth = {**incoming_auth}- for key in ("password", "passphrase", "private_key"):- if existing_auth.get(key) and not incoming_auth.get(key):- merged_auth[key] = existing_auth[key]+ if not ssh_tunnel_host_changed:+ for key in ("password", "passphrase", "private_key"):+ if existing_auth.get(key) and not incoming_auth.get(key):+ merged_auth[key] = existing_auth[key]merged_ssh_tunnel["auth"] = merged_authnew_job_inputs["ssh_tunnel"] = merged_ssh_tunneldiff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 39b3fdf937ef..88d3b137afac 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@@ -3077,7 +3077,7 @@ class TestExternalDataSource(APIBaseTest):f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",data={"job_inputs": {- "host": "new-host.example.com",+ "database": "other_db","password": None, # Frontend sends null},},@@ -3087,7 +3087,7 @@ class TestExternalDataSource(APIBaseTest):# Verify password was preserved, not overwritten with nullsource.refresh_from_db()- assert source.job_inputs["host"] == "new-host.example.com" # Host was updated+ assert source.job_inputs["database"] == "other_db" # Database was updatedassert source.job_inputs["password"] == "original_password" # Password preservedmock_validate_credentials.assert_called_once()@@ -3125,7 +3125,7 @@ class TestExternalDataSource(APIBaseTest):f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",data={"job_inputs": {- "host": "new-host.example.com",+ "database": "other_db","password": "", # Frontend sends empty string when user doesn't enter new password},},@@ -3135,7 +3135,7 @@ class TestExternalDataSource(APIBaseTest):# Verify password was preserved, not overwritten with empty stringsource.refresh_from_db()- assert source.job_inputs["host"] == "new-host.example.com" # Host was updated+ assert source.job_inputs["database"] == "other_db" # Database was updatedassert source.job_inputs["password"] == "original_password" # Password preservedmock_validate_credentials.assert_called_once()@@ -3185,7 +3185,7 @@ class TestExternalDataSource(APIBaseTest):"posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",return_value=(True, None),)- def test_update_with_host_change_revalidates_credentials(self, mock_validate_credentials):+ def test_update_with_host_change_without_credentials_is_rejected(self, mock_validate_credentials):source = ExternalDataSource.objects.create(team_id=self.team.pk,source_id=str(uuid.uuid4()),@@ -3214,9 +3214,50 @@ class TestExternalDataSource(APIBaseTest):},)+ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ source.refresh_from_db()+ assert source.job_inputs["host"] == "db.example.com"+ mock_validate_credentials.assert_not_called()++ @patch(+ "posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_with_host_change_and_credentials_succeeds(self, mock_validate_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_host_with_creds",+ job_inputs={+ "source_type": "Postgres",+ "host": "db.example.com",+ "port": "5432",+ "database": "mydb",+ "user": "dbuser",+ "password": "original_password",+ "schema": "public",+ },+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "host": "new-host.example.com",+ "password": "new_password",+ },+ },+ )+assert response.status_code == 200, response.json()source.refresh_from_db()assert source.job_inputs["host"] == "new-host.example.com"+ assert source.job_inputs["password"] == "new_password"mock_validate_credentials.assert_called_once()@patch(@@ -3320,12 +3361,13 @@ class TestExternalDataSource(APIBaseTest):},)- # Update without providing ssh_tunnel+ # Update without providing ssh_tunnel — include password since host is changingresponse = self.client.patch(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",data={"job_inputs": {"host": "new-host.example.com",+ "password": "new_password",},},)@@ -3335,7 +3377,7 @@ class TestExternalDataSource(APIBaseTest):source.refresh_from_db()assert source.job_inputs["host"] == "new-host.example.com"- assert source.job_inputs["password"] == "original_password"+ assert source.job_inputs["password"] == "new_password"mock_validate_credentials.assert_called_once()@override_settings(CLOUD_DEPLOYMENT="US")@@ -3368,6 +3410,44 @@ class TestExternalDataSource(APIBaseTest):},)+ assert response.status_code == 400+ # Host change without re-entering credentials is rejected before SSRF check+ assert "re-entering your credentials" in str(response.json())++ source.refresh_from_db()+ assert source.job_inputs["host"] == "db.example.com"++ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_update_blocks_internal_host_with_credentials(self):+ 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_internal_host_with_creds",+ job_inputs={+ "source_type": "Postgres",+ "host": "db.example.com",+ "port": "5432",+ "database": "mydb",+ "user": "dbuser",+ "password": "original_password",+ "schema": "public",+ },+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "host": "localhost",+ "password": "new_password",+ },+ },+ )+assert response.status_code == 400assert response.json()["detail"] == "Hosts with internal IP addresses are not allowed"@@ -3756,8 +3836,7 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["ssh_tunnel"]["enabled"] == "True"assert source.job_inputs["ssh_tunnel"]["auth"]["password"] == "ssh_secret_password"- def test_update_source_with_ssh_tunnel_enabled_missing_auth(self):- """Regression test: PATCH with ssh_tunnel enabled but no auth key should preserve existing auth."""+ def test_update_source_with_ssh_tunnel_host_change_without_auth_is_rejected(self):source = ExternalDataSource.objects.create(team_id=self.team.pk,source_id=str(uuid.uuid4()),@@ -3789,29 +3868,133 @@ class TestExternalDataSource(APIBaseTest):},)- with patch(- "posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",- return_value=(True, None),- ):- response = self.client.patch(- f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",- data={- "job_inputs": {- "ssh_tunnel": {- "enabled": True,- "host": "new-ssh.example.com",- "port": 22,+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "ssh_tunnel": {+ "enabled": True,+ "host": "new-ssh.example.com",+ "port": 22,+ },+ },+ },+ )++ assert response.status_code == 400+ assert "SSH tunnel host" in str(response.json())+ source.refresh_from_db()+ assert source.job_inputs["ssh_tunnel"]["host"] == "ssh.example.com"++ @patch(+ "posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_source_with_ssh_tunnel_host_change_and_auth_succeeds(self, mock_validate_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_ssh_host_with_auth",+ 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": "old_ssh_password",+ },+ },+ },+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "ssh_tunnel": {+ "enabled": True,+ "host": "new-ssh.example.com",+ "port": 22,+ "auth": {+ "selection": "password",+ "username": "sshuser",+ "password": "new_ssh_password",},},},- )+ },+ )assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.json()}"-source.refresh_from_db()assert source.job_inputs["ssh_tunnel"]["host"] == "new-ssh.example.com"+ assert source.job_inputs["ssh_tunnel"]["auth"]["password"] == "new_ssh_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_with_ssh_tunnel_same_host_preserves_auth(self, mock_validate_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_ssh_same_host",+ 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",+ },+ },+ },+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "ssh_tunnel": {+ "enabled": True,+ "host": "ssh.example.com",+ "port": 2222,+ },+ },+ },+ )++ assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.json()}"+ source.refresh_from_db()assert source.job_inputs["ssh_tunnel"]["auth"]["password"] == "ssh_secret_password"- assert source.job_inputs["ssh_tunnel"]["auth"]["username"] == "sshuser"+ mock_validate_credentials.assert_called_once()def test_update_legacy_auth_type_format_preserves_credentials(self):"""