You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by hu...@apache.org on 2026/10/06 16:25:41 UTC

(superset) 06/06: fix(security): stop a transform cancelling the placeholder-position gate

This is an automated email from the ASF dual-hosted git repository.

hughhhh pushed a commit to branch hughhhh/pfm-6-explore-indicator
in repository https://gitbox.apache.org/repos/asf/superset.git

commit c98c51af1a7b29272e43cf8c0d7e47eca7db45b6
Author: Hugh A Miles II <hu...@gmail.com>
AuthorDate: Tue Oct 6 12:24:12 2026 -0400

    fix(security): stop a transform cancelling the placeholder-position gate
    
    `placeholder_is_executable` compares two counts: `:value` occurrences in the
    raw text against the column references the identifier stand-in left in the
    parse tree. A transform naming that stand-in itself pays the difference.
    `concat(superset_pfm_value_standin, ':value')` has one placeholder, inside a
    literal contributing no reference, and one bare reference the owner wrote --
    the counts matched, and the gate passed a `:value` the engine never evaluates.
    
    That is the position the probe renders a bound value into, inside the owner's
    own quotes. A filter value closing the literal aliases a column of any table
    the connection can read into the stand-in's name, and the probe hands it back
    through the preview's emitted predicate -- a warehouse read for a principal
    with dataset write and no SQL Lab. Refused outright now; no legitimate
    transform names this identifier, and the comment claiming a collision could
    only fail closed was wrong.
    
    The compiled probe is pinned too, since each half is independently sufficient
    and the assembled query satisfied every check it had: one statement, no
    sub-query, `v0` its only alias. It may now carry no clause its builder did not
    add, and a FROM only where `select_without_from_suffix` asked for one -- the
    engine's own, not merely some table. A value could otherwise close the
    projection and append a FROM, or a WHERE, without disturbing the aliases.
    
    Two primitives carry it in `SQLStatement`, which also de-duplicates
    `is_bare_select_expression`'s clause walk. `get_clause_names` strips sqlglot's
    keyword-avoiding underscore so callers need not know its FROM is `from_`.
    A dialect whose statements cannot be taken apart declines rather than probing.
    
    Co-Authored-By: Claude Opus 5 (1M context) <no...@anthropic.com>
---
 superset/connectors/sqla/partition_mapping.py      | 86 +++++++++++++++++---
 superset/sql/parse.py                              | 55 ++++++++++++-
 .../connectors/sqla/partition_mapping_test.py      | 92 ++++++++++++++++++----
 tests/unit_tests/sql/parse_tests.py                | 49 ++++++++++++
 4 files changed, 254 insertions(+), 28 deletions(-)

diff --git a/superset/connectors/sqla/partition_mapping.py b/superset/connectors/sqla/partition_mapping.py
index 0377a251bbf..f006ea5f092 100644
--- a/superset/connectors/sqla/partition_mapping.py
+++ b/superset/connectors/sqla/partition_mapping.py
@@ -217,9 +217,13 @@ _PARSE_STANDIN = "NULL"
 #: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
 #: the parse tree no longer records that a placeholder was ever there. An
 #: identifier does leave a trace -- a column reference -- and one that is
-#: missing is a placeholder the engine will never evaluate. Named so it cannot
-#: plausibly collide with a real column; a collision only makes the count
-#: disagree, which fails closed.
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
 _PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
 
 #: Functions whose value depends on wall-clock time or randomness. The probe
@@ -566,9 +570,26 @@ def placeholder_is_executable(transform: str | None, engine: str) -> bool:
     count the column references it produced. A literal holds no column
     reference and a comment is not parsed at all, so either case comes back
     short of the number of placeholders the owner wrote.
