Skip to content

feat(dashboard): export dashboard chart data to Excel (async, S3 + email) - #41133

Merged
hughhhh merged 54 commits into
masterfrom
hughhhh/dashboard-export-spec-review
Jul 21, 2026
Merged

hughhhh merged 54 commits into
masterfrom
hughhhh/dashboard-export-spec-review

Conversation

@hughhhh

@hughhhh hughhhh commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

Adds an asynchronous "Export Data to Excel" action to the dashboard Download menu. A new POST /api/v1/dashboard/<pk>/export_xlsx/ endpoint enqueues a Celery task that re-runs each chart's saved query context under the requesting user with the live dashboard filter state applied, streams the results into a constant-memory multi-sheet .xlsx (one worksheet per chart, tab-nested charts included), uploads it to S3, and emails the user a time-limited pre-signed download link. The feature is disabled until EXCEL_EXPORT_S3_BUCKET is set (the endpoint returns 501 otherwise) and is gated on the Dashboard can_export permission. The branch also carries a small pre-existing package-lock.json lockfile bump, committed separately so it can be dropped independently.

Key design decisions (resolving gaps in the spec):

  • Reuses the existing chart-data row caps (ROW_LIMIT/SQL_MAX_ROW) plus an Excel per-sheet row clamp — no new limit config.
  • Extends get_dashboard_filter_context with an active_data_mask kwarg (backward compatible) and extracts the shared query-context merge helper.
  • Streaming writer sanitizes sheet names (forbidden chars, 31-char cap, de-dupe) and quotes formula-like cells (= + - @) to prevent injection.
  • Embedded/guest-token users are excluded in v1 (they have no email for delivery) → 400.
  • New config keys: EXCEL_EXPORT_S3_BUCKET, EXCEL_EXPORT_S3_KEY_PREFIX, EXCEL_EXPORT_LINK_TTL_SECONDS, EXCEL_EXPORT_S3_CLIENT_KWARGS. Requires a Celery worker, SMTP, and an S3 bucket (see UPDATING.md / docs).

TESTING INSTRUCTIONS

  • Unit: pytest tests/unit_tests/{utils/excel_streaming_tests.py,utils/s3_tests.py,charts/test_dashboard_filter_context.py,dashboards/test_excel_export_email.py,dashboards/test_excel_export_layout.py,tasks/test_export_dashboard_excel.py} (92 pass).
  • Frontend: cd superset-frontend && npm run test -- DownloadMenuItems (12 pass).
  • Integration: pytest tests/integration_tests/dashboards/api_tests.py -k export_xlsx.
  • Manual E2E: set EXCEL_EXPORT_S3_BUCKET (+ EXCEL_EXPORT_S3_CLIENT_KWARGS for MinIO/LocalStack), run a Celery worker and SMTP; trigger Download → Export Data to Excel on a tabbed, filtered dashboard; confirm the emailed pre-signed link downloads a workbook with one sheet per chart reflecting the active filters.

Validation

UI

Screenshot 2026-07-01 at 8 22 50 PM

After Export Button pressed

Screenshot 2026-07-01 at 8 22 57 PM

File Exported:

9e47388c-11ae-4589-a53e-38b8d695b1ce.xlsx

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags: none (gated by the EXCEL_EXPORT_S3_BUCKET config)
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

hughhhh and others added 12 commits June 13, 2026 09:52
Extract the extra_form_data merge block from the chart data GET endpoint
into apply_extra_form_data_to_query_context_json() in dashboard_filter_context,
so it can be reused by the upcoming dashboard Excel export task. No behavior
change; adds unit tests for the extracted helper.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extend get_dashboard_filter_context with an optional active_data_mask kwarg so
callers can resolve each in-scope native filter against live dashboard filter
state instead of saved defaults. A non-empty active extraFormData is applied,
an empty one clears the filter (no fallback to default), and filters absent
from the mask keep their defaults. Backward compatible: omitting the kwarg
reproduces initial-load behavior. Adds unit tests covering override, clear,
fallback, defaultToFirstItem, and out-of-scope cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add StreamingXlsxWriter, a constant-memory xlsxwriter wrapper that writes one
sheet per chart row-by-row, so multi-chart dashboard exports never hold more
than one row per sheet in memory. Includes sheet-name sanitization (forbidden
chars, 31-char cap, reserved 'History', case-insensitive de-duplication) and
per-cell sanitization (formula-injection quoting mirroring excel.quote_formulas,
Excel int/float precision limits, ISO temporal rendering). Reuses the neutral
document properties from utils.excel. Adds unit tests with an openpyxl
round-trip.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add get_charts_in_layout_order(), a depth-first walk of a dashboard's
position_json that returns its charts in visual order including tab-nested
charts. De-duplicates charts placed more than once, skips stale layout entries
with no backing chart, and appends charts absent from the layout at the end
ordered by id. Guards against cyclic layouts. Adds unit tests.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add superset.utils.s3 with upload_file_to_s3() (boto3 managed multipart) and
generate_presigned_url(). Credentials/region come from the standard boto3 chain;
operators can override client construction via EXCEL_EXPORT_S3_CLIENT_KWARGS
(e.g. endpoint_url for MinIO/LocalStack). Adds unit tests with mocked boto3.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add email rendering/delivery for dashboard Excel exports: success and failure
HTML bodies (inline styles only, no logo, matching report-notification emails),
subject lines prefixed with EMAIL_REPORTS_SUBJECT_PREFIX, and a send wrapper
over send_email_smtp. Dashboard titles and chart names are HTML-escaped to
prevent injection. Adds unit tests.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add config keys for the dashboard Excel export feature: EXCEL_EXPORT_S3_BUCKET
(None by default; the export endpoint returns 501 until set),
EXCEL_EXPORT_S3_KEY_PREFIX, EXCEL_EXPORT_LINK_TTL_SECONDS, and
EXCEL_EXPORT_S3_CLIENT_KWARGS. Documents prerequisites (worker, SMTP, bucket)
and the CELERY_CONFIG.imports requirement in UPDATING.md.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add the async task that exports a dashboard's chart data to a multi-sheet xlsx.
Running as the requesting user, it walks charts in layout order, re-runs each
saved query context with the live filter state applied, streams results into a
constant-memory workbook, uploads to S3, and emails a pre-signed link. Charts
with no/invalid query context or a failing query are skipped and listed in the
email; all-skipped dashboards get a summary sheet. On failure (incl. soft
timeout) it emails the user and always cleans up the temp file. Registers the
task in CeleryConfig.imports. Adds unit tests for happy path, skips, summary,
upload failure, and timeout.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add POST /api/v1/dashboard/<pk>/export_xlsx/ which validates the request and
enqueues the async Excel export task, returning 202 with a job id. Gated on the
Dashboard can_export permission (@permission_name("export")); returns 501 when
EXCEL_EXPORT_S3_BUCKET is unset, 404 for inaccessible/missing dashboards,
403 on object-level access denial, and 400 for guest/no-email users or empty
dashboards. The job id is used as the Celery task id for correlation. Adds the
request/response marshmallow schemas and integration tests.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add an 'Export Data to Excel' item to the dashboard Download submenu (below the
divider, above Export YAML/Example), gated on the Dashboard can_export
permission (userCanExport). It POSTs the live native-filter data mask to the
export_xlsx endpoint and toasts: a pending message on 202, a 'not configured'
message on 501, and a generic error otherwise. Adds jest tests for visibility,
the POST payload, and the toast paths.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add a using-superset doc covering the Export Data to Excel feature: how to
trigger it, worksheet/row-cap behavior, the S3/SMTP/Celery prerequisites, the
new config keys, presigned-URL security considerations, and the embedded/guest
limitation.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…apbox)

Pre-existing lockfile changes present in the workspace; committed separately
from the dashboard Excel export work so it can be dropped independently.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added api:dashboard Related to the REST endpoints of the Dashboard dashboard:export Related to exporting dashboards global:async-query Related to Async Queries feature labels Jun 16, 2026
@github-actions github-actions Bot added api Related to the REST API doc Namespace | Anything related to documentation dependencies:npm labels Jun 16, 2026
@netlify

