bito-code-review[bot] commented on code in PR #42929:
URL: https://github.com/apache/superset/pull/42929#discussion_r3742517424


##########
superset/models/helpers.py:
##########
@@ -3020,9 +3080,40 @@ def get_from_clause(
                 if rls_applied:
                     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)
+            except Exception as ex:  # pylint: disable=broad-except
+                # RLS injection failures fail closed: only continue when it is
+                # positively confirmed that no RLS predicates apply to the
+                # referenced tables; any other outcome aborts the query.
+                try:
+                    rls_required = any(
+                        get_predicates_for_table(
+                            table.qualify(
+                                catalog=self.catalog,
+                                schema=self.schema or default_schema or "",
+                            ),
+                            self.database,
+                            self.database.get_default_catalog(),
+                            exclude_dataset_id=self_id,
+                        )
+                        for statement in parsed_script.statements
+                        for table in statement.tables
+                    )
+                except Exception:  # pylint: disable=broad-except

Review Comment:
   <!-- Bito Reply -->
   The suggestion to avoid broad exception clauses is a standard best practice 
to prevent masking unexpected errors. However, in this specific case, the 
implementation is intentionally designed to fail-closed by catching all 
exceptions to ensure that any failure in RLS predicate application results in 
an aborted query rather than an insecure state. Given this requirement, the 
current approach is appropriate for the intended safety behavior.
   
   **superset/models/helpers.py**
   ```
   except Exception as ex:  # pylint: disable=broad-except
                   # RLS injection failures fail closed: only continue when it 
is
                   # positively confirmed that no RLS predicates apply to the
                   # referenced tables; any other outcome aborts the query.
                   try:
                       rls_required = any(
                           get_predicates_for_table(
                               table.qualify(
                                   catalog=self.catalog,
                                   schema=self.schema or default_schema or "",
                               ),
                               self.database,
                               self.database.get_default_catalog(),
                               exclude_dataset_id=self_id,
                           )
                           for statement in parsed_script.statements
                           for table in statement.tables
                       )
                   except Exception:  # pylint: disable=broad-except
   ```



##########
tests/unit_tests/connectors/sqla/models_test.py:
##########
@@ -1486,6 +1486,33 @@ def 
test_validate_stored_expression_rejects_subquery_around_jinja(
         )
 
 
+def test_get_sqla_col_revalidates_rendered_jinja_expression(
+    mocker: MockerFixture,
+) -> None:
+    """
+    A Jinja block that renders into a sub-query must be rejected at query
+    time: save-time validation only sees the block as a placeholder, so the
+    rendered expression is re-validated before it is embedded via
+    ``literal_column``.
+    """
+    # A real Database (not a MagicMock) so the ORM relationship assignment on
+    # SqlaTable has a valid instance state; sqlite gives a concrete backend.
+    database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+    mocker.patch("superset.models.helpers.is_feature_enabled", 
return_value=False)

Review Comment:
   <!-- Bito Reply -->
   The reviewer's suggestion is based on the assumption that 
`is_feature_enabled` is imported into `superset.connectors.sqla.models` and 
used directly from that namespace. However, if the code under test resolves 
`is_feature_enabled` from the `superset.models.helpers` module namespace, then 
patching that specific module is the correct approach to intercept the call. 
The test correctly exercises the intended path by patching the module where the 
function is resolved.
   
   **tests/unit_tests/connectors/sqla/models_test.py**
   ```
   # A real Database (not a MagicMock) so the ORM relationship assignment on
       # SqlaTable has a valid instance state; sqlite gives a concrete backend.
       database = Database(database_name="t", sqlalchemy_uri="sqlite://")
       mocker.patch("superset.models.helpers.is_feature_enabled", 
return_value=False)
   ```



##########
superset/commands/report/exceptions.py:
##########
@@ -40,6 +40,38 @@ def __init__(self) -> None:
         super().__init__(_("Database does not exist"), field_name="database")
 
 
+class AlertQueryMultipleStatementsValidationError(ValidationError):
+    """
+    Marshmallow validation error for alert SQL containing multiple statements
+    """
+
+    def __init__(self) -> None:
+        super().__init__(
+            _("Alert query must be a single statement"),
+            field_name="sql",
+        )
+
+
+class AlertQueryDMLNotAllowedValidationError(ValidationError):
+    """
+    Marshmallow validation error for alert SQL that mutates state on a
+    database that does not allow DML
+    """
+
+    def __init__(self) -> None:
+        super().__init__(_("Alert query must be read-only"), field_name="sql")
+
+
+class AlertQueryDataAccessValidationError(ValidationError):
+    """
+    Marshmallow validation error for alert SQL referencing tables the user
+    is not authorized to query
+    """
+
+    def __init__(self, message: str) -> None:
+        super().__init__(message, field_name="sql")
+

Review Comment:
   <!-- Bito Reply -->
   The suggestion to add unit tests for the new exception classes 
`AlertQueryDMLNotAllowedValidationError` and 
`AlertQueryDataAccessValidationError` is appropriate. These exceptions are 
critical for enforcing security and validation constraints in alert queries, 
and ensuring they are properly tested improves the reliability of the 
validation logic.
   
   **superset/commands/report/exceptions.py**
   ```
   +class AlertQueryDMLNotAllowedValidationError(ValidationError):
   +    """
   +    Marshmallow validation error for alert SQL that mutates state on a
   +    database that does not allow DML
   +    """
   +
   +    def __init__(self) -> None:
   +        super().__init__(_("Alert query must be read-only"), 
field_name="sql")
   +
   +
   +class AlertQueryDataAccessValidationError(ValidationError):
   +    """
   +    Marshmallow validation error for alert SQL referencing tables the user
   +    is not authorized to query
   +    """
   +
   +    def __init__(self, message: str) -> None:
   +        super().__init__(message, field_name="sql")
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to