codeant-ai-for-open-source[bot] commented on code in PR #41133: URL: https://github.com/apache/superset/pull/41133#discussion_r3593644755
########## superset/tasks/export_dashboard_excel.py: ########## @@ -0,0 +1,361 @@ +# 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. +""" +Celery task that exports every chart on a dashboard to a single multi-sheet +``.xlsx`` file, uploads it to S3, and emails the requesting user a pre-signed +download link. + +In ``"data"`` mode the task re-runs each chart's saved query context under the +requesting user, applies the live dashboard filter state, and streams the results +row-by-row into a constant-memory workbook so large dashboards never load all +data at once. In ``"images"`` mode non-table charts are instead rendered to +images (through the same headless path as scheduled reports, reflecting the live +filters) and embedded, while table-like charts stay tabular. +""" + +from __future__ import annotations + +import logging +import os +import tempfile +from datetime import datetime, timedelta, timezone +from typing import Any + +from celery.exceptions import SoftTimeLimitExceeded +from flask import current_app, g + +from superset import db, security_manager +from superset.charts.data.dashboard_filter_context import ( + apply_dashboard_filter_context, + get_dashboard_filter_context, +) +from superset.charts.schemas import ChartDataQueryContextSchema +from superset.commands.chart.data.get_data_command import ChartDataCommand +from superset.commands.distributed_lock.release import ReleaseDistributedLock +from superset.common.chart_data import ChartDataResultFormat, ChartDataResultType +from superset.dashboards.excel_export import email +from superset.dashboards.excel_export.layout import get_charts_in_layout_order +from superset.dashboards.excel_export.screenshot import render_chart_image +from superset.extensions import celery_app +from superset.utils import json, s3 +from superset.utils.core import override_user +from superset.utils.excel_streaming import StreamingXlsxWriter + +logger = logging.getLogger(__name__) + +# Export modes: "data" streams every chart's tabular result (the default, +# unchanged behavior); "images" embeds non-table charts as rendered images and +# keeps only table-like charts tabular. +EXPORT_MODE_DATA = "data" +EXPORT_MODE_IMAGES = "images" + +# Viz types kept as tabular data in image mode; everything else is rendered as an +# image. Operators can override the set via ``EXCEL_EXPORT_TABLE_VIZ_TYPES``. +TABLE_VIZ_TYPES = {"table", "pivot_table_v2", "pivot_table"} + +EXPORT_SOFT_TIME_LIMIT = 600 +EXPORT_HARD_TIME_LIMIT = 660 + +# Namespace + TTL for the per-user+dashboard in-flight lock the API acquires +# before enqueue and this task releases when it settles. The lock uses the +# shared, atomic DistributedLock backend (Redis when configured, the metadata +# DB otherwise) so it actually synchronizes across the web server and workers — +# unlike a plain cache, which is a no-op under the default ``NullCache``. +# The TTL outlives the hard time limit so a worker killed at that limit (which +# skips the ``finally`` release) cannot hold the lock forever; the release in +# ``finally`` is the fast path that frees it as soon as the task settles. +EXPORT_LOCK_NAMESPACE = "excel_export" +EXPORT_LOCK_TTL_SECONDS = EXPORT_HARD_TIME_LIMIT + 60 + + +def export_lock_params(user_id: int, dashboard_id: int) -> dict[str, int]: + """Key parameters identifying the per-user+dashboard in-flight lock.""" + return {"user_id": user_id, "dashboard_id": dashboard_id} + + +class _ChartSkippedError(Exception): + """Signals a chart that could not be exported and should be listed as skipped.""" + + +def _chart_label(chart: Any) -> str: + """Human-readable label for a chart in the skipped-charts list.""" + return f"{chart.id} - {chart.slice_name or ''}".strip() + + +def _record_to_row(record: dict[str, Any], colnames: list[str]) -> list[Any]: + return [record.get(col) for col in colnames] + + +def _table_viz_types() -> set[str]: + """Viz types kept tabular in image mode (config override or built-in default).""" + return current_app.config.get("EXCEL_EXPORT_TABLE_VIZ_TYPES") or TABLE_VIZ_TYPES + + +def _renders_as_image(chart: Any, mode: str) -> bool: + """Whether this chart is embedded as an image rather than streamed as data.""" + return mode == EXPORT_MODE_IMAGES and chart.viz_type not in _table_viz_types() + + +def _write_chart_image_sheet( + writer: StreamingXlsxWriter, + chart: Any, + dashboard_id: int, + active_data_mask: dict[str, Any], + user: Any, +) -> None: + """ + Render a single chart to an image and embed it as its own sheet. + + :raises _ChartSkippedError: if the chart could not be rendered + """ + image = render_chart_image(chart, dashboard_id, active_data_mask, user) + if image is None: + raise _ChartSkippedError + writer.add_image_sheet(_chart_label(chart), image) + + +def _write_chart_sheets( + writer: StreamingXlsxWriter, + chart: Any, + dashboard_id: int, + active_data_mask: dict[str, Any], +) -> None: + """ + Run a single chart's query and stream its result(s) into the workbook. + + Charts may yield more than one query (e.g. mixed-series charts); each becomes + its own sheet. Raises if the chart cannot be exported, so the caller can skip + it and note it in the email. + """ + json_body = json.loads(chart.query_context) + # Override any stale saved values: we always want full JSON results. + json_body["result_format"] = ChartDataResultFormat.JSON + json_body["result_type"] = ChartDataResultType.FULL + json_body.pop("force", None) + + filter_context = get_dashboard_filter_context( + dashboard_id=dashboard_id, + chart_id=chart.id, + active_data_mask=active_data_mask, + ) + if filter_context.extra_form_data: + apply_dashboard_filter_context(json_body, filter_context.extra_form_data) + + # Jinja macros resolve form data from g.form_data; expose the saved context. + g.form_data = json_body + + query_context = ChartDataQueryContextSchema().load(json_body) + command = ChartDataCommand(query_context) + command.validate() + result = command.run() + + for index, query in enumerate(result["queries"]): + colnames = query.get("colnames") or [] + data = query.get("data") or [] + if index == 0: + name = f"{chart.id} - {chart.slice_name or ''}" + else: + name = f"{chart.id}.{index} - {chart.slice_name or ''}" + writer.add_sheet( + name, + colnames, + (_record_to_row(record, colnames) for record in data), + ) + + +def _build_workbook( + path: str, + dashboard: Any, + active_data_mask: dict[str, Any], + job_id: str, + mode: str, + user: Any, +) -> dict[str, list[str]]: + """Build the workbook on disk. + + Return the charts that could not be exported, grouped by the reason they + were omitted (see the ``email.ERROR_*`` reason keys), so the notification + can explain each group separately. + """ + errored: dict[str, list[str]] = {} + writer = StreamingXlsxWriter(path) + try: + for chart in get_charts_in_layout_order(dashboard): + label = _chart_label(chart) + as_image = _renders_as_image(chart, mode) + # Image charts render from their saved params and don't need a query + # context; data (and table) charts still do. + if not as_image and not chart.query_context: + errored.setdefault(email.ERROR_NO_QUERY_CONTEXT, []).append(label) + continue + try: + if as_image: + _write_chart_image_sheet( + writer, chart, dashboard.id, active_data_mask, user + ) + else: + _write_chart_sheets(writer, chart, dashboard.id, active_data_mask) + except SoftTimeLimitExceeded: + # A soft timeout is a task-level signal, not a per-chart failure: + # let it propagate so the outer handler emails a failure and runs + # cleanup, rather than continuing until the hard limit kills the + # worker (which would skip cleanup, leak temp files, and hold the + # in-flight lock until its TTL). ``except Exception`` below would + # otherwise swallow it, since it subclasses ``Exception``. + raise + except _ChartSkippedError: + logger.warning( + "Skipping chart %s in dashboard export %s (could not render)", + chart.id, + job_id, + ) + errored.setdefault(email.ERROR_GENERAL, []).append(label) + except Exception: # pylint: disable=broad-except + logger.exception( + "Skipping chart %s in dashboard export %s", chart.id, job_id + ) + errored.setdefault(email.ERROR_GENERAL, []).append(label) + + if writer.sheet_count == 0: + flat = [label for labels in errored.values() for label in labels] + writer.add_summary_sheet( + "Export Summary", + ["No chart data could be exported.", *flat], + ) + finally: + writer.close() + return errored + + +def _send_failure_email( + user: Any, dashboard_title: str, requested_at: datetime +) -> None: + if not (user and getattr(user, "email", None)): + return + try: + email.send_export_email( + user.email, + email.build_subject(dashboard_title, success=False), + email.build_failure_email(dashboard_title, requested_at), + ) + except Exception: # pylint: disable=broad-except + logger.exception("Failed to send export failure email") + + +@celery_app.task( + name="export_dashboard_excel", + bind=True, + soft_time_limit=EXPORT_SOFT_TIME_LIMIT, + time_limit=EXPORT_HARD_TIME_LIMIT, + max_retries=0, +) +def export_dashboard_excel( + self: Any, # pylint: disable=unused-argument + dashboard_id: int, + user_id: int, + active_data_mask: dict[str, Any], + job_id: str, + mode: str = EXPORT_MODE_DATA, +) -> None: + """ + Export a dashboard's charts to an ``.xlsx`` and email a download link. + + :param dashboard_id: The dashboard to export + :param user_id: The requesting user (the task runs with their permissions) + :param active_data_mask: Live dashboard filter state keyed by native filter id + :param job_id: Correlation id, also the Celery task id and S3 object name + :param mode: ``"data"`` streams every chart's tabular result; ``"images"`` + embeds non-table charts as rendered images and keeps tables tabular + """ + # pylint: disable=import-outside-toplevel + from superset.models.dashboard import Dashboard + + requested_at = datetime.now(tz=timezone.utc) + user = security_manager.get_user_by_id(user_id) + dashboard_title = "" + tmp_path: str | None = None + + try: + with override_user(user, force=False): + dashboard = ( + db.session.query(Dashboard).filter_by(id=dashboard_id).one_or_none() + ) + if dashboard is None: + raise ValueError(f"Dashboard {dashboard_id} not found") + dashboard_title = dashboard.dashboard_title or f"Dashboard {dashboard_id}" + + file_descriptor, tmp_path = tempfile.mkstemp( + suffix=".xlsx", prefix=f"dash-export-{job_id}-" + ) + os.close(file_descriptor) + + errored = _build_workbook( + tmp_path, dashboard, active_data_mask, job_id, mode, user + ) + + bucket = current_app.config["EXCEL_EXPORT_S3_BUCKET"] + key = ( + f"{current_app.config['EXCEL_EXPORT_S3_KEY_PREFIX']}" + f"{dashboard_id}/{job_id}.xlsx" + ) + ttl = current_app.config["EXCEL_EXPORT_LINK_TTL_SECONDS"] + + s3.upload_file_to_s3(tmp_path, bucket, key) + download_url = s3.generate_presigned_url(bucket, key, ttl) + expires_at = datetime.now(tz=timezone.utc) + timedelta(seconds=ttl) + + if user and getattr(user, "email", None): + try: + email.send_export_email( + user.email, + email.build_subject(dashboard_title, success=True), + email.build_success_email( + dashboard_title=dashboard_title, + download_url=download_url, + requested_at=requested_at, + expires_at=expires_at, + ttl_seconds=ttl, + errored=errored, + ), + ) + except Exception: # pylint: disable=broad-except + # The file is already in S3; a send failure should not trigger + # a misleading failure email. + logger.exception("Failed to send export success email") + except SoftTimeLimitExceeded: + logger.warning("Dashboard excel export %s timed out", job_id) + _send_failure_email(user, dashboard_title, requested_at) + raise + except Exception: + logger.exception("Dashboard excel export %s failed", job_id) + _send_failure_email(user, dashboard_title, requested_at) + raise + finally: + try: + ReleaseDistributedLock( + EXPORT_LOCK_NAMESPACE, + export_lock_params(user_id, dashboard_id), + ).run() Review Comment: **Suggestion:** The lock release is keyed only by `user_id` + `dashboard_id`, so if the original lock expires (for example, due to queue delay before the worker starts) and a newer export acquires the same key, this task’s `finally` block can delete the newer lock and allow overlapping exports. Store an ownership token (for example `job_id`) in the lock and perform owner-checked release so a stale task cannot release another task’s lock. [race condition] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Concurrent dashboard Excel exports bypass single-export throttle. - ⚠️ Overlapping exports increase load on chart query engines. - ⚠️ Lock semantics diverge from API’s concurrency guarantees. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Call the dashboard Excel export endpoint `POST api/v1/dashboard/{dashboard_id}/export_xlsx/`, which in `superset/dashboards/api.py:1688-1717` computes `lock_params = export_lock_params(g.user.id, dashboard.id)` and calls `AcquireDistributedLock(EXPORT_LOCK_NAMESPACE, lock_params, ttl_seconds=EXPORT_LOCK_TTL_SECONDS).run()`. 2. Observe that `AcquireDistributedLock` (in `superset/commands/distributed_lock/acquire.py:73-80,88-99`) uses a key derived only from `namespace` and `params` (via `BaseDistributedLockCommand` at `superset/commands/distributed_lock/base.py:61-65`) and stores a fixed Redis value `"1"` with an expiration, without any owner/job identifier. 3. The same request enqueues the Celery task `export_dashboard_excel` (`superset/tasks/export_dashboard_excel.py:7-24,33-35`) with arguments `dashboard_id`, `user_id`, `active_data_mask`, and a `job_id` used only for filenames and emails, not for locking. 4. In the Celery worker, when `export_dashboard_excel` eventually finishes (success, timeout, or error), the `finally` block at `superset/tasks/export_dashboard_excel.py:88-93` calls `ReleaseDistributedLock(EXPORT_LOCK_NAMESPACE, export_lock_params(user_id, dashboard_id)).run()`, and `ReleaseDistributedLock._release_redis` (`superset/commands/distributed_lock/release.py:53-57`) blindly issues `redis_client.delete(self.redis_lock_key)` for that `namespace`+`params` key, regardless of who acquired the current lock. 5. If the first export’s lock expires before its task starts (for example, by configuring `EXPORT_LOCK_TTL_SECONDS` in `superset/tasks/export_dashboard_excel.py:81-82` to be shorter than queue delay, or under heavy backlog), a second `POST api/v1/dashboard/{dashboard_id}/export_xlsx/` acquires a new lock with the same `namespace`+`params` and enqueues a second task. 6. When the stale first task later runs and reaches its `finally` block, its `ReleaseDistributedLock` call deletes the newer task’s lock (same key, no owner check), so a third `POST api/v1/dashboard/{dashboard_id}/export_xlsx/` can acquire the lock while the second export is still running, violating the “one concurrent export per user+dashboard” guarantee encoded in `superset/dashboards/api.py:1688-1702`. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=559ecd2e48c943aa8d5ca98a9db8200b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=559ecd2e48c943aa8d5ca98a9db8200b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/tasks/export_dashboard_excel.py **Line:** 349:352 **Comment:** *Race Condition: The lock release is keyed only by `user_id` + `dashboard_id`, so if the original lock expires (for example, due to queue delay before the worker starts) and a newer export acquires the same key, this task’s `finally` block can delete the newer lock and allow overlapping exports. Store an ownership token (for example `job_id`) in the lock and perform owner-checked release so a stale task cannot release another task’s lock. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41133&comment_hash=0bbbeb60faed4a23b4687f802513796febdd2e3521eb18adeb52d0b5f76b1ce8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41133&comment_hash=0bbbeb60faed4a23b4687f802513796febdd2e3521eb18adeb52d0b5f76b1ce8&reaction=dislike'>👎</a> ########## superset/utils/excel.py: ########## @@ -41,18 +41,21 @@ "created": NEUTRAL_TIMESTAMP, } +# Leading characters that turn a cell into a formula in spreadsheet apps. Shared +# with the streaming writer (superset.utils.excel_streaming) so both export paths +# guard against the same formula-injection vectors. +FORMULA_PREFIXES = {"=", "+", "-", "@"} + def quote_formulas(df: pd.DataFrame) -> pd.DataFrame: """ Make sure to quote any formulas for security reasons. """ - formula_prefixes = {"=", "+", "-", "@"} - for col in df.select_dtypes(include="object").columns: df[col] = df[col].apply( lambda x: ( f"'{x}" - if isinstance(x, str) and len(x) and x[0] in formula_prefixes + if isinstance(x, str) and len(x) and x[0] in FORMULA_PREFIXES Review Comment: **Suggestion:** The formula guard only checks the first character (`x[0]`) and misses payloads with leading whitespace (for example `" =cmd"` or `"\t=cmd"`), which spreadsheet apps can still evaluate as formulas. Normalize leading whitespace before checking prefixes (as done in the streaming writer) so this export path blocks the same injection vectors. [security] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ XLSX chart exports permit whitespace-prefixed formula injection. - ⚠️ Users opening exports risk unintended formula execution. - ⚠️ Legacy Excel export weaker than streaming Excel protection. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Trigger an XLSX export that uses `df_to_excel()`, for example: - The legacy explore endpoint path that calls `generate_json(..., response_type=ChartDataResultFormat.XLSX)` in `superset/views/core.py:6-21`, which delegates to `_generate_xlsx()` at `superset/views/core.py:29-35` and then `df_to_excel(df, index=False)` at `superset/views/core.py:33-35,20`. - Or the `/api/v1/chart/data` endpoint when `result_format` is `"xlsx"`, which runs through `QueryContextProcessor.get_data()` and calls `excel.df_to_excel(...)` at `superset/common/query_context_processor.py:27-31`. 2. Ensure the underlying dataframe has an object column containing a value like `" =cmd()"` or `"\t@SUM(A1:A2)"`, e.g. by storing such strings in a varchar/text column that is returned in the chart query; the dataframe is provided by `viz_obj.get_df_payload()` in `superset/views/core.py:35-36` or by the query context pipeline before `excel.df_to_excel()` in `superset/common/query_context_processor.py:18-31`. 3. During export, `df_to_excel()` (`superset/utils/excel.py:66-75`) first calls `quote_formulas(df)` (`superset/utils/excel.py:50-63`), which for object columns applies the lambda at `superset/utils/excel.py:55-60`: `f"'{x}" if isinstance(x, str) and len(x) and x[0] in FORMULA_PREFIXES else x`. Because the check uses `x[0]` directly without stripping leading whitespace, values starting with space or tab before `"="`, `"+"`, `"-"`, or `"@"` bypass quoting and are written unchanged. 4. The resulting XLSX file is returned to the client (`XlsxResponse` in `superset/views/core.py:20-21` or raw bytes from `/api/v1/chart/data`), and when opened in Excel or similar spreadsheet software, those cells are interpreted as formulas (as acknowledged by `_quote_if_formula` in the streaming writer at `superset/utils/excel_streaming.py:56-66`, which explicitly strips leading whitespace before checking). This enables formula injection via leading whitespace in the non-streaming Excel export path. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ab9e25dde58e4f7288711af780121257&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ab9e25dde58e4f7288711af780121257&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/utils/excel.py **Line:** 58:58 **Comment:** *Security: The formula guard only checks the first character (`x[0]`) and misses payloads with leading whitespace (for example `" =cmd"` or `"\t=cmd"`), which spreadsheet apps can still evaluate as formulas. Normalize leading whitespace before checking prefixes (as done in the streaming writer) so this export path blocks the same injection vectors. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41133&comment_hash=dfdfa4baba6be507855c884fe24a951a025c60fe9f8d67ae4a9a235b95cd6631&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41133&comment_hash=dfdfa4baba6be507855c884fe24a951a025c60fe9f8d67ae4a9a235b95cd6631&reaction=dislike'>👎</a> -- 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]