netlify Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 12cd4a1
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a5e45957c744000089c3e51
😎 Deploy Preview https://deploy-preview-41133--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

…xport-spec-review

# Conflicts:
#	UPDATING.md
#	superset-frontend/package-lock.json
@codecov

codecov Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 37.57962% with 294 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.16%. Comparing base (034823e) to head (f456391).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
superset/tasks/export_dashboard_excel.py 30.00% 98 Missing ⚠️
superset/utils/excel_streaming.py 25.74% 75 Missing ⚠️
superset/dashboards/excel_export/email.py 29.50% 43 Missing ⚠️
superset/dashboards/excel_export/layout.py 15.00% 34 Missing ⚠️
superset/dashboards/excel_export/screenshot.py 42.30% 15 Missing ⚠️
superset/dashboards/api.py 78.04% 8 Missing and 1 partial ⚠️
superset/charts/data/dashboard_filter_context.py 11.11% 8 Missing ⚠️
superset/utils/s3.py 50.00% 8 Missing ⚠️
...hboard/components/menu/DownloadMenuItems/index.tsx 84.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #41133      +/-   ##
==========================================
- Coverage   65.25%   65.16%   -0.09%     
==========================================
  Files        2768     2774       +6     
  Lines      156303   156771     +468     
  Branches    35779    35843      +64     
==========================================
+ Hits       101989   102161     +172     
- Misses      52346    52641     +295     
- Partials     1968     1969       +1     
Flag Coverage Δ
hive 38.70% <29.82%> (+0.02%) ⬆️
javascript 70.89% <84.00%> (-0.01%) ⬇️
mysql 57.79% <34.97%> (-0.14%) ⬇️
postgres 57.85% <34.97%> (-0.14%) ⬇️
presto 40.62% <29.82%> (+0.01%) ⬆️
python 59.24% <34.97%> (-0.14%) ⬇️
sqlite 57.45% <34.97%> (-0.13%) ⬇️
unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@hughhhh
hughhhh requested a review from betodealmeida June 16, 2026 23:26
- export_xlsx: use request.get_json(silent=True) so a POST with no JSON
  content-type no longer raises 415/500 (returns 400/404/501 as intended).
- api_tests: register the FAB-generated can_export_xlsx permission in
  test_info_security_dashboard; replace the gamma test (Gamma has can_export)
  with a deterministic 404-for-inaccessible-dashboard check.
- type-annotate dict literals in the filter-context tests (mypy var-annotated).
- move MenuWrapperWithProps above first use (oxlint no-use-before-define).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@bito-code-review bito-code-review Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Agent Run #113c4b

Actionable Suggestions - 2
  • superset/dashboards/excel_export/email.py - 1
  • superset/tasks/export_dashboard_excel.py - 1
Additional Suggestions - 5
  • superset/dashboards/api.py - 1
    • Missing test for email requirement · Line 1452-1455
      The email requirement check at lines 1452-1455 has no test coverage. A user without an email address can trigger this code path, but the behavior is unverified. Add a test that mocks a user with no email attribute and asserts the 400 response.
  • superset/dashboards/schemas.py - 1
    • Naming Convention Inconsistency · Line 629-643
      The new `active_data_mask` and `job_id` fields use `snake_case`, while existing schemas in this file consistently use `camelCase` (e.g., `dataMask`, `activeTabs`, `urlParams`). This inconsistency may cause confusion for API consumers expecting consistent naming conventions.
  • superset/config.py - 1
    • Missing type annotations on constants · Line 1273-1275
      These two constants lack type annotations while `EXCEL_EXPORT_S3_BUCKET` (line 1271) and `EXCEL_EXPORT_S3_CLIENT_KWARGS` (line 1279) in the same block have them. Per AGENTS.md and dev-standard.mdc, all new Python code should include type hints for MyPy compliance.
      Code suggestion
      --- a/superset/config.py
      +++ b/superset/config.py
       @@ -1270,9 +1270,9 @@ EXCEL_EXPORT: dict[str, Any] = {}
        # disabled until this is set: the export endpoint returns 501 when it is None.
        EXCEL_EXPORT_S3_BUCKET: str | None = None
        # Key prefix for export objects: {prefix}{dashboard_id}/{job_id}.xlsx
      -EXCEL_EXPORT_S3_KEY_PREFIX = "dashboard-exports/"
      +EXCEL_EXPORT_S3_KEY_PREFIX: str = "dashboard-exports/"
        # Lifetime (seconds) of the pre-signed download URL emailed to the user (24h).
      -EXCEL_EXPORT_LINK_TTL_SECONDS = 86400
      +EXCEL_EXPORT_LINK_TTL_SECONDS: int = 86400
        # Extra kwargs passed to boto3.client("s3", ...) — e.g. region_name, or an
        # endpoint_url for S3-compatible stores (MinIO/LocalStack). Credentials
        EXCEL_EXPORT_S3_CLIENT_KWARGS: dict[str, Any] = {}
  • superset/utils/s3.py - 1
    • Unused logger variable · Line 34-34
      The `logger` is declared on line 34 but never used. Either remove it or add logging statements for S3 operations to aid debugging and observability.
  • superset/dashboards/excel_export/layout.py - 1
    • Missing cycle guard test · Line 69-69
      The `_walk_chart_ids` docstring advertises 'cycles are guarded against' and `visited_nodes` at line 49 provides that protection, but no test in `test_excel_export_layout.py` exercises a cycle. A test with a self-referential or cross-linked child would confirm the guard works and prevent silent regressions if the traversal logic is refactored.
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx - 1
  • tests/integration_tests/dashboards/api_tests.py - 1
Review Details
  • Files reviewed - 21 · Commit Range: 5421799..cc9d6f5
    • docs/docs/using-superset/exporting-dashboard-data.mdx
    • superset-frontend/src/dashboard/components/menu/DownloadMenuItems/DownloadMenuItems.test.tsx
    • superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx
    • superset/charts/data/api.py
    • superset/charts/data/dashboard_filter_context.py
    • superset/config.py
    • superset/dashboards/api.py
    • superset/dashboards/excel_export/__init__.py
    • superset/dashboards/excel_export/email.py
    • superset/dashboards/excel_export/layout.py
    • superset/dashboards/schemas.py
    • superset/tasks/export_dashboard_excel.py
    • superset/utils/excel_streaming.py
    • superset/utils/s3.py
    • tests/integration_tests/dashboards/api_tests.py
    • tests/unit_tests/charts/test_dashboard_filter_context.py
    • tests/unit_tests/dashboards/test_excel_export_email.py
    • tests/unit_tests/dashboards/test_excel_export_layout.py
    • tests/unit_tests/tasks/test_export_dashboard_excel.py
    • tests/unit_tests/utils/excel_streaming_tests.py
    • tests/unit_tests/utils/s3_tests.py
  • Files skipped - 2
    • UPDATING.md - Reason: Filter setting
    • superset-frontend/package-lock.json - Reason: Filter setting
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Comment on lines +46 to +51
def build_subject(dashboard_title: str, *, success: bool) -> str:
"""Build the email subject, prefixed with EMAIL_REPORTS_SUBJECT_PREFIX."""
prefix = current_app.config["EMAIL_REPORTS_SUBJECT_PREFIX"]
if success:
return f"{prefix}Your dashboard export is ready: {dashboard_title}"
return f"{prefix}Your dashboard export could not be completed: {dashboard_title}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing i18n translation wrappers

User-facing email text is hardcoded in English without translation wrappers. The existing superset/reports/notifications/email.py uses flask_babel.gettext as __() for all such strings. Apply the same pattern here for i18n consistency.

Code Review Run #113c4b


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's do this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to use translation wrappers is appropriate for consistency with the existing codebase. Applying this pattern ensures that user-facing email text is correctly internationalized. You can implement this by importing gettext as __ from flask_babel and wrapping the strings in build_subject and other functions.

superset/dashboards/excel_export/email.py

from flask_babel import gettext as __

