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(endpoints): refuse endpoint creation over a direct connection (#80740)

Jovan Sakovica952f7137efb
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index d5037bd62166..1a8d52439ba8 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -388,6 +388,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
inProgressViewEdits,
isSourceQueryLastRun,
isMultiQuery,
+ selectedConnectionId,
} = useValues(sqlEditorLogic)
const { convertToNotebook, openHistoryModal } = useActions(editorSceneLogic)
const {
@@ -428,6 +429,11 @@ function SQLEditorSceneTitle(): JSX.Element | null {
AccessControlLevel.Editor
)
+ // A direct connection's table names only resolve while it is selected, and an endpoint serves data from PostHog.
+ const saveAsEndpointDisabledReason = selectedConnectionId
+ ? "Endpoints can't query a direct connection. Switch the connection to PostHog (ClickHouse) and query a synced table instead."
+ : saveAsEndpointAccessDisabledReason
+
const continueInNotebookAccessDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Notebook,
AccessControlLevel.Editor
@@ -459,7 +465,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
item.action === 'view'
? saveAsViewAccessDisabledReason
: item.action === 'endpoint'
- ? saveAsEndpointAccessDisabledReason
+ ? saveAsEndpointDisabledReason
: undefined,
})),
[
@@ -469,7 +475,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
saveAsMenuItems.secondary,
saveAsView,
saveAsViewAccessDisabledReason,
- saveAsEndpointAccessDisabledReason,
+ saveAsEndpointDisabledReason,
]
)
@@ -668,7 +674,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
label: 'Save as endpoint...',
disabledReason:
saveAsDisabledReason ??
- saveAsEndpointAccessDisabledReason,
+ saveAsEndpointDisabledReason,
onClick: () => saveAsEndpoint(),
},
]}
@@ -735,8 +741,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
{
label: 'Save as endpoint...',
disabledReason:
- saveAsDisabledReason ??
- saveAsEndpointAccessDisabledReason,
+ saveAsDisabledReason ?? saveAsEndpointDisabledReason,
onClick: () => saveAsEndpoint(),
},
]}
@@ -803,7 +808,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
disabledReason={
saveAsDisabledReason ??
(saveAsMenuItems.primary.action === 'endpoint'
- ? saveAsEndpointAccessDisabledReason
+ ? saveAsEndpointDisabledReason
: saveAsMenuItems.primary.action === 'view'
? saveAsViewAccessDisabledReason
: undefined)
diff --git a/products/endpoints/backend/logic/validation.py b/products/endpoints/backend/logic/validation.py
index 6693b8d0d18b..29ce8fd6974d 100644
--- a/products/endpoints/backend/logic/validation.py
+++ b/products/endpoints/backend/logic/validation.py
@@ -65,9 +65,20 @@ def validate_bucket_overrides(bucket_overrides: dict[str, str] | None) -> None:
raise ValidationError(f"Invalid bucket override values: {invalid}. Valid options: {valid_options}")
+DIRECT_CONNECTION_UNSUPPORTED = (
+ "Endpoints can't query a direct connection. "
+ "Switch the connection to PostHog (ClickHouse) and query a synced table instead."
+)
+
+
def validate_hogql_query(query: HogQLQuery, team: Team, user: User) -> None:
"""Validate that a HogQL query parses, its variables are valid, and the author can
access every table/view it references."""
+ # A direct connection reads the customer's database live, so there is nothing for an
+ # endpoint to materialize and its table names only exist while that connection is selected.
+ if query.connectionId:
+ raise ValidationError({"query": DIRECT_CONNECTION_UNSUPPORTED})
+
try:
ast_node = parse_select(query.query)
except ExposedHogQLError as e:
diff --git a/products/endpoints/backend/tests/test_direct_connection_validation.py b/products/endpoints/backend/tests/test_direct_connection_validation.py
new file mode 100644
index 000000000000..056e8ab141c7
--- /dev/null
+++ b/products/endpoints/backend/tests/test_direct_connection_validation.py
@@ -0,0 +1,107 @@
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import HogQLQuery
+
+from posthog.hogql.database.database import Database
+
+from products.endpoints.backend.logic.validation import DIRECT_CONNECTION_UNSUPPORTED, validate_hogql_query
+from products.warehouse_sources.backend.facade.models import (
+ DataWarehouseCredential,
+ DataWarehouseTable,
+ ExternalDataSchema,
+ ExternalDataSource,
+)
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+
+
+class TestDirectConnectionValidation(APIBaseTest):
+ def _dual_mode_source(self) -> ExternalDataSource:
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="synced_pg_source",
+ source_type=ExternalDataSourceType.POSTGRES,
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ direct_query_enabled=True,
+ prefix="pg",
+ job_inputs={"schema": "public"},
+ )
+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="k", access_secret="s")
+ synced_table = DataWarehouseTable.objects.create(
+ name="pg_users",
+ format="Parquet",
+ team=self.team,
+ credential=credential,
+ external_data_source=source,
+ url_pattern="s3://bucket/users/*",
+ columns={"id": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField"}},
+ )
+ ExternalDataSchema.objects.create(
+ team=self.team,
+ name="public.users",
+ source=source,
+ table=synced_table,
+ should_sync=True,
+ sync_type_config={
+ "schema_metadata": {
+ "columns": [{"name": "id", "data_type": "integer", "is_nullable": False}],
+ "source_schema": "public",
+ "source_table_name": "users",
+ }
+ },
+ )
+ return source
+
+ def test_connection_selection_renames_the_same_table(self):
+ source = self._dual_mode_source()
+
+ with_connection = Database._build_from_sources(
+ Database._fetch_sources(team=self.team, connection_id=str(source.id))
+ )
+ without_connection = Database._build_from_sources(Database._fetch_sources(team=self.team))
+
+ assert with_connection.has_table("public.users")
+ assert not with_connection.has_table("postgres.pg.pg_users")
+
+ assert without_connection.has_table("postgres.pg.pg_users")
+ assert not without_connection.has_table("public.users")
+
+ def test_a_direct_connection_query_is_refused_by_name(self):
+ source = self._dual_mode_source()
+
+ with self.assertRaises(ValidationError) as ctx:
+ validate_hogql_query(
+ HogQLQuery(query="SELECT id FROM public.users", connectionId=str(source.id)),
+ self.team,
+ self.user,
+ )
+
+ detail = ctx.exception.detail
+ assert isinstance(detail, dict)
+ assert str(detail["query"]) == DIRECT_CONNECTION_UNSUPPORTED
+
+ def test_the_synced_copy_of_the_same_table_still_validates(self):
+ self._dual_mode_source()
+
+ validate_hogql_query(HogQLQuery(query="SELECT id FROM postgres.pg.pg_users"), self.team, self.user)
+
+ def test_creating_an_endpoint_over_a_direct_connection_is_refused(self):
+ source = self._dual_mode_source()
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/",
+ {
+ "name": "direct_users",
+ "query": {
+ "kind": "HogQLQuery",
+ "query": "SELECT id FROM public.users",
+ "connectionId": str(source.id),
+ },
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["detail"] == DIRECT_CONNECTION_UNSUPPORTED