: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(data-warehouse): duckdb table functions denylist (#60443)
George Munyoro35f9875ed3e9
diff --git a/posthog/hogql/database/schema/duckdb_table_functions.py b/posthog/hogql/database/schema/duckdb_table_functions.pyindex 86b21cfe48c0..b4dec65cf030 100644--- a/posthog/hogql/database/schema/duckdb_table_functions.py+++ b/posthog/hogql/database/schema/duckdb_table_functions.py@@ -9,6 +9,56 @@ from posthog.hogql.database.models import ()from posthog.hogql.errors import QueryError+_DANGEROUS_TABLE_FUNCTION_NAMES: frozenset[str] = frozenset(+ {+ "query",+ "read_text",+ "read_blob",+ "glob",+ "read_csv",+ "read_csv_auto",+ "read_json",+ "read_json_auto",+ "read_json_objects",+ "read_json_objects_auto",+ "read_ndjson",+ "read_ndjson_auto",+ "read_ndjson_objects",+ "read_parquet",+ "parquet_scan",+ "parquet_metadata",+ "parquet_schema",+ "parquet_file_metadata",+ "parquet_kv_metadata",+ "parquet_bloom_probe",+ "read_xlsx",+ "read_avro",+ "iceberg_scan",+ "iceberg_metadata",+ "iceberg_snapshots",+ "delta_scan",+ "sqlite_scan",+ "sqlite_attach",+ "postgres_scan",+ "postgres_scan_pushdown",+ "postgres_attach",+ "postgres_query",+ "mysql_scan",+ "mysql_query",+ }+)+_DANGEROUS_TABLE_FUNCTION_PREFIXES = ("read_", "scan_")+_DANGEROUS_TABLE_FUNCTION_SUFFIXES = ("_scan", "_attach")+++def is_dangerous_table_function(name: str) -> bool:+ lowered = name.lower()+ return (+ lowered in _DANGEROUS_TABLE_FUNCTION_NAMES+ or lowered.startswith(_DANGEROUS_TABLE_FUNCTION_PREFIXES)+ or lowered.endswith(_DANGEROUS_TABLE_FUNCTION_SUFFIXES)+ )+class RangeTable(FunctionCallTable, DANGEROUS_NoTeamIdCheckTable):"""DuckDB/Postgres range(start, stop, step) table function. Returns a single column of integers."""diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex bf4cd7a1f779..a86546230030 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -17,7 +17,10 @@ from posthog.hogql.database.s3_table import (DataWarehouseTable as HogQLDataWarehouseTable,S3Table,)-from posthog.hogql.database.schema.duckdb_table_functions import build_opaque_function_call_table+from posthog.hogql.database.schema.duckdb_table_functions import (+ build_opaque_function_call_table,+ is_dangerous_table_function,+)from posthog.hogql.database.schema.events import EventsTablefrom posthog.hogql.database.schema.persons import PersonsTablefrom posthog.hogql.errors import ImpossibleASTError, NotImplementedError, QueryError, ResolutionError@@ -2112,6 +2115,9 @@ class Resolver(CloningVisitor):if not _SAFE_TABLE_FUNCTION_NAME_RE.match(function_name):return None+ if is_dangerous_table_function(function_name):+ return None+return build_opaque_function_call_table(function_name)def _is_next_s3(self, node: Optional[ast.JoinExpr]):diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex 081cad24547a..2528cc8d4351 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -11,6 +11,7 @@ import psycopgfrom parameterized import parameterizedfrom posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_functionfrom posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.hogql.escape_sql import escape_postgres_identifierfrom posthog.hogql.query import (@@ -411,6 +412,67 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertIn(expected_sql_fragment, sql)self.assertEqual(executor.direct_postgres_source_id, str(source.id))+ @parameterized.expand(+ [+ ("read_text", "SELECT * FROM read_text('/etc/passwd')"),+ ("read_csv", "SELECT * FROM read_csv('http://169.254.169.254/latest/meta-data')"),+ ("glob", "SELECT * FROM glob('/etc/*')"),+ ("postgres_query", "SELECT * FROM postgres_query('db', 'SELECT 1')"),+ ("query", "SELECT * FROM query('SELECT * FROM read_text(''/etc/passwd'')')"),+ ]+ )+ def test_generate_sql_rejects_dangerous_table_function_even_if_cached_in_metadata(+ self, function_name: str, query: str+ ):+ 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",+ },+ connection_metadata={"available_table_functions": [function_name]},+ )++ executor = HogQLQueryExecutor(query=query, team=self.team, connection_id=str(source.id))++ with self.assertRaises((QueryError, ExposedHogQLError)) as ctx:+ executor.generate_clickhouse_sql()++ # Must fail at resolve time, not as an accepted opaque table (which fails generically at print).+ self.assertNotIn("is not supported in ClickHouse dialect", str(ctx.exception))++ @parameterized.expand(+ [+ ("query", True),+ ("read_csv", True),+ ("postgres_query", True),+ ("glob", True),+ ("READ_TEXT", True),+ ("read_anything", True),+ ("scan_anything", True),+ ("foo_scan", True),+ ("foo_attach", True),+ ("build_query", False),+ ("get_query", False),+ ("run_query", False),+ ("range", False),+ ("generate_series", False),+ ("unnest", False),+ ]+ )+ def test_is_dangerous_table_function(self, function_name: str, expected: bool):+ self.assertEqual(is_dangerous_table_function(function_name), expected)+def test_generate_sql_for_duckdb_direct_postgres_table_uses_connection_catalog(self):source = ExternalDataSource.objects.create(team=self.team,diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 7f35358b0713..d89f4f6cb086 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -22,6 +22,8 @@ from psycopg import sqlfrom psycopg.adapt import Loaderfrom structlog.types import FilteringBoundLogger+from posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_function+from posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.data_imports.naming_convention import NamingConventionfrom posthog.temporal.data_imports.pipelines.helpers import (@@ -779,6 +781,9 @@ def get_connection_metadata(except Exception as error:capture_exception(error)+ available_functions = [fn for fn in available_functions if not is_dangerous_table_function(fn)]+ available_table_functions = [fn for fn in available_table_functions if not is_dangerous_table_function(fn)]+return {"database": current_database,"version": version,