+
+    Which is why a transform naming the stand-in itself is refused outright. The
+    count is the whole gate, and a hand-written occurrence pays the difference:
+    ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+    a literal that contributes nothing, and one bare reference the owner wrote --
+    so the counts match and the gate passes a placeholder the engine will never
+    evaluate. The probe then renders the bound value inside the owner's quotes,
+    where a value closing the literal can alias a column of any table the
+    connection can read into the stand-in's name and have the probe hand it back
+    through the preview. There is no legitimate transform naming this identifier,
+    so refusing it costs nothing and makes the count mean what it claims.
     """
     if not transform:
         return False
+    if _PLACEHOLDER_STANDIN in transform.lower():
+        # Lowercased on both sides because `count_bare_column_references` is
+        # case-insensitive too: a dialect may normalize an unquoted identifier,
+        # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+        # while slipping past a case-sensitive check here.
+        return False
     expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
     if not expected:
         return False
@@ -1013,7 +1034,12 @@ def build_probe_sql(
     return "SELECT " + ", ".join(selections) + from_suffix
 
 
-def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
+def probe_sql_is_evaluable(
+    sql: str,
+    engine: str,
+    expected: int,
+    from_suffix: str = "",
+) -> bool:
     """
     Whether the compiled probe is still the query `build_probe_sql` intended.
 
@@ -1023,7 +1049,7 @@ def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
     are supplied by whoever is filtering a chart, not only by the owner who
     wrote the transform.
 
-    Three things have to hold, and all three are about the probe still being
+    Four things have to hold, and all four are about the probe still being
     readable rather than about taste:
 
     * One statement. A value that closes the expression and starts another
@@ -1035,9 +1061,17 @@ def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
       swallows the rest of its line including its own alias, and the engine
       still answers with a column -- so the count alone does not notice.
       Checking the aliases is what makes a missing one visible.
