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(mssql): quote T-SQL identifiers with special characters (#64028)

Tom Owersd94f338fa327
diff --git a/posthog/temporal/data_imports/sources/common/sql/identifiers.py b/posthog/temporal/data_imports/sources/common/sql/identifiers.py
index 49d25f8e64cd..be7245ed9fc0 100644
--- a/posthog/temporal/data_imports/sources/common/sql/identifiers.py
+++ b/posthog/temporal/data_imports/sources/common/sql/identifiers.py
@@ -107,11 +107,24 @@ class AnsiIdentifierQuoter(_BaseQuoter):
class BracketIdentifierQuoter(_BaseQuoter):
"""T-SQL quoting with square brackets (MSSQL, Azure SQL Server).
- The allowlist already rejects identifiers containing `]`, so no
- additional escaping is required — but the parent class still calls
- `_validate_identifier` before quoting, which is the actual safety
- boundary.
+ Unlike the backtick / ANSI quoters, this one does NOT use the strict
+ alphanumeric allowlist. T-SQL delimited identifiers legitimately contain
+ spaces, `#`, and other punctuation that the allowlist rejects (real
+ SQL Server schemas have columns like `Orden#` and tables like
+ `Forma Pago`), and the allowlist crashed the import on them. Square-bracket
+ quoting makes any such name safe by doubling a literal `]` to `]]` — the
+ same escaping SQL Server's own `QUOTENAME()` performs — so that is the
+ actual safety boundary here. Control characters (which bracket-quoting
+ cannot neutralise and never appear in a real identifier) are still rejected.
"""
_open = "["
_close = "]"
+
+ def quote(self, identifier: str) -> str:
+ if not identifier:
+ raise InvalidIdentifierError("Identifier may not be empty")
+ if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in identifier):
+ raise InvalidIdentifierError(f"Invalid SQL identifier: {identifier!r}")
+ escaped = identifier.replace("]", "]]")
+ return f"{self._open}{escaped}{self._close}"
diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py
index d34ea7d50165..ac406714c389 100644
--- a/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py
+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_identifiers.py
@@ -91,6 +91,15 @@ class TestBracketIdentifierQuoter:
("851", "[851]"),
("$col", "[$col]"),
("a-b", "[a-b]"),
+ # T-SQL delimited identifiers accept characters the alphanumeric
+ # allowlist rejects; these are all real SQL Server names.
+ ("Orden#", "[Orden#]"),
+ ("Forma Pago", "[Forma Pago]"),
+ ("Presupuesto Vs Ejecución Mes Actual Tiendas ", "[Presupuesto Vs Ejecución Mes Actual Tiendas ]"),
+ ("a[b", "[a[b]"),
+ # A literal `]` is escaped by doubling, exactly like QUOTENAME().
+ ("a]b", "[a]]b]"),
+ ("x]; DROP TABLE foo; --", "[x]]; DROP TABLE foo; --]"),
],
)
def test_accepts_allowed_identifiers(self, identifier: str, expected: str) -> None:
@@ -99,15 +108,9 @@ class TestBracketIdentifierQuoter:
@pytest.mark.parametrize(
"identifier",
[
- "bad;id",
- "drop table x",
- "a'b",
- 'a"b',
- "a]b",
- "a[b",
"a\nb",
- "a b",
- "x]; DROP TABLE foo; --",
+ "a\tb",
+ "a\x00b",
"",
],
)
@@ -115,9 +118,13 @@ class TestBracketIdentifierQuoter:
with pytest.raises(InvalidIdentifierError):
self.quoter.quote(identifier)
+ def test_quote_qualified_escapes_closing_bracket(self) -> None:
+ assert self.quoter.quote_qualified("dbo", "Orden#") == "[dbo].[Orden#]"
+ assert self.quoter.quote_qualified("d]o", "t]bl") == "[d]]o].[t]]bl]"
+
def test_quote_qualified_joins_with_dot(self) -> None:
assert self.quoter.quote_qualified("dbo", "users") == "[dbo].[users]"
def test_quote_qualified_rejects_any_unsafe_part(self) -> None:
with pytest.raises(InvalidIdentifierError):
- self.quoter.quote_qualified("dbo", "bad;table")
+ self.quoter.quote_qualified("dbo", "bad\ntable")
diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
index efd730de8251..08a8b57e0647 100644
--- a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
@@ -134,35 +134,50 @@ class TestBuildQuery:
)
@pytest.mark.parametrize(
- "schema,table_name",
+ "schema,table_name,expected_from",
[
- ("dbo]; DROP TABLE foo; --", "users"),
- ("dbo", "users]; DROP TABLE foo; --"),
- ("dbo with space", "users"),
- ("dbo", "users'name"),
+ # Injection payloads are neutralised by bracket-quoting (a literal `]`
+ # is doubled), so the whole payload stays inside one quoted identifier.
+ ("dbo]; DROP TABLE foo; --", "users", "FROM [dbo]]; DROP TABLE foo; --].[users]"),
+ ("dbo", "users]; DROP TABLE foo; --", "FROM [dbo].[users]]; DROP TABLE foo; --]"),
+ # Legal SQL Server names the old allowlist wrongly rejected.
+ ("dbo with space", "users", "FROM [dbo with space].[users]"),
+ ("dbo", "users'name", "FROM [dbo].[users'name]"),
+ ("dbo", "Orden#", "FROM [dbo].[Orden#]"),
],
)
- def test_rejects_unsafe_schema_or_table(self, schema, table_name):
+ def test_quotes_schema_or_table_safely(self, schema, table_name, expected_from):
+ query, _ = _build_query(
+ schema=schema,
+ table_name=table_name,
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ )
+ assert expected_from in query
+
+ def test_rejects_control_char_in_table(self):
with pytest.raises(ValueError, match="Invalid SQL identifier"):
_build_query(
- schema=schema,
- table_name=table_name,
+ schema="dbo",
+ table_name="users\nname",
should_use_incremental_field=False,
incremental_field=None,
incremental_field_type=None,
db_incremental_field_last_value=None,
)
- def test_rejects_unsafe_incremental_field(self):
- with pytest.raises(ValueError, match="Invalid SQL identifier"):
- _build_query(
- schema="dbo",
- table_name="users",
- should_use_incremental_field=True,
- incremental_field="created_at]; DROP TABLE foo; --",
- incremental_field_type=IncrementalFieldType.DateTime,
- db_incremental_field_last_value="2025-01-01",
- )
+ def test_quotes_unsafe_incremental_field_safely(self):
+ query, _ = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=True,
+ incremental_field="created_at]; DROP TABLE foo; --",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ db_incremental_field_last_value="2025-01-01",
+ )
+ assert "WHERE [created_at]]; DROP TABLE foo; --]" in query
class TestBuildQueryEnabledColumns:
@@ -351,11 +366,22 @@ class TestFetchAverageRowSize:
assert "TOP 100" in size_query
assert "DATALENGTH([id])" in size_query
- def test_rejects_malformed_column_names(self, impl, cursor, logger):
- # If INFORMATION_SCHEMA returns a weird column name, the quoter
- # must reject it rather than splice it into SQL. Method catches
+ def test_handles_column_names_with_special_chars(self, impl, cursor, logger):
+ # Real SQL Server columns like `Orden#` are legal under bracket-quoting;
+ # they must be sampled, not crash the quoter (the bug this fixes).
+ cursor.fetchall.return_value = [("Orden#",), ("Forma Pago",)]
+ cursor.fetchone.return_value = (42,)
+ result = impl.fetch_average_row_size(cursor, "dbo", "t", "SELECT 1", {}, logger)
+ assert result == 42
+ size_query = cursor.execute.call_args_list[1].args[0]
+ assert "DATALENGTH([Orden#])" in size_query
+ assert "DATALENGTH([Forma Pago])" in size_query
+
+ def test_rejects_control_char_column_names(self, impl, cursor, logger):
+ # A column name with a control character can't be made safe by
+ # bracket-quoting, so the quoter rejects it; the method catches
# and returns None.
- cursor.fetchall.return_value = [("bad;col",)]
+ cursor.fetchall.return_value = [("bad\ncol",)]
cursor.fetchone.return_value = (1,)
result = impl.fetch_average_row_size(cursor, "dbo", "t", "SELECT 1", {}, logger)
assert result is None