Repository navigation
fix(dashboard): guest sessions, pluggable storage, and streamed downloads for the Excel export - #43805
Conversation
…l expiry, and support guest/embedded sessions The Excel export success email links to a pre-signed S3 URL that is only valid for as long as both its own ExpiresIn and the credentials that signed it remain valid. Deployments authenticating via short-lived, auto-refreshed credentials (e.g. an EKS IRSA role assumed through AssumeRoleWithWebIdentity, which AWS caps at 12 hours) can silently invalidate the link long before EXCEL_EXPORT_LINK_TTL_SECONDS elapses. The email now links to a Superset redirect (export_xlsx/download/<job_id>/) instead of a raw S3 URL. The link's own lifetime is enforced independently via the key_value store, and a fresh pre-signed URL is generated -- with then-current credentials -- at click time. Reusing the same job_id-keyed store also removes a separate limitation: export_xlsx previously hard-required the requester to have an email address on file, since email was the only way to deliver the link, which excluded guest/embedded dashboard sessions entirely. The frontend can now poll a new export_xlsx_status/<job_id>/ endpoint and auto-download once ready, so an embedded session (no email) gets a working export too; a logged-in session gets both the auto-download and, still, the email. export_xlsx itself needs a CSRF exemption for this to work end-to-end: it's a POST route reachable from embedded/guest sessions whose requests carry no CSRF token, the same reason chart/data is already exempted.
…ng on g.user.id GuestUser extends AnonymousUserMixin and has no id attribute, so an embedded guest triggering export_xlsx crashed with AttributeError (500 Fatal error) on g.user.id before the task was ever enqueued. Pass user_id=None plus the guest token payload instead, and reconstruct the guest in the worker via get_guest_user_from_token (the async-queries pattern) so the export runs under the token's RLS rules and resource claims rather than an elevated identity. Guests share throttle-lock slot 0 per dashboard, acquired and released with the same key.
…est access Guest datasource authorization requires form_data.dashboardId to link a chart to the embedded dashboard (raise_for_access). The browser stamps it on every interactive request, but the export task replays saved query contexts that do not carry it, so every chart in a guest export failed the access check and the workbook came back empty. Stamp the exporting dashboard's id the same way the browser does; logged-in exports already carry dashboard scope and are unaffected.
Embedded (iframe) sessions get delivery neutral toast copy (no email promise a guest can never receive), a polling window that outlives the server task budget so a slow but successful export is not orphaned, and the image export item hidden (the webdriver cannot render Explore under a guest identity, so it would burn the whole task budget producing nothing). The pending toast now mirrors the screenshot download's repeating noDuplicate info toast for all sessions.
…s redirect The direct window.location.href assignment from the base branch trips the navigationUtils invariant scan: it bypasses ensureAppRoot (broken under subdirectory deployment) and the scheme guard. Use redirect() instead; tests assert the redirect call rather than the raw sink.
…t toast Customer feedback showed the email-only wording made the export read as an email delivery feature, prompting requests for a direct download that already exists. Promise both channels, matching actual behavior.
…mplementation superset/utils/s3.py is hardcoded to boto3/AWS S3, so a deployment whose EXCEL_EXPORT_S3_BUCKET names a native Google Cloud Storage bucket (not an S3-compatible one) has no way to make dashboard Excel export actually reach it: uploads and pre-signed download URLs both go through boto3 regardless. Add EXCEL_EXPORT_STORAGE, an optional config hook following the same "instance in config" idiom as RESULTS_BACKEND/CUSTOM_SECURITY_MANAGER: set it to an object implementing the small ExportStorage protocol (upload_file, generate_download_url) to take over both the task's upload and the download redirect's URL minting. Left unset, behavior is unchanged -- the existing boto3/S3 helpers run exactly as before. Ship GCSExportStorage (superset/utils/gcs.py) as a ready-to-use implementation for GCS-backed deployments, using the native google-cloud-storage client (Application Default Credentials) rather than S3-compatible interop credentials. google-cloud-storage is imported lazily and is only required if GCSExportStorage is actually configured, via a new excel-export-gcs extra (mirroring the existing excel-export/boto3 extra).
… dict
EXCEL_EXPORT_S3_BUCKET/EXCEL_EXPORT_S3_KEY_PREFIX were misleadingly named --
both are actually provider-agnostic (used by whichever EXCEL_EXPORT_STORAGE
backend is configured, not just S3), while EXCEL_EXPORT_S3_CLIENT_KWARGS is
genuinely S3/boto3-specific and only applies to the default backend. Having
these three flat, S3-flavored names sit alongside the newly-introduced,
correctly-generic EXCEL_EXPORT_STORAGE was confusing.
Fold bucket/key_prefix/client_kwargs/backend into a single
ExcelExportStorageConfig TypedDict under EXCEL_EXPORT_STORAGE, e.g.:
EXCEL_EXPORT_STORAGE = {
"bucket": "my-gcs-bucket",
"backend": GCSExportStorage(),
}
EXCEL_EXPORT_LINK_TTL_SECONDS stays a separate top-level setting: it bounds
the Superset-issued redirect link itself, independent of which storage
backend or bucket is configured.
Plain "backend" reads ambiguously next to the dict key of the same name; storage_backend matches what it actually holds.
…bucket configured The API already rejects export_xlsx with 501 when EXCEL_EXPORT_STORAGE has no bucket, but the Celery task itself trusted that check had already run. If the config is cleared after enqueue, or the task is invoked directly, it now fails with a clear SupersetException instead of an opaque boto3/SDK error for a None bucket.
…removing the implicit S3 fallback
A bucket alone was never enough to run exports (boto3 would fail without
S3 credentials/config), yet the code silently defaulted to the boto3/S3
helper whenever EXCEL_EXPORT_STORAGE["backend"] was unset. The backend is
now a required part of the config, symmetric across providers:
from superset.utils.s3 import S3ExportStorage # or gcs.GCSExportStorage
EXCEL_EXPORT_STORAGE = {"bucket": "...", "backend": S3ExportStorage()}
- superset/utils/s3.py module functions become an S3ExportStorage class
implementing the ExportStorage protocol; boto3 client_kwargs move from
the config dict to its constructor
- the export_xlsx 501 guard and the task's defensive check now require
both "bucket" and "backend"; the download route reports 501 instead of
falling back to boto3 when the backend is unset
- docs and UPDATING.md updated to the consolidated config shape (they
still described the pre-consolidation flat EXCEL_EXPORT_S3_* keys)
The storage config is not Excel-specific -- it names a bucket, a key prefix, and a pluggable backend, all of which apply equally to any other export file type stored there in the future. Only the storage config is renamed (ExcelExportStorageConfig -> ExportStorageConfig too); the genuinely Excel-specific keys (EXCEL_EXPORT_LINK_TTL_SECONDS, EXCEL_EXPORT_TABLE_VIZ_TYPES, EXCEL_EXPORT_QUERY_CONTEXT_BUILDER) keep their names.
A multi-tenant deployment sharing one export bucket across tenants only knows the per-tenant prefix in request/task context, the same reason the cache *_KEY_PREFIX configs accept callables. A callable is invoked per export; a plain string keeps working unchanged.
feat(dashboard): pluggable Excel export storage backend, with a GCS implementation
…ials Token-only Application Default Credentials (GKE workload identity, GCE metadata, Cloud Run) carry no private key, so local V4 signing raised AttributeError and every download click returned 500 while the upload itself succeeded. Route signing through the IAM signBlob API by passing the service account email and a fresh access token; key-file credentials keep signing locally. Also makes the missing-dependency test deterministic and drops a stale note about the S3 pre-signed cap.
…gning Review follow-ups: - run anonymous (Public-role) requesters under the anonymous principal - reject guest mode=images at the API, not just in the menu - gate delivery copy, poll window, and image export on the requester identity instead of iframe detection - record a running status when a worker starts, and restart the client's wait window on it so queue delay is not counted against the export - record the uploading storage backend on the download link and refuse to sign with a different backend - docs: guest polling flow, link vs storage URL lifetime, web-tier storage permissions
… gates Second review round: - transaction-wrap the export status writes: the worker session otherwise only commits when the task settles, so the running marker was invisible to polling web pods exactly when it mattered - reject mode=images for any session without a user id (anonymous too), matching the UI's predicate - request an explicit scope for the GCS signBlob credentials, which external-account/workload-identity ADC needs to refresh - one 12 minute poll window for every session: the export email is best-effort (SMTP optional, send failures swallowed), so the client cannot treat it as a fallback and stop polling early - cover the API-to-worker guest handoff (user_id None + token payload + lock slot 0) with an integration test - UPDATING.md: SMTP is optional, email delivery only
Replace the signed storage URL redirect with streaming the object through the download endpoint using the deployment's own storage credentials. Signing is impossible for some ambient identities: direct workload identity federation has no service account to sign as, so the IAM signBytes call failed with 400 "Invalid form of account ID <project>.svc.id.goog" on GKE clusters using principal-based grants. A signed URL is also a transferable bearer credential Superset can neither observe nor revoke once issued; streaming keeps the unguessable job id as the only credential and every download inside Superset. The ExportStorage protocol swaps generate_download_url for a chunked download method (FileNotFoundError for missing objects, answered as 410), and the whole signing apparatus (GCS signBlob fallback, IAM role prerequisite, presigned TTL) is removed along with its docs.
download() now returns (size, chunks): S3 reads ContentLength off the get_object response it already makes, GCS adds one metadata fetch that doubles as an eager existence check. With a declared length, a stream that dies midway is a failed download in the browser instead of a silently truncated file Excel rejects as corrupt, and users get a real progress bar.
# Conflicts: # superset/dashboards/api.py # tests/integration_tests/security_tests.py
Code Review Agent Run #297df5Actionable Suggestions - 0Additional Suggestions - 8
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
Code Review Agent Run #072c4dActionable Suggestions - 0Additional Suggestions - 1
Filtered by Review RulesBito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
…cel-export-guest-storage-stream # Conflicts: # superset/dashboards/api.py # tests/integration_tests/dashboards/api_tests.py
…ings The export toasts changed (auto-download replaced the email-only wording, and a slow-export message was added), so four new strings and one removed one were absent from the template. A string only reaches a .po catalog through this template, so without it they are untranslatable in every language, which is what `check_pot_drift` guards. The extraction is whole-file, so this also picks up four strings already in source but missing from the committed template (`Display format`, the CSRF and security-token messages). They are unrelated to this change and come along because the template cannot be regenerated selectively. Only the template is committed; the per-language catalogs are left alone, since the translations workflow runs babel_update itself on both sides of its comparison.
Code Review Agent Run #cca2d8Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
…cel-export-guest-storage-stream # Conflicts: # superset/translations/messages.pot
EnxDev
left a comment
There was a problem hiding this comment.
Back for another pass now that the guest revalidation and the slice_id stamping have landed. Both check out in the diff, and the test coverage around the worker paths is genuinely good.
Four notes inline, all small: the guest-only guard on the bundle export leaves the Public role uncovered, the in-workbook summary sheet drops the reason grouping the email has, the failure write can clobber a ready record, and the link TTL clamp misses anonymous sessions.
Separately, a +1 on @sadpandajoe's Cache-Control point on the download response, which is still open. There is precedent for it in the tree: superset/sqllab/api.py and superset/charts/data/api.py both set Cache-Control: no-cache on their download responses, and this one is login-free, so it has more reason to than either.
…cel-export-guest-storage-stream # Conflicts: # superset/translations/messages.pot
…umented 403 The bundle and example export guards keyed on ``is_guest_user()``, which is false for an anonymous session. With ``can_export`` granted to the Public role, FAB's ``is_item_public`` returns before any auth check, so both routes would answer fully unauthenticated requests with dataset SQL and database metadata. Key the guards on ``get_user_id() is None`` instead, the predicate the image export already uses. The download URL is a login-free bearer credential whose lifetime is enforced by the link record, but the streamed response carried no cache directives, so a shared proxy could keep serving the workbook after the link expired. Mark every download and status response ``no-store, no-cache, private``; a cached "pending" would strand a poller too. HEAD is answered as well, so the frontend can confirm a link before navigating to it. The status route documented only 200 and 401 while ``@protect()`` can answer 403; regenerate the spec.
…en iframe The hidden iframe is a frame navigation, so a deployment with ``frame-src 'none'`` blocks it silently while the success toast still fires, and a guest has no fallback. Replace it with a plain anchor to the attachment: no frame, the file streams to disk, and the page is not navigated because the response is an attachment. Two details decided the shape. An anchor carrying the ``download`` attribute is dropped by Chrome once user activation has expired, which after polling is always; verified against the server log, where such a click never arrived while a plain anchor did. And an error response would navigate instead of downloading, so the link is confirmed with a HEAD request first and a failure becomes a toast. The success toast now follows that check. Sessions without a user id no longer see Export YAML or Export as Example, since the API refuses both for them.
Three gaps around requesters who only ever see the polling window: The summary sheet flattened every skipped chart into one bare list, while the email renders a per-reason note. Share the email's grouping so the sheet carries the same remediation text; guests and the Public role see nothing else. A soft time limit landing after ``create_download_link`` overwrote the ready record with a failure, taking the bucket and key with it, so the poller was told the export failed and the emailed link 410d forever. Skip the failure write when the record already reports ready. The link TTL clamp keyed on the guest token, so an anonymous requester got the full 24 hour link despite having no email to revisit it from. Key it on the absence of a user id, matching the guards.
The download route runs the full view for HEAD, which the frontend sends before starting a download, but never iterates the response body, so the S3 object opened eagerly by get_object was left for the garbage collector. Check existence and size with head_object and open the body inside the stream, as the GCS backend already does.
There was a problem hiding this comment.
Code Review Agent Run #d60a4e
Actionable Suggestions - 1
-
superset/utils/s3.py - 1
- Uncaught GET error in stream · Line 107-107
Additional Suggestions - 1
-
superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx - 1
-
Duplicated anchor download · Line 237-242The hidden-anchor download pattern here (create ``, set `href`, `display:none`, append, `click()`, remove) duplicates `onExportAsExample` (lines 195-201). Both build the same idiom with minor differences (`download` attr, `removeChild` vs `remove`). Extracting a shared helper removes the divergence risk.
-
Review Details
-
Files reviewed - 10 · Commit Range:
44bfabc..d1c11b1- superset/dashboards/api.py
- tests/unit_tests/dashboards/api_test.py
- superset-frontend/src/dashboard/components/menu/DownloadMenuItems/DownloadMenuItems.test.tsx
- superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx
- superset/dashboards/excel_export/email.py
- superset/tasks/export_dashboard_excel.py
- tests/unit_tests/tasks/test_export_dashboard_excel.py
- superset/utils/s3.py
- tests/unit_tests/utils/s3_tests.py
- docs/docs/using-superset/exporting-dashboard-data.mdx
-
Files skipped - 1
- docs/static/resources/openapi.json - 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 an incremental AI Review. -
/review full- 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
…rd-excel-export-sync-fallback Reconcile the sync-download fallback with #43805 (guest sessions, pluggable EXPORT_STORAGE, streamed downloads): - Queue only when EXPORT_STORAGE has both a bucket and a backend; otherwise serve eligible data exports inline. - Carry master's workbook changes (dashboardId/slice_id stamping, per-reason summary sheet) into excel_export/workbook.py. - Use master's guest/anonymous identity and lock slot on both paths, so guests also get the direct download when storage is unset. - Frontend: keep the raw-response inline download and progress state, plus master's status polling for queued jobs. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…-migration-api All 31 translation catalogs conflicted on their POT-Creation-Date header because both sides regenerated them. Resolved by taking master's catalogs wholesale and re-running scripts/translations/babel_update.sh, so the result is a real extraction rather than a hand-stitched one. That also propagates the strings master added to its own .pot (#43805, #44169) into the .po files, which master had not done yet, and prunes the export message #43805 reworded away. Master's 95d8a99c822e (merge_deprecated_permissions_with_master_v3) took 93d1b4a76c02 as a parent, which is also this branch's migration parent, leaving a7f3c2e91d84 as a second Alembic head. Point down_revision at 95d8a99c822e, fix the Revises: docstring (stale since the previous merge), and redate the file so it sorts after its parent. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- test_export_api.py (#44929) patched superset.dashboards.api.get_user_id, which only exists on master via the Excel export rework (#43805, not on 7.0); 7.0's dashboard export has no anonymous-caller check to stub. - ExploreViewContainer.test.tsx (#44963) used userEvent.keyboard, which @testing-library/user-event 12 on 7.0 lacks; dispatch the equivalent Ctrl/Cmd+Enter keydown on document, where the shortcut handler listens.
SUMMARY
Consolidates and supersedes #43336 and #43340 into one reviewable PR against master, carrying the full dashboard Excel export hardening stack.
@eschutho's storage chain commits are preserved with her authorship; the branch is her stack plus every review round fix, merged with current master (all conflicts were import unions, verified by test suites and a byte comparison of the export code region).
What it contains, grouped:
Guest and identity fixes
g.user.id; the worker reconstructs the guest from the token payload (async_queriespattern), preserving RLS rules and resource claims.mode=imagesis rejected server side for any session without a user id, matching the UI gate.Pluggable export storage
EXPORT_STORAGEconfig with explicitS3ExportStorage/GCSExportStoragebackends and a lazy, callablekey_prefixfor multi tenant deployments.Streamed downloads (replaces signed URLs)
Content-Lengthis declared, so a stream that dies midway is a failed download in the browser rather than a silently truncated file.Status and polling
runningstatus is recorded (and committed immediately) when a worker picks the job up, so queue delay does not consume the client's polling window.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
No visual changes beyond toast copy; the export/download flows are API level.
TESTING INSTRUCTIONS
pytest tests/unit_tests/tasks/test_export_dashboard_excel.py tests/unit_tests/utils/gcs_tests.py tests/unit_tests/utils/s3_tests.py(70 tests)pytest tests/integration_tests/dashboards/api_tests.py -k "export_xlsx or download_xlsx"(25 tests)npm run test -- DownloadMenuItems.test.tsx(22 tests)EXPORT_STORAGE, export a dashboard logged in and as an embedded guest, click the download link; the file streams as an attachment with a declared length. GCS streaming additionally verified against fake-gcs-server, and the stack is validated in production on a GKE cluster using direct workload identity federation.ADDITIONAL INFORMATION