-
-    A ``FROM`` clause is allowed: ``select_without_from_suffix`` adds one on the
-    engines that cannot select without a table.
+    * No clause this function did not build, and a ``FROM`` only where
+      ``select_without_from_suffix`` asked for one -- the engine's own, not
+      merely some table. A rendered value can close the projection and append a
+      ``FROM`` of its own without disturbing the aliases that follow it, which
+      is a read of a table the mapping has no business reading; the same value
+      could append a ``WHERE`` and nothing would notice either.
+
+    Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+    spacing does not have to match what the probe emitted. Identifier case does,
+    which costs nothing: `_probe` hands the same engine constant to
+    `build_probe_sql` and to this gate.
     """
     try:
         script = SQLScript(sql, engine)
@@ -1046,11 +1080,40 @@ def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
     if len(script.statements) != 1:
         return False
     statement = script.statements[0]
+    if not isinstance(statement, SQLStatement):
+        # A dialect whose statements this gate cannot take apart -- KQL -- gets
+        # no probe rather than an unchecked one. It never had one: the clause
+        # inspection below is implemented for SQL statements only, and the
+        # alternative to declining here is an `AttributeError` that `_probe`
+        # swallows into the same outcome, less legibly.
+        return False
     if statement.has_subquery():
         return False
+    if statement.get_clause_names() - {"from"}:
+        return False
+    if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+        return False
     return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
 
 
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+    """
+    The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+    Parsed rather than string-compared so that the comparison in
+    `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+    not parse answers ``None``, which no statement carrying a FROM can match --
+    the probe then declines, which is the right way for an unreadable engine
+    constant to fail.
+    """
+    if not from_suffix.strip():
+        return None
+    try:
+        return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+    except SupersetParseError:
+        return None
+
+
 def evaluate_transform(
     database: Database,
     catalog: str | None,
@@ -1159,13 +1222,16 @@ def _probe(
         return None
 
     try:
+        from_suffix = database.db_engine_spec.select_without_from_suffix
         sql = build_probe_sql(
             transform,
             distinct,
             _dialect_for(database),
-            database.db_engine_spec.select_without_from_suffix,
+            from_suffix,
         )
-        if not probe_sql_is_evaluable(sql, database.backend, len(distinct)):
+        if not probe_sql_is_evaluable(
+            sql, database.backend, len(distinct), from_suffix
+        ):
             # Declining rather than raising, for the same reason every other
             # failure here declines: the chart query is already correct without
             # the mirror, and it is the only thing the caller is waiting on.
diff --git a/superset/sql/parse.py b/superset/sql/parse.py
index 914972d06b6..1070a727c48 100644
--- a/superset/sql/parse.py
+++ b/superset/sql/parse.py
@@ -1234,9 +1234,58 @@ class SQLStatement(BaseSQLStatement[exp.Expression]):
             return False
         if len(self._parsed.expressions) != 1:
             return False
-        return not any(
-            value for key, value in self._parsed.args.items() if key != "expressions"
-        )
+        return not self.get_clause_names()
+
+    def get_clause_names(self) -> set[str]:
+        """
+        Which clauses other than the projection this ``SELECT`` populates.
+
+        `is_bare_select_expression` answers "none of them", which is too strong
+        for a caller that assembles a statement with a FROM clause of its own
+        and needs to know that nothing *else* came along with it.
+
+        Reported as the set that is present rather than as a denylist of clause
+        names, for the same reason: a sqlglot release or a dialect introducing a
+        clause this does not know about shows up in the answer instead of being
+        silently permitted.
+
+        Returns an empty set for anything that is not a ``SELECT``, which such a
+        caller has to reject on other grounds anyway.
+
+        Trailing underscores are stripped, because sqlglot appends one to the
+        names that collide with a Python keyword -- its FROM clause is
+        ``from_``. Callers should not have to know that, nor track it across
+        sqlglot releases.
+
+        :return: clause names, e.g. ``{"from", "where"}``
+        """
+        if not isinstance(self._parsed, exp.Select):
+            return set()
+        return {
+            key.rstrip("_")
+            for key, value in self._parsed.args.items()
+            if value and key != "expressions"
+        }
+
+    def get_from_clause_sql(self) -> str | None:
+        """
+        This statement's ``FROM`` clause, rendered back to SQL.
+
+        For comparing an assembled statement's FROM against the one its builder
+        intended. Both sides are rendered rather than compared as raw text, so
+        the comparison does not depend on the whitespace the builder happened to
+        use. Identifier case is preserved, as it has to be for an engine that
+        treats it as significant.
+
+        :return: the rendered clause, or ``None`` where there is no FROM
+        """
+        if not isinstance(self._parsed, exp.Select):
+            return None
+        # ``from_`` is sqlglot's own name for it, the trailing underscore being
+        # how it avoids the Python keyword; both are read so that the lookup
+        # does not depend on which one a given release uses.
+        from_clause = self._parsed.args.get("from_") or self._parsed.args.get("from")
+        return from_clause.sql(dialect=self._dialect) if from_clause else None
 
     def get_select_aliases(self) -> list[str | None]:
         """
diff --git a/tests/unit_tests/connectors/sqla/partition_mapping_test.py b/tests/unit_tests/connectors/sqla/partition_mapping_test.py
index 9a29c918d3a..8e66e6fc7ce 100644
--- a/tests/unit_tests/connectors/sqla/partition_mapping_test.py
+++ b/tests/unit_tests/connectors/sqla/partition_mapping_test.py
@@ -1802,6 +1802,14 @@ def test_activity_is_exactly_the_absence_of_issues(transform: str | None) -> Non
         ("1 /* :value */", False),
         ("lower(x)", False),
         (None, False),
+        # The stand-in written by hand. It supplies the bare column reference a
+        # placeholder inside a literal failed to produce, so the counts cancel
+        # and the gate used to pass a `:value` the engine never evaluates.
+        ("concat(superset_pfm_value_standin, ':value')", False),
+        ("SUPERSET_PFM_VALUE_STANDIN || ':value'", False),
+        # Refused even alongside a placeholder that *is* executable: there is no
+        # legitimate transform naming this identifier at all.
+        ("concat(superset_pfm_value_standin, :value)", False),
     ],
 )
 def test_a_placeholder_is_executable_only_where_the_engine_reads_it(
@@ -1880,23 +1888,73 @@ def test_a_commented_placeholder_loses_the_alias_the_probe_reads_by() -> None:
     assert probe_sql_is_evaluable(sql, "sqlite", 1) is False
 
 
+def test_a_hand_written_standin_cannot_cancel_the_placeholder_count() -> None:
+    """
+    The count gate is two-sided, and a transform that writes the stand-in itself
+    pays the difference. `concat(superset_pfm_value_standin, ':value')` has one
+    `:value`, inside a literal that yields no column reference, and one bare
+    reference the owner wrote -- so the counts matched and the gate passed a
+    placeholder the engine never evaluates.
+
+    Which mattered because the probe then renders the bound value inside the
+    owner's quotes: a value closing that literal aliases a column of any table
+    the connection can read into the stand-in's own name, and the probe hands it
+    back through the preview's emitted predicate. A dataset-write principal
+    without SQL Lab could read the warehouse that way.
+
+    Both halves are pinned here because each is independently sufficient, and
+    the compiled probe used to satisfy every check it had: one statement, no
+    sub-query, and `v0` as its only alias.
+    """
+    transform = "concat(superset_pfm_value_standin, ':value')"
+
+    # The write-side gate, which is what keeps the transform from ever activating.
+    assert placeholder_is_executable(transform, "postgresql") is False
+    assert validate_transform(transform, "postgresql") != []
+
+    # And the probe-side backstop, for a transform stored before that gate
+    # existed: the smuggled FROM is not the one the engine asked for.
+    sql = build_probe_sql(
+        transform,
+        [") AS v0 FROM private.secrets AS p(superset_pfm_value_standin) -- "],
+    )
+    assert "FROM private.secrets" in sql
+    assert probe_sql_is_evaluable(sql, "postgresql", 1, "") is False
+
+
 @pytest.mark.parametrize(
-    "sql, expected, evaluable",
+    "sql, expected, suffix, evaluable",
     [
-        ("SELECT lower('a') AS v0", 1, True),
-        ("SELECT lower('a') AS v0, lower('b') AS v1", 2, True),
-        # `select_without_from_suffix`, for an engine that cannot select bare.
-        ("SELECT lower('a') AS v0 FROM DUAL", 1, True),
-        ("SELECT '' || (SELECT secret FROM vault) || '' AS v0", 1, False),
-        ("SELECT 1 -- 'x' AS v0", 1, False),
-        ("SELECT 1 AS v0; DROP TABLE t", 1, False),
-        ("SELECT lower('a') AS v0", 2, False),
-        ("SELECT lower('a')", 1, False),
-        ("not sql at all (", 1, False),
+        ("SELECT lower('a') AS v0", 1, "", True),
+        ("SELECT lower('a') AS v0, lower('b') AS v1", 2, "", True),
+        # `select_without_from_suffix`, for an engine that cannot select bare:
+        # accepted where the engine asked for that FROM...
+        ("SELECT lower('a') AS v0 FROM DUAL", 1, " FROM DUAL", True),
+        (
+            "SELECT lower('a') AS v0 FROM SYSIBM.SYSDUMMY1",
+            1,
+            " FROM SYSIBM.SYSDUMMY1",
+            True,
+        ),
+        # Spacing need not match; sqlglot renders both sides.
+        ("SELECT lower('a') AS v0 FROM DUAL", 1, "   from DUAL", True),
+        # ...and refused where it did not, or where the table is not the one it
+        # named. A rendered value can close the projection and append a FROM of
+        # its own without disturbing the aliases that follow.
+        ("SELECT lower('a') AS v0 FROM DUAL", 1, "", False),
+        ("SELECT lower('a') AS v0 FROM private.secrets", 1, " FROM DUAL", False),
+        # A WHERE is not a clause this gate's caller ever builds either.
+        ("SELECT lower('a') AS v0 WHERE 1 = 1", 1, "", False),
+        ("SELECT '' || (SELECT secret FROM vault) || '' AS v0", 1, "", False),
+        ("SELECT 1 -- 'x' AS v0", 1, "", False),
+        ("SELECT 1 AS v0; DROP TABLE t", 1, "", False),
+        ("SELECT lower('a') AS v0", 2, "", False),
+        ("SELECT lower('a')", 1, "", False),
+        ("not sql at all (", 1, "", False),
     ],
 )
 def test_the_probe_backstop_accepts_only_a_plain_projection_per_value(
-    sql: str, expected: int, evaluable: bool
+    sql: str, expected: int, suffix: str, evaluable: bool
 ) -> None:
     """
     The write-side gates all read the transform with a stand-in where the value
@@ -1905,7 +1963,11 @@ def test_the_probe_backstop_accepts_only_a_plain_projection_per_value(
     the owner who wrote the transform. This is the gate that sees the finished
     query.
 
-    A FROM clause is allowed, because `select_without_from_suffix` adds one on
-    Oracle and Db2.
+    A FROM clause is allowed only where `select_without_from_suffix` asked for
+    one, and only the one it named: Oracle and Db2 cannot select bare, which is
+    not a reason to let a value smuggle in a table of its own. Compared as
+    sqlglot renders both sides, so the suffix's own spacing does not have to
+    match what the probe emitted. Identifier case does: sqlglot preserves it,
+    and `_probe` hands the same constant to the builder and to this gate.
     """
-    assert probe_sql_is_evaluable(sql, "sqlite", expected) is evaluable
+    assert probe_sql_is_evaluable(sql, "sqlite", expected, suffix) is evaluable
diff --git a/tests/unit_tests/sql/parse_tests.py b/tests/unit_tests/sql/parse_tests.py
index 6c7fba884ae..5a0e7db61c7 100644
--- a/tests/unit_tests/sql/parse_tests.py
+++ b/tests/unit_tests/sql/parse_tests.py
@@ -7405,6 +7405,55 @@ def test_is_bare_select_expression(sql: str, engine: str, expected: bool) -> Non
     assert SQLStatement(sql, engine).is_bare_select_expression() is expected
 
 
+@pytest.mark.parametrize("engine", ["hive", "postgresql", "trino", "bigquery"])
+@pytest.mark.parametrize(
+    "sql, expected",
+    [
+        ("SELECT lower(country)", set()),
+        ("SELECT a, b", set()),
+        # Reported without sqlglot's keyword-avoiding underscore, which its FROM
+        # clause carries as `from_`. A caller comparing against {"from"} should
+        # not have to know that, nor track it across releases.
+        ("SELECT 1 FROM t", {"from"}),
+        ("SELECT 1 FROM t WHERE x = 1", {"from", "where"}),
+        ("SELECT 1 GROUP BY 1", {"group"}),
+        ("SELECT 1 LIMIT 1", {"limit"}),
+        ("INSERT INTO t VALUES (1)", set()),
+    ],
+)
+def test_get_clause_names(sql: str, engine: str, expected: set[str]) -> None:
+    """
+    Check the `get_clause_names` method.
+
+    Parametrized by engine for the same reason `is_bare_select_expression` is:
+    the answer is read off the parsed node's own arguments, so a dialect that
+    names one differently has to show up in the answer rather than vanish from
+    it.
+    """
+    assert SQLStatement(sql, engine).get_clause_names() == expected
+
+
+@pytest.mark.parametrize("engine", ["hive", "postgresql", "trino", "bigquery"])
+@pytest.mark.parametrize(
+    "sql, expected",
+    [
+        ("SELECT 1", None),
+        ("SELECT 1 FROM DUAL", "FROM DUAL"),
+        ("SELECT 1 FROM SYSIBM.SYSDUMMY1", "FROM SYSIBM.SYSDUMMY1"),
+        # Rendered, so the caller's own spacing does not have to match...
+        ("SELECT 1   FROM    DUAL", "FROM DUAL"),
+        # ...while identifier case, which an engine may treat as significant,
+        # survives.
+        ("SELECT 1 FROM dual", "FROM dual"),
+        ("SELECT 1 FROM a.b AS c", "FROM a.b AS c"),
+        ("INSERT INTO t VALUES (1)", None),
+    ],
+)
+def test_get_from_clause_sql(sql: str, engine: str, expected: str | None) -> None:
+    """Check the `get_from_clause_sql` method."""
+    assert SQLStatement(sql, engine).get_from_clause_sql() == expected
+
+
 @pytest.mark.parametrize(
     "sql, engine, expected",
     [