codeant-ai-for-open-source[bot] commented on code in PR #41133: URL: https://github.com/apache/superset/pull/41133#discussion_r3509724047
########## superset/tasks/export_dashboard_excel.py: ########## @@ -0,0 +1,246 @@ +# 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. + +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. +""" + +from __future__ import annotations + +import logging +import os +import tempfile +from datetime import datetime, timedelta +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.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.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__) + + +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 _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, +) -> list[str]: + """Build the workbook on disk; return the list of skipped chart labels.""" + skipped: list[str] = [] + writer = StreamingXlsxWriter(path) + try: + for chart in get_charts_in_layout_order(dashboard): + if not chart.query_context: + skipped.append(_chart_label(chart)) + continue + try: + _write_chart_sheets(writer, chart, dashboard.id, active_data_mask) + except Exception: # pylint: disable=broad-except + logger.exception( + "Skipping chart %s in dashboard export %s", chart.id, job_id + ) + skipped.append(_chart_label(chart)) + + if writer.sheet_count == 0: + writer.add_summary_sheet( + "Export Summary", + ["No chart data could be exported.", *skipped], + ) + finally: + writer.close() + return skipped + + +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=600, + time_limit=660, + 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, +) -> None: + """ + Export a dashboard's chart data 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 + """ + # pylint: disable=import-outside-toplevel + from superset.models.dashboard import Dashboard + + requested_at = datetime.utcnow() + user = security_manager.get_user_by_id(user_id) + dashboard_title = "" + tmp_path: str | None = None + + try: + with override_user(user, force=False): + dashboard = ( Review Comment: **Suggestion:** The task never validates that the requesting user still exists before exporting. If the user is deleted between enqueue and execution, the export can run under a null user context, skip secured chart queries, still upload an incomplete workbook, and send no notification. Add an explicit early failure when the user lookup returns null. [null pointer] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ Exports run with deleted or invalid requesting users. - ⚠️ Users receive no email for such broken exports. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. From the dashboard Excel export endpoint /api/v1/dashboard/{id}/export_xlsx/ in superset/dashboards/api.py lines 1388-1477, note that export_dashboard_excel is enqueued with kwargs including "user_id": g.user.id (lines 1468-1473); in a test, instead call export_dashboard_excel directly with a user_id that does not exist in the database. 2. In superset/tasks/export_dashboard_excel.py line 187, security_manager.get_user_by_id(user_id) returns None for this stale or invalid id, but the code does not validate this; it proceeds to set user to None, leaves dashboard_title empty, and enters the override_user context at line 192 with override_user(user, force=False). 3. The override_user implementation in superset/utils/core.py lines 1522-1546 sets g.user = user even when user is None in Celery contexts that do not already have g.user, so inside the with-block, g.user is None while export_dashboard_excel continues to query Dashboard (lines 193-199) and then calls _build_workbook at line 205. 4. Within _build_workbook and _write_chart_sheets, get_dashboard_filter_context in superset/charts/data/dashboard_filter_context.py lines 269-341 calls _check_dashboard_access (lines 258-266), which relies on security_manager.raise_for_access and the current g.user; with g.user None, access checks fail with a SupersetSecurityException that is caught by the broad per-chart except block in _build_workbook (lines 128-134), causing every chart to be skipped, yet the task still uploads the workbook to S3 (lines 207-215) and generates a presigned URL (line 215) without sending any success or failure email because user is None in both the success (lines 218-231) and _send_failure_email (lines 146-158) paths, leaving the original API caller with a 202 response but no notification or clear failure signal. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cccf4831e9f3415d921cbb1b62ad179a&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=cccf4831e9f3415d921cbb1b62ad179a&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:** 187:193 **Comment:** *Null Pointer: The task never validates that the requesting user still exists before exporting. If the user is deleted between enqueue and execution, the export can run under a null user context, skip secured chart queries, still upload an incomplete workbook, and send no notification. Add an explicit early failure when the user lookup returns null. 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=6462234d5bf627cc0c80532b4a675d12783173c0571069a2b1a5cb2e7a4c70c1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41133&comment_hash=6462234d5bf627cc0c80532b4a675d12783173c0571069a2b1a5cb2e7a4c70c1&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]