def build_subject(dashboard_title: str, *, success: bool) -> str:
    prefix = current_app.config["EMAIL_REPORTS_SUBJECT_PREFIX"]
    if success:
        return f"{prefix}{__('Your dashboard export is ready: %(title)s', title=dashboard_title)}"
    return f"{prefix}{__('Your dashboard export could not be completed: %(title)s', title=dashboard_title)}"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This hasn't been addressed yet.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to use translation wrappers is appropriate for consistency with the existing codebase. Applying this pattern ensures that user-facing email text is correctly internationalized. You can implement this by importing gettext as __ from flask_babel and wrapping the strings in build_subject and other functions.

superset/dashboards/excel_export/email.py

from flask_babel import gettext as __

def build_subject(dashboard_title: str, *, success: bool) -> str:
    prefix = current_app.config["EMAIL_REPORTS_SUBJECT_PREFIX"]
    if success:
        return f"{prefix}{__('Your dashboard export is ready: %(title)s', title=dashboard_title)}"
    return f"{prefix}{__('Your dashboard export could not be completed: %(title)s', title=dashboard_title)}"

# pylint: disable=import-outside-toplevel
from superset.models.dashboard import Dashboard

requested_at = datetime.utcnow()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace deprecated datetime.utcnow

Replace deprecated datetime.utcnow() with datetime.now(datetime.timezone.utc) or datetime.now(tz=timezone.utc). Similar issue at line 217.

Code suggestion
Check the AI-generated fix before applying
 -from datetime import datetime, timedelta
 +from datetime import datetime, timedelta, timezone
  from typing import Any
 
  from celery.exceptions import SoftTimeLimitExceeded
 @@ -185,7 +185,7 @@
      dashboard_id: int,
      user_id: int,
  ) -> None:
 -    requested_at = datetime.utcnow()
 +    requested_at = datetime.now(tz=timezone.utc)
      user = security_manager.get_user_by_id(user_id)
      dashboard_title = ""

Code Review Run #113c4b


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

^ This

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to replace datetime.utcnow() with datetime.now(tz=timezone.utc) is correct and follows modern Python best practices for handling timezones. Using datetime.utcnow() is deprecated because it returns a naive datetime object, which can lead to ambiguity; using datetime.now(tz=timezone.utc) ensures the object is timezone-aware.

superset/tasks/export_dashboard_excel.py

-    requested_at = datetime.utcnow()
+    requested_at = datetime.now(tz=timezone.utc)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This hasn't been addressed yet.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to replace datetime.utcnow() with datetime.now(tz=timezone.utc) is correct and follows modern Python best practices. Using datetime.utcnow() is deprecated because it returns a naive datetime object, which can lead to ambiguity; using datetime.now(tz=timezone.utc) ensures the object is timezone-aware.

superset/tasks/export_dashboard_excel.py

-    requested_at = datetime.utcnow()
+    requested_at = datetime.now(tz=timezone.utc)

ClientErrorObject exposes status via Partial<SupersetClientResponse> (a union),
so destructuring it directly fails tsc (TS2339). Read it through a narrow cast;
runtime behavior is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
permalinkKey = fields.Str(required=False) # noqa: N815


class DashboardExportXlsxPostSchema(Schema):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a concise class docstring immediately under this new schema class declaration to describe its request payload purpose. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python class and it does not include a docstring immediately under the class definition. That matches the custom rule requiring new functions and classes to be documented inline.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/schemas.py
**Line:** 628:628
**Comment:**
	*Custom Rule: Add a concise class docstring immediately under this new schema class declaration to describe its request payload purpose.

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
👍 | 👎

EXPIRES = datetime(2026, 1, 2, 12, 0, 0)


def test_success_email_contains_link_and_expiry() -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a short docstring to this new test function describing the expected success-email content it validates. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python test function and it has no docstring. The custom rule requires new Python functions and classes to include docstrings, so the suggestion identifies a real violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_email.py
**Line:** 28:28
**Comment:**
	*Custom Rule: Add a short docstring to this new test function describing the expected success-email content it validates.

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
👍 | 👎

assert "<li>" not in html # no skipped section


def test_success_email_lists_skipped_charts() -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a concise docstring explaining that this test verifies skipped charts are rendered in the success email body. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python test function and it lacks a docstring. That violates the rule requiring docstrings for new Python functions and classes.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_email.py
**Line:** 44:44
**Comment:**
	*Custom Rule: Add a concise docstring explaining that this test verifies skipped charts are rendered in the success email body.

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
👍 | 👎

assert "<li>10 - Broken chart</li>" in html


def test_success_email_escapes_title() -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a docstring clarifying that this test checks HTML escaping behavior for unsafe dashboard titles. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

The function is newly added and does not include a docstring. This matches the custom rule for documenting new Python functions.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_email.py
**Line:** 57:57
**Comment:**
	*Custom Rule: Add a docstring clarifying that this test checks HTML escaping behavior for unsafe dashboard titles.

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
👍 | 👎

assert "&lt;script&gt;" in html


def test_failure_email_body() -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a brief docstring indicating this test validates the failure-email template content for unsuccessful exports. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This newly introduced test function has no docstring, so it violates the requirement that new Python functions and classes should be documented inline.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_email.py
**Line:** 70:70
**Comment:**
	*Custom Rule: Add a brief docstring indicating this test validates the failure-email template content for unsuccessful exports.

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
👍 | 👎

