You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by be...@apache.org on 2026/03/16 23:59:44 UTC

(superset) branch conservative-rls updated (6ecc446f59f -> 68b0aa11e4c)

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

beto pushed a change to branch conservative-rls
in repository https://gitbox.apache.org/repos/asf/superset.git


 discard 6ecc446f59f feat: apply RLS conservatively
     new 68b0aa11e4c feat: apply RLS conservatively

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (6ecc446f59f)
            \
             N -- N -- N   refs/heads/conservative-rls (68b0aa11e4c)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../models/test_virtual_dataset_format.py          | 42 ++++++++++++----------
 1 file changed, 23 insertions(+), 19 deletions(-)


(superset) 01/01: feat: apply RLS conservatively

Posted by be...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

beto pushed a commit to branch conservative-rls
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 68b0aa11e4c91c4f6f249c845b1afb630a33d0e2
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Mon Mar 16 19:49:52 2026 -0400

    feat: apply RLS conservatively
---
 superset/models/helpers.py                         |  11 +-
 superset/sql/parse.py                              |  13 +-
 superset/utils/rls.py                              |   6 +-
 .../models/test_virtual_dataset_format.py          | 389 +++++++++++++++++++++
 4 files changed, 410 insertions(+), 9 deletions(-)

diff --git a/superset/models/helpers.py b/superset/models/helpers.py
index 704b0f4c56a..a4f5cae5c5c 100644
--- a/superset/models/helpers.py
+++ b/superset/models/helpers.py
@@ -2049,15 +2049,20 @@ class ExploreMixin:  # pylint: disable=too-many-public-methods
         if parsed_script.statements:
             default_schema = self.database.get_default_schema(self.catalog)
             try:
-                for statement in parsed_script.statements:
+                # Only regenerate the SQL if RLS predicates were actually applied.
+                # Unnecessary round-tripping through sqlglot can alter SQL in
+                # dialect-specific ways (e.g. dropping column aliases, rewriting
+                # Redshift-specific syntax) and break virtual dataset queries.
+                if any(
                     apply_rls(
                         self.database,
                         self.catalog,
                         self.schema or default_schema or "",
                         statement,
                     )
-                # Regenerate the SQL after RLS application
-                from_sql = parsed_script.format()
+                    for statement in parsed_script.statements
+                ):
+                    from_sql = parsed_script.format()
             except Exception as ex:
                 # Log the error but don't fail - RLS application is best-effort
                 logger.warning("Failed to apply RLS to virtual dataset SQL: %s", ex)
diff --git a/superset/sql/parse.py b/superset/sql/parse.py
index 4f9c92a2776..3f4892cfcfa 100644
--- a/superset/sql/parse.py
+++ b/superset/sql/parse.py
@@ -260,12 +260,15 @@ class RLSAsSubqueryTransformer(RLSTransformer):
             if node.alias:
                 alias = node.alias
             else:
