: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(warehouse-sources): escape column names in the s3 structure argument (#91115)
Daniel RC9905ba66542b
diff --git a/posthog/hogql/escape_sql.py b/posthog/hogql/escape_sql.pyindex 3e3ea60c778e..bf24f81dc3e7 100644--- a/posthog/hogql/escape_sql.py+++ b/posthog/hogql/escape_sql.py@@ -24,6 +24,10 @@ escape_chars_map = {singlequote_escape_chars_map = {**escape_chars_map, "'": "\\'"}# The HogQL/ClickHouse parsers only accept a doubled backtick inside a quoted identifier, not a backslash-escaped one.backquote_escape_chars_map = {**escape_chars_map, "`": "``"}+# Lets the common all-safe identifier skip the per-character rebuild below. Identifier quoting runs+# per column on every query's database build, where that rebuild measured ~25x the cost of a plain+# f-string.+_backquote_escape_chars_re = re.compile("[" + re.escape("".join(backquote_escape_chars_map)) + "]")def safe_identifier(identifier: str) -> str:@@ -306,6 +310,18 @@ def quote_clickhouse_identifier(identifier: str) -> str:"""Quote an identifier without validating whether it is safe to interpolate into SQL."""if re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", identifier):return identifier+ return backquote_clickhouse_identifier(identifier)+++def backquote_clickhouse_identifier(identifier: str) -> str:+ """Backtick-quote a ClickHouse identifier, always, and escape the contents.++ Callers that write an identifier into a grammar ClickHouse re-parses (the S3 table function+ ``structure`` argument) need the quotes on every name, because dropping them for simple names+ changes the text emitted for identifiers that already work.+ """+ if not _backquote_escape_chars_re.search(identifier):+ return f"`{identifier}`"return "`{}`".format("".join(backquote_escape_chars_map.get(c, c) for c in identifier))diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.pyindex aaaa6f6bdf2e..897811226707 100644--- a/products/data_warehouse/backend/models/test/test_table.py+++ b/products/data_warehouse/backend/models/test/test_table.py@@ -517,6 +517,26 @@ class TestTable(BaseTest):}}+ @parameterized.expand(+ [+ ("backtick", "id`"),+ ("backslash", "id\\"),+ ("newline", "id\n"),+ ("carriage_return", "id\r"),+ ("null_byte", "id\0"),+ ]+ )+ def test_get_columns_rejects_unquotable_column_names(self, _name: str, column_name: str):+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)+ table = DataWarehouseTable.objects.create(+ name="test_table", url_pattern="", credential=credential, format="Parquet", team=self.team+ )++ with patch("products.warehouse_sources.backend.models.table.sync_execute") as sync_execute_results:+ sync_execute_results.return_value = [[column_name, "String"]]+ with pytest.raises(Exception, match="PostHog can't use the column name"):+ table.get_columns()+@parameterized.expand([("get_columns", "id,Int64\n"),@@ -632,7 +652,26 @@ class TestTable(BaseTest):[IntegerDatabaseField(name="id", nullable=False)],)- def test_hogql_definition_column_name_hyphen(self):+ @parameterized.expand(+ [+ (+ "hyphen",+ "timestamp-dash",+ "`id` String, `timestamp-dash` DateTime64(3, 'UTC')",+ ),+ (+ "backtick_closing_the_identifier",+ "x` String DEFAULT hostName(), y",+ "`id` String, `x`` String DEFAULT hostName(), y` DateTime64(3, 'UTC')",+ ),+ (+ "backslash",+ "a\\b",+ "`id` String, `a\\\\b` DateTime64(3, 'UTC')",+ ),+ ]+ )+ def test_hogql_definition_quotes_special_column_names(self, _name: str, column_name: str, expected_structure: str):credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)table = DataWarehouseTable.objects.create(name="bla",@@ -641,15 +680,15 @@ class TestTable(BaseTest):team=self.team,columns={"id": {"clickhouse": "String", "hogql": "StringDatabaseField"},- "timestamp-dash": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ column_name: {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},},credential=credential,)definition = table.hogql_definition()assert isinstance(definition, HogQLDataWarehouseTable)- assert list(definition.fields.keys()) == ["id", "timestamp-dash"]- assert definition.structure == "`id` String, `timestamp-dash` DateTime64(3, 'UTC')"+ assert list(definition.fields.keys()) == ["id", column_name]+ assert definition.structure == expected_structuredef test_complex_type_with_array_nested_datetime_fields(self):credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.pyindex 90c85287ccde..c84f2d6db11c 100644--- a/products/data_warehouse/backend/presentation/views/table.py+++ b/products/data_warehouse/backend/presentation/views/table.py@@ -594,7 +594,12 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mdef refresh_schema(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:table: DataWarehouseTable = self.get_object()- table.columns = table.get_columns()+ # get_columns surfaces read failures as a plain Exception carrying a user-facing message.+ # Without this it reaches the handler as a 500, the same way TableSerializer.create avoids.+ try:+ table.columns = table.get_columns()+ except Exception as err:+ raise serializers.ValidationError(str(err))table.save()return response.Response(status=status.HTTP_200_OK)diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 95d083cccf20..3b14f13ff604 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -30,7 +30,11 @@ from posthog.hogql.database.s3_table import (DataWarehouseTable as HogQLDataWarehouseTable,build_function_call,)-from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_param_clickhouse+from posthog.hogql.escape_sql import (+ backquote_clickhouse_identifier,+ escape_clickhouse_identifier,+ escape_param_clickhouse,+)from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries@@ -114,6 +118,14 @@ type DataWarehouseTableIntrospectedColumns = dict[str, DataWarehouseTableIntrosp# and never user-facing.HIDDEN_COLUMNS: frozenset[str] = frozenset({"_dlt_id", "_dlt_load_id", "_ph_debug", PARTITION_KEY})+# Characters that carry quoting meaning once a column name is written into SQL. The structure+# builder escapes them already, so this is a second layer: it keeps such a name out of the other+# sinks that read this column store, not all of which escape as thoroughly (for example+# _quote_identifier in the ClickHouse source connector doubles backticks but not backslashes).+# These names are addressable from HogQL, which escapes them correctly, so this rejects on the+# storage risk rather than on usability.+REJECTED_COLUMN_NAME_CHARACTERS: frozenset[str] = frozenset("`\\\r\n\0")+# chdb has no query timeout, and a stalled S3 read can wedge a web worker indefinitely# (each request also pins ~300MB of RSS for the embedded ClickHouse). Running it in a# subprocess lets us kill it and degrade to the ClickHouse-cluster fallback.@@ -266,10 +278,14 @@ def hogql_fields_and_structure_for_columns(column_invalid = Falseif not column_invalid or (modifiers is not None and modifiers.s3TableUseInvalidColumns):+ # ClickHouse re-parses this string with its column-declaration parser, so an unescaped+ # backtick closes the identifier and the rest of the name is read as more declaration+ # syntax, up to DEFAULT expressions that run server-side.+ quoted_column = backquote_clickhouse_identifier(column)if is_nullable:- structure.append(f"`{column}` Nullable({clickhouse_type})")+ structure.append(f"{quoted_column} Nullable({clickhouse_type})")else:- structure.append(f"`{column}` {clickhouse_type}")+ structure.append(f"{quoted_column} {clickhouse_type}")fields[column] = get_hogql_field_for_column(column, type, clickhouse_type, is_nullable)@@ -562,7 +578,13 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletcolumns: DataWarehouseTableIntrospectedColumns = {}for item in result:- columns[str(item[0])] = DataWarehouseTableIntrospectedColumn(+ column_name = str(item[0])+ if REJECTED_COLUMN_NAME_CHARACTERS.intersection(column_name):+ raise Exception(+ f"PostHog can't use the column name {column_name!r}. Column names can't contain "+ "backticks, backslashes, line breaks, or null bytes. Rename the column, then try again."+ )+ columns[column_name] = DataWarehouseTableIntrospectedColumn(hogql=CLICKHOUSE_HOGQL_MAPPING[clean_type(str(item[1]))].__name__,clickhouse=item[1],valid=True,