sadpandajoe commented on code in PR #45681:
URL: https://github.com/apache/superset/pull/45681#discussion_r4396807564
##########
superset/models/helpers.py:
##########
@@ -4104,6 +4111,490 @@ def get_rendered_sql(
def text(self, clause: str) -> TextClause:
return self.db_engine_spec.get_text_clause(clause)
+ def _get_rls_schema(self) -> str:
+ """Resolve RLS tables with the same schema policy as SQL
expressions."""
+ return get_rls_schema(
+ self.database,
+ self.catalog,
+ self.schema,
+ self.sql or "",
+ self.template_params_dict,
+ )
+
+ def _get_filter_column(
+ self,
+ name: str,
+ columns_by_name: dict[str, "TableColumn"],
+ ) -> Optional["TableColumn"]:
+ """Resolve real names before the first matching verbose filter
label."""
+ col = columns_by_name.get(name)
+ if col is not None:
+ return col
+ return next((col for col in self.columns if col.verbose_name == name),
None)
+
+ def _get_adhoc_column_rls_expression(
+ self,
+ col: AdhocColumn,
+ rendered_sql: str,
+ template_processor: BaseTemplateProcessor,
+ ) -> str | None:
+ """Query-backed adhoc columns execute their rendered SQL literally."""
+ return rendered_sql
+
+ def _get_rls_expression_sources( # noqa: C901
+ self,
+ expression: str,
+ template_processor: BaseTemplateProcessor,
+ ) -> set[str]:
+ """Inspect SQL and literal template inputs without executing any
macros.
+
+ Include parameter values and constant outputs so templated subqueries
+ and saved-column references are not mistaken for plain expressions.
+ This is only a prefilter; rendered SQL still undergoes AST discovery.
+ """
+ sources = {expression.strip()}
+ try:
+ template = template_processor.env.parse(expression)
+ except TemplateError:
+ return sources
+ unknown = object()
+
+ def literal(node: nodes.Node) -> Any: # noqa: C901
+ """Read JSON values and concatenate strings, never calls or
filters."""
+ if isinstance(node, nodes.Const):
+ return node.value
+ if isinstance(node, nodes.TemplateData):
+ return node.data
+ if isinstance(node, nodes.Name):
+ return self.template_params_dict.get(node.name, unknown)
+ if isinstance(node, (nodes.Getattr, nodes.Getitem)):
+ value = literal(node.node)
+ key = (
+ node.attr if isinstance(node, nodes.Getattr) else
literal(node.arg)
+ )
+ if isinstance(value, dict) and isinstance(key, (str, int)):
+ return value.get(key, unknown)
+ if isinstance(value, list) and isinstance(key, int):
+ try:
+ return value[key]
+ except IndexError:
+ pass
+ return unknown
+ if isinstance(node, nodes.Add):
+ left, right = literal(node.left), literal(node.right)
+ if isinstance(left, str) and isinstance(right, str):
+ return left + right
+ if isinstance(left, (int, float)) and isinstance(right, (int,
float)):
+ return left + right
+ return unknown
+ parts = node.nodes if isinstance(node, (nodes.Output,
nodes.Concat)) else []
+ values = [literal(part) for part in parts]
+ if parts and all(
+ isinstance(value, (str, int, float, bool, type(None)))
+ for value in values
+ ):
+ return "".join(str(value) for value in values)
+ return unknown
+
+ for output in template.find_all(nodes.Output):
+ if isinstance(value := literal(output), str):
+ sources.add(value.strip())
+ return sources
+
+ def _may_have_rls_subquery(
+ self,
+ expression: str,
+ template_processor: BaseTemplateProcessor,
+ ) -> bool | None:
+ """Detect subqueries without rendering; return None for ambiguous
SQL."""
+ ambiguous = False
+ for source in self._get_rls_expression_sources(expression,
template_processor):
+ # Jinja calls are opaque, not SQL. Inspect the surrounding SQL and
+ # literal template outputs separately, without executing either.
+ source = re.sub(
+ r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", "NULL", source,
flags=re.DOTALL
+ )
+ # Use the execution parser, not a keyword gate: table subqueries
+ # can start with FROM, including in otherwise SELECT-less SQL.
+ try:
+ script = SQLScript(f"SELECT {source}",
self.db_engine_spec.engine)
+ except SupersetParseError:
+ ambiguous = True
+ else:
+ if any(
+ statement.has_subquery() and statement.tables
+ for statement in script.statements
+ ):
+ return True
+ return None if ambiguous else False
+
+ def _get_query_sql_expressions( # noqa: C901
+ self,
+ query_obj: QueryObjectDict,
+ template_processor: BaseTemplateProcessor,
+ granularity: str | None,
+ removed_filters: list[str],
+ unrendered_templates: list[str],
+ ) -> list[str]:
+ """Render SQL-bearing chart fields without building a chart or its
prequeries.
+
+ Render only possible subqueries, once per source, matching execution.
+ An adhoc column resolving to saved metadata also checks its expression.
+ """
+ columns_by_name = {col.column_name: col for col in self.columns}
+ columns = {name: col.expression for name, col in
columns_by_name.items()}
+ metrics = {metric.metric_name: metric.expression for metric in
self.metrics}
+ selected_columns = query_obj.get("columns") or []
+ selected_metrics = query_obj.get("metrics") or []
+ adhoc_columns_by_label = {
+ col.get("label"): col
+ for col in selected_columns
+ if utils.is_adhoc_column(col)
+ }
+ metric_labels = {utils.get_metric_name(metric) for metric in
selected_metrics}
+ expressions: list[str] = []
+ from_template_rendered = False
+
+ def record_unrendered_template(expression: str) -> None:
+ """Keep opaque macro outputs viewer-scoped without executing
them."""
+ if self._may_have_rls_subquery(expression, template_processor) is
None:
+ unrendered_templates.append(expression)
+ return
+ try:
+ template = template_processor.env.parse(expression)
+ except TemplateError:
+ unrendered_templates.append(expression)
+ return
+ string_inputs = any(
+ isinstance(node, nodes.TemplateData)
+ or (isinstance(node, nodes.Const) and isinstance(node.value,
str))
+ or (
+ isinstance(node, nodes.Name)
+ and isinstance(self.template_params_dict.get(node.name),
str)
+ )
+ for node in template.find_all(nodes.Node)
+ )
+ unknown_string_operation = string_inputs and any(
Review Comment:
A template whose only operator falls outside the Call/Filter/Getattr/Getitem
and string checks, such as `{{ 1 * 2 }}`, is treated as inspectable, so the
collector adds no viewer-scoped marker. At execution it renders to `2`, which
can resolve to a saved column named `2` whose expression is `(SELECT
MAX(secret) FROM protected)`, so the viewer's RLS on `protected` is applied to
the query but not reflected in the key. With template processing and adhoc
subqueries enabled, two viewers with different RLS on `protected` would then
share a cache entry. Should any node type this prefilter cannot evaluate
statically (Mul, Sub, Div, conditionals, and so on) fall back to the
viewer-scoped key the way calls and filters do?
--
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]