-                name = ".".join(
-                    part
-                    for part in (node.catalog or "", node.db or "", node.name)
-                    if part
+                # Use just the table name (not schema-qualified) so that
+                # column references like ``table.column`` still resolve after
+                # the table is replaced with a subquery.  Using the full
+                # ``schema.table`` path as a quoted identifier creates a
+                # mismatch: the columns reference ``table`` but the alias is
+                # ``"schema.table"``, which are different identifiers.
+                alias = exp.TableAlias(
+                    this=exp.Identifier(this=node.name, quoted=True)
                 )
-                alias = exp.TableAlias(this=exp.Identifier(this=name, quoted=True))
 
             node.set("alias", None)
             node = exp.Subquery(
diff --git a/superset/utils/rls.py b/superset/utils/rls.py
index 05f8ea9058c..7e6cdf2aee7 100644
--- a/superset/utils/rls.py
+++ b/superset/utils/rls.py
@@ -34,9 +34,11 @@ def apply_rls(
     catalog: str | None,
     schema: str,
     parsed_statement: BaseSQLStatement[Any],
-) -> None:
+) -> bool:
     """
     Modify statement inplace to ensure RLS rules are applied.
+
+    :returns: True if any RLS predicates were actually applied, False otherwise.
     """
     # There are two ways to insert RLS: either replacing the table with a subquery
     # that has the RLS, or appending the RLS to the ``WHERE`` clause. The former is
@@ -57,7 +59,9 @@ def apply_rls(
             if predicate
         ]
 
+    has_predicates = any(predicates.values())
     parsed_statement.apply_rls(catalog, schema, predicates, method)
+    return has_predicates
 
 
 def get_predicates_for_table(
diff --git a/tests/unit_tests/models/test_virtual_dataset_format.py b/tests/unit_tests/models/test_virtual_dataset_format.py
new file mode 100644
index 00000000000..d180ee118e2
--- /dev/null
+++ b/tests/unit_tests/models/test_virtual_dataset_format.py
@@ -0,0 +1,389 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Tests for virtual dataset SQL handling with RLS and sqlglot formatting.
+
+Two issues are covered:
+
+1. **Unnecessary sqlglot round-trip** – ``get_from_clause()`` used to call
+   ``format()`` even when no RLS rules applied, which could silently rewrite
+   dialect-specific SQL (e.g. ``NVL`` → ``COALESCE`` on Redshift).
+
+2. **RLS subquery alias mismatch** – ``RLSAsSubqueryTransformer`` used the
+   fully-qualified table name (``"schema.table"``) as the subquery alias,
+   which broke column references that used just the table name
+   (``table.column``), producing Redshift errors like
+   ``column "X" does not exist in virtual_table``.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+from sqlalchemy.sql.elements import TextClause
+
+from superset.models.helpers import ExploreMixin
+from superset.sql.parse import RLSMethod, SQLStatement, Table
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def virtual_datasource() -> MagicMock:
+    """
+    Create a mock datasource that behaves like a virtual dataset.
+    """
+    datasource = MagicMock(spec=ExploreMixin)
+
+    # Wire up real methods from ExploreMixin
+    datasource.get_from_clause = ExploreMixin.get_from_clause.__get__(datasource)
+    datasource.text = lambda sql: TextClause(sql)
+
+    # Mock the database and db_engine_spec
+    datasource.db_engine_spec.engine = "redshift"
+    datasource.db_engine_spec.get_cte_query.return_value = None
+    datasource.db_engine_spec.cte_alias = "__cte"
+    datasource.database.get_default_schema.return_value = "public"
+    datasource.catalog = None
+    datasource.schema = "public"
+
+    return datasource
+
+
+def _set_virtual_sql(datasource: MagicMock, sql: str) -> None:
+    """
+    Configure the mock datasource to return the given SQL.
+    """
+    datasource.get_rendered_sql.return_value = sql
+
+
+def _get_subquery_sql(datasource: MagicMock) -> str:
+    """
+    Run get_from_clause and extract the inner SQL from the virtual_table alias.
+    """
+    from_clause, _ = datasource.get_from_clause(template_processor=None)
+    return str(from_clause.element).strip()
+
+
+# ---------------------------------------------------------------------------
+# 1. format() should only run when RLS predicates were actually applied
+# ---------------------------------------------------------------------------
+
+
+class TestVirtualDatasetNoRLS:
+    """
+    When no RLS predicates apply, the virtual dataset SQL must not be
+    round-tripped through sqlglot's formatter.
+    """
+
+    @patch("superset.models.helpers.apply_rls", return_value=False)
+    def test_sql_preserved_when_no_rls(
+        self,
+        mock_apply_rls: MagicMock,
+        virtual_datasource: MagicMock,
+        app: Flask,
+    ) -> None:
+        """
+        The original SQL should be used verbatim when apply_rls returns False.
+        """
+        original_sql = "SELECT hotel_id, is_top_hotel_chain_burn FROM public.hotels"
+        _set_virtual_sql(virtual_datasource, original_sql)
+
+        inner_sql = _get_subquery_sql(virtual_datasource)
+        assert inner_sql == original_sql
+
+    @patch("superset.models.helpers.apply_rls", return_value=False)
+    def test_redshift_nvl_preserved_when_no_rls(
+        self,
+        mock_apply_rls: MagicMock,
+        virtual_datasource: MagicMock,
+        app: Flask,
+    ) -> None:
+        """
+        sqlglot rewrites ``NVL(a, b)`` → ``COALESCE(a, b)`` for Redshift.
+        Without the fix the inner SQL would be silently rewritten.
+        """
+        original_sql = "SELECT hotel_id, NVL(burn_flag, false) FROM hotels"
+        _set_virtual_sql(virtual_datasource, original_sql)
+
+        inner_sql = _get_subquery_sql(virtual_datasource)
+        assert "NVL" in inner_sql
+        assert "COALESCE" not in inner_sql
+
+    @patch("superset.models.helpers.apply_rls", return_value=False)
+    def test_redshift_current_timestamp_preserved_when_no_rls(
+        self,
+        mock_apply_rls: MagicMock,
+        virtual_datasource: MagicMock,
+        app: Flask,
+    ) -> None:
+        """
+        sqlglot rewrites ``current_timestamp`` → ``GETDATE()`` for Redshift.
+        """
+        original_sql = "SELECT hotel_id, current_timestamp FROM hotels"
+        _set_virtual_sql(virtual_datasource, original_sql)
+
+        inner_sql = _get_subquery_sql(virtual_datasource)
+        assert "current_timestamp" in inner_sql
+        assert "GETDATE" not in inner_sql
+
+    @patch("superset.models.helpers.apply_rls", return_value=False)
+    def test_redshift_cast_syntax_preserved_when_no_rls(
+        self,
+        mock_apply_rls: MagicMock,
+        virtual_datasource: MagicMock,
+        app: Flask,
+    ) -> None:
+        """
+        sqlglot rewrites Redshift ``::`` cast syntax to ``CAST(... AS ...)``.
+        """
+        original_sql = (
+            "SELECT hotel_name::varchar(256) AS name, "
+            "is_top_hotel_chain_burn FROM public.hotels"
+        )
+        _set_virtual_sql(virtual_datasource, original_sql)
+
+        inner_sql = _get_subquery_sql(virtual_datasource)
+        assert "::varchar(256)" in inner_sql
+
+
+class TestVirtualDatasetWithRLS:
+    """
+    When RLS predicates are applied, the SQL must be regenerated via
+    sqlglot to serialize the AST modifications.
+    """
+
+    @patch("superset.models.helpers.apply_rls", return_value=True)
+    def test_sql_reformatted_when_rls_applied(
+        self,
+        mock_apply_rls: MagicMock,
+        virtual_datasource: MagicMock,
+        app: Flask,
+    ) -> None:
+        """
+        When apply_rls returns True, the SQL should be regenerated through
+        sqlglot's format() to serialize the AST modifications.
+        """
+        original_sql = "SELECT hotel_id, is_top_hotel_chain_burn FROM public.hotels"
+        _set_virtual_sql(virtual_datasource, original_sql)
+
+        inner_sql = _get_subquery_sql(virtual_datasource)
+
+        # After format(), sqlglot pretty-prints (adds newlines, etc.)
+        assert inner_sql != original_sql
+        # But the column must still be present
+        assert "is_top_hotel_chain_burn" in inner_sql
+
+
+# ---------------------------------------------------------------------------
+# 2. apply_rls() return value
+# ---------------------------------------------------------------------------
+
+
+class TestApplyRlsReturnValue:
+    """
+    Test that apply_rls correctly reports whether predicates were applied.
+    """
+
+    def test_returns_false_when_no_tables(self, app: Flask) -> None:
+        """
+        apply_rls should return False when the statement has no tables.
+        """
+        from superset.utils.rls import apply_rls
+
+        database = MagicMock()
+        database.db_engine_spec.get_rls_method.return_value = MagicMock()
+        database.get_default_catalog.return_value = None
+
+        statement = MagicMock()
+        statement.tables = []
+
+        result = apply_rls(
+            database=database,
+            catalog=None,
+            schema="public",
+            parsed_statement=statement,
+        )
+        assert result is False
+
+    @patch("superset.utils.rls.get_predicates_for_table")
+    def test_returns_false_when_predicates_empty(
+        self,
+        mock_get_predicates: MagicMock,
+        app: Flask,
+    ) -> None:
+        """
+        apply_rls should return False when tables exist but have no RLS rules.
+        """
+        from superset.utils.rls import apply_rls
+
+        mock_get_predicates.return_value = []
+
+        database = MagicMock()
+        database.db_engine_spec.get_rls_method.return_value = MagicMock()
+        database.get_default_catalog.return_value = None
+
+        mock_table = MagicMock()
+        mock_table.qualify.return_value = Table("hotels", "public", None)
+
+        statement = MagicMock()
+        statement.tables = [mock_table]
+
+        result = apply_rls(
+            database=database,
+            catalog=None,
+            schema="public",
+            parsed_statement=statement,
+        )
+        assert result is False
+
+    @patch("superset.utils.rls.get_predicates_for_table")
+    def test_returns_true_when_predicates_exist(
+        self,
+        mock_get_predicates: MagicMock,
+        app: Flask,
+    ) -> None:
+        """
+        apply_rls should return True when RLS predicates are found.
+        """
+        from superset.utils.rls import apply_rls
+
+        mock_get_predicates.return_value = ["tenant_id = 42"]
+
+        database = MagicMock()
+        database.db_engine_spec.get_rls_method.return_value = MagicMock()
+        database.get_default_catalog.return_value = None
+
+        mock_table = MagicMock()
+        mock_table.qualify.return_value = Table("hotels", "public", None)
+
+        statement = MagicMock()
+        statement.tables = [mock_table]
+        statement.parse_predicate.return_value = MagicMock()
+
+        result = apply_rls(
+            database=database,
+            catalog=None,
+            schema="public",
+            parsed_statement=statement,
+        )
+        assert result is True
+        statement.apply_rls.assert_called_once()
+
+
+# ---------------------------------------------------------------------------
+# 3. RLS subquery alias must use just the table name, not schema-qualified
+# ---------------------------------------------------------------------------
+
+
+class TestRLSSubqueryAlias:
+    """
+    When RLSAsSubqueryTransformer replaces a table with a filtered subquery,
+    the subquery alias must match what column references in the query expect.
+
+    If the SQL says ``SELECT hotels.col FROM public.hotels``, the subquery
+    must be aliased as ``"hotels"`` (not ``"public.hotels"``), otherwise
+    ``hotels.col`` won't resolve and Redshift returns::
+
+        column "col" does not exist in virtual_table
+    """
+
+    def test_table_qualified_columns_no_alias(self, app: Flask) -> None:
+        """
+        Column references like ``hotels.col`` must resolve after RLS wraps
+        ``public.hotels`` in a subquery.
+        """
+        sql = (
+            "SELECT hotels.hotel_id, hotels.is_top_hotel_chain_burn "
+            "FROM public.hotels"
+        )
+        statement = SQLStatement(sql, engine="redshift")
+        predicate = statement.parse_predicate("tenant_id = 1")
+        statement.apply_rls(
+            None,
+            "public",
+            {Table("hotels", "public", None): [predicate]},
+            RLSMethod.AS_SUBQUERY,
+        )
+        result = statement.format()
+
+        # The subquery alias must be just "hotels", not "public.hotels"
+        assert 'AS "hotels"' in result
+        assert 'AS "public.hotels"' not in result
+        assert "hotels.is_top_hotel_chain_burn" in result
+
+    def test_catalog_schema_qualified_table_no_alias(self, app: Flask) -> None:
+        """
+        Even with a catalog-qualified table, the subquery alias should be
+        just the table name so that ``table.col`` references still work.
+        """
+        sql = (
+            "SELECT hotels.hotel_id, hotels.is_top_hotel_chain_burn "
+            "FROM mycat.public.hotels"
+        )
+        statement = SQLStatement(sql, engine="redshift")
+        predicate = statement.parse_predicate("tenant_id = 1")
+        statement.apply_rls(
+            None,
+            "public",
+            {Table("hotels", "public", "mycat"): [predicate]},
+            RLSMethod.AS_SUBQUERY,
+        )
+        result = statement.format()
+
+        assert 'AS "hotels"' in result
+        assert 'AS "mycat.public.hotels"' not in result
+
+    def test_explicit_alias_preserved(self, app: Flask) -> None:
+        """
+        When the table already has an explicit alias, it should be reused.
+        """
+        sql = "SELECT h.hotel_id, h.is_top_hotel_chain_burn " "FROM public.hotels h"
+        statement = SQLStatement(sql, engine="redshift")
+        predicate = statement.parse_predicate("tenant_id = 1")
+        statement.apply_rls(
+            None,
+            "public",
+            {Table("hotels", "public", None): [predicate]},
+            RLSMethod.AS_SUBQUERY,
+        )
+        result = statement.format()
+
+        assert "AS h" in result
+        assert "h.is_top_hotel_chain_burn" in result
+
+    def test_unqualified_columns_work(self, app: Flask) -> None:
+        """
+        Unqualified column references should work regardless of the alias.
+        """
+        sql = "SELECT hotel_id, is_top_hotel_chain_burn FROM public.hotels"
+        statement = SQLStatement(sql, engine="redshift")
+        predicate = statement.parse_predicate("tenant_id = 1")
+        statement.apply_rls(
+            None,
+            "public",
+            {Table("hotels", "public", None): [predicate]},
+            RLSMethod.AS_SUBQUERY,
+        )
+        result = statement.format()
+
+        assert "is_top_hotel_chain_burn" in result
+        assert "WHERE" in result  # RLS predicate applied