Comment on lines +25 to +26
def _chart_node(node_id: str, chart_id: int) -> dict[str, Any]:
return {"id": node_id, "type": "CHART", "meta": {"chartId": chart_id}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a concise docstring to this helper function describing the chart node structure it builds for layout fixtures. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python function and it has no docstring. The custom rule requires newly added functions to be documented inline, so the suggestion correctly identifies a real violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_layout.py
**Line:** 25:26
**Comment:**
	*Custom Rule: Add a concise docstring to this helper function describing the chart node structure it builds for layout fixtures.

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
👍 | 👎

Comment on lines +29 to +33
def _dashboard(position: dict[str, Any], chart_ids: list[int]) -> MagicMock:
dashboard = MagicMock()
dashboard.position = position
dashboard.slices = [MagicMock(id=cid) for cid in chart_ids]
return dashboard

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a docstring explaining that this helper constructs a mocked dashboard object with position metadata and slice mocks. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This newly added helper function lacks a docstring. That violates the rule requiring new Python functions to include docstrings.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_layout.py
**Line:** 29:33
**Comment:**
	*Custom Rule: Add a docstring explaining that this helper constructs a mocked dashboard object with position metadata and slice mocks.

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
👍 | 👎

Comment on lines +36 to +37
def _ids(slices: list[Any]) -> list[int]:
return [slc.id for slc in slices]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a short docstring to clarify that this helper extracts and returns chart IDs from slice-like objects. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a new Python function without a docstring, so it matches the custom rule violation exactly.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_layout.py
**Line:** 36:37
**Comment:**
	*Custom Rule: Add a short docstring to clarify that this helper extracts and returns chart IDs from slice-like objects.

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
👍 | 👎

Comment on lines +40 to +49
def test_grid_order() -> None:
position = {
"ROOT_ID": {"type": "ROOT", "children": ["GRID_ID"]},
"GRID_ID": {"type": "GRID", "children": ["ROW-1"]},
"ROW-1": {"type": "ROW", "children": ["CHART-a", "CHART-b"]},
"CHART-a": _chart_node("CHART-a", 1),
"CHART-b": _chart_node("CHART-b", 2),
}
dashboard = _dashboard(position, [2, 1])
assert _ids(get_charts_in_layout_order(dashboard)) == [1, 2]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a test docstring summarizing the behavior being validated for chart ordering in a basic grid layout. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

Test functions are Python functions, and this newly added one does not include a docstring. The rule applies to newly added Python functions, so this is a real violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_layout.py
**Line:** 40:49
**Comment:**
	*Custom Rule: Add a test docstring summarizing the behavior being validated for chart ordering in a basic grid layout.

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
👍 | 👎

Comment on lines +52 to +63
def test_tab_nested_order() -> None:
position = {
"ROOT_ID": {"type": "ROOT", "children": ["GRID_ID"]},
"GRID_ID": {"type": "GRID", "children": ["TABS-1"]},
"TABS-1": {"type": "TABS", "children": ["TAB-1", "TAB-2"]},
"TAB-1": {"type": "TAB", "children": ["CHART-a"]},
"TAB-2": {"type": "TAB", "children": ["CHART-b"]},
"CHART-a": _chart_node("CHART-a", 10),
"CHART-b": _chart_node("CHART-b", 20),
}
dashboard = _dashboard(position, [20, 10])
assert _ids(get_charts_in_layout_order(dashboard)) == [10, 20]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a docstring to this test function describing that nested tab layout traversal should preserve expected chart export order. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This newly added test function has no docstring, which violates the requirement that new Python functions be documented inline.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_layout.py
**Line:** 52:63
**Comment:**
	*Custom Rule: Add a docstring to this test function describing that nested tab layout traversal should preserve expected chart export order.

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
👍 | 👎

Comment on lines +42 to +43
def _fmt(dt: datetime) -> str:
return dt.strftime(_DATETIME_FORMAT)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a short docstring to this helper function describing that it formats a datetime using the module-level export timestamp format. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python function in the new file, and it has no docstring.
The custom rule requires newly added functions to be documented inline, so the
suggestion correctly identifies a real violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/excel_export/email.py
**Line:** 42:43
**Comment:**
	*Custom Rule: Add a short docstring to this helper function describing that it formats a datetime using the module-level export timestamp format.

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
👍 | 👎

Comment on lines +54 to +62
def _skipped_section(skipped_charts: list[str]) -> str:
if not skipped_charts:
return ""
items = "".join(f"<li>{escape(label)}</li>" for label in skipped_charts)
return (
"<p>Note: the following charts were omitted because they have no saved "
"query context. To include them, open each chart in Explore and re-save."
f"</p><ul>{items}</ul>"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a docstring to this helper function that explains when skipped charts are rendered and what HTML fragment it returns. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This newly added helper function does not include a docstring.
Because the rule requires new functions to be documented inline, the suggestion
points to a genuine violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/excel_export/email.py
**Line:** 54:62
**Comment:**
	*Custom Rule: Add a docstring to this helper function that explains when skipped charts are rendered and what HTML fragment it returns.

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
👍 | 👎

Comment on lines +60 to +61

def _record_to_row(record: dict[str, Any], colnames: list[str]) -> list[Any]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a concise docstring to this new helper function describing that it converts a record dictionary into a row ordered by the provided column names. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

The function is newly added and has no docstring, which violates the rule that new Python functions should be documented inline.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/tasks/export_dashboard_excel.py
**Line:** 60:61
**Comment:**
	*Custom Rule: Add a concise docstring to this new helper function describing that it converts a record dictionary into a row ordered by the provided column names.

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
👍 | 👎

Comment on lines +147 to +151
def _send_failure_email(
user: Any, dashboard_title: str, requested_at: datetime
) -> None:
if not (user and getattr(user, "email", None)):
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a docstring to this new function explaining when failure emails are sent and the purpose of its input parameters. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

The function is newly added and does not include a docstring, so it matches the custom rule requiring docstrings for new Python functions and classes.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/tasks/export_dashboard_excel.py
**Line:** 147:151
**Comment:**
	*Custom Rule: Add a docstring to this new function explaining when failure emails are sent and the purpose of its input parameters.

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
👍 | 👎

response_roles = [result["text"] for result in response["result"]]
assert response_roles == ["Alpha"]

def test_export_xlsx_501_when_bucket_unset(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add full type hints to this new test method signature, including an explicit -> None return annotation. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python test method and it has no parameter or return type annotations. The custom rule requires new Python code to be fully typed, so the omission is a real violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/integration_tests/dashboards/api_tests.py
**Line:** 3281:3281
**Comment:**
	*Custom Rule: Add full type hints to this new test method signature, including an explicit `-> None` return annotation.

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
👍 | 👎

db.session.commit()

@patch("superset.dashboards.api.export_dashboard_excel")
def test_export_xlsx_404_for_missing_dashboard(self, mock_task):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add type annotations for both parameters and return value in this new patched test method (including a concrete type for mock_task and -> None). [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This new test method introduces an untyped parameter (mock_task) and lacks an explicit return annotation. That violates the rule requiring new or modified Python functions to include type hints.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/integration_tests/dashboards/api_tests.py
**Line:** 3294:3294
**Comment:**
	*Custom Rule: Add type annotations for both parameters and return value in this new patched test method (including a concrete type for `mock_task` and `-> None`).

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
👍 | 👎

mock_task.apply_async.assert_not_called()

@patch("superset.dashboards.api.export_dashboard_excel")
def test_export_xlsx_400_for_empty_dashboard(self, mock_task):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Update this new method definition to include explicit parameter and return type hints, following the fully typed new-code rule. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

The method is newly added and its signature is untyped: the mocked argument has no annotation and there is no -> None return type. This matches the type-hint violation described by the rule.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/integration_tests/dashboards/api_tests.py
**Line:** 3306:3306
**Comment:**
	*Custom Rule: Update this new method definition to include explicit parameter and return type hints, following the fully typed new-code rule.

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
👍 | 👎


@pytest.mark.usefixtures("load_world_bank_dashboard_with_slices")
@patch("superset.dashboards.api.export_dashboard_excel")
def test_export_xlsx_202_enqueues_task(self, mock_task):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add missing type hints to this new test method signature, including the mocked argument type and an explicit -> None return type. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This newly introduced test method has an unannotated mocked parameter and no return type annotation. The custom rule explicitly requires new Python code to be fully typed, so this is a verified violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/integration_tests/dashboards/api_tests.py
**Line:** 3325:3325
**Comment:**
	*Custom Rule: Add missing type hints to this new test method signature, including the mocked argument type and an explicit `-> None` return type.

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
👍 | 👎

assert kwargs["kwargs"]["dashboard_id"] == dashboard.id

@patch("superset.dashboards.api.export_dashboard_excel")
def test_export_xlsx_404_for_inaccessible_dashboard(self, mock_task):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add explicit typing to this newly added test method signature so parameters and return value are fully annotated. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a new Python test method with no type hints for its parameter or return value. Since the surrounding code is being changed and new Python code should be fully typed, the suggestion identifies a real issue.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/integration_tests/dashboards/api_tests.py
**Line:** 3347:3347
**Comment:**
	*Custom Rule: Add explicit typing to this newly added test method signature so parameters and return value are fully annotated.

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
👍 | 👎

# --- StreamingXlsxWriter (round-trip via openpyxl) ---


def _read_workbook(path: str) -> dict[str, list[list[object]]]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a docstring that explains the input and expected output contract of this helper function. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This helper is newly added and lacks a docstring in the final file.
The rule explicitly flags newly added Python functions without docstrings.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/utils/excel_streaming_tests.py
**Line:** 105:105
**Comment:**
	*Custom Rule: Add a docstring that explains the input and expected output contract of this helper function.

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
👍 | 👎

return sheets


def test_writer_writes_one_sheet_per_chart(tmp_path: Path) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a docstring summarizing the workbook-writing scenario and expected sheet-level outcome checked by this test. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

The test function is newly introduced and has no docstring.
That matches the custom rule for newly added Python functions.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/utils/excel_streaming_tests.py
**Line:** 116:116
**Comment:**
	*Custom Rule: Add a docstring summarizing the workbook-writing scenario and expected sheet-level outcome checked by this test.

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
👍 | 👎

assert list(sheets.keys()) == ["Export"]


def test_writer_summary_sheet(tmp_path: Path) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a brief docstring describing the summary-sheet behavior being verified. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added function and the final file does not include a docstring for it.
The custom rule requires docstrings on newly added Python functions and classes.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/utils/excel_streaming_tests.py
**Line:** 163:163
**Comment:**
	*Custom Rule: Add a brief docstring describing the summary-sheet behavior being verified.

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
👍 | 👎

Comment on lines +40 to +43
def test_client_kwargs_passthrough(
mock_app: MagicMock, mock_client_fn: MagicMock
) -> None:
mock_app.config = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an inline docstring to this newly added test function to explain the client kwargs passthrough scenario it verifies. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python function, and it does not include a docstring. The custom rule explicitly requires new functions and classes to be documented inline, so the suggestion correctly identifies a real violation.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/utils/s3_tests.py
**Line:** 40:43
**Comment:**
	*Custom Rule: Add an inline docstring to this newly added test function to explain the client kwargs passthrough scenario it verifies.

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
👍 | 👎

Comment on lines +59 to +60
def test_generate_presigned_url(mock_app: MagicMock, mock_client_fn: MagicMock) -> None:
mock_app.config = {"EXCEL_EXPORT_S3_CLIENT_KWARGS": {}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a concise docstring at the beginning of this new test function to describe the presigned URL generation expectation. [custom_rule]

Severity Level: Minor ⚠️

Why it matters? 🤔

This is a newly added Python function, and it lacks a docstring. That matches the custom rule requiring newly added functions and classes to include docstrings, so the violation is real.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/utils/s3_tests.py
**Line:** 59:60
**Comment:**
	*Custom Rule: Add a concise docstring at the beginning of this new test function to describe the presigned URL generation expectation.

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
👍 | 👎

…e flags

Address review of #41133:

- Reuse the dashboard can_export permission for export_xlsx via
  method_permission_name instead of the inert @permission_name decorator,
  which FAB ignored and which derived an unassigned can_export_xlsx perm
  that the frontend never checks. Drop the decorator and the stale test
  assertion; add a regression test proving a can_export-only role is
  admitted (202) not rejected (403).
- Reject mode="images" with 404 when the webdriver screenshot flags are
  off, mirroring the UI gate and validate_feature_flags behavior; add
  flag-on/off regression tests.
- Frontend: distinguish the throttle 202 (no job_id) from a real enqueue
  and show an "already in progress" toast instead of the misleading
  "being prepared" one.
- Drop personal verification scaffolding (VERIFY_EXCEL_EXPORT.md,
  docker-compose-excel-verify.yml) and revert the check-yaml exclusion
  that only that compose file required.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread superset/config.py
Comment on lines +1451 to +1452
# Key prefix for export objects: {prefix}{dashboard_id}/{job_id}.xlsx
EXCEL_EXPORT_S3_KEY_PREFIX = "dashboard-exports/"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an explicit type annotation to this new configuration constant. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

This new module-level configuration constant is a string value that can be explicitly annotated, but it is currently assigned without a type hint, matching the custom rule violation.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/config.py
**Line:** 1451:1452
**Comment:**
	*Custom Rule: Add an explicit type annotation to this new configuration constant.

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
👍 | 👎

Comment thread superset/config.py
Comment on lines +1453 to +1456
# Lifetime (seconds) of the pre-signed download URL emailed to the user (24h).
# Note: AWS S3 caps pre-signed URL lifetime at 7 days (604800 seconds); larger
# values are rejected by S3, so keep this at or below that when using AWS.
EXCEL_EXPORT_LINK_TTL_SECONDS = 86400

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an explicit type annotation to this new numeric configuration constant. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

This new numeric configuration constant is introduced without an explicit type hint, even though it is annotatable as an integer, so the suggestion accurately identifies a real type-hint rule violation.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/config.py
**Line:** 1453:1456
**Comment:**
	*Custom Rule: Add an explicit type annotation to this new numeric configuration constant.

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
👍 | 👎

"""
if not errored:
return ""
notes = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an explicit type annotation for this dictionary assignment so the local collection type is declared. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

The custom rule requires type hints on relevant variables that can be annotated. This local dictionary is assigned without an explicit type annotation, so the suggestion identifies a real rule violation.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/excel_export/email.py
**Line:** 94:94
**Comment:**
	*Custom Rule: Add an explicit type annotation for this dictionary assignment so the local collection type is declared.

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
👍 | 👎

),
}
fallback = __("The following charts could not be exported:")
ordered = [ERROR_NO_QUERY_CONTEXT, ERROR_GENERAL]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Annotate this list variable with its element type to satisfy the type-hint requirement for relevant local variables. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

This is a local list variable in new Python code and it lacks an explicit type hint even though its element type is known, matching the rule's requirement.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/excel_export/email.py
**Line:** 105:105
**Comment:**
	*Custom Rule: Annotate this list variable with its element type to satisfy the type-hint requirement for relevant local variables.

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
👍 | 👎



def test_duplicate_chart_placement_exported_once() -> None:
position = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Provide an explicit local type annotation for this position object to satisfy the rule on relevant variable hints. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

The position local in this test is also unannotated in newly added code, so it fits the custom type-hint rule.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_layout.py
**Line:** 67:67
**Comment:**
	*Custom Rule: Provide an explicit local type annotation for this `position` object to satisfy the rule on relevant variable hints.

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
👍 | 👎



def test_orphan_charts_appended_by_id() -> None:
position = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Annotate this local position variable with its mapping type in this test to keep type hints complete in added code. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

This test introduces another annotatable local mapping without an explicit type hint, which is exactly the kind of omission the rule flags.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_layout.py
**Line:** 80:80
**Comment:**
	*Custom Rule: Annotate this local `position` variable with its mapping type in this test to keep type hints complete in added code.

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
👍 | 👎

Comment on lines +150 to +154
filter_context = get_dashboard_filter_context(
dashboard_id=dashboard_id,
chart_id=chart.id,
active_data_mask=active_data_mask,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: This call happens once per chart and get_dashboard_filter_context re-queries the dashboard and reparses its metadata each time, creating an avoidable N+1 pattern on dashboards with many charts. Precompute the dashboard filter metadata/context once per export (or pass the already-loaded dashboard structure) to avoid repeated DB and JSON work in the chart loop. [performance]

Severity Level: Critical 🚨
- ❌ Export task issues redundant dashboard queries per chart.
- ⚠️ Large dashboard exports slower, more likely to timeout.
Steps of Reproduction ✅
1. Create or identify a dashboard with many charts and native filters in Superset; this
dashboard will be served via the Dashboard API in superset/dashboards/api.py.

2. Trigger an Excel export by calling POST /api/v1/dashboard/{pk}/export_xlsx/ implemented
in superset/dashboards/api.py lines 22-30 and 1656-66. The endpoint validates the payload,
checks permissions, and enqueues the Celery task export_dashboard_excel.apply_async with
kwargs including dashboard_id, user_id, active_data_mask, job_id, and mode (lines 48-57).

3. A Celery worker executes export_dashboard_excel
(superset/tasks/export_dashboard_excel.py lines 266-308). Inside the task, it queries the
Dashboard once with db.session.query(Dashboard).filter_by(id=dashboard_id).one_or_none()
(lines 293-297) and then calls _build_workbook(tmp_path, dashboard, active_data_mask,
job_id, mode, user) (lines 306-308).

4. In _build_workbook (superset/tasks/export_dashboard_excel.py lines 180-241), the code
iterates over get_charts_in_layout_order(dashboard) and, for each chart that is not
rendered as an image, calls _write_chart_sheets(writer, chart, dashboard.id,
active_data_mask) (lines 197-211). _write_chart_sheets (lines 131-177) calls
get_dashboard_filter_context(dashboard_id=dashboard_id, chart_id=chart.id,
active_data_mask=active_data_mask) for every chart. get_dashboard_filter_context in
superset/charts/data/dashboard_filter_context.py (lines 269-312) performs its own
db.session.query(Dashboard).filter_by(id=dashboard_id).one_or_none(), checks access, and
parses dashboard.json_metadata and dashboard.position_json on each invocation. This
per-chart call pattern produces an N+1 query and metadata parsing pattern on dashboards
with many charts, increasing CPU, database load, and export runtime for every use of the
export_xlsx endpoint.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/tasks/export_dashboard_excel.py
**Line:** 150:154
**Comment:**
	*Performance: This call happens once per chart and `get_dashboard_filter_context` re-queries the dashboard and reparses its metadata each time, creating an avoidable N+1 pattern on dashboards with many charts. Precompute the dashboard filter metadata/context once per export (or pass the already-loaded dashboard structure) to avoid repeated DB and JSON work in the chart loop.

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
👍 | 👎

Comment on lines +196 to +202
row_cap = MAX_DATA_ROWS_PER_SHEET - 1
written = 0
truncated = False
for row in rows:
if written >= row_cap:
truncated = True
break

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The row-cap calculation is off by one: MAX_DATA_ROWS_PER_SHEET already excludes the header row, but another - 1 is applied before truncation checks. This drops one extra data row and marks sheets as truncated even when the input exactly fits Excel’s real per-sheet data capacity. [off-by-one]

Severity Level: Major ⚠️
- ⚠️ Last valid row dropped near Excel row limit.
- ⚠️ Truncation notice misleading when data fits sheet capacity.
Steps of Reproduction ✅
1. Trigger any dashboard Excel export using POST /api/v1/dashboard/{pk}/export_xlsx/
(superset/dashboards/api.py lines 22-30 and 1656-66), which enqueues
export_dashboard_excel and ultimately constructs a StreamingXlsxWriter in _build_workbook
(superset/tasks/export_dashboard_excel.py line 195) and calls writer.add_sheet for each
chart result (lines 166-177).

2. Prepare a chart whose query returns exactly 1,048,575 data rows, the maximum number of
data rows Excel can hold when one row is reserved for the header; this dataset is passed
as the rows iterable into StreamingXlsxWriter.add_sheet.

3. In StreamingXlsxWriter.add_sheet (superset/utils/excel_streaming.py lines 189-214),
MAX_DATA_ROWS_PER_SHEET is defined as 1_048_576 - 1 with the comment “A worksheet holds at
most 1,048,576 rows; one is reserved for the header” (lines 49-50). However, row_cap is
then computed as MAX_DATA_ROWS_PER_SHEET - 1 (line 196), giving a cap of 1_048_574 data
rows instead of the full 1_048_575 capacity.

4. As the for loop over rows executes (lines 199-205), once written reaches 1_048_574, the
condition written >= row_cap becomes true, truncated is set to True, and the loop breaks,
so only 1_048_574 data rows are written. The subsequent truncation notice logic (lines
206-211) writes a “[Truncated: only first 1,048,574 rows exported]” message, even though
Excel could have stored all 1,048,575 rows without truncation. The last valid row is never
written, and the sheet is incorrectly marked as truncated for an input that exactly fits
Excel’s per-sheet data capacity.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/utils/excel_streaming.py
**Line:** 196:202
**Comment:**
	*Off By One: The row-cap calculation is off by one: `MAX_DATA_ROWS_PER_SHEET` already excludes the header row, but another `- 1` is applied before truncation checks. This drops one extra data row and marks sheets as truncated even when the input exactly fits Excel’s real per-sheet data capacity.

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
👍 | 👎

return _quote_if_formula(str(value))


class StreamingXlsxWriter:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hughhhh the @betodealmeida 's question seems to be still open. Since ChartDataCommand.run() already loads all rows into memory, the new streaming module doesn't provide constant-memory exports.
If that's the case, why introduce a new module instead of reusing superset.utils.excel?
I think this should be answered before merging.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point on memory, and you're right that ChartDataCommand.run() materializes each chart's rows — the module never claimed to fix that (the docstring says it "bounds only the writer's own footprint, not the caller's"). What constant_memory still buys is separate from the source data: without it, xlsxwriter retains every written cell across all sheets until close(). A dashboard export is inherently multi-sheet, so bounding the writer's accumulation is a real win even though each chart's source rows are transiently materialized one at a time.

On reuse: superset.utils.excel.df_to_excel is single-sheet and pandas-DataFrame→BytesIO; this path needs many sheets streamed to a temp file for S3. Beyond multi-sheet, the new module adds things excel.py doesn't have and that a dashboard (arbitrary user-named charts) requires:

  • Sheet-name sanitization + de-dup — Excel's 31-char limit, forbidden []:*?/\, the reserved "History" name, case-insensitive collision suffixes. pandas would raise or silently overwrite on invalid/duplicate names.
  • Stricter cell coercion — Decimal NaN/Inf, ints > 10^15, tz-aware datetimes, and formula-injection quoting that lstrips first (so " =cmd" / "\t=cmd" are caught — excel.py's quote_formulas only checks x[0] and misses those).

It already reuses what's shareable from excel.py, and I've just consolidated the formula-prefix set into a single FORMULA_PREFIXES constant there (54ef804de4) so both writers guard the same vectors from one source of truth (NEUTRAL_DOCUMENT_PROPERTIES was already shared). Reusing df_to_excel wholesale would mean building a DataFrame per chart — reintroducing exactly the materialization you flagged — and still wouldn't cover multi-sheet-to-disk or the sheet-name handling.

Comment on lines 291 to +311
method_permission_name = {
**MODEL_API_RW_METHOD_PERMISSION_MAP,
"restore": "write",
# Reuse the dashboard ``can_export`` permission (the frontend gates the
# menu item on it) instead of the ``can_export_xlsx`` FAB would otherwise
# derive from the method name.
"export_xlsx": "export",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

method_permission_name["export_xlsx"] = "export" doesn't seem to take effect.
Users with only the can_export permission still receive a 401, while the frontend shows the Export to Excel action to those same users.
The existing test (test_export_xlsx_admitted_with_can_export_only) is failing for this reason. @hughhhh would make sense to verify that the endpoint is actually enforcing can_export instead of falling back to can_export_xlsx?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 401 was a bug in the test's login, not the permission mapping — fixed in 5ac547a3d8. temporary_user(login=True) was creating a passwordless user, so FAB's login raised on check_password_hash(None) and the request arrived unauthenticated (401), not the 403 a permission mismatch would produce. It now clones the Gamma user, which already carries dashboard can_export.

The mapping does take effect. In flask_appbuilder/api/__init__.py, get_method_permission() is:

if self.method_permission_name:
    return self.method_permission_name.get(method_name, method_name)

When method_permission_name is set (it is on DashboardRestApi), FAB uses the map and ignores any @permission_name decorator — so export_xlsx → "export" → can_export, and base_permissions gets can_export, not can_export_xlsx. This is the same path as the existing "restore": "write".

It's also asserted by test_info_security_dashboard, whose exact-set (==) permission check passes with can_export present and can_export_xlsx absent — which it couldn't if the fallback to can_export_xlsx were still happening.

hughhhh and others added 2 commits July 15, 2026 15:51
The regression test used temporary_user(login=True) on a passwordless
temp user, so the form login failed (check_password_hash(None) ->
AttributeError) and the request came back 401 instead of 202, failing
CI on all backends. Clone the Gamma user instead: it has a valid login
password and already carries dashboard can_export by default (the exact
principal the frontend shows the Excel menu to), so the test faithfully
reproduces the FE/BE gate the fix aligns.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@bito-code-review

bito-code-review Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #5de0e9

Actionable Suggestions - 0
Review Details
  • Files reviewed - 5 · Commit Range: 27496d4..5ac547a
    • .pre-commit-config.yaml
    • superset-frontend/src/dashboard/components/menu/DownloadMenuItems/DownloadMenuItems.test.tsx
    • superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx
    • superset/dashboards/api.py
    • tests/integration_tests/dashboards/api_tests.py
  • Files skipped - 2
    • VERIFY_EXCEL_EXPORT.md - Reason: Filter setting
    • docker-compose-excel-verify.yml - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Hoist the CSV/formula-injection prefix set to a module-level
FORMULA_PREFIXES in superset.utils.excel and consume it from the
streaming writer instead of redefining it, so both export paths guard
the same vectors from one source of truth. Behavior is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@bito-code-review

bito-code-review Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #6d7de9

Actionable Suggestions - 0
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset/utils/excel_streaming.py - 1
    • Wrong function body in _coerce_float_cell · Line 69-70
Review Details
  • Files reviewed - 2 · Commit Range: 5ac547a..54ef804
    • superset/utils/excel.py
    • superset/utils/excel_streaming.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

Comment on lines +1652 to +1654
payload = DashboardExportXlsxPostSchema().load(
request.get_json(silent=True) or {}
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an explicit type annotation for the schema-loaded request payload variable. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

The new local variable payload is assigned without any type annotation, even though it is a clearly annotatable Python variable loaded from a schema. This matches the rule requiring type hints on relevant variables in modified Python code.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/api.py
**Line:** 1652:1654
**Comment:**
	*Custom Rule: Add an explicit type annotation for the schema-loaded request payload variable.

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
👍 | 👎

# otherwise) so the guard works across the web server and workers and is
# not a no-op under the default cache. The task releases it when it
# settles; the TTL is the backstop if that release is ever lost.
lock_params = export_lock_params(g.user.id, dashboard.id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a concrete type annotation to the distributed lock parameter variable. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

The local variable lock_params is introduced without a type annotation, despite being a new annotatable Python variable in modified code. This is a real match for the type-hint requirement.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/api.py
**Line:** 1690:1690
**Comment:**
	*Custom Rule: Add a concrete type annotation to the distributed lock parameter variable.

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
👍 | 👎

message="An Excel export for this dashboard is already in progress.",
)

job_id = str(uuid.uuid4())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an explicit type annotation to the generated export job identifier variable. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

The variable job_id is newly introduced and unannotated, even though it is a straightforward string-valued local that can be typed. This is a valid omission under the type-hint rule.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/api.py
**Line:** 1703:1703
**Comment:**
	*Custom Rule: Add an explicit type annotation to the generated export job identifier variable.

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
👍 | 👎

Comment thread superset/utils/excel.py
Comment on lines +44 to +47
# 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 = {"=", "+", "-", "@"}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an explicit type annotation to this new constant so it complies with the required type-hinting rule for annotatable variables. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

The new module-level constant is introduced without a type annotation even though it can be typed as a set of strings. This violates the Python type-hint requirement for annotatable variables.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/utils/excel.py
**Line:** 44:47
**Comment:**
	*Custom Rule: Add an explicit type annotation to this new constant so it complies with the required type-hinting rule for annotatable variables.

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
👍 | 👎

Comment on lines +3330 to +3344
def test_export_xlsx_202_when_export_already_in_progress(
self, mock_task, mock_acquire
):
"""Dashboard API: export_xlsx does not enqueue a second concurrent export."""
# An in-flight lock is already held for this user+dashboard.
mock_acquire.return_value.run.side_effect = LockAlreadyHeldException("held")
self.login(ADMIN_USERNAME)
dashboard = db.session.query(Dashboard).filter_by(slug="world_health").first()
rv = self.client.post(
f"api/v1/dashboard/{dashboard.id}/export_xlsx/",
json={"active_data_mask": {}},
)
assert rv.status_code == 202
assert "already in progress" in rv.data.decode("utf-8")
mock_task.apply_async.assert_not_called()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Annotate each parameter and the return type in this multiline method definition to satisfy typing requirements. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

This multiline newly added function signature also omits type hints for its parameters and return type, so the custom typing rule applies.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/integration_tests/dashboards/api_tests.py
**Line:** 3330:3344
**Comment:**
	*Custom Rule: Annotate each parameter and the return type in this multiline method definition to satisfy typing requirements.

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
👍 | 👎


def test_render_chart_image_builds_url_with_slice_id_and_filters() -> None:
chart = _chart()
active_mask = {"NATIVE_FILTER-1": {"extraFormData": {"filters": [{"col": "a"}]}}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add a concrete type annotation for this structured test variable so new code consistently provides hints for relevant variables. [custom_rule]

Severity Level: Minor 🧹

Why it matters? ⭐

This local variable is a newly added complex Python value that can be annotated, but it is not typed. That is a real violation of the requirement to add type hints to relevant variables in new or modified Python code.

Rule source 📖

.cursor/rules/dev-standard.mdc (line 28)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/dashboards/test_excel_export_screenshot.py
**Line:** 53:53
**Comment:**
	*Custom Rule: Add a concrete type annotation for this structured test variable so new code consistently provides hints for relevant variables.

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
👍 | 👎

Comment on lines +3367 to +3370
@patch("superset.dashboards.api.security_manager.raise_for_access")
def test_export_xlsx_admitted_with_can_export_only(
self, mock_raise, mock_task, mock_acquire
):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: This test patches out security_manager.raise_for_access, which bypasses a real authorization check in the endpoint and can let the test pass even if access-control behavior regresses. Remove this patch (or assert it is called with the expected dashboard) so the test validates the true integration of permission mapping plus dashboard access logic. [incomplete implementation]

Severity Level: Major ⚠️
⚠️ Excel export auth regressions may go undetected by tests.
⚠️ Test passes even if raise_for_access call removed.
Steps of Reproduction ✅
1. Inspect the dashboard Excel export endpoint implementation at
`superset/dashboards/api.py:1588-1619` and `superset/dashboards/api.py:1600-1675`. The
`DashboardRestApi.export_xlsx` method (decorated with `@expose("/<pk>/export_xlsx/",
methods=("POST",))` and `@protect()`) calls
`security_manager.raise_for_access(dashboard=dashboard)` inside a `try/except
SupersetSecurityException` block to enforce a 403 when the user lacks access.

2. Inspect the integration test `test_export_xlsx_admitted_with_can_export_only` in
`tests/integration_tests/dashboards/api_tests.py:164-193` (corresponding to diff lines
3363-3393). The test is decorated with
`@patch("superset.dashboards.api.security_manager.raise_for_access")` and receives
`mock_raise` but never asserts on it; `raise_for_access` is replaced with a MagicMock
during the test run.

3. Run the test suite (e.g. `pytest
tests/integration_tests/dashboards/api_tests.py::TestDashboardApi::test_export_xlsx_admitted_with_can_export_only`).
During this test, the real authorization logic inside `security_manager.raise_for_access`
(implemented in `superset/security/manager.py` and exercised by
`tests/unit_tests/subjects/test_raise_for_access.py`) is completely bypassed because the
patched MagicMock never raises `SupersetSecurityException`, regardless of actual dashboard
access rules.

4. To see the false-positive behavior concretely, deliberately break the endpoint’s access
check by removing or commenting out the
`security_manager.raise_for_access(dashboard=dashboard)` call in
`superset/dashboards/api.py:72-75` (inside `export_xlsx`) and rerun
`test_export_xlsx_admitted_with_can_export_only`. The test still passes (asserting only
status 202 and `export_dashboard_excel.apply_async` being called) even though the endpoint
no longer performs the dashboard access check, proving that the current patching strategy
lets authorization regressions slip through.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/integration_tests/dashboards/api_tests.py
**Line:** 3367:3370
**Comment:**
	*Incomplete Implementation: This test patches out `security_manager.raise_for_access`, which bypasses a real authorization check in the endpoint and can let the test pass even if access-control behavior regresses. Remove this patch (or assert it is called with the expected dashboard) so the test validates the true integration of permission mapping plus dashboard access logic.

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
👍 | 👎

Comment on lines +259 to +267
...(isWebDriverScreenshotEnabled
? [
{
key: 'export-xlsx-images',
label: t('Export Images to Excel'),
onClick: () => onExportXlsx('images'),
},
]
: []),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The new image-mode Excel action is gated only by webdriver feature flags and ignores the existing canExportImage permission signal, so users who are explicitly blocked from image export can still trigger mode="images" and receive chart images via Excel. Gate this menu item with the same image-export permission logic used for PDF/PNG (and keep backend authorization aligned) to avoid a permission bypass. [security]

Severity Level: Critical 🚨
❌ Dashboard image-export restriction bypassed via Excel images mode.
⚠️ Users without can_export_image can email chart screenshots.
⚠️ Download menu shows image export to unauthorized users.
⚠️ Backend export_xlsx endpoint ignores granular image permission.
Steps of Reproduction ✅
1. When a dashboard is rendered, the header component `Header/index.tsx:96` calls
`useHeaderActionsMenu` from
`superset-frontend/src/dashboard/components/Header/useHeaderActionsDropdownMenu.tsx:41-74`,
passing `userCanExport` (from `HeaderDropdownProps` in `Header/types.ts:52-56`) and
receiving `canExportImage` from `usePermissions()`
(`superset-frontend/src/hooks/usePermissions.ts:43-52`).

2. For a role where `can_export` on `Dashboard` is granted but `can_export_image` on
`Superset` is not, `usePermissions` computes `canExportImage` as `false` while
`userCanExport` remains `true` (`useHeaderActionsDropdownMenu.tsx:57-58`), so screenshot
items are disabled via `imageDisabled = canExportImage === false`
(`DownloadMenuItems/index.tsx:203`) but this flag is not used for Excel image export.

3. With webdriver screenshot flags enabled (`isWebDriverScreenshotEnabled` at
`DownloadMenuItems/index.tsx:87-89`) and Excel export configured server-side,
`useDownloadMenuItems` builds `exportMenuItems` (`DownloadMenuItems/index.tsx:247-269`),
always adding the `export-xlsx-images` menu item when `userCanExport` is truthy and
`isWebDriverScreenshotEnabled` is true, regardless of `canExportImage`; the item’s
`onClick` calls `onExportXlsx('images')` (`DownloadMenuItems/index.tsx:170-201`).

4. Clicking “Export Images to Excel” in the dashboard Download menu
(`DownloadMenuItems.test.tsx:50-63` shows this label wired) issues `POST
/api/v1/dashboard/<pk>/export_xlsx/` with `mode: 'images'`
(`DownloadMenuItems/index.tsx:172-175`), which is authorized by the backend using only the
dashboard `export` method permission (`superset/dashboards/api.py:306-313` and
`1597-1605`), allowing a user explicitly denied `can_export_image` to receive chart images
embedded in an Excel workbook via the async export task
(`superset/tasks/export_dashboard_excel.py:20-32`).

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx
**Line:** 259:267
**Comment:**
	*Security: The new image-mode Excel action is gated only by webdriver feature flags and ignores the existing `canExportImage` permission signal, so users who are explicitly blocked from image export can still trigger `mode="images"` and receive chart images via Excel. Gate this menu item with the same image-export permission logic used for PDF/PNG (and keep backend authorization aligned) to avoid a permission bypass.

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
👍 | 👎

Comment on lines +349 to +352
ReleaseDistributedLock(
EXPORT_LOCK_NAMESPACE,
export_lock_params(user_id, dashboard_id),
).run()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Severity Level: Major ⚠️
- ❌ Concurrent dashboard Excel exports bypass single-export throttle.
- ⚠️ Overlapping exports increase load on chart query engines.
- ⚠️ Lock semantics diverge from API’s concurrency guarantees.
Steps of Reproduction ✅
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`.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
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
👍 | 👎

Comment thread superset/utils/excel.py
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Severity Level: Critical 🚨
- ❌ XLSX chart exports permit whitespace-prefixed formula injection.
- ⚠️ Users opening exports risk unintended formula execution.
- ⚠️ Legacy Excel export weaker than streaming Excel protection.
Steps of Reproduction ✅
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.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
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
👍 | 👎

@EnxDev

EnxDev commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

@betodealmeida, would you mind taking another look when you have a chance? Thanks!

…xport-spec-review

# Conflicts:
#	UPDATING.md
Comment on lines +1598 to +1606
@expose("/<pk>/export_xlsx/", methods=("POST",))
@protect()
@safe
@statsd_metrics
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.export_xlsx",
log_to_statsd=False,
)
def export_xlsx(self, pk: int) -> WerkzeugResponse:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Change this new public endpoint to accept a dashboard UUID instead of an integer primary key, and resolve the dashboard by UUID to avoid exposing internal numeric identifiers in the API contract. [custom_rule]

Severity Level: Major ⚠️

Why it matters? ⭐

This is a new public REST endpoint, and it exposes the dashboard via an integer primary key (pk: int) in the URL. The rule requires UUIDs for public API exposure, so this is a real violation.

Rule source 📖

=== .github/copilot-instructions.md === (line 51)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/api.py
**Line:** 1598:1606
**Comment:**
	*Custom Rule: Change this new public endpoint to accept a dashboard UUID instead of an integer primary key, and resolve the dashboard by UUID to avoid exposing internal numeric identifiers in the API contract.

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
👍 | 👎

Comment on lines +294 to +296
dashboard = (
db.session.query(Dashboard).filter_by(id=dashboard_id).one_or_none()
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add an explicit authorization check with security_manager.raise_for_access(...) immediately after loading the dashboard resource before exporting any chart data. [custom_rule_security]

Severity Level: Critical 🚨

Why it matters? ⭐

Dashboards are explicitly covered by the rule for data-bearing resources, and this code loads a dashboard and proceeds to export its chart data without calling security_manager.raise_for_access(...). The suggestion identifies a real rule violation present in the shown code.

Rule source 📖

=== .github/copilot-instructions.md === (line 79)

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/tasks/export_dashboard_excel.py
**Line:** 294:296
**Comment:**
	*Custom Rule Security: Add an explicit authorization check with `security_manager.raise_for_access(...)` immediately after loading the dashboard resource before exporting any chart data.

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
👍 | 👎

Comment on lines +1702 to +1705
)

job_id = str(uuid.uuid4())
try:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The lock-held branch returns HTTP 202 without a job_id, but the documented 202 response schema requires a job_id; clients that parse successful responses by schema can fail on this path. Return a status/body shape consistent with the contract (for example include the existing job id if available, or use a different status code/schema for “already running”). [possible bug]

Severity Level: Major ⚠️
- ❌ Lock-throttle 202 response breaks OpenAPI response contract.
- ⚠️ API clients may mis-handle already-running export responses.
Steps of Reproduction ✅
1. Start Superset with this PR code and configure `EXCEL_EXPORT_S3_BUCKET` in
`superset/config.py` so `export_xlsx` does not return 501 (see check at
`superset/dashboards/api.py:1646`).

2. As a user with Dashboard `can_export` permission and an email address, open a dashboard
with at least one chart so `dashboard.slices` is non-empty
(`superset/models/dashboard.py`, used at `superset/dashboards/api.py:1688`).

3. Trigger the Excel export twice for the same dashboard and user (e.g. via the frontend
`onExportXlsx()` in
`superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx:170`, which
POSTs to `POST /api/v1/dashboard/<pk>/export_xlsx/` implemented at
`superset/dashboards/api.py:1599-1723`).

4. On the first request, `AcquireDistributedLock(...).run()` at
`superset/dashboards/api.py:1696-1701` succeeds and
`export_dashboard_excel.apply_async(...)` is called, then `self.response(202,
job_id=job_id)` is returned at `superset/dashboards/api.py:1723` matching
`DashboardExportXlsxResponseSchema` (declared in the OpenAPI block at
`superset/dashboards/api.py:1608-1633`).

5. While the Celery task is still running and the lock not yet released by
`export_dashboard_excel` (see lock namespace `EXPORT_LOCK_NAMESPACE` imported at
`superset/dashboards/api.py:145-150` and used in the task), send another POST to the same
endpoint.

6. On the second request, `AcquireDistributedLock(...).run()` raises
`LockAlreadyHeldException` (imported at `superset/dashboards/api.py:132`), hitting the
`except LockAlreadyHeldException` branch at lines `1702-1705` which returns
`self.response(202, message="An Excel export for this dashboard is already in progress.")`
without a `job_id` field.

7. Any client that relies on the OpenAPI contract that 202 responses conform to
`DashboardExportXlsxResponseSchema` (registered in `openapi_spec_component_schemas` at
`superset/dashboards/api.py:512-520`) and expects a `job_id` will fail to deserialize or
treat this successful 202 as schema-invalid.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/dashboards/api.py
**Line:** 1702:1705
**Comment:**
	*Possible Bug: The lock-held branch returns HTTP 202 without a `job_id`, but the documented 202 response schema requires a `job_id`; clients that parse successful responses by schema can fail on this path. Return a status/body shape consistent with the contract (for example include the existing job id if available, or use a different status code/schema for “already running”).

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
👍 | 👎

@rusackas

Copy link
Copy Markdown
Member

SO MANY open bot comment threads here... can you help assess and apply/refute the changes, and mark them as resolved? Would love to see this merged, but it looks scary as-is.

…xport-spec-review

# Conflicts:
#	UPDATING.md
@justinpark

Copy link
Copy Markdown
Member

@hughhhh Frontend CI (lint check) failed from here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api:dashboard Related to the REST endpoints of the Dashboard api Related to the REST API dashboard:export Related to exporting dashboards doc Namespace | Anything related to documentation global:async-query Related to Async Queries feature hold:testing! On hold for testing size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants