You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/08/13 03:13:52 UTC
(superset) branch master updated: fix(dataset): improve dataset, report, and expression validation (#42929)
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 0915a39bcbe fix(dataset): improve dataset, report, and expression validation (#42929)
0915a39bcbe is described below
commit 0915a39bcbecabd0c3e773b787e227e9c9229fad
Author: Evan Rusackas <ev...@preset.io>
AuthorDate: Wed Aug 12 20:13:45 2026 -0700
fix(dataset): improve dataset, report, and expression validation (#42929)
Co-authored-by: Claude Opus 4.8 <no...@anthropic.com>
---
superset/commands/dataset/update.py | 135 +++++++++++++++++----
superset/commands/report/alert.py | 31 +++++
superset/commands/report/base.py | 58 ++++++++-
superset/commands/report/create.py | 2 +
superset/commands/report/exceptions.py | 32 +++++
superset/commands/report/update.py | 13 ++
superset/connectors/sqla/models.py | 43 +++++++
superset/models/helpers.py | 100 ++++++++++++++-
tests/integration_tests/reports/alert_tests.py | 5 +
tests/unit_tests/commands/dataset/update_test.py | 96 +++++++++++++++
tests/unit_tests/commands/report/alert_test.py | 5 +
tests/unit_tests/commands/report/base_test.py | 92 ++++++++++++++
tests/unit_tests/commands/report/update_test.py | 6 +
tests/unit_tests/connectors/sqla/models_test.py | 79 +++++++++++-
.../models/test_virtual_dataset_format.py | 34 ++++++
15 files changed, 699 insertions(+), 32 deletions(-)
diff --git a/superset/commands/dataset/update.py b/superset/commands/dataset/update.py
index 057ebf7de13..d168553769d 100644
--- a/superset/commands/dataset/update.py
+++ b/superset/commands/dataset/update.py
@@ -123,13 +123,66 @@ class UpdateDatasetCommand(UpdateMixin, BaseCommand):
# we know we have a valid model
self._model = cast(SqlaTable, self._model)
database_id = self._properties.pop("database_id", None)
- catalog = self._properties.get("catalog")
- new_db_connection: Database | None = None
+ new_db_connection = self._get_new_database_connection(database_id, exceptions)
+ db = new_db_connection or self._model.database
+ database_changed = new_db_connection is not None
+
+ # Detect a caller-supplied change to the source binding, inspected
+ # before the catalog normalization below injects derived values.
+ source_changed = database_changed or any(
+ field in self._properties
+ and self._properties[field] != getattr(self._model, field)
+ for field in ("catalog", "schema", "table_name")
+ )
+
+ catalog, schema, table = self._resolve_catalog_schema_table(db, exceptions)
+
+ # Repointing to a different database connection requires access to
+ # that connection, independent of the caller's editorship of this
+ # dataset -- only persist the change once that's confirmed.
+ if new_db_connection:
+ self._apply_database_repoint(new_db_connection, table, exceptions)
+ # Validate uniqueness
+ if not DatasetDAO.validate_update_uniqueness(
+ db,
+ table,
+ self._model_id,
+ ):
+ exceptions.append(DatasetExistsValidationError(table))
+
+ # Repointing a physical dataset (or converting a virtual dataset to a
+ # physical one) runs the same data-access check as the create path.
+ # Skip it when the database connection itself changed: that case is
+ # already covered by the repoint check above, against the same
+ # (db, table) pair.
+ sql = self._properties.get("sql", self._model.sql)
+ if (
+ not new_db_connection
+ and not sql
+ and (source_changed or ("sql" in self._properties and self._model.sql))
+ ):
+ self._validate_table_access(db, table, exceptions)
+
+ self._validate_sql_access(db, catalog, schema, exceptions)
+
+ def _get_new_database_connection(
+ self, database_id: int | None, exceptions: list[ValidationError]
+ ) -> Database | None:
+ # we know we have a valid model
+ self._model = cast(SqlaTable, self._model)
if database_id and database_id != self._model.database.id:
- if not (new_db_connection := DatasetDAO.get_database_by_id(database_id)):
- exceptions.append(DatabaseNotFoundValidationError())
- db = new_db_connection or self._model.database
+ if new_db_connection := DatasetDAO.get_database_by_id(database_id):
+ return new_db_connection
+ exceptions.append(DatabaseNotFoundValidationError())
+ return None
+
+ def _resolve_catalog_schema_table(
+ self, db: Database, exceptions: list[ValidationError]
+ ) -> tuple[str | None, str | None, Table]:
+ # we know we have a valid model
+ self._model = cast(SqlaTable, self._model)
+ catalog = self._properties.get("catalog")
default_catalog = db.get_default_catalog()
# If multi-catalog is disabled, and catalog provided is not
@@ -161,29 +214,28 @@ class UpdateDatasetCommand(UpdateMixin, BaseCommand):
schema,
catalog,
)
+ return catalog, schema, table
- # Repointing to a different database connection requires access to
- # that connection, independent of the caller's editorship of this
- # dataset -- only persist the change once that's confirmed.
- if new_db_connection:
- try:
- security_manager.raise_for_access(
- database=new_db_connection, table=table
- )
- except SupersetSecurityException as ex:
- exceptions.append(DatasetDataAccessIsNotAllowed(ex.error.message))
- else:
- self._properties["database"] = new_db_connection
-
- # Validate uniqueness
- if not DatasetDAO.validate_update_uniqueness(
- db,
- table,
- self._model_id,
- ):
- exceptions.append(DatasetExistsValidationError(table))
+ def _apply_database_repoint(
+ self,
+ new_db_connection: Database,
+ table: Table,
+ exceptions: list[ValidationError],
+ ) -> None:
+ try:
+ security_manager.raise_for_access(database=new_db_connection, table=table)
+ except SupersetSecurityException as ex:
+ exceptions.append(DatasetDataAccessIsNotAllowed(ex.error.message))
+ else:
+ self._properties["database"] = new_db_connection
- self._validate_sql_access(db, catalog, schema, exceptions)
+ def _validate_table_access(
+ self, db: Database, table: Table, exceptions: list[ValidationError]
+ ) -> None:
+ try:
+ security_manager.raise_for_access(database=db, table=table)
+ except SupersetSecurityException as ex:
+ exceptions.append(DatasetDataAccessIsNotAllowed(ex.error.message))
def _validate_sql_access(
self,
@@ -226,6 +278,9 @@ class UpdateDatasetCommand(UpdateMixin, BaseCommand):
self._validate_metrics(metrics, exceptions)
self._validate_expressions(metrics, "metrics", exceptions)
+ if predicate := self._properties.get("fetch_values_predicate"):
+ self._validate_fetch_values_predicate(predicate, exceptions)
+
if folders := self._properties.get("folders"):
valid_uuids: set[UUID] = set()
if metrics:
@@ -334,6 +389,34 @@ class UpdateDatasetCommand(UpdateMixin, BaseCommand):
)
)
+ def _validate_fetch_values_predicate(
+ self,
+ predicate: str,
+ exceptions: list[ValidationError],
+ ) -> None:
+ """
+ Validate ``fetch_values_predicate`` with the same parser-based
+ validator used for stored column and metric expressions.
+ """
+ self._model = cast(SqlaTable, self._model)
+ database = self._properties.get("database") or self._model.database
+ catalog = self._properties.get("catalog", self._model.catalog)
+ schema = self._properties.get("schema", self._model.schema)
+ try:
+ validate_stored_expression(database, catalog, schema, predicate)
+ except (SupersetSecurityException, QueryClauseValidationException) as ex:
+ message = (
+ ex.error.message
+ if isinstance(ex, SupersetSecurityException)
+ else ex.message
+ )
+ exceptions.append(
+ ValidationError(
+ message,
+ field_name="fetch_values_predicate",
+ )
+ )
+
@staticmethod
def _get_duplicates(data: list[dict[str, Any]], key: str) -> list[str]:
duplicates = [
diff --git a/superset/commands/report/alert.py b/superset/commands/report/alert.py
index e0acaa142cb..a8927ad22f7 100644
--- a/superset/commands/report/alert.py
+++ b/superset/commands/report/alert.py
@@ -39,7 +39,9 @@ from superset.commands.report.exceptions import (
AlertValidatorConfigError,
ReportScheduleExecutorNotFoundError,
)
+from superset.exceptions import SupersetSecurityException
from superset.reports.models import ReportSchedule, ReportScheduleValidatorType
+from superset.sql.parse import SQLScript
from superset.tasks.utils import get_executor
from superset.utils import json
from superset.utils.core import override_user
@@ -181,6 +183,18 @@ class AlertCommand(BaseCommand):
"execution_id": self._execution_id,
}
+ def _validate_rendered_sql(self, rendered_sql: str) -> None:
+ """
+ Enforce SQL-level constraints on the rendered alert query: a single
+ statement, and no mutations unless the database allows DML.
+ """
+ database = self._report_schedule.database
+ script = SQLScript(rendered_sql, engine=database.backend)
+ if len(script.statements) != 1:
+ raise AlertQueryError(message=_("Alert query must be a single statement"))
+ if script.has_mutation() and not database.allow_dml:
+ raise AlertQueryError(message=_("Alert query must be read-only"))
+
@logs_context(context_func=_get_alert_metadata_from_object)
def _execute_query(self) -> pd.DataFrame:
"""
@@ -196,6 +210,7 @@ class AlertCommand(BaseCommand):
try:
rendered_sql = sql_template.process_template(self._report_schedule.sql)
+ self._validate_rendered_sql(rendered_sql)
limited_rendered_sql = self._report_schedule.database.apply_limit_to_sql(
rendered_sql, ALERT_SQL_LIMIT
)
@@ -220,6 +235,18 @@ class AlertCommand(BaseCommand):
raise ReportScheduleExecutorNotFoundError(username)
with override_user(user):
+ # Run table-level authorization as the executing user against
+ # the rendered SQL.
+ try:
+ security_manager.raise_for_access(
+ database=self._report_schedule.database,
+ sql=rendered_sql,
+ force_dataset_match=True,
+ )
+ except SupersetSecurityException as ex:
+ raise AlertQueryError(
+ message=_("Alert query failed the authorization check")
+ ) from ex
start = default_timer()
df = self._report_schedule.database.get_df(sql=limited_rendered_sql)
stop = default_timer()
@@ -236,6 +263,10 @@ class AlertCommand(BaseCommand):
# A missing executor user is a configuration problem, not a transient
# query error; surface the typed error rather than masking it.
raise
+ except AlertQueryError:
+ # Re-raise the typed validation/authorization errors as-is instead
+ # of masking them behind the generic error below.
+ raise
except Exception as ex:
logger.warning("An error occurred when running alert query")
# The exception message here can reveal to much information to malicious
diff --git a/superset/commands/report/base.py b/superset/commands/report/base.py
index b69c36513c9..ca91883605e 100644
--- a/superset/commands/report/base.py
+++ b/superset/commands/report/base.py
@@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
import logging
+import re
from typing import Any, Optional
from croniter import croniter, CroniterBadDateError
@@ -25,6 +26,9 @@ from marshmallow import ValidationError
from superset import security_manager
from superset.commands.base import BaseCommand
from superset.commands.report.exceptions import (
+ AlertQueryDataAccessValidationError,
+ AlertQueryDMLNotAllowedValidationError,
+ AlertQueryMultipleStatementsValidationError,
ChartNotFoundValidationError,
ChartNotSavedValidationError,
DashboardNotFoundValidationError,
@@ -38,16 +42,22 @@ from superset.commands.report.exceptions import (
from superset.daos.base import BaseDAO
from superset.daos.chart import ChartDAO
from superset.daos.dashboard import DashboardDAO
-from superset.exceptions import SupersetSecurityException
+from superset.exceptions import SupersetParseError, SupersetSecurityException
+from superset.models.core import Database
from superset.reports.models import (
ReportCreationMethod,
ReportScheduleType,
)
from superset.reports.types import ReportScheduleExtra
+from superset.sql.parse import SQLScript
from superset.utils import json
logger = logging.getLogger(__name__)
+# Matches balanced Jinja blocks so templated alert SQL can be recognized and
+# its static validation deferred to execution time.
+_JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
class BaseReportScheduleCommand(BaseCommand):
_properties: dict[str, Any]
@@ -58,6 +68,52 @@ class BaseReportScheduleCommand(BaseCommand):
def validate(self) -> None:
pass
+ def validate_alert_query(
+ self,
+ database: Database,
+ sql: str,
+ exceptions: list[ValidationError],
+ ) -> None:
+ """
+ Validate alert SQL at save time: it must parse as a single statement,
+ must not mutate state unless the database allows DML, and the saving
+ user must be authorized for the tables it reads. Templated SQL that
+ only parses after rendering is validated at execution time on the
+ rendered query.
+ """
+ contains_jinja = bool(_JINJA_BLOCK_RE.search(sql))
+ try:
+ script = SQLScript(sql, engine=database.backend)
+ except SupersetParseError as ex:
+ if not contains_jinja:
+ exceptions.append(
+ ValidationError(
+ _("Invalid SQL: %(error)s", error=ex.error.message),
+ field_name="sql",
+ )
+ )
+ return
+ if len(script.statements) != 1:
+ exceptions.append(AlertQueryMultipleStatementsValidationError())
+ return
+ if script.has_mutation() and not database.allow_dml:
+ exceptions.append(AlertQueryDMLNotAllowedValidationError())
+ return
+ try:
+ security_manager.raise_for_access(
+ database=database, sql=sql, force_dataset_match=True
+ )
+ except SupersetSecurityException as ex:
+ exceptions.append(AlertQueryDataAccessValidationError(ex.error.message))
+ except SupersetParseError as ex:
+ if not contains_jinja:
+ exceptions.append(
+ ValidationError(
+ _("Invalid SQL: %(error)s", error=ex.error.message),
+ field_name="sql",
+ )
+ )
+
def _check_object_access(
self,
object_id: int,
diff --git a/superset/commands/report/create.py b/superset/commands/report/create.py
index 5cfdbdbd14a..eaaebebac29 100644
--- a/superset/commands/report/create.py
+++ b/superset/commands/report/create.py
@@ -129,6 +129,8 @@ class CreateReportScheduleCommand(CreateMixin, BaseReportScheduleCommand):
database_id = self._properties["database"]
if database := DatabaseDAO.find_by_id(database_id):
self._properties["database"] = database
+ if sql := self._properties.get("sql"):
+ self.validate_alert_query(database, sql, exceptions)
else:
exceptions.append(DatabaseNotFoundValidationError())
except KeyError:
diff --git a/superset/commands/report/exceptions.py b/superset/commands/report/exceptions.py
index a248d494e0f..3ebdf51426d 100644
--- a/superset/commands/report/exceptions.py
+++ b/superset/commands/report/exceptions.py
@@ -40,6 +40,38 @@ class DatabaseNotFoundValidationError(ValidationError):
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")
+
+
class ReportScheduleDatabaseNotAllowedValidationError(ValidationError):
"""
Marshmallow validation error for database reference on a Report type schedule
diff --git a/superset/commands/report/update.py b/superset/commands/report/update.py
index 569b5d332c8..7aad68542da 100644
--- a/superset/commands/report/update.py
+++ b/superset/commands/report/update.py
@@ -149,6 +149,19 @@ class UpdateReportScheduleCommand(UpdateMixin, BaseReportScheduleCommand):
exceptions.append(DatabaseNotFoundValidationError())
self._properties["database"] = database
+ # Re-validate the alert SQL whenever the SQL or the target database
+ # changes, using the stored value for whichever half is absent from
+ # the payload.
+ if report_type == ReportScheduleType.ALERT and (
+ "sql" in self._properties or "database" in self._properties
+ ):
+ effective_database = (
+ self._properties.get("database") or self._model.database
+ )
+ effective_sql = self._properties.get("sql", self._model.sql)
+ if effective_database and effective_sql:
+ self.validate_alert_query(effective_database, effective_sql, exceptions)
+
# validate report frequency
try:
self.validate_report_frequency(
diff --git a/superset/connectors/sqla/models.py b/superset/connectors/sqla/models.py
index e7ad6a7beeb..88e14873109 100644
--- a/superset/connectors/sqla/models.py
+++ b/superset/connectors/sqla/models.py
@@ -81,6 +81,7 @@ from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.exceptions import (
ColumnNotFoundException,
DatasetInvalidPermissionEvaluationException,
+ QueryClauseValidationException,
QueryObjectValidationError,
SupersetParseError,
SupersetSecurityException,
@@ -103,6 +104,7 @@ from superset.models.helpers import (
SoftDeleteMixin,
SQLA_QUERY_KEYS,
validate_adhoc_subquery,
+ validate_rendered_expression,
validate_stored_expression_at_query_time,
)
from superset.models.slice import Slice
@@ -1215,6 +1217,14 @@ class TableColumn(AuditMixinNullable, ImportExportMixin, CertificationMixin, Mod
msg=msg,
)
) from ex
+ if expression != self.expression:
+ # Re-check the rendered expression before embedding it.
+ expression = validate_rendered_expression(
+ expression,
+ self.database,
+ self.table.catalog if self.table else None,
+ self.table.schema if self.table else None,
+ )
expression = self._validate_stored_expression(expression)
col = literal_column(expression, type_=type_)
else:
@@ -1263,6 +1273,14 @@ class TableColumn(AuditMixinNullable, ImportExportMixin, CertificationMixin, Mod
msg=msg,
)
) from ex
+ if expression != self.expression:
+ # Re-check the rendered expression before embedding it.
+ expression = validate_rendered_expression(
+ expression,
+ self.database,
+ self.table.catalog if self.table else None,
+ self.table.schema if self.table else None,
+ )
expression = self._validate_stored_expression(expression)
col = literal_column(expression, type_=type_)
else:
@@ -1368,6 +1386,14 @@ class SqlMetric(AuditMixinNullable, ImportExportMixin, CertificationMixin, Model
msg=msg,
)
) from ex
+ if expression != self.expression:
+ # Re-check the rendered expression before embedding it.
+ expression = validate_rendered_expression(
+ expression,
+ self.table.database,
+ self.table.catalog,
+ self.table.schema,
+ )
if expression:
expression = self._validate_stored_expression(expression)
@@ -1780,7 +1806,24 @@ class SqlaTable(
fetch_values_predicate
)
try:
+ # Re-validate the rendered predicate with the same parser policy
+ # as stored column and metric expressions before embedding it.
+ validate_stored_expression(
+ self.database, self.catalog, self.schema, fetch_values_predicate
+ )
return self.text(fetch_values_predicate)
+ except (SupersetSecurityException, QueryClauseValidationException) as ex:
+ message = (
+ ex.error.message
+ if isinstance(ex, SupersetSecurityException)
+ else ex.message
+ )
+ raise QueryObjectValidationError(
+ _(
+ "Fetch values predicate failed SQL validation: %(msg)s",
+ msg=message,
+ )
+ ) from ex
except (TemplateError, SupersetSyntaxErrorException) as ex:
msg = getattr(ex, "message", str(ex))
raise QueryObjectValidationError(
diff --git a/superset/models/helpers.py b/superset/models/helpers.py
index 7bbc1433b0d..0f086c831e1 100644
--- a/superset/models/helpers.py
+++ b/superset/models/helpers.py
@@ -153,7 +153,7 @@ from superset.utils.date_parser import (
TimeDeltaAmbiguousError,
)
from superset.utils.dates import datetime_to_epoch
-from superset.utils.rls import apply_rls
+from superset.utils.rls import apply_rls, get_predicates_for_table
class ValidationResultDict(TypedDict):
@@ -329,6 +329,62 @@ def validate_stored_expression_at_query_time(
return expression
+def validate_rendered_expression(
+ expression: str,
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+) -> str:
+ """
+ Apply the stored-expression validation policy to a rendered expression.
+
+ Query-time counterpart to ``validate_stored_expression``: it runs on the
+ already-rendered expression that is embedded via ``literal_column`` and
+ applies the same policy, failing closed on unparseable results.
+
+ :param expression: the rendered expression
+ :returns: the expression to embed, possibly rewritten with RLS predicates
+ :raises QueryObjectValidationError: on multi-statement, set-operation,
+ disallowed sub-query, or sanitization failures -- matching the
+ ``QueryObjectValidationError`` contract callers already expect from
+ ``validate_stored_expression_at_query_time``, rather than letting a
+ raw ``SupersetSecurityException`` escape uncaught.
+ """
+ engine = database.backend
+ wrapped = f"SELECT {expression}"
+
+ try:
+ parsed = SQLStatement(wrapped, engine)
+ except SupersetParseError as ex:
+ raise QueryObjectValidationError(
+ _("Custom SQL fields cannot be parsed as a single SQL statement.")
+ ) from ex
+
+ if parsed.is_set_operation():
+ raise QueryObjectValidationError(
+ _("Custom SQL fields cannot contain set operations.")
+ )
+
+ try:
+ wrapped = validate_adhoc_subquery(
+ wrapped, database, catalog, schema or "", engine
+ )
+ except SupersetSecurityException as ex:
+ raise QueryObjectValidationError(ex.message) from ex
+ try:
+ wrapped = sanitize_clause(wrapped, engine)
+ except QueryClauseValidationException as ex:
+ raise QueryObjectValidationError(ex.message) from ex
+
+ prefix, expression = re.split(
+ r"SELECT\s+",
+ wrapped,
+ maxsplit=1,
+ flags=re.IGNORECASE,
+ )
+ return expression.strip()
+
+
def json_to_dict(json_str: str) -> dict[Any, Any]:
if json_str:
val = re.sub(",[ \t\r\n]+}", "}", json_str)
@@ -3083,9 +3139,40 @@ class ExploreMixin: # pylint: disable=too-many-public-methods
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
+ rls_required = True
+ if rls_required:
+ raise QueryObjectValidationError(
+ _(
+ "Row-level security could not be applied to the "
+ "virtual dataset query, so it cannot be run "
+ "securely: %(msg)s",
+ msg=str(ex),
+ )
+ ) from ex
+ logger.warning(
+ "RLS application to virtual dataset SQL failed, but no "
+ "predicates apply to its tables; continuing: %s",
+ ex,
+ )
cte = self.db_engine_spec.get_cte_query(from_sql)
from_clause = (
@@ -3782,6 +3869,11 @@ class ExploreMixin: # pylint: disable=too-many-public-methods
if expression := tbl_column.expression:
if template_processor:
expression = template_processor.process_template(expression)
+ if expression != tbl_column.expression:
+ # Re-check the rendered expression before embedding it.
+ expression = validate_rendered_expression(
+ expression, self.database, self.catalog, self.schema
+ )
expression = self._validate_stored_expression(expression)
col = literal_column(expression, type_=type_)
else:
diff --git a/tests/integration_tests/reports/alert_tests.py b/tests/integration_tests/reports/alert_tests.py
index d2b5942d694..bb8c163e615 100644
--- a/tests/integration_tests/reports/alert_tests.py
+++ b/tests/integration_tests/reports/alert_tests.py
@@ -104,6 +104,9 @@ def test_execute_query_as_report_executor(
)
command = AlertCommand(report_schedule=report_schedule, execution_id=uuid.uuid4())
override_user_mock = mocker.patch("superset.commands.report.alert.override_user")
+ # override_user is mocked, so no real executor context is set; the alert
+ # authorization check is covered elsewhere, so keep it a no-op here.
+ mocker.patch("superset.commands.report.alert.security_manager.raise_for_access")
cm = (
pytest.raises(type(expected_result))
if isinstance(expected_result, Exception)
@@ -128,6 +131,7 @@ def test_execute_query_mutate_query_enabled(
app.config["MUTATE_ALERT_QUERY"] = True
mocker.patch("superset.commands.report.alert.override_user")
+ mocker.patch("superset.commands.report.alert.security_manager.raise_for_access")
mock_df = mocker.MagicMock(spec=pd.DataFrame)
mock_df.empty = True
mock_database = get_example_database()
@@ -171,6 +175,7 @@ def test_execute_query_mutate_query_disabled(
app.config["MUTATE_ALERT_QUERY"] = False
mocker.patch("superset.commands.report.alert.override_user")
+ mocker.patch("superset.commands.report.alert.security_manager.raise_for_access")
mock_database = mocker.MagicMock()
admin_user = get_user("admin")
diff --git a/tests/unit_tests/commands/dataset/update_test.py b/tests/unit_tests/commands/dataset/update_test.py
index 6d343ee00b3..c6949201d41 100644
--- a/tests/unit_tests/commands/dataset/update_test.py
+++ b/tests/unit_tests/commands/dataset/update_test.py
@@ -38,6 +38,7 @@ from superset.commands.dataset.update import (
from superset.datasets.schemas import FolderSchema
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.exceptions import SupersetSecurityException
+from superset.sql.parse import Table
from superset.subjects.exceptions import SubjectsNotFoundValidationError
from tests.unit_tests.conftest import with_feature_flags
@@ -278,6 +279,60 @@ def test_update_dataset_database_id_change_allowed_with_access(
assert update_kwargs["attributes"]["database"] is mock_new_database
+def test_update_dataset_physical_repoint_requires_table_access(
+ mocker: MockerFixture,
+) -> None:
+ """
+ Repointing a physical dataset at a different table must pass the same
+ ``raise_for_access(database=..., table=...)`` gate the create path
+ enforces; editorship alone must not grant access to the new table.
+ """
+ mock_dataset_dao = mocker.patch("superset.commands.dataset.update.DatasetDAO")
+ mocker.patch(
+ "superset.commands.dataset.update.security_manager.raise_for_editorship",
+ )
+ mocker.patch("superset.commands.utils.security_manager.is_admin", return_value=True)
+
+ mock_database = mocker.MagicMock()
+ mock_database.id = 1
+ mock_database.get_default_catalog.return_value = "catalog"
+ mock_database.allow_multi_catalog = False
+
+ mock_dataset = mocker.MagicMock()
+ mock_dataset.database = mock_database
+ mock_dataset.catalog = "catalog"
+ mock_dataset.schema = "public"
+ mock_dataset.table_name = "allowed_table"
+ mock_dataset.sql = None # physical dataset
+ mock_dataset.editors = []
+
+ mock_dataset_dao.find_by_id.return_value = mock_dataset
+ mock_dataset_dao.validate_update_uniqueness.return_value = True
+
+ raise_for_access = mocker.patch(
+ "superset.commands.dataset.update.security_manager.raise_for_access",
+ side_effect=SupersetSecurityException(
+ SupersetError(
+ error_type=SupersetErrorType.DATASOURCE_SECURITY_ACCESS_ERROR,
+ message="You don't have access to the table 'restricted_table'",
+ level=ErrorLevel.ERROR,
+ )
+ ),
+ )
+
+ with pytest.raises(DatasetInvalidError) as excinfo:
+ UpdateDatasetCommand(1, {"table_name": "restricted_table"}).run()
+
+ raise_for_access.assert_called_once_with(
+ database=mock_database,
+ table=Table("restricted_table", "public", "catalog"),
+ )
+ assert any(
+ "You don't have access to the table" in str(exc)
+ for exc in excinfo.value._exceptions
+ )
+
+
@pytest.mark.parametrize(
("payload, exception, error_msg"),
[
@@ -1219,3 +1274,44 @@ def test_validate_folders_metrics_vs_columns_behavior(mocker: MockerFixture) ->
command2._validate_semantics([])
except Exception as e:
pytest.fail(f"Should work with new metric UUIDs when new metrics provided: {e}")
+
+
+def test_update_dataset_rejects_malicious_fetch_values_predicate(
+ mocker: MockerFixture,
+) -> None:
+ """
+ ``fetch_values_predicate`` is wrapped verbatim into a raw WHERE clause at
+ query time, so the command routes it through the stored-expression
+ validator; a UNION-based predicate is rejected at save time.
+ """
+ mock_dataset_dao = mocker.patch("superset.commands.dataset.update.DatasetDAO")
+ mocker.patch(
+ "superset.commands.dataset.update.security_manager.raise_for_editorship",
+ )
+ mocker.patch("superset.commands.utils.security_manager.is_admin", return_value=True)
+ mocker.patch(
+ "superset.commands.utils.security_manager.get_user_by_id", return_value=None
+ )
+ mock_database = mocker.MagicMock()
+ mock_database.id = 1
+ mock_database.backend = "sqlite"
+ mock_database.allow_multi_catalog = False
+ mock_database.get_default_catalog.return_value = "catalog"
+ mock_dataset = mocker.MagicMock()
+ mock_dataset.database = mock_database
+ mock_dataset.catalog = "catalog"
+ mock_dataset.schema = None
+ mock_dataset_dao.find_by_id.return_value = mock_dataset
+ mock_dataset_dao.get_database_by_id.return_value = mock_database
+ mock_dataset_dao.validate_update_uniqueness.return_value = True
+
+ payload = {
+ "fetch_values_predicate": "1=0 UNION SELECT card_number FROM billing.cards"
+ }
+ with pytest.raises(DatasetInvalidError) as excinfo:
+ UpdateDatasetCommand(1, payload).run()
+ assert any(
+ isinstance(exc, ValidationError)
+ and "fetch_values_predicate" in (exc.field_name or "")
+ for exc in excinfo.value._exceptions
+ )
diff --git a/tests/unit_tests/commands/report/alert_test.py b/tests/unit_tests/commands/report/alert_test.py
index c2f63f2435d..13164230006 100644
--- a/tests/unit_tests/commands/report/alert_test.py
+++ b/tests/unit_tests/commands/report/alert_test.py
@@ -511,8 +511,11 @@ def test_execute_query_raises_when_executor_user_missing(
username, rather than swallowing it into an opaque ``AlertQueryError`` (or
surfacing a NoneType/AttributeError from the downstream auth flow).
"""
+ template_processor_mock = mocker.Mock()
+ template_processor_mock.process_template.return_value = "SELECT value FROM metrics"
mocker.patch(
"superset.commands.report.alert.jinja_context.get_template_processor",
+ return_value=template_processor_mock,
)
mocker.patch(
"superset.commands.report.alert.get_executor",
@@ -526,6 +529,8 @@ def test_execute_query_raises_when_executor_user_missing(
report_schedule_mock = mocker.Mock()
report_schedule_mock.id = 1
report_schedule_mock.sql = "SELECT value FROM metrics"
+ report_schedule_mock.database.backend = "sqlite"
+ report_schedule_mock.database.allow_dml = False
command = AlertCommand(
report_schedule=report_schedule_mock,
diff --git a/tests/unit_tests/commands/report/base_test.py b/tests/unit_tests/commands/report/base_test.py
index 93055e38a32..46c51d5d776 100644
--- a/tests/unit_tests/commands/report/base_test.py
+++ b/tests/unit_tests/commands/report/base_test.py
@@ -24,6 +24,7 @@ from typing import Any, Callable
from unittest.mock import patch
import pytest
+from pytest_mock import MockerFixture
from superset.commands.report.base import BaseReportScheduleCommand
from superset.commands.report.exceptions import (
@@ -318,3 +319,94 @@ def test_validate_report_frequency_using_callable() -> None:
"1,6 * * * *",
ReportScheduleType.REPORT,
)
+
+
+def test_validate_alert_query_rejects_multi_statement_sql() -> None:
+ """
+ Alert SQL is validated at save time; multi-statement SQL cannot be
+ persisted for later raw execution by the alert runner.
+ """
+ from unittest.mock import MagicMock
+
+ from marshmallow import ValidationError
+
+ from superset.commands.report.base import BaseReportScheduleCommand
+ from superset.commands.report.exceptions import (
+ AlertQueryMultipleStatementsValidationError,
+ )
+
+ database = MagicMock()
+ database.backend = "sqlite"
+ database.allow_dml = False
+
+ exceptions: list[ValidationError] = []
+ BaseReportScheduleCommand().validate_alert_query(
+ database, "SELECT 1; DROP TABLE ab_user", exceptions
+ )
+
+ assert len(exceptions) == 1
+ assert isinstance(exceptions[0], AlertQueryMultipleStatementsValidationError)
+
+
+def test_validate_alert_query_rejects_dml_when_not_allowed() -> None:
+ """A mutating alert query is rejected unless the database allows DML."""
+ from unittest.mock import MagicMock
+
+ from marshmallow import ValidationError
+
+ from superset.commands.report.base import BaseReportScheduleCommand
+ from superset.commands.report.exceptions import (
+ AlertQueryDMLNotAllowedValidationError,
+ )
+
+ database = MagicMock()
+ database.backend = "sqlite"
+ database.allow_dml = False
+
+ exceptions: list[ValidationError] = []
+ BaseReportScheduleCommand().validate_alert_query(
+ database, "UPDATE ab_user SET active = 1", exceptions
+ )
+
+ assert len(exceptions) == 1
+ assert isinstance(exceptions[0], AlertQueryDMLNotAllowedValidationError)
+
+
+def test_validate_alert_query_rejects_unauthorized_tables(
+ mocker: MockerFixture,
+) -> None:
+ """A single read-only statement referencing tables the user cannot access
+ is rejected via the table-level authorization check."""
+ from unittest.mock import MagicMock
+
+ from marshmallow import ValidationError
+
+ from superset.commands.report.base import BaseReportScheduleCommand
+ from superset.commands.report.exceptions import (
+ AlertQueryDataAccessValidationError,
+ )
+ from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
+ from superset.exceptions import SupersetSecurityException
+
+ mocker.patch(
+ "superset.commands.report.base.security_manager.raise_for_access",
+ side_effect=SupersetSecurityException(
+ SupersetError(
+ error_type=SupersetErrorType.TABLE_SECURITY_ACCESS_ERROR,
+ message="You need access to the following tables: `secret`",
+ level=ErrorLevel.ERROR,
+ )
+ ),
+ )
+
+ database = MagicMock()
+ database.backend = "sqlite"
+ database.allow_dml = False
+
+ exceptions: list[ValidationError] = []
+ BaseReportScheduleCommand().validate_alert_query(
+ database, "SELECT * FROM secret", exceptions
+ )
+
+ assert len(exceptions) == 1
+ assert isinstance(exceptions[0], AlertQueryDataAccessValidationError)
diff --git a/tests/unit_tests/commands/report/update_test.py b/tests/unit_tests/commands/report/update_test.py
index 22216970d7b..4ca4d5bc13b 100644
--- a/tests/unit_tests/commands/report/update_test.py
+++ b/tests/unit_tests/commands/report/update_test.py
@@ -81,6 +81,12 @@ def _setup_mocks(mocker: MockerFixture, model: Mock) -> None:
UpdateReportScheduleCommand,
"validate_report_frequency",
)
+ # Alert-query validation has dedicated coverage in base_test.py; these
+ # tests focus on database-presence handling, so stub it out here.
+ mocker.patch.object(
+ UpdateReportScheduleCommand,
+ "validate_alert_query",
+ )
mocker.patch(
"superset.commands.report.update.compute_subjects",
)
diff --git a/tests/unit_tests/connectors/sqla/models_test.py b/tests/unit_tests/connectors/sqla/models_test.py
index 26cf2dd4060..e95ff6c3d2e 100644
--- a/tests/unit_tests/connectors/sqla/models_test.py
+++ b/tests/unit_tests/connectors/sqla/models_test.py
@@ -39,7 +39,11 @@ from superset.exceptions import (
SupersetSecurityException,
)
from superset.models.core import Database
-from superset.models.helpers import ExploreMixin, validate_adhoc_subquery
+from superset.models.helpers import (
+ ExploreMixin,
+ validate_adhoc_subquery,
+ validate_rendered_expression,
+)
from superset.sql.parse import Table
from superset.superset_typing import QueryObjectDict
from superset.utils import json
@@ -1645,6 +1649,79 @@ def test_get_sqla_col_catches_subquery_beside_unparseable_syntax(
tc.get_sqla_col()
+def test_validate_rendered_expression_rejects_multi_statement(
+ mocker: MockerFixture,
+) -> None:
+ database = _database_for_expression(mocker)
+ with pytest.raises(QueryObjectValidationError):
+ validate_rendered_expression("1; DROP TABLE users", database, None, "public")
+
+
+def test_validate_rendered_expression_rejects_set_operation(
+ mocker: MockerFixture,
+) -> None:
+ database = _database_for_expression(mocker)
+ with pytest.raises(QueryObjectValidationError):
+ validate_rendered_expression(
+ "1 UNION SELECT password FROM ab_user", database, None, "public"
+ )
+
+
+def test_validate_rendered_expression_rejects_subquery(
+ mocker: MockerFixture,
+) -> None:
+ """
+ With ``ALLOW_ADHOC_SUBQUERY=False`` (the default), a rendered expression
+ containing a sub-query is rejected by the same ``validate_adhoc_subquery``
+ gate used for stored and adhoc expressions.
+ """
+ database = _database_for_expression(mocker)
+ mocker.patch("superset.models.helpers.is_feature_enabled", return_value=False)
+ with pytest.raises(QueryObjectValidationError):
+ validate_rendered_expression(
+ "(SELECT password FROM ab_user LIMIT 1)", database, None, "public"
+ )
+
+
+def test_validate_rendered_expression_accepts_valid_expression(
+ mocker: MockerFixture,
+) -> None:
+ """A benign rendered expression is returned unchanged (no RLS applied)."""
+ database = _database_for_expression(mocker)
+ mocker.patch("superset.models.helpers.is_feature_enabled", return_value=False)
+ result = validate_rendered_expression("SUM(amount)", database, None, "public")
+ assert result == "SUM(amount)"
+
+
+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``. The failure surfaces as a chart-level
+ ``QueryObjectValidationError``, matching the stored-expression path,
+ rather than a raw ``SupersetSecurityException``.
+ """
+ # 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)
+ table = SqlaTable(table_name="t", database=database)
+ tbl_column = TableColumn(
+ column_name="c",
+ expression='{{ "(SELECT password FROM ab_user LIMIT 1)" }}',
+ table=table,
+ )
+ template_processor = mocker.MagicMock()
+ template_processor.process_template.return_value = (
+ "(SELECT password FROM ab_user LIMIT 1)"
+ )
+ with pytest.raises(QueryObjectValidationError):
+ tbl_column.get_sqla_col(template_processor=template_processor)
+
+
def test_has_extra_cache_key_calls_scans_guest_token_rls(
mocker: MockerFixture,
) -> None:
diff --git a/tests/unit_tests/models/test_virtual_dataset_format.py b/tests/unit_tests/models/test_virtual_dataset_format.py
index 921abe4048d..5df5a4ac2f1 100644
--- a/tests/unit_tests/models/test_virtual_dataset_format.py
+++ b/tests/unit_tests/models/test_virtual_dataset_format.py
@@ -38,6 +38,7 @@ import pytest
from flask import Flask
from sqlalchemy.sql.elements import TextClause
+from superset.exceptions import QueryObjectValidationError
from superset.models.helpers import ExploreMixin
from superset.sql.parse import RLSMethod, SQLStatement, Table
@@ -380,3 +381,36 @@ class TestRLSSubqueryAlias:
assert "is_green" in result
assert "WHERE" in result # RLS predicate applied
+
+
+# ---------------------------------------------------------------------------
+# 4. RLS injection failures must fail closed when predicates apply
+# ---------------------------------------------------------------------------
+
+
+class TestVirtualDatasetRLSFailClosed:
+ """
+ When RLS predicates exist for the underlying tables but cannot be
+ injected into the virtual dataset SQL, the query must be aborted
+ instead of running against the unfiltered inner SQL.
+ """
+
+ @patch(
+ "superset.models.helpers.get_predicates_for_table",
+ return_value=["user_id = 42"],
+ )
+ @patch(
+ "superset.models.helpers.apply_rls",
+ side_effect=NotImplementedError("engine cannot apply RLS"),
+ )
+ def test_raises_when_rls_predicates_cannot_be_applied(
+ self,
+ mock_apply_rls: MagicMock,
+ mock_get_predicates: MagicMock,
+ virtual_datasource: MagicMock,
+ app: Flask,
+ ) -> None:
+ _set_virtual_sql(virtual_datasource, "SELECT pen_id FROM public.pens")
+
+ with pytest.raises(QueryObjectValidationError):
+ virtual_datasource.get_from_clause(template_processor=None)