: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(batch-exports): validate HogQL select from fields (#85847)
Ross533f6d000ced
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex 6125f6d486b4..6bc9b29bd3a5 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -80,6 +80,7 @@ from products.batch_exports.backend.temporal.destinations.constants import (AZURE_BLOB_SUPPORTED_COMPRESSIONS,S3_SUPPORTED_COMPRESSIONS,)+from products.batch_exports.backend.temporal.sql.events import EXPORTABLE_EVENTS_MODEL_FIELDSlogger = structlog.get_logger(__name__)@@ -881,6 +882,24 @@ class _SubqueryFinder(TraversingVisitor):self.found = True+class _DatabaseFieldFinder(TraversingVisitor):+ """Walk an AST subtree and collect the names of the database fields it reads."""++ def __init__(self, context: HogQLContext):+ super().__init__()+ self.context = context+ self.names: set[str] = set()++ def visit_field(self, node: ast.Field):+ resolve = getattr(node.type, "resolve_database_field", None)+ if resolve is not None:+ database_field = resolve(self.context)+ name = getattr(database_field, "name", None)+ if name is not None:+ self.names.add(name)+ super().visit_field(node)++INTERNAL_NETWORKS = (ipaddress.ip_network("10.0.0.0/8"),ipaddress.ip_network("172.16.0.0/12"),@@ -1524,13 +1543,14 @@ class BatchExportSerializer(serializers.ModelSerializer):return batch_export_schemadef validate_hogql_query(self, hogql_query: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery:- """Validate a HogQLQuery being used for batch exports.+ """Validate a HogQL query being used for events batch exports.This method essentially checks that a query is supported by batch exports:1. UNION ALL is not supported.2. Any JOINs are not supported.3. Query must SELECT FROM events, and only from events.4. Subqueries in SELECT expressions are not supported.+ 5. Query must select only from those fields we expose from the events table."""if isinstance(hogql_query, ast.SelectSetQuery):@@ -1562,6 +1582,18 @@ class BatchExportSerializer(serializers.ModelSerializer):if subquery_finder.found:raise serializers.ValidationError("Subqueries in SELECT expressions are not supported")+ # Check that the query only selects from those fields we expose from the events table.+ field_finder = _DatabaseFieldFinder(HogQLContext(team_id=self.context["team_id"], enable_select_queries=True))+ for field in parsed.select:+ field_finder.visit(field)++ unsupported = sorted(field_finder.names - EXPORTABLE_EVENTS_MODEL_FIELDS)+ if unsupported:+ raise serializers.ValidationError(+ f"Batch exports cannot read these fields: {', '.join(unsupported)}. "+ f"Supported fields are: {', '.join(sorted(EXPORTABLE_EVENTS_MODEL_FIELDS))}."+ )+return hogql_querydef update(self, batch_export: BatchExport, validated_data: dict) -> BatchExport:diff --git a/products/batch_exports/backend/temporal/sql/events.py b/products/batch_exports/backend/temporal/sql/events.pyindex e110eb27de15..34d99fb13045 100644--- a/products/batch_exports/backend/temporal/sql/events.py+++ b/products/batch_exports/backend/temporal/sql/events.py@@ -2,6 +2,25 @@from string import Template+# Projected columns a HogQL query can select.+# NOTE: this is just for the 'old' version of our HogQL support, where a user can define a custom+# SELECT FROM clause, useful for defining a custom schema. It's not related to the new HogQL model,+# in which a user can use any arbitrary SELECT query.+EXPORTABLE_EVENTS_MODEL_FIELDS = frozenset(+ {+ "team_id",+ "timestamp",+ "event",+ "distinct_id",+ "uuid",+ "created_at",+ "elements_chain",+ "person_id",+ "properties",+ "person_properties",+ }+)+SELECT_FROM_EVENTS_VIEW = Template("""SELECTdiff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.pyindex 968e5ab53e05..30834438c372 100644--- a/products/batch_exports/backend/tests/api/test_create.py+++ b/products/batch_exports/backend/tests/api/test_create.py@@ -588,6 +588,18 @@ def test_create_batch_export_with_custom_schema("SELECT coalesce((SELECT uuid FROM events LIMIT 1), uuid) AS foo FROM events","Subqueries in SELECT expressions are not supported",),+ (+ "SELECT event, $session_id FROM events",+ "Batch exports cannot read these fields: $session_id. Supported fields are: created_at, "+ "distinct_id, elements_chain, event, person_id, person_properties, properties, team_id, "+ "timestamp, uuid.",+ ),+ (+ "SELECT event, person.created_at FROM events",+ "Batch exports cannot read these fields: person_created_at. Supported fields are: created_at, "+ "distinct_id, elements_chain, event, person_id, person_properties, properties, team_id, "+ "timestamp, uuid.",+ ),],)def test_create_batch_export_fails_with_invalid_query(