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(hogql): block multi-statement raw direct Postgres queries (#63178)

George Munyorodd40feedf521
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index cdffda71bf43..3209d96263d0 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -3,6 +3,7 @@ from datetime import date, datetime
from typing import ClassVar, Literal, Optional, TypedDict, Union, cast
import psycopg
+import sqlparse
from opentelemetry import trace
from psycopg.types.datetime import DateLoader
@@ -141,6 +142,20 @@ def postgres_error_to_message(error: Exception) -> str:
return message.splitlines()[0]
+def ensure_single_direct_postgres_statement(sql: str) -> str:
+ """Reject multi-statement raw SQL.
+
+ Raw queries run without bound parameters, so psycopg uses the simple query
+ protocol, which runs every ``;``-separated statement in one round trip. A
+ caller could commit out of the read-only transaction and ``BEGIN READ WRITE``
+ to perform writes; restricting to one statement keeps it read-only.
+ """
+ statements = [statement for statement in sqlparse.split(sql) if statement.strip(" \t\r\n;")]
+ if len(statements) > 1:
+ raise ExposedHogQLError("Raw queries must contain a single statement.")
+ return sql
+
+
def direct_postgres_session_setup_sql(
schema: str | None,
connection_metadata: dict[str, object] | None = None,
@@ -755,7 +770,7 @@ class HogQLQueryExecutor:
raise ExposedHogQLError("Sending a raw query requires a valid connection.")
self.connection_id = str(source.id)
self.direct_postgres_source_id = self.connection_id
- self.direct_postgres_sql = str(self.query)
+ self.direct_postgres_sql = ensure_single_direct_postgres_statement(str(self.query))
self._execute_direct_postgres_query()
def _capture_send_raw_query_translation_error(self) -> None:
diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.py
index 2528cc8d4351..e4ea1566a88e 100644
--- a/posthog/hogql/test/test_direct_postgres_query.py
+++ b/posthog/hogql/test/test_direct_postgres_query.py
@@ -18,6 +18,7 @@ from posthog.hogql.query import (
HogQLQueryExecutor,
LenientDirectPostgresDateLoader,
direct_postgres_session_setup_sql,
+ ensure_single_direct_postgres_statement,
get_runtime_direct_postgres_connection_metadata,
parse_lenient_direct_postgres_date,
postgres_error_to_message,
@@ -1099,6 +1100,62 @@ class TestDirectPostgresQuery(APIBaseTest):
mocked_connection.execute.assert_called_once_with("SELECT current_database(), version()")
mocked_cursor.execute.assert_called_once_with("SELECT 1 AS value", None)
+ @parameterized.expand(
+ [
+ ("explicit_read_write", "COMMIT; BEGIN READ WRITE; UPDATE t SET a = 1; COMMIT;"),
+ ("set_then_write", "SET default_transaction_read_only = off; UPDATE t SET a = 1;"),
+ ("two_selects", "SELECT 1; SELECT 2"),
+ ]
+ )
+ def test_ensure_single_direct_postgres_statement_rejects_multi_statement(self, _name: str, sql: str):
+ with self.assertRaises(ExposedHogQLError):
+ ensure_single_direct_postgres_statement(sql)
+
+ @parameterized.expand(
+ [
+ ("plain_select", "SELECT 1 AS value"),
+ ("trailing_semicolon", "SELECT 1 AS value;"),
+ ("stray_empty_statements", "SELECT 1 AS value; ; "),
+ ("percent_literal", "SELECT name FROM t WHERE name LIKE '%admin%'"),
+ ("semicolon_in_literal", "SELECT 'a;b' AS value"),
+ ("dollar_quoted", "SELECT $$a;b;c$$ AS value"),
+ ]
+ )
+ def test_ensure_single_direct_postgres_statement_allows_single_statement(self, _name: str, sql: str):
+ self.assertEqual(ensure_single_direct_postgres_statement(sql), sql)
+
+ @patch("posthog.hogql.query.psycopg.connect")
+ def test_send_raw_query_rejects_multi_statement_before_execution(self, mock_connect):
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="source_id",
+ connection_id="connection_id",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type="Postgres",
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ prefix="ph3",
+ job_inputs={
+ "host": "localhost",
+ "port": 5432,
+ "database": "postgres",
+ "user": "postgres",
+ "password": "postgres",
+ "schema": "ph3",
+ },
+ )
+
+ executor = HogQLQueryExecutor(
+ query="COMMIT; BEGIN READ WRITE; UPDATE t SET a = 1; COMMIT;",
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ with self.assertRaises(ExposedHogQLError):
+ executor.execute()
+
+ mock_connect.assert_not_called()
+
def test_selected_connection_rejects_disabled_direct_tables(self):
source = ExternalDataSource.objects.create(
team=self.team,